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