-
Notifications
You must be signed in to change notification settings - Fork 12
/
lint.js
350 lines (318 loc) · 10.7 KB
/
lint.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
'use strict';
const _ = require('lodash'),
h = require('highland'),
utils = require('clayutils'),
yaml = require('js-yaml'),
config = require('./config'),
prefixes = require('../prefixes'),
rest = require('../rest'),
refProp = '_ref',
DEFAULT_CONCURRENCY = 10,
CONCURRENCY_TIME = 100;
/**
* expand references in component lists
* @param {array} val
* @return {array}
*/
function expandListReferences(val) {
if (_.has(_.head(val), refProp)) {
// component list! return the references
return _.map(val, (item) => item[refProp]);
} else {
return [];
}
}
/**
* expand references in component properties
* @param {object} val
* @return {array}
*/
function expandPropReferences(val) {
if (_.has(val, refProp)) {
return [val[refProp]];
} else {
return [];
}
}
/**
* list all references in a component
* @param {object} data
* @return {array} of uris
*/
function listComponentReferences(data) {
return _.reduce(data, (result, val) => {
if (_.isArray(val)) {
return result.concat(expandListReferences(val));
} else if (_.isObject(val)) {
return result.concat(expandPropReferences(val));
} else {
return result;
}
}, []);
}
/**
* throw errors in the same place they can be dealt with
* @param {object|Error} item
* @return {object}
*/
function toError(item) {
if (item instanceof Error) {
throw item;
} else {
return item;
}
}
/**
* push rest errors into the stream
* @param {Error} err
* @param {function} push
*/
function pushRestError(err, push) {
push(null, { type: 'error', message: err.url }); // every url that errors out should be captured
}
/**
* recursively check all references in a component or layout
* @param {*} url
* @param {string} prefix
* @param {number} concurrency
* @param {string} ext
* @return {Stream}
*/
function checkComponent(url, prefix, concurrency, ext = '') {
if (_.isObject(url)) {
return h.of(url); // error / success object, pass it on
} else if (_.isString(url) && !_.includes(url, 'http')) {
// uri, convert it to url
url = prefixes.uriToUrl(prefix, url);
}
// if extension has been passed in (with a uri), make sure we keep checking it
// otherwise, check the url for an extension, then...
// remove extension from the url to check against composed json, then check with the extension afterwards
if (!ext.length && _.isString(url) && prefixes.getExt(url)) {
ext = prefixes.getExt(url);
url = url.slice(0, url.indexOf(ext));
}
// first, do a quick check against the composed json
return rest.get(`${url}.json`)
.flatMap((res) => {
if (res instanceof Error) {
// some child is broken, start the linting process in earnest
return rest.get(url)
.map(toError)
.flatMap((data) => {
const children = listComponentReferences(data);
return h([h.of({ type: 'success', message: url }), h(children)]).merge();
})
.errors(pushRestError)
.flatMap((uri) => checkComponent(uri, prefix, concurrency, ext))
.ratelimit(concurrency, CONCURRENCY_TIME);
} else if (ext.length) {
// data is fine, check the rendered version
return rest.get(`${url}${ext}`, { type: 'text' })
.flatMap((res) => {
if (res instanceof Error) {
// render is broken, start checking children
return rest.get(url)
.map(toError)
.flatMap((data) => {
const children = listComponentReferences(data);
return h([
h.of({ type: 'error', message: `${url}${ext}` }), // the .ext errored,
h.of({ type: 'success', message: url }), // but the data succeeded
h(children)
]).merge(); // which means it's either this template or a child that's breaking it
})
.errors(pushRestError)
.flatMap((uri) => checkComponent(uri, prefix, concurrency, ext))
.ratelimit(concurrency, CONCURRENCY_TIME);
} else {
return h.of({ type: 'success', message: `${url}${ext}` });
}
});
} else {
// everything's fine! no need to lint any children
return h.of({ type: 'success', message: `${url}${ext}` });
}
});
}
/**
* check all references in a page
* @param {string} url
* @param {string} prefix
* @param {number} concurrency
* @return {Stream}
*/
function checkPage(url, prefix, concurrency) {
let ext = '';
// if we're checking a page with an extension, cut it off from the url and pass it into the component checking
if (_.isString(url) && prefixes.getExt(url)) {
ext = prefixes.getExt(url);
url = url.slice(0, url.indexOf(ext));
}
// first, do a quick check against the composed json
return rest.get(`${url}.json`)
.flatMap((res) => {
if (res instanceof Error) {
// some child is broken, start the linting process in earnest
return rest.get(url)
.map(toError)
.flatMap((data) => {
const layout = data.layout,
children = _.reduce(data, (uris, area) => _.isArray(area) ? uris.concat(area) : uris, []);
return h([h.of({ type: 'success', message: url }), h.of(layout), h(children)]).merge();
})
.errors(pushRestError)
.flatMap((uri) => checkComponent(uri, prefix, concurrency, ext))
.ratelimit(concurrency, CONCURRENCY_TIME);
} else if (ext.length) {
// data is fine, check the rendered version
return rest.get(`${url}${ext}`, { type: 'text' })
.flatMap((res) => {
if (res instanceof Error) {
// render is broken, start checking children
return rest.get(url)
.map(toError)
.flatMap((data) => {
const layout = data.layout,
children = _.reduce(data, (uris, area) => _.isArray(area) ? uris.concat(area) : uris, []);
return h([
h.of({ type: 'error', message: `${url}${ext}` }), // the .ext errored,
h.of({ type: 'success', message: url }), // but the data succeeded
h.of(layout), // which means either the layout
h(children) // or the children are broken
]).merge();
})
.errors(pushRestError)
.flatMap((uri) => checkComponent(uri, prefix, concurrency, ext))
.ratelimit(concurrency, CONCURRENCY_TIME);
} else {
return h.of({ type: 'success', message: `${url}${ext}` });
}
});
} else {
// everything's fine! no need to lint any children
return h.of({ type: 'success', message: url });
}
});
}
/**
* determine the page uri, then run checks against it
* @param {string} url
* @param {number} concurrency
* @return {Stream}
*/
function checkPublicUrl(url, concurrency) {
return rest.findURI(url)
.map(toError)
.flatMap(({ uri, prefix }) => {
const pageURL = prefixes.uriToUrl(prefix, uri);
return h([h.of({ type: 'success', message: url }), checkPage(`${pageURL}.html`, prefix, concurrency)]).merge();
}).errors(pushRestError);
}
/**
* lint a url, recursively determining if all components exist
* @param {string} rawUrl url or alias, will be run through config
* @param {object} options
* @return {Stream}
*/
function lintUrl(rawUrl, options = {}) {
const concurrency = options.concurrency || DEFAULT_CONCURRENCY,
url = config.get('url', rawUrl);
if (!url) {
// exit early if there's no url
return h.of({ type: 'error', message: 'URL is not defined! Please specify a url to lint' });
}
if (utils.isComponent(url) || utils.isLayout(url)) {
return checkComponent(url, prefixes.getFromUrl(url), concurrency);
} else if (utils.isPage(url)) {
return checkPage(url, prefixes.getFromUrl(url), concurrency);
} else {
return checkPublicUrl(url, concurrency);
}
}
/**
* determine if a schema has a description
* @param {object} obj
* @return {boolean}
*/
function noDescription(obj) {
return !_.has(obj, '_description');
}
/**
* Check if a string contains non-letter, non-number, or non-underscore chars
*
* @param {string} str
* @return {boolean}
*/
function isValidKilnDotNotation(str) {
// https://regex101.com/r/wapXTM/2 for an example of this regex in action
// This function is used after "toDotNotation()" in "assertCamelCasedProps()" below
// "toDotNotation" actually allows numbers, which are not valid property accessors in dot notation, but which is why we permit numbers here
// If the regex returns false, it means that the string is valid
return !/[^\w\$_]/g.test(str);
}
/**
* determine if a schema has camelCased props
* @param {obj} obj
* @return {array}
*/
function nonCamelCasedProps(obj) {
return _.reduce(obj, (errors, value, key) => {
return !isValidKilnDotNotation(key) ? errors.concat(key) : errors;
}, []);
}
/**
* determine if a schema has groups that reference non-existant fields
* @param {obj} obj
* @return {array}
*/
function nonexistentGroupFields(obj) {
return _.reduce(_.get(obj, '_groups'), (errors, group, groupName) => {
const fields = group.fields;
_.each(fields, (field) => {
if (!_.has(obj, field)) {
errors.push(`${groupName} » ${field}`);
}
});
return errors;
}, []);
}
/**
* lint schemas for:
* - valid yaml syntax
* - has _description
* - all root-level properties are camelCase
* - _group fields refer to existing properties
* @param {string} str of yaml
* @return {Stream}
*/
function lintSchema(str) {
return h([str])
.map(yaml.load)
.errors((e, push) => {
push(null, { type: 'error', message: `YAML syntax error: ${e.message.slice(0, e.message.indexOf(':'))}` });
}).flatMap((obj) => {
if (obj.type && obj.type === 'error') {
return h.of(obj); // pass through errors
} else {
let errors = [];
// lint schema!
if (noDescription(obj)) {
errors.push({ type: 'error', message: 'Schema has no _description' });
}
if (nonCamelCasedProps(obj).length) {
errors.push({ type: 'error', message: 'Properties must be camelCased', details: nonCamelCasedProps(obj).join('\n') });
}
if (nonexistentGroupFields(obj).length) {
errors.push({ type: 'error', message: 'Fields referenced by groups don\'t exist', details: nonexistentGroupFields(obj).join('\n') });
}
if (errors.length) {
return h(errors);
} else {
return h.of({ type: 'success' });
}
}
});
}
module.exports.lintUrl = lintUrl;
module.exports.lintSchema = lintSchema;