-
Notifications
You must be signed in to change notification settings - Fork 20
/
validate.mjs
100 lines (89 loc) · 2.31 KB
/
validate.mjs
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
import { readFile } from 'fs/promises'
import Ajv from 'ajv/dist/2020.js'
import addFormats from 'ajv-formats'
import meta from 'ajv/dist/refs/json-schema-2020-12/index.js'
import { glob as baseGlob } from 'glob'
import { execa, ExecaError } from 'execa'
let ref
try {
const { stdout } = await execa`git describe --exact-match --tags`
ref = stdout
} catch (e) {
if (e instanceof ExecaError && e.failed) ref = 'main'
else throw e
}
const schemaIdPrefix = `https://gcn.nasa.gov/schema/${ref}`
const ajv = new Ajv({
validateSchema: true,
verbose: true,
allowUnionTypes: true,
})
addFormats(ajv)
ajv.addMetaSchema(meta)
async function glob(path) {
return await baseGlob(path, {
ignore: ['test/**', 'node_modules/**'],
posix: true,
})
}
async function validate() {
const schemaFilenames = await glob('**/*.schema.json')
const schemas = await Promise.all(
schemaFilenames.map(async (match) => {
const json = JSON.parse(
await readFile(match, {
encoding: 'utf-8',
}),
)
const expectedId = `${schemaIdPrefix}/${match}`
if (json['$id'] !== expectedId) {
console.error(
`error: ${match}: expected value of $id to be ${expectedId}, but found ${json['$id']}`,
)
process.exitCode = 1
}
return json
}),
)
try {
ajv.addSchema(schemas).compile(true)
} catch (e) {
if (e instanceof Error) {
process.exitCode = 1
console.error(`error: ${e.message}`)
} else {
throw e
}
}
const exampleFilenames = await glob('**/*.example.json')
await Promise.all(
exampleFilenames.map(async (path) => {
const example = JSON.parse(
await readFile(path, {
encoding: 'utf-8',
}),
)
const schemaId = example['$schema']
if (!schemaId) {
process.exitCode = 1
console.error(`error: ${path}: missing required $schema property`)
return
}
try {
ajv.validate(schemaId, example)
} catch (e) {
if (e instanceof Error) {
process.exitCode = 1
console.error(`error: ${path}: ${e.message}`)
} else {
throw e
}
}
if (ajv.errors) {
console.log(JSON.stringify(ajv.errors, null, 2))
process.exitCode = 1
}
}),
)
}
await validate()