UNPKG

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