UNPKG

2.14 kBJavaScriptView Raw
1const urlJoin = require('../utils/urlJoin');
2const isURL = require('../utils/is-url');
3const Asset = require('../Asset');
4const logger = require('@parcel/logger');
5
6// A list of all attributes in a schema that may produce a dependency
7// Based on https://schema.org/ImageObject
8// Section "Instances of ImageObject may appear as values for the following properties"
9const SCHEMA_ATTRS = [
10 'logo',
11 'photo',
12 'image',
13 'thumbnail',
14 'screenshot',
15 'primaryImageOfPage',
16 'embedUrl',
17 'thumbnailUrl',
18 'video',
19 'contentUrl'
20];
21
22class JSONLDAsset extends Asset {
23 constructor(name, options) {
24 super(name, options);
25 this.type = 'jsonld';
26 }
27
28 parse(content) {
29 return JSON.parse(content.trim());
30 }
31
32 collectDependencies() {
33 if (!this.options.publicURL.startsWith('http')) {
34 logger.warn(
35 "Please specify a publicURL using --public-url, otherwise schema assets won't be collected"
36 );
37 return;
38 }
39
40 for (let schemaKey in this.ast) {
41 if (SCHEMA_ATTRS.includes(schemaKey)) {
42 this.collectFromKey(this.ast, schemaKey);
43 this.isAstDirty = true;
44 }
45 }
46 }
47
48 // Auxiliary method for collectDependencies() to use for recursion
49 collectFromKey(schema, schemaKey) {
50 if (!schema.hasOwnProperty(schemaKey)) {
51 return;
52 }
53 // values can be strings or objects
54 // if it's not a string, it should have a url
55 if (typeof schema[schemaKey] === 'string') {
56 let assetPath = this.addURLDependency(schema[schemaKey]);
57 if (!isURL(assetPath)) {
58 // paths aren't allowed, values must be urls
59 assetPath = urlJoin(this.options.publicURL, assetPath);
60 }
61 schema[schemaKey] = assetPath;
62 } else if (Array.isArray(schema[schemaKey])) {
63 Object.keys(schema[schemaKey]).forEach(i => {
64 this.collectFromKey(schema[schemaKey], i);
65 });
66 } else {
67 this.collectFromKey(schema[schemaKey], 'url');
68 }
69 }
70
71 generate() {
72 if (this.options.production) {
73 return JSON.stringify(this.ast);
74 } else {
75 return JSON.stringify(this.ast, null, 2);
76 }
77 }
78}
79
80module.exports = JSONLDAsset;