-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsfcc-schemas.js
563 lines (464 loc) · 17.3 KB
/
sfcc-schemas.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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
const fs = require('fs');
const path = require('path');
const validator = require('xsd-schema-validator');
const chalk = require('chalk');
const glob = require('glob-promise');
const xml2js = require('xml2js-es6-promise');
const _ = require('lodash');
const cliprogress = require('cli-progress');
const readdir = require('recursive-readdir');
const moment = require('moment');
const { timeout, TimeoutError } = require('promise-timeout');
const PromisePool = require('es6-promise-pool');
const yargs = require('yargs')
const { log } = console;
let options = {
projectpath: 'cartridges/app_project/cartridge',
sfrapath: 'exports/storefront-reference-architecture/cartridges/app_storefront_base/cartridge',
timeout: 5000
};
async function xsdfy () {
let files = await findXmlFiles();
let xsdmap = buildXsdMapping();
for (let j = 0; j < files.length; j++) {
let xml = files[j];
let xmllocal = path.relative(process.cwd(), xml);
let xmlcontent = fs.readFileSync(xml, 'UTF-8');
let ns = getNamespace(xmlcontent);
let schemaLocation = getSchemaLocation(xmlcontent);
if (schemaLocation) {
log(chalk.green(`File ${xmllocal} already mapped to ${schemaLocation}`));
} else {
let xsdfile = xsdmap.get(ns);
if (xsdfile) {
let xsdrelative = path.relative(xml, xsdfile);
log(chalk.yellow(`Adding xsd to ${xml} -> ${xsdrelative}`));
xmlcontent = xmlcontent.replace(`${ns}"`, `${ns}" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="${ns} ${xsdrelative}"`);
fs.writeFileSync(xml, xmlcontent);
} else {
log(chalk.yellow(`Unmapped: ${xml}`));
}
}
}
}
async function validate (failsonerror) {
let files = await findXmlFiles();
let xsdmap = buildXsdMapping();
let results = [];
let message = `Validating ${files.length} xml files using sfcc schemas`;
const progress = new cliprogress.Bar({
format: `${chalk.green(message)} [${chalk.cyan('{bar}')}] {percentage}% | {value}/{total}`
}, cliprogress.Presets.rect);
progress.start(files.length, 0);
let count = 0;
let promisecount = 0;
let pool = new PromisePool(() => {
if (promisecount < files.length) {
let xml = files[promisecount];
promisecount++
return new Promise(async (resolve) => {
let xmlcontent = fs.readFileSync(xml, 'UTF-8');
let filename = path.basename(xml);
progress.update(++count);
let ns = getNamespace(xmlcontent);
if (!ns) {
chalk.red(`Namespace not found for ${filename}`);
}
let xsd = xsdmap.get(ns);
if (!xsd) {
if (ns !== 'http://www.demandware.com/xml/impex/accessrole/2007-09-05') { // exclude known missing ns
log(chalk.yellow(`No xsd found for namespace ${ns}`));
}
resolve();
} else {
let res = {};
try {
// console.log(chalk.yellow(`Applying timeout to ${xml}`));
res = await timeout(validateXml(xml, xsd), options.timeout);
}
catch (err) {
if (err instanceof TimeoutError) {
// console.error(`Timeout validating ${xml}`);
res = {
xml: xml,
valid: false,
processerror: 'true',
messages: [`Validation timeout after ${options.timeout}ms`]
};
}
}
// console.log(chalk.green(`Done with ${xml}`));
results.push(res);
resolve();
}
})
}
return null;
}, 20);
await pool.start();
progress.stop();
let successcount = results.filter(i => i.valid).length;
let errorcount = results.filter(i => !i.valid && !i.processerror).length;
let notvalidated = results.filter(i => i.processerror).length;
if (errorcount > 0) {
log(chalk`Validated ${results.length} files: {green ${successcount} valid} and {red ${errorcount} with errors}\n`);
} else {
log(chalk`Validated ${results.length} files: {green all good} 🍺\n`);
}
if (notvalidated > 0) {
log(chalk.yellow(`${notvalidated} files cannot be validated (environment problems or timeout)\n`));
}
results.forEach((result) => {
if (!result.valid) {
log(chalk.redBright(`File ${result.xml} invalid:`));
result.messages.forEach(i => {
let msg = i;
if (msg && msg.indexOf && msg.indexOf('cvc-complex-type') > -1 && msg.indexOf(': ') > -1) {
msg = msg.substr(msg.indexOf(': ') + 2);
}
log(chalk.redBright(`● ${msg}`));
});
if (result.messages.length === 0) {
log(chalk.redBright(`● ${JSON.stringify(result)}`));
}
log('\n');
}
});
if (failsonerror && errorcount > 0) {
log(chalk.redBright(`${errorcount} xml files failed validation\n`));
process.exit(2); // fail build;
throw new Error(`${errorcount} xml files failed validation`);
}
}
async function findXmlFiles () {
return glob(`${path.join(process.cwd(), 'sites')}/**/*.xml`);
}
function buildXsdMapping () {
let xsdfolder = path.join(process.cwd(), 'node_modules/sfcc-schemas/xsd/');
let xsdmap = new Map();
fs.readdirSync(xsdfolder).forEach((file) => {
let fullpath = path.join(xsdfolder, file);
let ns = getNamespace(fs.readFileSync(fullpath, 'utf-8'));
if (ns) {
xsdmap.set(ns, fullpath);
} else {
chalk.red(`Namespace not found in xsd ${fullpath}`);
}
});
return xsdmap;
}
function getNamespace (xmlcontent) {
let match = xmlcontent.match(new RegExp('xmlns(?::loc)? *= *"([a-z0-9/:.-]*)"'));
if (match) {
return match[1];
}
return null;
}
function getSchemaLocation (xmlcontent) {
let match = xmlcontent.match(/xsi:schemaLocation="(.*)"/);
// let match = xmlcontent.match(new RegExp('xsi:schemaLocation="([.|\n]*)"'));
if (match) {
return match[1];
}
return null;
}
async function validateXml (xml, xsd) {
return new Promise((resolve) => {
// process.stdout.write('.');
validator.validateXML({ file: xml }, xsd, (err, result) => {
if (err) {
if (result) {
if (!result.messages || result.messages.length === 0) {
result.messages.push(err);
result.processerror = true;
}
} else {
log(chalk.red(err));
return {};
}
}
result.xml = xml;
result.xsd = xsd;
resolve(result);
});
});
}
async function parseMeta (source) {
let exts = await xml2js(fs.readFileSync(source, 'utf-8'), {
trim: true,
normalizeTags: true,
mergeAttrs: true,
explicitArray: false,
attrNameProcessors: [function (name) { return _.replace(name, /-/g, ''); }],
tagNameProcessors: [function (name) { return _.replace(name, /-/g, ''); }]
});
if (exts.metadata && exts.metadata.typeextension) {
ensureArray(exts.metadata, 'typeextension');
exts = exts.metadata.typeextension.map(i => cleanupEntry(i)).filter(i => i.attributedefinitions);
} else if (exts.metadata && exts.metadata.customtype) {
ensureArray(exts.metadata, 'customtype');
exts = exts.metadata.customtype.map(i => cleanupEntry(i));
}
ensureArray(exts.urlrules, 'pipelinealiases');
cleanI18n(exts);
fs.writeFileSync(path.join(process.cwd(), 'output/config/', `${path.basename(source)}.json`), JSON.stringify(exts, null, 2));
// date parsing utils
exts.moment = moment;
return exts;
}
function ensureArray (object, field) {
if (object && object[field] && !object[field].length) {
object[field] = [object[field]];
}
}
function cleanupEntry (i) {
let res = i;
// normalize
if (res.customattributedefinitions) {
res.attributedefinitions = res.customattributedefinitions;
delete res.customattributedefinitions;
}
delete res.systemattributedefinitions;
// cleanup single attributes without array
if (res.attributedefinitions && res.attributedefinitions.attributedefinition && res.attributedefinitions.attributedefinition.attributeid) {
res.attributedefinitions.attributedefinition = [res.attributedefinitions.attributedefinition];
}
return res;
}
function cleanI18n (obj) {
Object
.entries(obj)
.forEach(entry => {
let [k, v] = entry;
if (v !== null && typeof v === 'object' && !v.escape) {
if (v._ && v['xml:lang'] && Object.keys(v).length === 2) {
obj[k] = v._;
// log(`-> replaced ${obj[k]}`);
}
cleanI18n(v);
}
});
}
async function entrypoints () {
const regex = /server\.(get|post)\(['" \n]*([a-zA-Z0-9]*)['" ]*/gm;
let inputpath = path.join(process.cwd(), 'output/code');
if (!fs.existsSync(inputpath)) {
return;
}
let files = await readdir(inputpath, [(i, stats) => !stats.isDirectory() && path.basename(path.dirname(i)) !== 'controllers' && path.extname(i) !== 'js']);
let mapping = {};
for (let j = 0; j < files.length; j++) {
let file = files[j];
let controllername = path.basename(file);
controllername = controllername.substr(0, controllername.lastIndexOf('.'));
let dirname = path.basename(path.dirname(path.dirname(path.dirname(file))));
let filecontent = fs.readFileSync(file);
let m;
// eslint-disable-next-line no-cond-assign
while ((m = regex.exec(filecontent)) !== null) {
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
let pipeline = `${controllername}-${m[2]}`;
let method = _.upperCase(m[1]);
if (mapping[pipeline]) {
mapping[pipeline].cartridges.push(dirname);
} else {
mapping[pipeline] = {
pipeline: pipeline,
method: method,
controller: controllername,
cartridges: [dirname]
};
}
}
}
return mapping;
}
async function listcontrollers () {
let projectbase = path.join(process.cwd(), options.projectpath);
if (!fs.existsSync(projectbase)) {
log(`Skipping controller docs, folder ${projectbase} not available`);
return;
}
let files = await readdir(path.join(projectbase, 'controllers'));
files = files.map(i => path.relative(projectbase, i));
let sfrabase = path.join(process.cwd(), options.projectpath);
sfrabase = path.join(process.cwd(), options.sfrapath);
let sfrafiles = await readdir(path.join(sfrabase, 'controllers'));
sfrafiles = sfrafiles.map(i => path.relative(sfrabase, i));
let controllers = files.map(i => ({
name: i,
project: true,
sfra: sfrafiles.includes(i)
}));
let sfracontrollers = sfrafiles.filter(i => !files.includes(i)).map(i => ({
name: i,
project: false,
sfra: true
}));
controllers = controllers.concat(sfracontrollers);
let templates = await readdir(path.join(projectbase, 'templates/default'));
templates = templates.map(i => path.relative(projectbase, i));
let sfratemplates = await readdir(path.join(sfrabase, 'templates/default'));
sfratemplates = sfratemplates.map(i => path.relative(sfrabase, i));
let templatesprj = templates.map(i => ({
name: i,
project: true,
sfra: sfratemplates.includes(i)
}));
let context = {
controllers: controllers,
templates: templatesprj
};
let output = path.join(process.cwd(), 'output/config/', 'controllers.html');
fs.writeFileSync(output, _.template(fs.readFileSync(path.resolve(__dirname, `templates/controllers.html`), 'utf-8'))(context));
log(chalk.green(`Generated documentation at ${output}`));
}
async function metacheatsheet () {
const argv = yargs.argv;
options.projectpath = argv.projectpath || options.projectpath;
options.sfrapath = argv.sfrapath || options.sfrapath;
await buildMeta();
await buildFromXml('sites/site_template/services.xml', 'services.html');
await buildFromXml('sites/site_template/jobs.xml', 'jobs.html');
await buildSeo('url-rules.xml', 'seo.html');
await buildFromXml('sites/site_template/pagemetatag.xml', 'pagemetatag.html');
await listcontrollers();
await buildAssetDoc();
}
async function buildMeta () {
let definitionspath = path.join(process.cwd(), 'sites/site_template/meta/custom-objecttype-definitions.xml');
let extensionspath = path.join(process.cwd(), 'sites/site_template/meta/system-objecttype-extensions.xml');
let exts = await parseMeta(extensionspath);
let defs = await parseMeta(definitionspath);
let context = {
extensions: exts,
definitions: defs
};
let output = path.join(process.cwd(), 'output/config/', 'metacheatsheet.html');
fs.writeFileSync(output, _.template(fs.readFileSync(path.resolve(__dirname, `templates/meta.html`), 'utf-8'))(context));
log(chalk.green(`Generated documentation at ${output}`));
}
async function buildFromXml (input, html) {
let inputpath = path.join(process.cwd(), input);
if (!fs.existsSync(inputpath)) {
return;
}
let output = path.join(process.cwd(), 'output/config/', html);
fs.writeFileSync(output, _.template(fs.readFileSync(path.resolve(__dirname, `templates/${html}`), 'utf-8'))(await parseMeta(inputpath)));
log(chalk.green(`Generated documentation at ${output}`));
}
async function buildSeo (xml, html) {
let mappings = await entrypoints();
let context = await parseXmlSites(xml, 'seo.html');
if (!context) {
return;
}
context.sites.forEach(site => {
let siteentrypoints = JSON.parse(JSON.stringify(mappings));
if (site.urlrules && site.urlrules.pipelinealiases && site.urlrules.pipelinealiases[0]) {
site.urlrules.pipelinealiases[0].pipelinealias.forEach(alias => {
if (siteentrypoints[alias.pipeline]) {
siteentrypoints[alias.pipeline].alias = alias._;
} else {
// console.log(`Not existing remapping: ${alias._}=${alias.pipeline}`);
siteentrypoints[alias.pipeline] = {
alias: alias._,
pipeline: alias.pipeline,
controller: alias.pipeline.substr(0, alias.pipeline.indexOf('-')),
cartridges: []
}
};
});
}
let entrypointsarray = Object.keys(siteentrypoints).map(i => siteentrypoints[i]).sort((a, b) => a.pipeline.localeCompare(b.pipeline));
site.entrypoints = entrypointsarray;
})
let output = path.join(process.cwd(), 'output/config/', html);
fs.writeFileSync(output, _.template(fs.readFileSync(path.resolve(__dirname, `templates/${html}`), 'utf-8'))(context));
log(chalk.green(`Generated documentation at ${output}`));
}
async function isml() {
let inputpath = path.join(process.cwd(), `${options.projectpath}/templates/default`);
if (!fs.existsSync(inputpath)) {
return;
}
let sfrapath = path.join(process.cwd(), `${options.sfrapath}/templates/default`);
let sfrafiles = await readdir(sfrapath);
let mapping = sfrafiles.filter(i => path.extname(i) === '.isml').map(i => ({
path: i,
template: path.relative(sfrapath, i),
type: 'sfra'
})
);
let files = await readdir(inputpath);
let projectmapping = files.filter(i => path.extname(i) === '.isml').map(i => ({
path: i,
template: path.relative(inputpath, i),
type: 'project'
})
);
projectmapping.forEach(i => {
let idx = mapping.findIndex(p => p.template === i.template);
if (idx) {
mapping.splice(idx, 1);
}
});
return mapping.concat(projectmapping).sort((a, b) => a.template.localeCompare(b.template));
}
async function buildAssetDoc() {
let html = 'assets.html';
let ismls = await isml();
if (!ismls) {
return;
}
const assetsregexp = /iscontentasset['" a-zA-Z0-9-/\n]* aid="([a-zA-Z0-9-_/]*)/gm;
const slotregexp = /isslot['" a-zA-Z0-9-/\n]* id="([a-zA-Z0-9-_/]*)/gm;
const includesregexp = /isinclude['" a-zA-Z0-9-/\n]* template="([a-zA-Z0-9-_/]*)/gm;
ismls.forEach(i => {
let filecontent = fs.readFileSync(i.path);
i.assets = regexpmatch(assetsregexp, filecontent);
i.slots = regexpmatch(slotregexp, filecontent);
i.includes = regexpmatch(includesregexp, filecontent);
});
ismls = ismls.filter(i => i.assets.length !== 0 || i.slots.length !== 0 || i.includes.length !== 0);
// log('isml:', JSON.stringify(ismls, null, 2));
let contentonly = ismls.filter(i => i.assets.length !== 0 || i.slots.length !== 0);
let output = path.join(process.cwd(), 'output/config/', html);
fs.writeFileSync(output, _.template(fs.readFileSync(path.resolve(__dirname, `templates/${html}`), 'utf-8'))({ templates: ismls , content: contentonly }));
log(chalk.green(`Generated documentation at ${output}`));
}
function regexpmatch(regex, filecontent) {
let matches = [];
let m;
// eslint-disable-next-line no-cond-assign
while ((m = regex.exec(filecontent)) !== null) {
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
matches.push(m[1]);
}
return matches;
}
async function parseXmlSites (filename, html) {
let files = await readdir(path.join(process.cwd(), 'sites/site_template/sites/'), [(i, stats) => !stats.isDirectory() && path.basename(i) !== "url-rules.xml"]);
if (!files || files.length === 0) {
return;
}
let context = { sites: [] };
for (let j = 0; j < files.length; j++) {
let single = await parseMeta(files[j]);
single.id = path.basename(path.dirname(files[j]));
context.sites.push(single);
}
return context;
}
// eslint-disable-next-line no-unused-vars
async function buildFromXmlSites (filename, html) {
let context = await parseXmlSites(filename, html);
let output = path.join(process.cwd(), 'output/config/', html);
fs.writeFileSync(output, _.template(fs.readFileSync(path.resolve(__dirname, `templates/${html}`), 'utf-8'))(context));
log(chalk.green(`Generated documentation at ${output}`));
}
module.exports = { validate, xsdfy, metacheatsheet };