forked from SchemaStore/schemastore
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cli.js
1606 lines (1429 loc) · 49.4 KB
/
cli.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
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/// <binding AfterBuild='build' />
// @ts-check
import path from 'node:path'
import fs from 'node:fs/promises'
import fsCb from 'node:fs'
import readline from 'node:readline'
import util from 'node:util'
import _AjvDraft04 from 'ajv-draft-04'
import { Ajv as AjvDraft06And07 } from 'ajv'
import _Ajv2019 from 'ajv/dist/2019.js'
import _Ajv2020 from 'ajv/dist/2020.js'
import _addFormats from 'ajv-formats'
import { ajvFormatsDraft2019 } from '@hyperupcall/ajv-formats-draft2019'
// import spectralCore from '@stoplight/spectral-core'
// import Parsers from '@stoplight/spectral-parsers'
// import spectralRuntime from '@stoplight/spectral-runtime' // eslint-disable-line n/no-extraneous-import
// import { bundleAndLoadRuleset } from '@stoplight/spectral-ruleset-bundler/with-loader'
import schemasafe from '@exodus/schemasafe'
import TOML from 'smol-toml'
import YAML from 'yaml'
import jsonlint from '@prantlf/jsonlint'
import * as jsoncParser from 'jsonc-parser'
import ora from 'ora'
import chalk from 'chalk'
import minimist from 'minimist'
import fetch from 'node-fetch'
/**
* Ajv defines types, but they don't work when importing the library with
* ESM syntax. Tweaking `jsconfig.json` with `esModuleInterop` didn't seem
* to fix things, so manually set the types with a cast. This issue is
* tracked upstream at https://github.com/ajv-validator/ajv/issues/2132.
*/
/** @type {typeof _AjvDraft04.default} */
const AjvDraft04 = /** @type {any} */ (_AjvDraft04)
/** @type {typeof _Ajv2019.default} */
const Ajv2019 = /** @type {any} */ (_Ajv2019)
/** @type {typeof _Ajv2020.default} */
const Ajv2020 = /** @type {any} */ (_Ajv2020)
/** @type {typeof _addFormats.default} */
const addFormats = /** @type {any} */ (_addFormats)
// Declare constants.
const AjvDraft06SchemaJson = await readJsonFile(
'node_modules/ajv/dist/refs/json-schema-draft-06.json',
)
const CatalogFile = './src/api/json/catalog.json'
const Catalog = /** @type {CatalogJson} */ (
jsoncParser.parse(await fs.readFile(CatalogFile, 'utf-8'))
)
const SchemaValidationFile = './src/schema-validation.jsonc'
const SchemaValidation = /** @type {SchemaValidationJson} */ (
jsoncParser.parse(await fs.readFile(SchemaValidationFile, 'utf-8'))
)
const SchemaDir = './src/schemas/json'
const TestPositiveDir = './src/test'
const TestNegativeDir = './src/negative_test'
const UrlSchemaStore = 'https://json.schemastore.org/'
const [SchemasToBeTested, FoldersPositiveTest, FoldersNegativeTest] = (
await Promise.all([
fs.readdir(SchemaDir),
fs.readdir(TestPositiveDir),
fs.readdir(TestNegativeDir),
])
).map((files) => {
return files.filter((file) => !isIgnoredFile(file))
})
// prettier-ignore
const SchemaDialects = [
{ draftVersion: '2020-12', url: 'https://json-schema.org/draft/2020-12/schema', isActive: true, isTooHigh: true },
{ draftVersion: '2019-09', url: 'https://json-schema.org/draft/2019-09/schema', isActive: true, isTooHigh: true },
{ draftVersion: 'draft-07', url: 'http://json-schema.org/draft-07/schema#', isActive: true, isTooHigh: false },
{ draftVersion: 'draft-06', url: 'http://json-schema.org/draft-06/schema#', isActive: false, isTooHigh: false },
{ draftVersion: 'draft-04', url: 'http://json-schema.org/draft-04/schema#', isActive: false, isTooHigh: false },
{ draftVersion: 'draft-03', url: 'http://json-schema.org/draft-03/schema#', isActive: false, isTooHigh: false },
]
/** @type {{ _: string[], help?: boolean, SchemaName?: string, 'schema-name'?: string, 'unstable-check-with'?: string }} */
const argv = /** @type {any} */ (
minimist(process.argv.slice(2), {
string: ['SchemaName', 'schema-name', 'unstable-check-with'],
boolean: ['help'],
})
)
if (argv.SchemaName) {
process.stderr.write(
`WARNING: Please use "--schema-name" instead of "--SchemaName". The flag "--SchemaName" will be removed.\n`,
)
argv['schema-name'] = argv.SchemaName
}
/**
* @typedef {Object} JsonSchemaAny
* @property {string} $schema
* @property {string | undefined} $ref
*
* @typedef {Object} JsonSchemaDraft04
* @property {undefined} $id
* @property {string} id
*
* @typedef {Object} JsonSchemaDraft07
* @property {string} $id
* @property {undefined} id
*
* @typedef {JsonSchemaAny & (JsonSchemaDraft04 | JsonSchemaDraft07)} JsonSchema
*/
/**
* @typedef {Object} CatalogJsonEntry
* @property {string} name
* @property {string} description
* @property {string[]} fileMatch
* @property {string} url
* @property {Record<string, string>} versions
*
* @typedef {Object} CatalogJson
* @property {number} version
* @property {CatalogJsonEntry[]} schemas
*/
/**
* @typedef {Object} SchemaValidationJsonOption
* @property {string[]} unknownFormat
* @property {string[]} unknownKeywords
* @property {string[]} externalSchema
*
* @typedef {Object} SchemaValidationJson
* @property {string[]} ajvNotStrictMode
* @property {string[]} fileMatchConflict
* @property {string[]} highSchemaVersion
* @property {string[]} missingCatalogUrl
* @property {string[]} skiptest
* @property {string[]} catalogEntryNoLintNameOrDescription
* @property {Record<string, SchemaValidationJsonOption>} options
*/
/**
* @typedef {Object} DataFile
* @property {Buffer} buffer
* @property {string} text
* @property {Record<PropertyKey, unknown>} json
* @property {string} name
* @property {string} path
*
* @typedef {Object} SchemaFile
* @property {Buffer} buffer
* @property {string} text
* @property {JsonSchema} json
* @property {string} name
* @property {string} path
*/
async function exists(/** @type {string} */ filepath) {
return fs
.stat(filepath)
.then(() => {
return true
})
.catch((/** @type {NodeJS.ErrnoException} */ err) => {
if (err instanceof Error && err.code === 'ENOENT') {
return false
} else {
throw err
}
})
}
async function readJsonFile(/** @type {string} */ filename) {
return JSON.parse(await fs.readFile(filename, 'utf-8'))
}
function isIgnoredFile(/** @type {string} */ file) {
return file === '.DS_Store'
}
async function forEachCatalogUrl(
/** @type {((arg0: string) => (void | Promise<void>))} */ fn,
) {
for (const catalogEntry of Catalog.schemas) {
await fn(catalogEntry.url)
for (const url of Object.values(catalogEntry?.versions ?? {})) {
await fn(url)
}
}
}
/**
* @typedef {Object} ExtraParams
@property {any} spinner
}
* @typedef {Object} ForEachTestFile
* @property {string} [actionName]
* @property {(arg0: SchemaFile, arg1: ExtraParams) => Promise<any>} [onSchemaFile]
* @property {(arg0: SchemaFile, arg1: DataFile, data: any, arg2: ExtraParams) => Promise<void>} [onPositiveTestFile]
* @property {(arg0: SchemaFile, arg1: DataFile, data: any, arg2: ExtraParams) => Promise<void>} [onNegativeTestFile]
* @property {(arg0: SchemaFile, arg1: ExtraParams) => Promise<void>} [afterSchemaFile]
*/
async function forEachFile(/** @type {ForEachTestFile} */ obj) {
const spinner = ora()
if (obj.actionName) {
spinner.start()
}
for (const dirent1 of await fs.readdir(SchemaDir, { withFileTypes: true })) {
if (isIgnoredFile(dirent1.name)) continue
const schemaName = dirent1.name
const schemaId = schemaName.replace('.json', '')
if (argv['schema-name'] && argv['schema-name'] !== schemaName) {
continue
}
if (SchemaValidation.skiptest.includes(schemaName)) {
continue
}
const schemaPath = path.join(SchemaDir, schemaName)
const schemaFile = await toFile(schemaPath)
spinner.text = `Running "${obj.actionName}" on file "${schemaFile.path}"`
const data = await obj?.onSchemaFile?.(schemaFile, { spinner })
if (obj?.onPositiveTestFile) {
const positiveTestDir = path.join(TestPositiveDir, schemaId)
if (await exists(positiveTestDir)) {
for (const testfile of await fs.readdir(positiveTestDir)) {
if (isIgnoredFile(testfile)) continue
const testfilePath = path.join(TestPositiveDir, schemaId, testfile)
let file = await toFile(testfilePath)
await obj.onPositiveTestFile(schemaFile, file, data, { spinner })
}
}
}
if (obj?.onNegativeTestFile) {
const negativeTestDir = path.join(TestNegativeDir, schemaId)
if (await exists(negativeTestDir)) {
for (const testfile of await fs.readdir(negativeTestDir)) {
if (isIgnoredFile(testfile)) continue
const testfilePath = path.join(TestNegativeDir, schemaId, testfile)
let file = await toFile(testfilePath)
await obj.onNegativeTestFile(schemaFile, file, data, { spinner })
}
}
}
await obj?.afterSchemaFile?.(schemaFile, { spinner })
}
if (obj.actionName) {
spinner.stop()
console.info(`✔️ Completed "${obj.actionName}"`)
}
}
async function toFile(/** @type {string} */ schemaPath) {
const buffer = await fs.readFile(schemaPath)
const text = buffer.toString()
return {
buffer,
text,
json: await readDataFile({ filepath: schemaPath, text }),
name: path.basename(schemaPath),
path: schemaPath,
}
}
async function readDataFile(
/** @type {{filepath: string, text: string }} */ obj,
) {
const fileExtension = path.parse(obj.filepath).ext
switch (fileExtension) {
case '.json':
try {
return JSON.parse(obj.text)
} catch (err) {
printErrorAndExit(err, [`Failed to parse JSON file "${obj.filepath}"`])
}
break
case '.jsonc':
try {
return jsoncParser.parse(obj.text)
} catch (err) {
printErrorAndExit(err, [`Failed to parse JSONC file "${obj.filepath}"`])
}
break
case '.yaml':
case '.yml':
try {
return YAML.parse(obj.text)
} catch (err) {
printErrorAndExit(err, [`Failed to parse YAML file "${obj.filepath}"`])
}
break
case '.toml':
try {
return TOML.parse(obj.text)
} catch (err) {
printErrorAndExit(err, [`Failed to parse TOML file "${obj.filepath}"`])
}
break
default:
printErrorAndExit(new Error(), [
`Unable to handle file extension "${fileExtension}" for file "${obj.filepath}"`,
])
break
}
}
/**
* @param {unknown} error
* @param {string[]} [messages]
* @param {string} [extraText]
* @returns {never}
*/
function printErrorAndExit(error, messages, extraText) {
if (Array.isArray(messages) && messages.length > 0) {
console.warn('---')
for (const msg of messages) {
console.error(chalk.red('>>') + ' ' + msg)
}
}
if (extraText) {
process.stderr.write(extraText)
process.stderr.write('\n')
}
console.warn('---')
process.stderr.write(error instanceof Error ? (error?.stack ?? '') : '')
process.stderr.write('\n')
process.exit(1)
}
function getSchemaDialect(/** @type {string} */ schemaUrl) {
const schemaDialect = SchemaDialects.find((obj) => schemaUrl === obj.url)
if (!schemaDialect) {
throw new Error(`No schema dialect found for url: ${schemaUrl}`)
}
return schemaDialect
}
/**
* @typedef {Object} AjvFactoryOptions
* @property {string} draftVersion
* @property {boolean} fullStrictMode
* @property {string[]} [unknownFormats]
* @property {string[]} [unknownKeywords]
* @property {string[]} [unknownSchemas]
* @property {Record<PropertyKey, unknown>} [options]
*/
/**
* Returns the correct and configured Ajv instance for a particular $schema version
*/
async function ajvFactory(
/** @type {AjvFactoryOptions} */ {
draftVersion,
fullStrictMode = true,
unknownFormats = [],
unknownKeywords = [],
unknownSchemas = [],
options,
},
) {
let ajvOptions = {}
Object.assign(
ajvOptions,
fullStrictMode
? {
strict: true,
}
: {
strictTypes: false, // recommended: true
strictTuples: false, // recommended: true
allowMatchingProperties: true, // recommended: false
},
)
Object.assign(ajvOptions, options)
let ajv
switch (draftVersion) {
case 'draft-04':
ajv = new AjvDraft04(ajvOptions)
addFormats(ajv)
break
case 'draft-06':
ajv = new AjvDraft06And07(ajvOptions)
ajv.addMetaSchema(AjvDraft06SchemaJson)
addFormats(ajv)
break
case 'draft-07':
/**
* Note that draft-07 defines iri{,-reference}, idn-{hostname,email}, which
* are not available through `addFormats`. So, use `ajvFormatsDraft2019` to
* obtain these. Thus, some draft2019 formats like "duration" are applied.
* See https://ajv.js.org/packages/ajv-formats.html for details.
*/
ajv = new AjvDraft06And07(ajvOptions)
addFormats(ajv)
ajvFormatsDraft2019(ajv)
break
case '2019-09':
ajv = new Ajv2019(ajvOptions)
addFormats(ajv)
ajvFormatsDraft2019(ajv)
break
case '2020-12':
ajv = new Ajv2020(ajvOptions)
addFormats(ajv)
ajvFormatsDraft2019(ajv)
break
default:
throw new Error('No JSON Schema version specified')
}
/**
* In strict mode, Ajv will throw an error if it does not
* recognize any non-standard formats. That is, unrecognized
* values of the "format" field. Supply this information to
* Ajv to prevent errors.
*/
for (const format of unknownFormats) {
ajv.addFormat(format, true)
}
/**
* Ditto, but with keywords (ex. "x-intellij-html-description")..
*/
for (const unknownKeyword of unknownKeywords) {
ajv.addKeyword(unknownKeyword)
}
/**
* Ditto, but with "$ref" URIs to external schemas.
*/
for (const schemaPath of unknownSchemas) {
ajv.addSchema(await readJsonFile(schemaPath))
}
return ajv
}
function getSchemaOptions(/** @type {string} */ schemaName) {
const options = SchemaValidation.options[schemaName] ?? {}
return {
unknownFormats: options.unknownFormat ?? [],
unknownKeywords: options.unknownKeywords ?? [],
unknownSchemas: (options.externalSchema ?? []).map((schemaName2) => {
return path.join(SchemaDir, schemaName2)
}),
}
}
async function taskNewSchema() {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
})
console.log('Enter the name of the schema (without .json extension)')
await handleInput()
async function handleInput(/** @type {string | undefined} */ schemaName) {
if (!schemaName || schemaName.endsWith('.json')) {
rl.question('input: ', handleInput)
return
}
const schemaFile = path.join(SchemaDir, schemaName + '.json')
const testDir = path.join(TestPositiveDir, schemaName)
const testFile = path.join(testDir, `${schemaName}.json`)
if (await exists(schemaFile)) {
throw new Error(`Schema file already exists: ${schemaFile}`)
}
console.info(`Creating schema file at 'src/${schemaFile}'...`)
console.info(`Creating positive test file at 'src/${testFile}'...`)
await fs.mkdir(path.dirname(schemaFile), { recursive: true })
await fs.writeFile(
schemaFile,
`{
"$id": "https://json.schemastore.org/${schemaName}.json",
"$schema": "http://json-schema.org/draft-07/schema#",
"additionalProperties": true,
"properties": {
},
"type": "object"
}\n`,
)
await fs.mkdir(testDir, { recursive: true })
await fs.writeFile(
testFile,
`"Replace this file with an example/test that passes schema validation. Supported formats are JSON, YAML, and TOML. We recommend adding as many files as possible to make your schema most robust."\n`,
)
console.info(`Please add the following to 'src/api/json/catalog.json':
{
"name": "",
"description": "",
"fileMatch": ["${schemaName}.yml", "${schemaName}.yaml"],
"url": "https://json.schemastore.org/${schemaName}.json"
}`)
process.exit(0)
}
}
async function taskLint() {
const /** @type {{count: number, file: string}[]} */ entries = []
await forEachFile({
actionName: 'lint',
async onSchemaFile(schema) {
// This checks to be sure $id is a schemastore.org URL.
// Commenting out because it is overly aggressive for now.
// await assertSchemaHasCorrectMetadata(schema)
await assertTopLevelRefIsStandalone(schema)
// await assertSchemaNoSmartQuotes(schema)
try {
const errors = schemasafe.lint(schema.json, {
// mode: 'strong',
requireSchema: true,
requireValidation: true,
requireStringValidation: false,
complexityChecks: true,
forbidNoopValues: true,
extraFormats: false,
schemas: {},
})
for (const err of errors) {
console.log(`${schema.name}: ${err.message}`)
}
entries.push({
count: errors.length,
file: schema.name,
})
} catch (err) {
console.log(err)
return
}
},
})
entries.sort((a, b) => a.count - b.count)
for (const entry of entries) {
console.info(`${entry.count}: ${entry.file}`)
}
// await forEachFile({
// async onSchemaFile(schema) {
// const doc = new spectralCore.Document(
// schema.text,
// Parsers.Json,
// schema.name,
// )
// const spectral = new spectralCore.Spectral()
//
// const schemaDialect = getSchemaDialect(schema.json.$schema)
//
// let spectralFile
// if (schemaDialect.draftVersion === 'draft-04') {
// spectralFile = 'config/.spectral-draft04.yaml'
// } else if (schemaDialect.draftVersion === 'draft-06') {
// spectralFile = 'config/.spectral-draft06.yaml'
// } else if (schemaDialect.draftVersion === 'draft-07') {
// spectralFile = 'config/.spectral-draft07.yaml'
// } else {
// throw new Error(
// `Unsupported schema version: ${schemaDialect.draftVersion}`,
// )
// }
//
// spectral.setRuleset(
// await bundleAndLoadRuleset(path.join(process.cwd(), spectralFile), {
// fs: fsCb,
// fetch: spectralRuntime.fetch,
// }),
// )
//
// const result = await spectral.run(doc)
// if (result.length > 0) {
// console.log(result)
// }
// },
// })
}
async function taskCheck() {
console.info(`===== VALIDATE PRECONDITIONS =====`)
await assertFileSystemIsValid()
// Check catalog.json.
await assertFileValidatesAgainstSchema(
CatalogFile,
path.join(SchemaDir, 'schema-catalog.json'),
)
await assertFilePassesJsonLint(await toFile(CatalogFile))
assertCatalogJsonHasNoDuplicateNames()
assertCatalogJsonHasNoBadFields()
assertCatalogJsonHasNoFileMatchConflict()
await assertCatalogJsonLocalUrlsMustRefFile()
await assertCatalogJsonIncludesAllSchemas()
// Check schema-validation.jsonc.
await assertFileValidatesAgainstSchema(
SchemaValidationFile,
'./src/schema-validation.schema.json',
)
toFile
await assertFilePassesJsonLint(await toFile(SchemaValidationFile), {
ignoreComments: true,
})
await assertSchemaValidationJsonReferencesNoNonexistentFiles()
assertSchemaValidationJsonHasValidSkipTest()
// Run pre-checks (checks before JSON Schema validation) on all files
console.info(`===== VALIDATE SCHEMAS =====`)
await forEachFile({
actionName: 'pre-checks',
async onSchemaFile(schema) {
assertFileHasNoBom(schema)
assertFileHasCorrectExtensions(schema.path, ['.json'])
await assertFilePassesJsonLint(schema)
await assertSchemaHasValidIdField(schema)
await assertSchemaHasValidSchemaField(schema)
},
async onPositiveTestFile(file) {
assertFileHasNoBom(file)
assertFileHasCorrectExtensions(file.path, [
'.json',
'.yml',
'.yaml',
'.toml',
])
if (!file.path.endsWith('.json')) {
await assertFilePassesJsonLint(file)
}
},
async onNegativeTestFile(file) {
assertFileHasNoBom(file)
assertFileHasCorrectExtensions(file.path, [
'.json',
'.yml',
'.yaml',
'.toml',
])
if (!file.path.endsWith('.json')) {
await assertFilePassesJsonLint(file)
}
},
})
// Run tests against JSON schemas
await forEachFile({
actionName: 'Ajv validation',
async onSchemaFile(schemaFile, { spinner }) {
const isFullStrictMode = !SchemaValidation.ajvNotStrictMode.includes(
schemaFile.name,
)
const schemaDialect = getSchemaDialect(schemaFile.json.$schema)
const options = getSchemaOptions(schemaFile.name)
const ajv = await ajvFactory({
draftVersion: schemaDialect.draftVersion,
fullStrictMode: isFullStrictMode,
unknownFormats: options.unknownFormats,
unknownKeywords: options.unknownKeywords,
unknownSchemas: options.unknownSchemas,
})
let validateFn
try {
validateFn = ajv.compile(schemaFile.json)
} catch (err) {
spinner.fail()
printErrorAndExit(err, [
`Failed to compile schema file ${schemaFile.path}`,
])
}
return {
validateFn,
}
},
async onPositiveTestFile(schemaFile, testFile, data, { spinner }) {
const validate = data.validateFn
if (!validate(testFile.json)) {
spinner.fail()
printErrorAndExit(
validate.err,
[
`Schema validation failed ./${testFile.path}`,
`Showing first error out of ${validate.errors?.length ?? '?'} total error(s)`,
],
util.formatWithOptions(
{ colors: true },
'%O',
validate.errors?.[0] ?? '???',
),
)
}
},
async onNegativeTestFile(schemaFile, testFile, data, { spinner }) {
const validate = data.validateFn
if (validate(testFile.json)) {
spinner.fail()
printErrorAndExit(new Error(), [
`Schema validation succeeded but was supposed to fail ./${testFile.path}`,
`For schema ${schemaFile.path}`,
])
}
},
})
// Print information.
console.info(`===== REPORT =====`)
await printSimpleStatistics()
await printCountSchemaVersions()
}
async function taskCheckStrict() {
const ajv = await ajvFactory({
draftVersion: 'draft-07',
fullStrictMode: false,
})
const metaSchemaFile = await toFile(
'./src/schemas/json/metaschema-draft-07-unofficial-strict.json',
)
let validateFn
try {
validateFn = ajv.compile(metaSchemaFile.json)
} catch (err) {
printErrorAndExit(err, [
`Failed to compile schema file ${metaSchemaFile.path}`,
])
}
await forEachFile({
actionName: 'strict metaschema check',
async onSchemaFile(schemaFile, { spinner }) {
const validate = validateFn
if (!validate(schemaFile.json)) {
spinner.fail()
printErrorAndExit(
validate.err,
[
`Schema validation failed ./${schemaFile.path}`,
`Showing first error out of ${validate.errors?.length ?? '?'} total error(s)`,
],
util.formatWithOptions(
{ colors: true },
'%O',
validate.errors?.[0] ?? '???',
),
)
}
},
})
// Print information.
console.info(`===== REPORT =====`)
await printSimpleStatistics()
await printCountSchemaVersions()
}
async function taskCheckRemote() {
console.info('TODO')
}
async function taskReport() {
await printSchemaReport()
}
async function taskMaintenance() {
{
console.info(`===== BROKEN SCHEMAS =====`)
forEachCatalogUrl(async (url) => {
if (url.startsWith(UrlSchemaStore)) return
await fetch(url, { method: 'HEAD' })
.then((res) => {
if (!res.ok) {
console.info(`NOT OK (${res.status}/${res.statusText}): ${url}`)
}
return undefined
})
.catch((err) => {
console.info(`NOT OK (${err.code}): ${url}`)
})
})
}
// await printDowngradableSchemaVersions()
}
async function assertFileSystemIsValid() {
/**
* Check that files exist only where files belong, and directories exist only
* where directories belong.
*/
{
for (const dirent of await fs.readdir(SchemaDir, {
withFileTypes: true,
})) {
if (isIgnoredFile(dirent.name)) continue
const schemaName = dirent.name
const schemaPath = path.join(SchemaDir, schemaName)
if (!dirent.isFile()) {
printErrorAndExit(new Error(), [
`Expected only files under directory "${SchemaDir}"`,
`Found non-file at "./${schemaPath}"`,
])
}
}
await Promise.all([onTestDir(TestPositiveDir), onTestDir(TestNegativeDir)])
async function onTestDir(/** @type {string} */ rootTestDir) {
for (const dirent of await fs.readdir(rootTestDir, {
withFileTypes: true,
})) {
if (isIgnoredFile(dirent.name)) continue
const testDir = path.join(rootTestDir, dirent.name)
if (!dirent.isDirectory()) {
printErrorAndExit(new Error(), [
`Expected only directories under directory "${rootTestDir}"`,
`Found non-directory at "./${testDir}"`,
])
}
for (const dirent of await fs.readdir(testDir, {
withFileTypes: true,
})) {
if (isIgnoredFile(dirent.name)) continue
const schemaName = dirent.name
const schemaPath = path.join(testDir, schemaName)
if (!dirent.isFile()) {
printErrorAndExit(new Error(), [
`Expected only files under directory "./${testDir}"`,
`Found non-file at "./${schemaPath}"`,
])
}
}
}
}
}
/**
* Check that each test file has a corresponding schema. We only need to
* check "one way". That is, a schema doesn't need to have any corresponding
* positive or negative tests.
*/
{
await Promise.all([onTestDir(TestPositiveDir), onTestDir(TestNegativeDir)])
async function onTestDir(/** @type {string} */ rootTestDir) {
for (const testDir of await fs.readdir(rootTestDir)) {
if (isIgnoredFile(testDir)) continue
const schemaName = testDir + '.json'
const schemaPath = path.join(SchemaDir, schemaName)
if (!(await exists(schemaPath))) {
printErrorAndExit(new Error(), [
`Failed to find a schema file at "${schemaPath}"`,
])
}
}
}
}
console.info('✔️ Directory structure conforms to expected layout')
}
function assertCatalogJsonHasNoDuplicateNames() {
/** @type {string[]} */
const schemaNames = Catalog.schemas.map((entry) => entry.name)
/** @type {string[]} */
for (const catalogEntry of Catalog.schemas) {
if (
schemaNames.indexOf(catalogEntry.name) !==
schemaNames.lastIndexOf(catalogEntry.name)
) {
printErrorAndExit(new Error(), [
`Found two schema entries with duplicate "name" of "${catalogEntry.name}" in file "${CatalogFile}"`,
`Expected the "name" property of schema entries to be unique`,
])
}
}
}
function assertCatalogJsonHasNoBadFields() {
for (const catalogEntry of Catalog.schemas) {
if (
SchemaValidation.catalogEntryNoLintNameOrDescription.includes(
catalogEntry.url,
)
) {
continue
}
for (const property of /** @type {const} */ (['name', 'description'])) {
if (
/$[,. \t-]/u.test(catalogEntry?.[property]) ||
/[,. \t-]$/u.test(catalogEntry?.[property])
) {
printErrorAndExit(new Error(), [
`Expected the "name" or "description" properties of catalog entries to not end with characters ",.<space><tab>-"`,
`The invalid entry has a "url" of "${catalogEntry.url}" in file "${CatalogFile}"`,
])
}
}
for (const property of /** @type {const} */ (['name', 'description'])) {
if (catalogEntry?.[property]?.toLowerCase()?.includes('schema')) {
printErrorAndExit(new Error(), [
`Expected the "name" or "description" properties of catalog entries to not include the word "schema"`,
`All files are already schemas, so its meaning is implied`,
`If the JSON schema is actually a meta-schema (or some other exception applies), ignore this error by appending to the property "catalogEntryNoLintNameOrDescription" in file "${SchemaValidationFile}"`,
`The invalid entry has a "url" of "${catalogEntry.url}" in file "${CatalogFile}"`,
])
}
}
for (const property of /** @type {const} */ (['name', 'description'])) {
if (catalogEntry?.[property]?.toLowerCase()?.includes('\n')) {
printErrorAndExit(new Error(), [
`Expected the "name" or "description" properties of catalog entries to not include a newline character"`,
`The invalid entry has a "url" of "${catalogEntry.url}" in file "${CatalogFile}"`,
])
}
}
for (const fileGlob of catalogEntry.fileMatch ?? []) {
if (fileGlob.includes('/')) {
// A folder must start with **/
if (!fileGlob.startsWith('**/')) {
printErrorAndExit(new Error(), [
'Expected the "fileMatch" values of catalog entries to start with "**/" if it matches a directory',
`The invalid entry has a "url" of "${catalogEntry.url}" in file "${CatalogFile}"`,
])
}
}
}
}
console.info(`✔️ catalog.json has no fields that break guidelines`)
}
function assertCatalogJsonHasNoFileMatchConflict() {
const /** @type {string[]} */ allFileMatches = []
for (const catalogEntry of Catalog.schemas) {
for (const fileGlob of catalogEntry.fileMatch ?? []) {
// Ignore globs that are OK to conflict for backwards compatibility.
if (SchemaValidation.fileMatchConflict.includes(fileGlob)) {
continue
}
if (allFileMatches.includes(fileGlob)) {
printErrorAndExit(new Error(), [
`Expected "fileMatch" value of "${fileGlob}" to be unique across all "fileMatch" properties in file "${CatalogFile}"`,
])
}
allFileMatches.push(fileGlob)
}
}
console.info('✔️ catalog.json has no duplicate "fileMatch" values')
}
async function assertCatalogJsonLocalUrlsMustRefFile() {
await forEachCatalogUrl((/** @type {string} */ catalogUrl) => {
// Skip external schemas.
if (!catalogUrl.startsWith(UrlSchemaStore)) {
return
}
const filename = new URL(catalogUrl).pathname.slice(1)
// Check that local URLs have end in .json