yamlctl 0.1.5 → 0.1.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -1
- package/package.json +3 -2
- package/src/cli.js +179 -126
- package/src/document.js +26 -11
- package/src/explain.js +7 -3
- package/src/resources.js +9 -3
- package/src/reuse.js +61 -0
- package/src/rules.js +33 -35
- package/src/schema.js +106 -32
- package/src/store.js +60 -26
package/README.md
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
[](https://github.com/devpro/yamlctl/actions/workflows/ci.yml)
|
|
4
4
|
[](https://www.npmjs.com/package/yamlctl)
|
|
5
|
+
[](https://sonarcloud.io/dashboard?id=devpro_yamlctl)
|
|
5
6
|
|
|
6
7
|
Edit YAML files from the command line.
|
|
7
8
|
|
|
@@ -15,7 +16,7 @@ Edit YAML files from the command line.
|
|
|
15
16
|
|
|
16
17
|
## Install
|
|
17
18
|
|
|
18
|
-
Node.js
|
|
19
|
+
Node.js 22 or later:
|
|
19
20
|
|
|
20
21
|
```bash
|
|
21
22
|
npm install --global yamlctl
|
|
@@ -192,6 +193,7 @@ Without any schema, it still edits the file, checks nothing, and says so.
|
|
|
192
193
|
A file naming a schema that cannot be loaded is read with a warning and never written, since checking nothing where the file asked for a check is worse than stopping.
|
|
193
194
|
|
|
194
195
|
Drafts 07, 2019-09 and 2020-12 are supported, and a schema can be split across files and addresses: every `$ref` is followed, relative to the document's `$id` when it has one.
|
|
196
|
+
A local copy of a published schema works as the published schema, and its relative `$ref`s are read from the files beside it, without the network.
|
|
195
197
|
|
|
196
198
|
A schema named by an `https://` address, the ones [SchemaStore](https://www.schemastore.org/) publishes for instance, is fetched along with every remote document its `$ref`s reach:
|
|
197
199
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "yamlctl",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.7",
|
|
4
4
|
"description": "Read and edit YAML data files from the command line, entry by entry, every change checked against the file's JSON Schema",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"yaml",
|
|
@@ -23,7 +23,7 @@
|
|
|
23
23
|
"LICENSE"
|
|
24
24
|
],
|
|
25
25
|
"engines": {
|
|
26
|
-
"node": ">=
|
|
26
|
+
"node": ">=22"
|
|
27
27
|
},
|
|
28
28
|
"repository": {
|
|
29
29
|
"type": "git",
|
|
@@ -35,6 +35,7 @@
|
|
|
35
35
|
"homepage": "https://github.com/devpro/yamlctl#readme",
|
|
36
36
|
"scripts": {
|
|
37
37
|
"test": "node --test test/*.test.js",
|
|
38
|
+
"test:coverage": "mkdir -p coverage && node --experimental-test-coverage --test-coverage-include=\"bin/**\" --test-coverage-include=\"src/**\" --test-reporter=spec --test-reporter-destination=stdout --test-reporter=lcov --test-reporter-destination=coverage/lcov.info --test test/*.test.js",
|
|
38
39
|
"smoke": "scripts/smoke_pack.sh"
|
|
39
40
|
},
|
|
40
41
|
"dependencies": {
|
package/src/cli.js
CHANGED
|
@@ -70,43 +70,35 @@ Examples:
|
|
|
70
70
|
|
|
71
71
|
class UsageError extends Error {}
|
|
72
72
|
|
|
73
|
+
const configured = (changed) => (changed ? 'configured' : 'unchanged');
|
|
74
|
+
|
|
73
75
|
// The verbs writing an entry, named and behaving as kubectl's do, so someone who knows one knows the other.
|
|
74
76
|
// `exists` is what the entry must be beforehand, `fields` and `filename` the input each takes, and `done` what the output says.
|
|
75
77
|
const WRITES = {
|
|
76
78
|
create: { exists: false, fields: true, filename: true, done: () => 'created' },
|
|
77
|
-
apply: { exists: null, fields: true, filename: true, done: (existed, changed) => (
|
|
79
|
+
apply: { exists: null, fields: true, filename: true, done: (existed, changed) => (existed ? configured(changed) : 'created') },
|
|
78
80
|
patch: { exists: true, fields: true, filename: false, done: (existed, changed) => (changed ? 'patched' : 'patched (no change)') },
|
|
79
81
|
replace: { exists: true, fields: false, filename: true, done: (existed, changed) => (changed ? 'replaced' : 'replaced (no change)') },
|
|
80
82
|
};
|
|
81
83
|
const VERBS = 'list, get, create, apply, patch, replace, delete, explain or check';
|
|
82
84
|
|
|
85
|
+
// The options taking no value, which refuse one rather than ignoring it, since `--force=false` would otherwise force.
|
|
86
|
+
const FLAGS = { '--force': 'force', '--ignore-not-found': 'ignoreNotFound', '--prune': 'prune', '--all': 'all', '--offline': 'offline', '--refresh': 'refresh', '-h': 'help', '--help': 'help', '-v': 'version', '--version': 'version' };
|
|
87
|
+
|
|
88
|
+
const VALUES = { '-C': 'dir', '--dir': 'dir', '--data-file': 'dataFile', '-o': 'output', '--output': 'output', '-f': 'filename', '--filename': 'filename', '--prefix': 'prefix' };
|
|
89
|
+
|
|
83
90
|
// Options may come anywhere, before or after the resource, so `yamlctl -C data projects list` and `yamlctl projects list -C data` read the same.
|
|
84
91
|
export function parseArgs(argv) {
|
|
85
92
|
const options = { dir: '.', dataFile: null, output: null, filename: null, force: false, ignoreNotFound: false, prune: false, all: false, prefix: null, offline: false, refresh: false, help: false, version: false };
|
|
86
93
|
const words = [];
|
|
87
94
|
for (let i = 0; i < argv.length; i++) {
|
|
88
95
|
const arg = argv[i];
|
|
89
|
-
|
|
96
|
+
if (Object.hasOwn(FLAGS, arg)) options[FLAGS[arg]] = true;
|
|
97
|
+
else if (Object.hasOwn(VALUES, arg)) {
|
|
90
98
|
if (i + 1 >= argv.length) throw new UsageError(`${arg} needs a value`);
|
|
91
|
-
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
else if (arg === '--data-file') options.dataFile = value();
|
|
95
|
-
else if (arg === '-o' || arg === '--output') options.output = value();
|
|
96
|
-
else if (arg === '-f' || arg === '--filename') options.filename = value();
|
|
97
|
-
else if (arg === '--force') options.force = true;
|
|
98
|
-
else if (arg === '--ignore-not-found') options.ignoreNotFound = true;
|
|
99
|
-
else if (arg === '--prune') options.prune = true;
|
|
100
|
-
else if (arg === '--all') options.all = true;
|
|
101
|
-
else if (arg === '--prefix') options.prefix = value();
|
|
102
|
-
else if (arg === '--offline') options.offline = true;
|
|
103
|
-
else if (arg === '--refresh') options.refresh = true;
|
|
104
|
-
else if (arg === '-h' || arg === '--help') options.help = true;
|
|
105
|
-
else if (arg === '-v' || arg === '--version') options.version = true;
|
|
106
|
-
else if (arg.startsWith('--') && arg.includes('=')) {
|
|
107
|
-
const [flag, ...rest] = arg.split('=');
|
|
108
|
-
argv.splice(i + 1, 0, rest.join('='));
|
|
109
|
-
argv[i] = flag;
|
|
99
|
+
options[VALUES[arg]] = argv[++i];
|
|
100
|
+
} else if (arg.startsWith('--') && arg.includes('=')) {
|
|
101
|
+
argv.splice(i, 1, ...splitOption(arg));
|
|
110
102
|
i--;
|
|
111
103
|
} else if (arg.startsWith('-') && arg !== '-' && !arg.includes('=')) throw new UsageError(`unknown option ${arg}`);
|
|
112
104
|
else words.push(arg);
|
|
@@ -115,6 +107,13 @@ export function parseArgs(argv) {
|
|
|
115
107
|
return { options, words };
|
|
116
108
|
}
|
|
117
109
|
|
|
110
|
+
// `--option=value` as the option and its value.
|
|
111
|
+
function splitOption(arg) {
|
|
112
|
+
const [flag, ...rest] = arg.split('=');
|
|
113
|
+
if (Object.hasOwn(FLAGS, flag)) throw new UsageError(`${flag} takes no value`);
|
|
114
|
+
return [flag, rest.join('=')];
|
|
115
|
+
}
|
|
116
|
+
|
|
118
117
|
// The schemas the command can reach are fetched first, the only step needing the network, so everything after it runs synchronously from what was fetched.
|
|
119
118
|
// Only the files a command could read are looked at: the one --data-file names, else every data file of the directory.
|
|
120
119
|
export async function main(argv, io = {}) {
|
|
@@ -191,23 +190,29 @@ export function run(argv, { out = (text) => process.stdout.write(text), err = (t
|
|
|
191
190
|
if (words[0] === 'check' && words.length === 1) return checkDirectory(needNoOutput(context, 'check'));
|
|
192
191
|
if (words.length < 2) throw new UsageError(`${words[0]} needs a verb: ${VERBS}`);
|
|
193
192
|
|
|
194
|
-
|
|
195
|
-
const target = resolveResource({ dir, name, file });
|
|
196
|
-
// A file naming a schema that cannot be loaded is not written: checking nothing where the file asked for a check is the one outcome worse than stopping.
|
|
197
|
-
if (target.schemaError && (Object.hasOwn(WRITES, verb) || verb === 'delete')) throw new Error(`${display(target.file, cwd)} ${target.schemaError}, so it is not written`);
|
|
198
|
-
if (target.schemaError) err(`warning: ${display(target.file, cwd)} ${target.schemaError}, so nothing is checked\n`);
|
|
199
|
-
else if (!target.schema) err(`warning: no schema found for ${display(target.file, cwd)}, so nothing is checked\n`);
|
|
200
|
-
if (Object.hasOwn(WRITES, verb)) return write(verb, { ...context, name, target, args });
|
|
201
|
-
const commands = { list, get, delete: remove, explain: (c) => explainCommand(needNoOutput(c, 'explain')), check: (c) => checkResource(needNoOutput(c, 'check')) };
|
|
202
|
-
if (!Object.hasOwn(commands, verb)) throw new UsageError(`unknown verb ${verb}, use ${VERBS}`);
|
|
203
|
-
return commands[verb]({ ...context, name, target, args });
|
|
193
|
+
return runVerb(context, words);
|
|
204
194
|
} catch (e) {
|
|
205
|
-
err(`error: ${
|
|
195
|
+
err(`error: ${reason(e)}\n`);
|
|
206
196
|
if (e instanceof UsageError) err(`Run yamlctl --help for the usage.\n`);
|
|
207
197
|
return 1;
|
|
208
198
|
}
|
|
209
199
|
}
|
|
210
200
|
|
|
201
|
+
function runVerb(context, [name, verb, ...args]) {
|
|
202
|
+
const { dir, file, err, cwd } = context;
|
|
203
|
+
const target = resolveResource({ dir, name, file });
|
|
204
|
+
// A file naming a schema that cannot be loaded is not written: checking nothing where the file asked for a check is the one outcome worse than stopping.
|
|
205
|
+
if (target.schemaError && (Object.hasOwn(WRITES, verb) || verb === 'delete')) throw new Error(`${display(target.file, cwd)} ${target.schemaError}, so it is not written`);
|
|
206
|
+
if (target.schemaError) err(`warning: ${display(target.file, cwd)} ${target.schemaError}, so nothing is checked\n`);
|
|
207
|
+
else if (!target.schema) err(`warning: no schema found for ${display(target.file, cwd)}, so nothing is checked\n`);
|
|
208
|
+
if (Object.hasOwn(WRITES, verb)) return write(verb, { ...context, name, target, args });
|
|
209
|
+
const commands = { list, get, delete: remove, explain: (c) => explainCommand(needNoOutput(c, 'explain')), check: (c) => checkResource(needNoOutput(c, 'check')) };
|
|
210
|
+
if (!Object.hasOwn(commands, verb)) throw new UsageError(`unknown verb ${verb}, use ${VERBS}`);
|
|
211
|
+
return commands[verb]({ ...context, name, target, args });
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
const reason = (e) => (e instanceof Error ? e.message : String(e));
|
|
215
|
+
|
|
211
216
|
// Pruning deletes what the file does not hold, so it is refused without a scope saying which entries it may delete, as kubectl refuses it without a selector or --all.
|
|
212
217
|
function checkPrune(options, verb) {
|
|
213
218
|
if (!options.prune) {
|
|
@@ -251,7 +256,8 @@ function resources({ dir, options, out, cwd }) {
|
|
|
251
256
|
printData(found.map((r) => ({ ...r, file: display(r.file, cwd), schema: r.schema ? display(r.schema, cwd) : null })), options.output, out);
|
|
252
257
|
return 0;
|
|
253
258
|
}
|
|
254
|
-
const
|
|
259
|
+
const schemaOf = (r) => (r.schema ? display(r.schema, cwd) : '-');
|
|
260
|
+
const rows = found.map((r) => [r.name ?? '-', display(r.file, cwd), r.entries ?? '-', r.error ? `error: ${r.error}` : schemaOf(r)]);
|
|
255
261
|
out(table(['RESOURCE', 'FILE', 'ENTRIES', 'SCHEMA'], rows));
|
|
256
262
|
return 0;
|
|
257
263
|
}
|
|
@@ -294,81 +300,122 @@ const REPLACE_USAGE = 'replace takes -f <file> only, patch takes <key> <field>=<
|
|
|
294
300
|
|
|
295
301
|
// Every entry the command writes is checked against the file as it will be, and the file is written once, or not at all when one of them fails.
|
|
296
302
|
function write(verb, context) {
|
|
297
|
-
const { target,
|
|
298
|
-
const
|
|
299
|
-
const { map } = target;
|
|
300
|
-
const { document, schema } = target;
|
|
303
|
+
const { target, options } = context;
|
|
304
|
+
const { map, document } = target;
|
|
301
305
|
const entries = document.data[map] ?? {};
|
|
302
|
-
|
|
306
|
+
const changes = options.filename ? changesFromFile(verb, entries, context) : changesFromFields(verb, entries, context);
|
|
307
|
+
checkExistence(WRITES[verb], map, entries, changes);
|
|
303
308
|
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
const
|
|
315
|
-
|
|
309
|
+
const next = { ...document.data, [map]: { ...entries } };
|
|
310
|
+
for (const { key, entry } of changes) next[map][key] = entry;
|
|
311
|
+
const pruned = options.prune ? prunedKeys(entries, changes, options) : [];
|
|
312
|
+
for (const key of pruned) delete next[map][key];
|
|
313
|
+
checkChanges(changes, next, context);
|
|
314
|
+
refuseReferenced(target, next, pruned);
|
|
315
|
+
|
|
316
|
+
const lines = [];
|
|
317
|
+
for (const { key, entry } of changes) {
|
|
318
|
+
const existed = Object.hasOwn(entries, key);
|
|
319
|
+
const changed = !existed || !sameData(entries[key], entry);
|
|
320
|
+
if (changed) setEntry(document, map, key, entry);
|
|
321
|
+
lines.push(`${map}/${key} ${WRITES[verb].done(existed, changed)}\n`);
|
|
322
|
+
}
|
|
323
|
+
for (const key of pruned) {
|
|
324
|
+
deleteEntry(document, map, key);
|
|
325
|
+
lines.push(`${map}/${key} pruned\n`);
|
|
316
326
|
}
|
|
327
|
+
writeDocument(document);
|
|
328
|
+
printWritten(changes, pruned, lines, context);
|
|
329
|
+
return 0;
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
const sourceName = (filename) => (filename === '-' ? 'standard input' : filename);
|
|
333
|
+
|
|
334
|
+
// The entries to write, each under its key as it will be in the file.
|
|
335
|
+
function changesFromFile(verb, entries, context) {
|
|
336
|
+
const { args, options } = context;
|
|
337
|
+
if (!WRITES[verb].filename) throw new UsageError('patch takes <key> <field>=<value>..., replace takes -f <file>');
|
|
338
|
+
if (args.length) throw new UsageError(verb === 'replace' ? REPLACE_USAGE : `${verb} takes -f <file> without a key`);
|
|
339
|
+
const given = readEntries(options.filename, context);
|
|
340
|
+
refuseProto(given, sourceName(options.filename));
|
|
341
|
+
return Object.entries(given).map(([key, entry]) => ({ key, entry: verb === 'apply' ? mergePatch(entries[key], entry) : entry }));
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
function changesFromFields(verb, entries, { target, name, args }) {
|
|
345
|
+
const rules = WRITES[verb];
|
|
346
|
+
if (!rules.fields) throw new UsageError(REPLACE_USAGE);
|
|
347
|
+
const key = needKey(args, verb, rules.filename);
|
|
348
|
+
if (key === '__proto__') throw new Error('__proto__ is not an entry key');
|
|
349
|
+
const assignments = args.slice(1);
|
|
350
|
+
if (!assignments.length) throw new UsageError(`${verb} needs at least one <field>=<value>${rules.filename ? ', or -f <file>' : ''}`);
|
|
351
|
+
const base = isObject(entries[key]) ? entries[key] : {};
|
|
352
|
+
return [{ key, entry: assign(structuredClone(base), assignments, { schema: target.schema, map: target.map, name }) }];
|
|
353
|
+
}
|
|
317
354
|
|
|
355
|
+
function checkExistence(rules, map, entries, changes) {
|
|
318
356
|
for (const { key } of changes) {
|
|
319
357
|
const exists = Object.hasOwn(entries, key);
|
|
320
358
|
if (rules.exists === false && exists) throw new Error(`${map}/${key} already exists, use apply, patch or replace to change it`);
|
|
321
359
|
if (rules.exists === true && !exists) throw new Error(`no entry ${key} in ${map}`);
|
|
322
360
|
}
|
|
361
|
+
}
|
|
323
362
|
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
}
|
|
363
|
+
// The keys of the entries --prune deletes: those within its scope that the file does not hold.
|
|
364
|
+
function prunedKeys(entries, changes, options) {
|
|
365
|
+
const owned = (key) => options.all || key.startsWith(options.prefix);
|
|
366
|
+
const outside = changes.find(({ key }) => !owned(key));
|
|
367
|
+
if (outside) throw new Error(`${sourceName(options.filename)} holds ${outside.key}, outside the prefix ${options.prefix} it prunes`);
|
|
368
|
+
return Object.keys(entries).filter((key) => owned(key) && !changes.some((change) => change.key === key));
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
function checkChanges(changes, next, { target, options, err, cwd }) {
|
|
372
|
+
const { map, document, schema } = target;
|
|
334
373
|
const problems = [];
|
|
335
374
|
for (const { key, entry } of changes) {
|
|
336
375
|
if (schema) problems.push(...schema.validate(schema.entryPointer(map), entry, `${map}/${key}`));
|
|
337
376
|
problems.push(...checkSet({ schema, data: next, previous: document.data, map, key, entry, force: options.force }).map((problem) => `${map}/${key}: ${problem}`));
|
|
338
377
|
}
|
|
339
|
-
if (problems.length)
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
}
|
|
343
|
-
|
|
378
|
+
if (!problems.length) return;
|
|
379
|
+
for (const problem of problems) err(`${problem}\n`);
|
|
380
|
+
const subject = options.filename ? display(target.file, cwd) : `${map}/${changes[0].key}`;
|
|
381
|
+
throw new Error(`${subject} not written`);
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
// `next` is the file as it will be, so an entry deleted along with every entry naming it is not refused.
|
|
385
|
+
function refuseReferenced({ schema, map }, next, keys) {
|
|
386
|
+
for (const key of keys) {
|
|
344
387
|
const referencing = referencesTo({ schema, data: next, map, key });
|
|
345
388
|
if (referencing.length) throw new Error(`${map}/${key} is still named by ${referencing.join(', ')}: delete or change them first`);
|
|
346
389
|
}
|
|
390
|
+
}
|
|
347
391
|
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
const changed = !existed || !sameData(entries[key], entry);
|
|
352
|
-
if (changed) setEntry(document, map, key, entry);
|
|
353
|
-
lines.push(`${map}/${key} ${rules.done(existed, changed)}\n`);
|
|
354
|
-
}
|
|
355
|
-
for (const key of pruned) {
|
|
356
|
-
deleteEntry(document, map, key);
|
|
357
|
-
lines.push(`${map}/${key} pruned\n`);
|
|
358
|
-
}
|
|
359
|
-
writeDocument(document);
|
|
360
|
-
// A pipeline reads the entries or their paths rather than a sentence, and -o name keeps the entries pruned, since they are part of what was done.
|
|
361
|
-
if (options.output === 'name') for (const key of [...changes.map((change) => change.key), ...pruned]) out(`${map}/${key}\n`);
|
|
392
|
+
// A pipeline reads the entries or their paths rather than a sentence, and -o name keeps the entries pruned, since they are part of what was done.
|
|
393
|
+
function printWritten(changes, pruned, lines, { target, options, out }) {
|
|
394
|
+
if (options.output === 'name') for (const key of [...changes.map((change) => change.key), ...pruned]) out(`${target.map}/${key}\n`);
|
|
362
395
|
else if (options.output) printData(Object.fromEntries(changes.map(({ key, entry }) => [key, entry])), options.output, out);
|
|
363
396
|
else for (const line of lines) out(line);
|
|
364
|
-
return 0;
|
|
365
397
|
}
|
|
366
398
|
|
|
367
399
|
const isObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
368
400
|
|
|
401
|
+
// JavaScript takes an assignment to `__proto__` for a change of prototype, which loses the value and, through a path, reaches every object of the process.
|
|
402
|
+
function refuseProto(entries, source) {
|
|
403
|
+
if (Object.hasOwn(entries, '__proto__')) throw new Error(`${source}: __proto__ is not an entry key`);
|
|
404
|
+
const holds = (value) => value !== null && typeof value === 'object' && (Object.hasOwn(value, '__proto__') || Object.values(value).some(holds));
|
|
405
|
+
for (const [key, entry] of Object.entries(entries)) {
|
|
406
|
+
if (holds(entry)) throw new Error(`${source}: ${key}: __proto__ is not a field name`);
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
|
|
369
410
|
// Equal whatever the order of the fields, since an entry read from a file lists them in whatever order its author chose.
|
|
370
411
|
function sameData(a, b) {
|
|
371
|
-
|
|
412
|
+
// By code unit, since a comparison by locale takes distinct keys for equal, and their order would then be the one of the file.
|
|
413
|
+
const byCodeUnit = (x, y) => (x < y ? -1 : 1);
|
|
414
|
+
const canonical = (value) => {
|
|
415
|
+
if (Array.isArray(value)) return value.map(canonical);
|
|
416
|
+
if (!isObject(value)) return value;
|
|
417
|
+
return Object.fromEntries(Object.keys(value).sort(byCodeUnit).map((key) => [key, canonical(value[key])]));
|
|
418
|
+
};
|
|
372
419
|
return JSON.stringify(canonical(a ?? null)) === JSON.stringify(canonical(b ?? null));
|
|
373
420
|
}
|
|
374
421
|
|
|
@@ -384,23 +431,23 @@ function mergePatch(target, patch) {
|
|
|
384
431
|
return result;
|
|
385
432
|
}
|
|
386
433
|
|
|
434
|
+
function readGiven(filename, cwd) {
|
|
435
|
+
try {
|
|
436
|
+
return readFileSync(resolve(cwd, filename), 'utf8');
|
|
437
|
+
} catch (e) {
|
|
438
|
+
throw new Error(`cannot read ${filename}: ${reason(e)}`);
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
|
|
387
442
|
// The entries an -f file holds by key, the shape get and list -o yaml print, each one an object.
|
|
388
443
|
function readEntries(filename, { stdin, cwd }) {
|
|
389
|
-
const source = filename
|
|
390
|
-
|
|
391
|
-
if (filename === '-') text = stdin();
|
|
392
|
-
else {
|
|
393
|
-
try {
|
|
394
|
-
text = readFileSync(resolve(cwd, filename), 'utf8');
|
|
395
|
-
} catch (e) {
|
|
396
|
-
throw new Error(`cannot read ${filename}: ${e instanceof Error ? e.message : String(e)}`);
|
|
397
|
-
}
|
|
398
|
-
}
|
|
444
|
+
const source = sourceName(filename);
|
|
445
|
+
const text = filename === '-' ? stdin() : readGiven(filename, cwd);
|
|
399
446
|
let entries;
|
|
400
447
|
try {
|
|
401
448
|
entries = parse(text);
|
|
402
449
|
} catch (e) {
|
|
403
|
-
throw new Error(`${source} is not valid YAML: ${
|
|
450
|
+
throw new Error(`${source} is not valid YAML: ${reason(e)}`);
|
|
404
451
|
}
|
|
405
452
|
if (entries === null || entries === undefined) throw new Error(`${source} holds no entries`);
|
|
406
453
|
if (!isObject(entries)) throw new Error(`${source} does not hold entries by key`);
|
|
@@ -420,31 +467,36 @@ function assign(entry, assignments, { schema, map, name }) {
|
|
|
420
467
|
const path = assignment.slice(0, at);
|
|
421
468
|
const text = assignment.slice(at + 1);
|
|
422
469
|
const segments = path.split('.');
|
|
423
|
-
if (segments.
|
|
470
|
+
if (segments.includes('')) throw new UsageError(`${path} is not a field path`);
|
|
471
|
+
if (segments.includes('__proto__')) throw new Error(`${path}: __proto__ is not a field name`);
|
|
424
472
|
const field = schema ? schema.field(entryPointer, segments) : null;
|
|
425
473
|
if (schema && !field) {
|
|
426
474
|
if (schema.field(entryPointer, segments, { throughLists: true })) throw new Error(`${path}: goes into a list, which is set whole as JSON: ${segments[0]}='[...]'`);
|
|
427
475
|
throw new Error(`${path}: no such field in ${map}, run yamlctl ${name} explain to list them`);
|
|
428
476
|
}
|
|
429
|
-
|
|
430
|
-
for (const segment of segments.slice(0, -1)) {
|
|
431
|
-
if (!isObject(parent[segment])) parent[segment] = {};
|
|
432
|
-
parent = parent[segment];
|
|
433
|
-
}
|
|
434
|
-
const last = segments.at(-1);
|
|
435
|
-
if (text === '') {
|
|
436
|
-
delete parent[last];
|
|
437
|
-
continue;
|
|
438
|
-
}
|
|
439
|
-
try {
|
|
440
|
-
parent[last] = field ? typedValue(field.schema, text) : parseLoose(text);
|
|
441
|
-
} catch (e) {
|
|
442
|
-
throw new Error(`${path}: ${e instanceof Error ? e.message : String(e)}`);
|
|
443
|
-
}
|
|
477
|
+
setField(entry, segments, field, text);
|
|
444
478
|
}
|
|
445
479
|
return entry;
|
|
446
480
|
}
|
|
447
481
|
|
|
482
|
+
function setField(entry, segments, field, text) {
|
|
483
|
+
let parent = entry;
|
|
484
|
+
for (const segment of segments.slice(0, -1)) {
|
|
485
|
+
if (!isObject(parent[segment])) parent[segment] = {};
|
|
486
|
+
parent = parent[segment];
|
|
487
|
+
}
|
|
488
|
+
const last = segments.at(-1);
|
|
489
|
+
if (text === '') {
|
|
490
|
+
delete parent[last];
|
|
491
|
+
return;
|
|
492
|
+
}
|
|
493
|
+
try {
|
|
494
|
+
parent[last] = field ? typedValue(field.schema, text) : parseLoose(text);
|
|
495
|
+
} catch (e) {
|
|
496
|
+
throw new Error(`${segments.join('.')}: ${reason(e)}`);
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
|
|
448
500
|
// Without a schema a value is read the way YAML would read it, so a number or a list typed on the command line keeps its type.
|
|
449
501
|
function parseLoose(text) {
|
|
450
502
|
try {
|
|
@@ -455,36 +507,35 @@ function parseLoose(text) {
|
|
|
455
507
|
}
|
|
456
508
|
|
|
457
509
|
function remove(context) {
|
|
458
|
-
const { target,
|
|
510
|
+
const { target, options, out } = context;
|
|
459
511
|
if (options.output && options.output !== 'name') throw new UsageError('delete takes -o name only');
|
|
460
512
|
const { map } = target;
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
if (args.length) throw new UsageError('delete takes -f <file> without a key');
|
|
464
|
-
keys = Object.keys(readEntries(options.filename, context));
|
|
465
|
-
} else {
|
|
466
|
-
needKey(args, 'delete', true);
|
|
467
|
-
keys = [...new Set(args)];
|
|
468
|
-
}
|
|
469
|
-
const { document, schema } = target;
|
|
513
|
+
const keys = keysToDelete(context);
|
|
514
|
+
const { document } = target;
|
|
470
515
|
const entries = document.data[map] ?? {};
|
|
471
516
|
const present = [];
|
|
472
517
|
for (const key of keys) {
|
|
473
518
|
if (Object.hasOwn(entries, key)) present.push(key);
|
|
474
519
|
else if (!options.ignoreNotFound) throw new Error(`no entry ${key} in ${map}`);
|
|
475
520
|
}
|
|
476
|
-
// Checked against the file as it will be, so an entry deleted along with every entry naming it is not refused.
|
|
477
521
|
const next = { ...document.data, [map]: Object.fromEntries(Object.entries(entries).filter(([key]) => !present.includes(key))) };
|
|
478
|
-
|
|
479
|
-
const referencing = referencesTo({ schema, data: next, map, key });
|
|
480
|
-
if (referencing.length) throw new Error(`${map}/${key} is still named by ${referencing.join(', ')}: delete or change them first`);
|
|
481
|
-
}
|
|
522
|
+
refuseReferenced(target, next, present);
|
|
482
523
|
for (const key of present) deleteEntry(document, map, key);
|
|
483
524
|
writeDocument(document);
|
|
484
525
|
for (const key of present) out(options.output === 'name' ? `${map}/${key}\n` : `${map}/${key} deleted\n`);
|
|
485
526
|
return 0;
|
|
486
527
|
}
|
|
487
528
|
|
|
529
|
+
function keysToDelete(context) {
|
|
530
|
+
const { args, options } = context;
|
|
531
|
+
if (options.filename) {
|
|
532
|
+
if (args.length) throw new UsageError('delete takes -f <file> without a key');
|
|
533
|
+
return Object.keys(readEntries(options.filename, context));
|
|
534
|
+
}
|
|
535
|
+
needKey(args, 'delete', true);
|
|
536
|
+
return [...new Set(args)];
|
|
537
|
+
}
|
|
538
|
+
|
|
488
539
|
function explainCommand({ target, args, out }) {
|
|
489
540
|
const { map } = target;
|
|
490
541
|
if (!target.schema) throw new Error(`${basename(target.file)} has no schema to explain`);
|
|
@@ -512,9 +563,11 @@ function report(opened, { out, err, cwd }) {
|
|
|
512
563
|
}
|
|
513
564
|
const problems = problemsOf(opened);
|
|
514
565
|
for (const problem of problems) err(`${problem}\n`);
|
|
566
|
+
if (problems.length) return false;
|
|
515
567
|
const entries = opened.maps.reduce((total, map) => total + Object.keys(opened.document.data[map] ?? {}).length, 0);
|
|
516
|
-
|
|
517
|
-
|
|
568
|
+
const counted = `${entries} ${entries === 1 ? 'entry' : 'entries'}, `;
|
|
569
|
+
out(`${where}: ${opened.maps.length ? counted : ''}valid\n`);
|
|
570
|
+
return true;
|
|
518
571
|
}
|
|
519
572
|
|
|
520
573
|
function checkResource(context) {
|
|
@@ -529,7 +582,7 @@ function checkDirectory(context) {
|
|
|
529
582
|
try {
|
|
530
583
|
opened = openFile(path);
|
|
531
584
|
} catch (e) {
|
|
532
|
-
context.err(`${display(path, context.cwd)}: ${
|
|
585
|
+
context.err(`${display(path, context.cwd)}: ${reason(e)}\n`);
|
|
533
586
|
ok = false;
|
|
534
587
|
continue;
|
|
535
588
|
}
|
package/src/document.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// A YAML data file read and written in place, so the entries yamlctl does not touch, the comments and the order of the file come back exactly as they were.
|
|
2
2
|
import { readFileSync, writeFileSync } from 'node:fs';
|
|
3
|
-
import { isMap, parseDocument } from 'yaml';
|
|
3
|
+
import { isMap, isScalar, parseDocument } from 'yaml';
|
|
4
4
|
|
|
5
5
|
export function readDocument(file) {
|
|
6
6
|
let text;
|
|
@@ -25,7 +25,8 @@ export function render(doc) {
|
|
|
25
25
|
// Written only when something changed, so running the same command twice leaves the file, and its modification time, alone.
|
|
26
26
|
export function writeDocument(document) {
|
|
27
27
|
const next = render(document.doc);
|
|
28
|
-
|
|
28
|
+
// A file laid out another way renders differently with nothing edited, so it is compared with its own rendering as well.
|
|
29
|
+
if (next === document.text || next === render(parseDocument(document.text))) return false;
|
|
29
30
|
writeFileSync(document.file, next);
|
|
30
31
|
return true;
|
|
31
32
|
}
|
|
@@ -35,10 +36,23 @@ export function setEntry(document, map, key, entry) {
|
|
|
35
36
|
// An empty map is usually written `{}`, and an entry added to it would stay on that one line, so the map becomes a block first.
|
|
36
37
|
const node = doc.get(map, true);
|
|
37
38
|
if (node && typeof node === 'object' && 'flow' in node) node.flow = false;
|
|
38
|
-
if (
|
|
39
|
-
const
|
|
39
|
+
if (node?.items === undefined) doc.set(map, doc.createNode({}));
|
|
40
|
+
const path = [map, keyIn(doc.get(map, true), key)];
|
|
41
|
+
const current = doc.getIn(path, true);
|
|
40
42
|
if (isMap(current)) update(doc, current, entry);
|
|
41
|
-
else doc.setIn(
|
|
43
|
+
else doc.setIn(path, doc.createNode(entry));
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// Spelled the way toJS spells it, an empty key included.
|
|
47
|
+
function nameOf(pair) {
|
|
48
|
+
const key = isScalar(pair.key) ? pair.key.value : pair.key;
|
|
49
|
+
return key === null ? '' : String(key);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// The key of a map as its file holds it: YAML reads `80` and `true` as a number and a boolean, which the name of the field, a string, does not find.
|
|
53
|
+
function keyIn(node, name) {
|
|
54
|
+
const items = isMap(node) ? node.items : [];
|
|
55
|
+
return items.find((pair) => nameOf(pair) === name)?.key ?? name;
|
|
42
56
|
}
|
|
43
57
|
|
|
44
58
|
const isObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
@@ -46,11 +60,11 @@ const isObject = (value) => value !== null && typeof value === 'object' && !Arra
|
|
|
46
60
|
// An entry already in the file is changed field by field rather than rebuilt, since a node built anew carries none of the comments written inside the old one.
|
|
47
61
|
// A field keeps its place, a new one goes last, and a value replaced keeps the comments written before and after it.
|
|
48
62
|
function update(doc, node, value) {
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
63
|
+
// Listed before any is deleted, since deleting one while going through them skips the next.
|
|
64
|
+
const dropped = node.items.filter((pair) => !Object.hasOwn(value, nameOf(pair)));
|
|
65
|
+
for (const pair of dropped) node.delete(pair.key);
|
|
66
|
+
for (const [name, next] of Object.entries(value)) {
|
|
67
|
+
const key = keyIn(node, name);
|
|
54
68
|
const child = node.get(key, true);
|
|
55
69
|
if (isMap(child) && isObject(next)) {
|
|
56
70
|
update(doc, child, next);
|
|
@@ -68,5 +82,6 @@ function update(doc, node, value) {
|
|
|
68
82
|
}
|
|
69
83
|
|
|
70
84
|
export function deleteEntry(document, map, key) {
|
|
71
|
-
|
|
85
|
+
const { doc } = document;
|
|
86
|
+
doc.deleteIn([map, keyIn(doc.get(map, true), key)]);
|
|
72
87
|
}
|
package/src/explain.js
CHANGED
|
@@ -9,7 +9,8 @@ export function explain(schema, map, segments) {
|
|
|
9
9
|
const { schema: node, pointer } = here;
|
|
10
10
|
const lines = [];
|
|
11
11
|
|
|
12
|
-
|
|
12
|
+
const subject = segments.length ? `FIELD: ${segments.join('.')}` : `RESOURCE: ${map}`;
|
|
13
|
+
lines.push(`${subject} <${describeType(schema, pointer, node)}>`);
|
|
13
14
|
if (node.description) lines.push('', 'DESCRIPTION:', ...node.description.split('\n').map((line) => ` ${line}`));
|
|
14
15
|
const values = node.enum ?? node.items?.enum;
|
|
15
16
|
if (values) lines.push('', 'VALUES:', ` ${values.filter((v) => v !== null).map((v) => JSON.stringify(v)).join(', ')}`);
|
|
@@ -27,7 +28,10 @@ export function explain(schema, map, segments) {
|
|
|
27
28
|
const nameWidth = Math.max(...rows.map(([name]) => name.length));
|
|
28
29
|
const typeWidth = Math.max(...rows.map(([, type]) => type.length));
|
|
29
30
|
lines.push('', 'FIELDS:');
|
|
30
|
-
for (const [name, type, summary] of rows)
|
|
31
|
+
for (const [name, type, summary] of rows) {
|
|
32
|
+
const described = summary ? `${type.padEnd(typeWidth)} ${summary}` : type;
|
|
33
|
+
lines.push(` ${name.padEnd(nameWidth)} ${described}`);
|
|
34
|
+
}
|
|
31
35
|
}
|
|
32
36
|
return `${lines.join('\n')}\n`;
|
|
33
37
|
}
|
|
@@ -54,7 +58,7 @@ function describeType(schema, pointer, node) {
|
|
|
54
58
|
const items = schema.unwrap(`${pointer}/items`).schema;
|
|
55
59
|
if (items.properties) return '[]object';
|
|
56
60
|
if (items.enum) return '[]enum';
|
|
57
|
-
return `[]${types(items).
|
|
61
|
+
return `[]${types(items).find((type) => type !== 'null') ?? 'any'}`;
|
|
58
62
|
}
|
|
59
63
|
if (node.enum) return 'enum';
|
|
60
64
|
return kinds.join('|') || 'any';
|
package/src/resources.js
CHANGED
|
@@ -31,9 +31,12 @@ export function openFile(file) {
|
|
|
31
31
|
}
|
|
32
32
|
const maps = schema ? schema.entryMaps() : mapsWithoutSchema(document.data);
|
|
33
33
|
const singulars = Object.fromEntries(maps.map((map) => [map, schema?.mapOptions(map).singular]).filter(([, singular]) => typeof singular === 'string' && singular));
|
|
34
|
-
|
|
34
|
+
const schemaPath = schema ? schema.path : namedPath(found);
|
|
35
|
+
return { file, document, schema, schemaPath, schemaError, maps, singulars };
|
|
35
36
|
}
|
|
36
37
|
|
|
38
|
+
const namedPath = (found) => (found.uri ? displayUri(found.uri) : null);
|
|
39
|
+
|
|
37
40
|
// The map a name on the command line means in one opened file: the map of that name, else the one declaring it as its singular.
|
|
38
41
|
function mapNamed(opened, name) {
|
|
39
42
|
if (opened.maps.includes(name)) return name;
|
|
@@ -83,10 +86,13 @@ export function resolveResource({ dir, name, file = null }) {
|
|
|
83
86
|
const named = files.filter((path) => stem(path) === name || basename(path) === name);
|
|
84
87
|
if (named.length) {
|
|
85
88
|
const maps = [...new Set(named.flatMap((path) => openFile(path).maps))];
|
|
86
|
-
|
|
89
|
+
const commands = maps.map((map) => `yamlctl ${map} ...`).join(', ');
|
|
90
|
+
const hint = maps.length ? `use ${commands}` : 'and holds no map of entries';
|
|
91
|
+
throw new Error(`${named.map((path) => basename(path)).join(' and ')} ${named.length > 1 ? 'are files' : 'is a file'} rather than a resource, ${hint}`);
|
|
87
92
|
}
|
|
88
93
|
const known = listResources(dir).filter((resource) => resource.name).map((resource) => resource.name);
|
|
89
|
-
throw new Error(`no resource ${name} in ${dir}
|
|
94
|
+
if (known.length) throw new Error(`no resource ${name} in ${dir}, the resources are ${known.join(', ')}`);
|
|
95
|
+
throw new Error(`no resource ${name} in ${dir}, which holds no ${files.length ? 'map of entries' : 'YAML data file'}`);
|
|
90
96
|
}
|
|
91
97
|
|
|
92
98
|
// Every name the command line accepts, the way `kubectl api-resources` lists them.
|
package/src/reuse.js
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
// The results of a validator's functions, kept for the length of one check.
|
|
2
|
+
//
|
|
3
|
+
// ajv calls one function per `$ref` and remembers nothing, so alternatives leading back to the same schema are explored once per combination of branches, which is exponential in how deeply a value nests.
|
|
4
|
+
// Its errors repeat just as much, millions of them for a few distinct ones, so each function's are reduced as they leave it rather than once at the end.
|
|
5
|
+
|
|
6
|
+
// The start of the function ajv generates for a schema, everything before it being constants.
|
|
7
|
+
const GENERATED = /return function (validate\d+)(\([\s\S]*)$/;
|
|
8
|
+
|
|
9
|
+
// For ajv's `code.process` option, the one place where every generated function passes, calls to itself included.
|
|
10
|
+
// Code of another shape is left alone, which is slower and not wrong.
|
|
11
|
+
export const reuseResults = (code) => code.replace(GENERATED, 'const $1 = self.reuse(function $2); return $1');
|
|
12
|
+
|
|
13
|
+
// An evaluated set of properties is written into by whoever merges it with its own, so what is kept is never what is handed out.
|
|
14
|
+
const copied = (props) => (props && typeof props === 'object' ? { ...props } : props);
|
|
15
|
+
const copiedEvaluated = (evaluated) => ({ props: copied(evaluated.props), items: evaluated.items });
|
|
16
|
+
const isDynamic = (evaluated) => Boolean(evaluated?.dynamicProps || evaluated?.dynamicItems);
|
|
17
|
+
|
|
18
|
+
function at(map, key) {
|
|
19
|
+
if (!map.has(key)) map.set(key, new Map());
|
|
20
|
+
return map.get(key);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// `distinct` takes a function's errors and leaves out those that say nothing more.
|
|
24
|
+
export function reuser(distinct) {
|
|
25
|
+
let depth = 0;
|
|
26
|
+
// Dropped when the outermost function returns, since a value can be changed in place before it is checked again.
|
|
27
|
+
let results = null;
|
|
28
|
+
|
|
29
|
+
const recall = (validate, known) => {
|
|
30
|
+
// The caller appends to these errors and truncates them.
|
|
31
|
+
validate.errors = known.errors && [...known.errors];
|
|
32
|
+
if (known.evaluated) Object.assign(validate.evaluated, copiedEvaluated(known.evaluated));
|
|
33
|
+
return known.valid;
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
return (run) => {
|
|
37
|
+
const validate = (data, context = {}) => {
|
|
38
|
+
// Anchors are only ever added during a check, so their number stands for which ones are set.
|
|
39
|
+
const anchors = () => Object.keys(context.dynamicAnchors ?? {}).length;
|
|
40
|
+
const before = anchors();
|
|
41
|
+
if (!depth) results = new Map();
|
|
42
|
+
// The value is part of the key as well as its path, since a property name is checked at the path of the object holding it.
|
|
43
|
+
const known = at(at(at(results, validate), before), context.instancePath ?? '');
|
|
44
|
+
if (known.has(data)) return recall(validate, known.get(data));
|
|
45
|
+
depth++;
|
|
46
|
+
try {
|
|
47
|
+
const valid = run(data, context);
|
|
48
|
+
if (!valid) validate.errors = distinct(validate.errors);
|
|
49
|
+
// A function that set an anchor has to run again wherever the anchor is not set yet.
|
|
50
|
+
if (anchors() === before) {
|
|
51
|
+
known.set(data, { valid, errors: validate.errors && [...validate.errors], evaluated: isDynamic(validate.evaluated) ? copiedEvaluated(validate.evaluated) : null });
|
|
52
|
+
}
|
|
53
|
+
return valid;
|
|
54
|
+
} finally {
|
|
55
|
+
depth--;
|
|
56
|
+
if (!depth) results = null;
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
return validate;
|
|
60
|
+
};
|
|
61
|
+
}
|
package/src/rules.js
CHANGED
|
@@ -37,54 +37,52 @@ export function checkSet({ schema, data, previous = data, map, key, entry, force
|
|
|
37
37
|
const defaults = defaultsOf(schema, data, map);
|
|
38
38
|
for (const rule of fieldRules(schema, map)) {
|
|
39
39
|
const value = effective(entry, defaults, rule.field);
|
|
40
|
-
|
|
41
|
-
if (rule['key-of'] && value !== null) {
|
|
42
|
-
const targetMap = rule['key-of'] === '.' ? map : rule['key-of'];
|
|
43
|
-
const targets = data[targetMap] ?? {};
|
|
44
|
-
const names = Array.isArray(value) ? value : [value];
|
|
45
|
-
for (const name of names) {
|
|
46
|
-
if (targetMap === map && name === key) {
|
|
47
|
-
problems.push(`${rule.field}: ${key} cannot name itself`);
|
|
48
|
-
continue;
|
|
49
|
-
}
|
|
50
|
-
if (!Object.hasOwn(targets, name)) {
|
|
51
|
-
problems.push(`${rule.field}: ${name} is not an entry of ${targetMap}, create it first`);
|
|
52
|
-
continue;
|
|
53
|
-
}
|
|
54
|
-
const targetDefaults = defaultsOf(schema, data, targetMap);
|
|
55
|
-
for (const [field, expected] of Object.entries(rule['target-must'] ?? {})) {
|
|
56
|
-
const actual = effective(targets[name], targetDefaults, field);
|
|
57
|
-
if (!same(actual, expected)) problems.push(`${rule.field}: ${name} must have ${field}: ${JSON.stringify(expected)}, it has ${JSON.stringify(actual)}`);
|
|
58
|
-
}
|
|
59
|
-
}
|
|
60
|
-
}
|
|
61
|
-
|
|
40
|
+
if (rule['key-of'] && value !== null) problems.push(...namedProblems(rule, value, { schema, data, map, key }));
|
|
62
41
|
if (rule.immutable && Object.hasOwn(previous[map] ?? {}, key) && !force) {
|
|
63
42
|
const before = effective(previous[map][key], defaultsOf(schema, previous, map), rule.field);
|
|
64
|
-
|
|
65
|
-
const reason = typeof rule.immutable === 'string' ? `, ${rule.immutable}` : '';
|
|
66
|
-
problems.push(`${rule.field}: changing ${JSON.stringify(before)} to ${JSON.stringify(value)} needs --force${reason}`);
|
|
67
|
-
}
|
|
43
|
+
problems.push(...immutableProblems(rule, before, value));
|
|
68
44
|
}
|
|
69
45
|
}
|
|
70
46
|
return problems;
|
|
71
47
|
}
|
|
72
48
|
|
|
49
|
+
const mapNamedBy = (rule, map) => (rule['key-of'] === '.' ? map : rule['key-of']);
|
|
50
|
+
|
|
51
|
+
const listed = (value) => (Array.isArray(value) ? value : [value]);
|
|
52
|
+
|
|
53
|
+
function namedProblems(rule, value, { schema, data, map, key }) {
|
|
54
|
+
const targetMap = mapNamedBy(rule, map);
|
|
55
|
+
const targets = data[targetMap] ?? {};
|
|
56
|
+
return listed(value).flatMap((name) => {
|
|
57
|
+
if (targetMap === map && name === key) return [`${rule.field}: ${key} cannot name itself`];
|
|
58
|
+
if (!Object.hasOwn(targets, name)) return [`${rule.field}: ${name} is not an entry of ${targetMap}, create it first`];
|
|
59
|
+
return targetProblems(rule, name, targets[name], defaultsOf(schema, data, targetMap));
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function targetProblems(rule, name, target, defaults) {
|
|
64
|
+
return Object.entries(rule['target-must'] ?? {}).flatMap(([field, expected]) => {
|
|
65
|
+
const actual = effective(target, defaults, field);
|
|
66
|
+
return same(actual, expected) ? [] : [`${rule.field}: ${name} must have ${field}: ${JSON.stringify(expected)}, it has ${JSON.stringify(actual)}`];
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function immutableProblems(rule, before, value) {
|
|
71
|
+
if (same(before, value)) return [];
|
|
72
|
+
const reason = typeof rule.immutable === 'string' ? `, ${rule.immutable}` : '';
|
|
73
|
+
return [`${rule.field}: changing ${JSON.stringify(before)} to ${JSON.stringify(value)} needs --force${reason}`];
|
|
74
|
+
}
|
|
75
|
+
|
|
73
76
|
// The entries still naming one about to be deleted, since deleting it would leave each of them pointing at nothing.
|
|
74
77
|
export function referencesTo({ schema, data, map, key }) {
|
|
75
78
|
if (!schema) return [];
|
|
76
79
|
const found = [];
|
|
77
80
|
for (const other of schema.entryMaps()) {
|
|
78
81
|
const defaults = defaultsOf(schema, data, other);
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
const
|
|
82
|
-
|
|
83
|
-
for (const [name, entry] of Object.entries(data[other] ?? {})) {
|
|
84
|
-
if (other === map && name === key) continue;
|
|
85
|
-
const value = effective(entry, defaults, rule.field);
|
|
86
|
-
if ((Array.isArray(value) ? value : [value]).includes(key)) found.push(`${other}/${name}`);
|
|
87
|
-
}
|
|
82
|
+
const rules = fieldRules(schema, other).filter((rule) => rule['key-of'] && mapNamedBy(rule, other) === map);
|
|
83
|
+
for (const rule of rules) {
|
|
84
|
+
const naming = Object.entries(data[other] ?? {}).filter(([name, entry]) => !(other === map && name === key) && listed(effective(entry, defaults, rule.field)).includes(key));
|
|
85
|
+
found.push(...naming.map(([name]) => `${other}/${name}`));
|
|
88
86
|
}
|
|
89
87
|
}
|
|
90
88
|
return found;
|
package/src/schema.js
CHANGED
|
@@ -9,6 +9,7 @@ import { existsSync } from 'node:fs';
|
|
|
9
9
|
import { basename, dirname, isAbsolute, join } from 'node:path';
|
|
10
10
|
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
11
11
|
import { createRequire } from 'node:module';
|
|
12
|
+
import { reuseResults, reuser } from './reuse.js';
|
|
12
13
|
import { baseOf, documentAt, hasDocument, isRemote, referencedDocuments } from './store.js';
|
|
13
14
|
|
|
14
15
|
const require = createRequire(import.meta.url);
|
|
@@ -57,11 +58,21 @@ function pointerKeys(fragment, pointer) {
|
|
|
57
58
|
return fragment
|
|
58
59
|
.split('/')
|
|
59
60
|
.filter(Boolean)
|
|
60
|
-
.map((key) => decodeURIComponent(key).
|
|
61
|
+
.map((key) => decodeURIComponent(key).replaceAll('~1', '/').replaceAll('~0', '~'));
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function typeOf(value) {
|
|
65
|
+
if (value === null) return 'null';
|
|
66
|
+
return Array.isArray(value) ? 'array' : typeof value;
|
|
61
67
|
}
|
|
62
68
|
|
|
63
69
|
const isNull = (schema) => schema?.type === 'null' || (Array.isArray(schema?.type) && schema.type.length === 1 && schema.type[0] === 'null');
|
|
64
70
|
|
|
71
|
+
function validatorOf(draft) {
|
|
72
|
+
if (draft.includes('2020-12')) return Ajv2020;
|
|
73
|
+
return draft.includes('2019-09') ? Ajv2019 : Ajv;
|
|
74
|
+
}
|
|
75
|
+
|
|
65
76
|
export class Schema {
|
|
66
77
|
// `uri` defaults to an address of its own for a schema built in memory.
|
|
67
78
|
// It has a path, unlike a `urn:`, since a URL parser following the WHATWG standard refuses to resolve a relative reference against an opaque one, and the reference would then be dropped rather than reported as missing.
|
|
@@ -69,19 +80,18 @@ export class Schema {
|
|
|
69
80
|
this.root = root;
|
|
70
81
|
this.uri = uri;
|
|
71
82
|
this.path = displayUri(uri);
|
|
72
|
-
this.documents = new Map(
|
|
73
|
-
this.bases = new Map(
|
|
83
|
+
this.documents = new Map();
|
|
84
|
+
this.bases = new Map();
|
|
85
|
+
this.keep(root, uri);
|
|
74
86
|
this.missing = [];
|
|
75
87
|
const draft = String(root.$schema ?? '');
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
this.ajv =
|
|
79
|
-
this.ajv.addKeyword(EXTENSION);
|
|
80
|
-
this.ajv.addSchema(root, uri);
|
|
88
|
+
this.Validator = validatorOf(draft);
|
|
89
|
+
this.added = [[root, uri]];
|
|
90
|
+
this.ajv = this.validator({ code: { process: reuseResults } });
|
|
81
91
|
|
|
82
92
|
// Every document a reference can reach is given to the validator up front, since it compiles synchronously and cannot go looking for one halfway through.
|
|
83
93
|
const added = new Set([root]);
|
|
84
|
-
const queue = referencedDocuments(root,
|
|
94
|
+
const queue = referencedDocuments(root, uri);
|
|
85
95
|
while (queue.length) {
|
|
86
96
|
const next = queue.shift();
|
|
87
97
|
if (this.documents.has(next)) continue;
|
|
@@ -91,16 +101,36 @@ export class Schema {
|
|
|
91
101
|
continue;
|
|
92
102
|
}
|
|
93
103
|
const document = documentAt(next);
|
|
94
|
-
this.
|
|
95
|
-
this.bases.set(next, baseOf(document, next));
|
|
104
|
+
this.keep(document, next);
|
|
96
105
|
if (!added.has(document)) {
|
|
97
106
|
added.add(document);
|
|
107
|
+
this.added.push([document, next]);
|
|
98
108
|
this.ajv.addSchema(document, next);
|
|
99
109
|
}
|
|
100
|
-
queue.push(...referencedDocuments(document,
|
|
110
|
+
queue.push(...referencedDocuments(document, next));
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// keeps a document under its address and under its `$id`, because a `#` reference in it resolves against the `$id`
|
|
115
|
+
keep(document, uri) {
|
|
116
|
+
const base = baseOf(document, uri);
|
|
117
|
+
this.documents.set(uri, document);
|
|
118
|
+
this.bases.set(uri, base);
|
|
119
|
+
if (!this.documents.has(base)) {
|
|
120
|
+
this.documents.set(base, document);
|
|
121
|
+
this.bases.set(base, base);
|
|
101
122
|
}
|
|
102
123
|
}
|
|
103
124
|
|
|
125
|
+
// Unknown formats and keywords are tolerated rather than refused, since a schema written for an editor carries both and they say nothing about validity.
|
|
126
|
+
validator(options) {
|
|
127
|
+
const ajv = new this.Validator({ allErrors: true, strict: false, validateFormats: false, ...options });
|
|
128
|
+
ajv.reuse = reuser(distinct);
|
|
129
|
+
ajv.addKeyword(EXTENSION);
|
|
130
|
+
for (const [document, uri] of this.added) ajv.addSchema(document, uri);
|
|
131
|
+
return ajv;
|
|
132
|
+
}
|
|
133
|
+
|
|
104
134
|
// A pointer relative to the root, `#/definitions/project`, or absolute, `<uri>#/definitions/project`.
|
|
105
135
|
absolute(pointer) {
|
|
106
136
|
return pointer.startsWith('#') ? `${this.uri}${pointer}` : pointer;
|
|
@@ -198,28 +228,35 @@ export class Schema {
|
|
|
198
228
|
// Every problem in one value, each with the path it was found at.
|
|
199
229
|
// A failing `anyOf` or `oneOf` is reported through the branch closest to the value, found by validating the value against each branch on its own.
|
|
200
230
|
// ajv reports every branch, which reads as contradictions: a job told both to add `uses` and to drop `steps`.
|
|
201
|
-
validate(pointer, value, prefix
|
|
231
|
+
validate(pointer, value, prefix) {
|
|
232
|
+
return this.problems(pointer, value, prefix, 0, new Map());
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
// Branches leading back to the same schema ask the same question again, once per combination of branches, so each answer is kept.
|
|
236
|
+
// The value is part of the question since two paths can read the same, `a.b` and `a` then `b`, and the depth since it bounds what is explained.
|
|
237
|
+
problems(pointer, value, prefix, depth, known) {
|
|
238
|
+
const key = JSON.stringify([pointer, prefix, depth]);
|
|
239
|
+
if (!known.has(key)) known.set(key, new Map());
|
|
240
|
+
const answers = known.get(key);
|
|
241
|
+
if (!answers.has(value)) answers.set(value, this.explained(pointer, value, prefix, depth, known));
|
|
242
|
+
return answers.get(value);
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
explained(pointer, value, prefix, depth, known) {
|
|
202
246
|
const full = this.absolute(pointer).replace(/#$/, '');
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
check = this.ajv.getSchema(full);
|
|
206
|
-
} catch (e) {
|
|
207
|
-
const reason = e instanceof Error ? e.message : String(e);
|
|
208
|
-
throw new Error(this.missing.length ? `the schema cannot be applied, ${this.missing.map(displayUri).join(', ')} could not be loaded (${reason})` : `the schema cannot be applied: ${reason}`);
|
|
209
|
-
}
|
|
210
|
-
if (!check) throw new Error(`cannot compile the schema at ${full}`);
|
|
211
|
-
if (check(value)) return [];
|
|
247
|
+
const found = this.errorsOf(full, value);
|
|
248
|
+
if (!found) return [];
|
|
212
249
|
// A branch allowing null never explains anything, since the value is not null.
|
|
213
|
-
let errors =
|
|
250
|
+
let errors = found.filter((error) => !(error.keyword === 'type' && [error.params.type].flat().join() === 'null'));
|
|
214
251
|
const closest = [];
|
|
215
252
|
const handled = [];
|
|
216
253
|
const alternatives = errors.filter((error) => error.keyword === 'anyOf' || error.keyword === 'oneOf').sort((x, y) => x.instancePath.length - y.instancePath.length);
|
|
217
254
|
for (const alternative of alternatives) {
|
|
218
255
|
if (handled.some((path) => within(alternative.instancePath, path))) continue;
|
|
219
|
-
const branches = depth < 8 ? this.branches(full
|
|
256
|
+
const branches = depth < 8 ? this.branches(full, alternative, value) : null;
|
|
220
257
|
if (!branches) continue;
|
|
221
258
|
const here = `${prefix}${dotted(alternative.instancePath)}`;
|
|
222
|
-
const results = branches.map((branch) => this.
|
|
259
|
+
const results = branches.map((branch) => this.problems(branch.pointer, branch.value, here, depth + 1, known));
|
|
223
260
|
// A oneOf failing because two branches pass is not a problem any branch can explain, so its own message is kept.
|
|
224
261
|
if (results.some((result) => !result.length)) continue;
|
|
225
262
|
// The closest branch is the one the value's own fields agree with most, so problems on the value itself count first, since a problem deeper down means the shape matched.
|
|
@@ -235,10 +272,37 @@ export class Schema {
|
|
|
235
272
|
return [...new Set([...formatErrors(errors, prefix), ...closest])];
|
|
236
273
|
}
|
|
237
274
|
|
|
275
|
+
// The errors of a value, or null when it is valid.
|
|
276
|
+
// Reusing results takes stack of its own, so a value deeper than that allows is checked again without it.
|
|
277
|
+
errorsOf(full, value) {
|
|
278
|
+
let check = this.compiled(full);
|
|
279
|
+
try {
|
|
280
|
+
if (check(value)) return null;
|
|
281
|
+
} catch (e) {
|
|
282
|
+
if (!(e instanceof RangeError)) throw e;
|
|
283
|
+
this.plain ??= this.validator({});
|
|
284
|
+
check = this.compiled(full, this.plain);
|
|
285
|
+
if (check(value)) return null;
|
|
286
|
+
}
|
|
287
|
+
return check.errors ?? [];
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
compiled(full, ajv = this.ajv) {
|
|
291
|
+
let check;
|
|
292
|
+
try {
|
|
293
|
+
check = ajv.getSchema(full);
|
|
294
|
+
} catch (e) {
|
|
295
|
+
const reason = e instanceof Error ? e.message : String(e);
|
|
296
|
+
throw new Error(this.missing.length ? `the schema cannot be applied, ${this.missing.map(displayUri).join(', ')} could not be loaded (${reason})` : `the schema cannot be applied: ${reason}`);
|
|
297
|
+
}
|
|
298
|
+
if (!check) throw new Error(`cannot compile the schema at ${full}`);
|
|
299
|
+
return check;
|
|
300
|
+
}
|
|
301
|
+
|
|
238
302
|
// The branches of the alternative an error reports, each as the pointer to validate and the value it applies to, or null when the alternative cannot be located.
|
|
239
303
|
branches(pointer, error, value) {
|
|
240
|
-
const segments = error.instancePath.split('/').slice(1).map((key) => key.
|
|
241
|
-
let here = this.unwrapRef(pointer);
|
|
304
|
+
const segments = error.instancePath.split('/').slice(1).map((key) => key.replaceAll('~1', '/').replaceAll('~0', '~'));
|
|
305
|
+
let here = this.unwrapRef(pointer.includes('#') ? pointer : `${pointer}#`);
|
|
242
306
|
let data = value;
|
|
243
307
|
for (const segment of segments) {
|
|
244
308
|
const { schema } = this.at(here);
|
|
@@ -264,7 +328,7 @@ export class Schema {
|
|
|
264
328
|
typeMatches(pointer, value) {
|
|
265
329
|
const allowed = types(this.unwrap(pointer).schema);
|
|
266
330
|
if (!allowed.length) return true;
|
|
267
|
-
const actual =
|
|
331
|
+
const actual = typeOf(value);
|
|
268
332
|
if (actual === 'number') return allowed.includes('number') || (allowed.includes('integer') && Number.isInteger(value));
|
|
269
333
|
return allowed.includes(actual);
|
|
270
334
|
}
|
|
@@ -291,11 +355,11 @@ export class Schema {
|
|
|
291
355
|
}
|
|
292
356
|
|
|
293
357
|
// A key as one segment of a JSON pointer, escaped the way RFC 6901 and a URI fragment both require.
|
|
294
|
-
export const escapeKey = (key) => encodeURIComponent(String(key).
|
|
358
|
+
export const escapeKey = (key) => encodeURIComponent(String(key).replaceAll('~', '~0').replaceAll('/', '~1'));
|
|
295
359
|
|
|
296
360
|
export function types(schema) {
|
|
297
361
|
if (!schema) return [];
|
|
298
|
-
if (schema.type) return [].
|
|
362
|
+
if (schema.type) return [schema.type].flat();
|
|
299
363
|
if (schema.properties || schema.additionalProperties !== undefined) return ['object'];
|
|
300
364
|
if (schema.items) return ['array'];
|
|
301
365
|
return [];
|
|
@@ -333,7 +397,17 @@ function fromEnum(values, text) {
|
|
|
333
397
|
}
|
|
334
398
|
|
|
335
399
|
const within = (path, root) => path === root || path.startsWith(`${root}/`);
|
|
336
|
-
const dotted = (instancePath) => instancePath.
|
|
400
|
+
const dotted = (instancePath) => instancePath.replaceAll('/', '.').replaceAll('~1', '/').replaceAll('~0', '~');
|
|
401
|
+
|
|
402
|
+
// The errors that differ in what is read from them: the keyword, the path and the message.
|
|
403
|
+
function distinct(errors) {
|
|
404
|
+
const found = new Map();
|
|
405
|
+
for (const error of errors) {
|
|
406
|
+
const key = JSON.stringify([error.keyword, error.instancePath, describe(error)]);
|
|
407
|
+
if (!found.has(key)) found.set(key, error);
|
|
408
|
+
}
|
|
409
|
+
return [...found.values()];
|
|
410
|
+
}
|
|
337
411
|
|
|
338
412
|
function formatErrors(errors, prefix) {
|
|
339
413
|
const seen = new Set();
|
|
@@ -356,7 +430,7 @@ function describe(error) {
|
|
|
356
430
|
if (keyword === 'enum') return `must be one of ${params.allowedValues.filter((v) => v !== null).map((v) => JSON.stringify(v)).join(', ')}`;
|
|
357
431
|
if (keyword === 'const') return `must be ${JSON.stringify(params.allowedValue)}`;
|
|
358
432
|
if (keyword === 'required') return `missing required field ${params.missingProperty}`;
|
|
359
|
-
if (keyword === 'type') return `must be ${[].
|
|
433
|
+
if (keyword === 'type') return `must be ${[params.type].flat().join(' or ')}`;
|
|
360
434
|
// A pattern can hold a line break, which printed raw splits one message over two lines.
|
|
361
435
|
if (keyword === 'pattern') return `must match the pattern ${JSON.stringify(params.pattern)}`;
|
|
362
436
|
if (keyword === 'oneOf') return params.passingSchemas ? 'matches more than one of the alternatives, where exactly one is expected' : 'matches none of the alternatives';
|
package/src/store.js
CHANGED
|
@@ -10,6 +10,8 @@ import { fileURLToPath } from 'node:url';
|
|
|
10
10
|
|
|
11
11
|
const documents = new Map();
|
|
12
12
|
const failures = new Map();
|
|
13
|
+
// maps a published address to the local file that replaces it, so that a schema copied to disk works without the network
|
|
14
|
+
const copies = new Map();
|
|
13
15
|
|
|
14
16
|
// A day, long enough that a pipeline running every few minutes does not download the same schema each time, short enough that a published fix arrives the next day.
|
|
15
17
|
export const CACHE_TTL_MS = 24 * 60 * 60 * 1000;
|
|
@@ -25,8 +27,9 @@ export function cacheDir(env = process.env) {
|
|
|
25
27
|
// The document at a URI without its fragment, or an error saying why it is not there.
|
|
26
28
|
export function documentAt(uri) {
|
|
27
29
|
if (documents.has(uri)) return documents.get(uri);
|
|
28
|
-
|
|
29
|
-
|
|
30
|
+
const at = locationOf(uri);
|
|
31
|
+
if (at.startsWith('file:')) {
|
|
32
|
+
const path = fileURLToPath(at);
|
|
30
33
|
let parsed;
|
|
31
34
|
try {
|
|
32
35
|
parsed = JSON.parse(readFileSync(path, 'utf8'));
|
|
@@ -43,10 +46,16 @@ export function documentAt(uri) {
|
|
|
43
46
|
|
|
44
47
|
export function hasDocument(uri) {
|
|
45
48
|
if (documents.has(uri)) return true;
|
|
46
|
-
|
|
49
|
+
const at = locationOf(uri);
|
|
50
|
+
if (at.startsWith('file:')) return existsSync(fileURLToPath(at));
|
|
47
51
|
return false;
|
|
48
52
|
}
|
|
49
53
|
|
|
54
|
+
// gives the local copy of a URI when there is one, because a published schema can be read from disk
|
|
55
|
+
export function locationOf(uri) {
|
|
56
|
+
return copies.get(uri) ?? uri;
|
|
57
|
+
}
|
|
58
|
+
|
|
50
59
|
// For a test, or a caller holding a schema that is not in a file.
|
|
51
60
|
export function registerDocument(uri, document) {
|
|
52
61
|
documents.set(uri, document);
|
|
@@ -55,6 +64,7 @@ export function registerDocument(uri, document) {
|
|
|
55
64
|
export function forget() {
|
|
56
65
|
documents.clear();
|
|
57
66
|
failures.clear();
|
|
67
|
+
copies.clear();
|
|
58
68
|
}
|
|
59
69
|
|
|
60
70
|
// The URI a document's relative references resolve against: its own `$id` when it has one, as the specification says, else where it was read from.
|
|
@@ -63,14 +73,20 @@ export function baseOf(document, uri) {
|
|
|
63
73
|
const id = document?.$id ?? document?.id;
|
|
64
74
|
if (typeof id !== 'string') return uri;
|
|
65
75
|
try {
|
|
66
|
-
return new URL(id, uri).href.
|
|
76
|
+
return new URL(id, uri).href.split('#', 1)[0];
|
|
67
77
|
} catch {
|
|
68
78
|
return uri;
|
|
69
79
|
}
|
|
70
80
|
}
|
|
71
81
|
|
|
72
|
-
//
|
|
73
|
-
|
|
82
|
+
// finds every `$ref` in a document, resolved against its base and without the fragment: these are the documents that a validation can reach.
|
|
83
|
+
// `uri` is the address of the document, and `location` is where it was read from.
|
|
84
|
+
// treats a document on disk with an `$id` at another address as a copy of a published schema, as a package ships it.
|
|
85
|
+
// reads a relative reference from the file beside the copy when that file exists, because it has the same version as the copy and a copy is often used without the network.
|
|
86
|
+
export function referencedDocuments(document, uri, location = locationOf(uri)) {
|
|
87
|
+
const base = baseOf(document, uri);
|
|
88
|
+
const local = location.startsWith('file:') && base !== location;
|
|
89
|
+
if (local && !copies.has(base)) copies.set(base, location);
|
|
74
90
|
const found = new Set();
|
|
75
91
|
const visit = (node) => {
|
|
76
92
|
if (Array.isArray(node)) return node.forEach(visit);
|
|
@@ -78,7 +94,9 @@ export function referencedDocuments(document, base) {
|
|
|
78
94
|
for (const [key, value] of Object.entries(node)) {
|
|
79
95
|
if (key === '$ref' && typeof value === 'string' && !value.startsWith('#')) {
|
|
80
96
|
try {
|
|
81
|
-
|
|
97
|
+
const target = new URL(value, base).href.split('#', 1)[0];
|
|
98
|
+
found.add(target);
|
|
99
|
+
if (local) copyBeside(target, value, location);
|
|
82
100
|
} catch {
|
|
83
101
|
// A reference that is not a URL cannot be followed, and validation says so when it reaches it.
|
|
84
102
|
}
|
|
@@ -89,29 +107,44 @@ export function referencedDocuments(document, base) {
|
|
|
89
107
|
return [...found];
|
|
90
108
|
}
|
|
91
109
|
|
|
110
|
+
// records the file beside a local copy as the copy of a published address, but only when that file exists, so that a missing file is still reported under the published address
|
|
111
|
+
function copyBeside(target, reference, location) {
|
|
112
|
+
if (copies.has(target)) return;
|
|
113
|
+
const beside = new URL(reference, location).href.split('#', 1)[0];
|
|
114
|
+
if (beside !== target && beside.startsWith('file:') && existsSync(fileURLToPath(beside))) copies.set(target, beside);
|
|
115
|
+
}
|
|
116
|
+
|
|
92
117
|
// Fetches every remote document reachable from the URIs given, following `$ref`s through local and remote documents alike, and keeps each one in the cache.
|
|
93
118
|
// A document the cache holds and that is younger than the TTL is not fetched again; `refresh` fetches regardless, `offline` never fetches.
|
|
94
119
|
// A fetch that fails falls back to a cached copy of any age, said in a warning.
|
|
95
120
|
// A document with no copy at all is recorded as a failure rather than thrown, so the command decides what an unavailable schema means for what it was asked to do.
|
|
96
121
|
export async function prefetch(uris, { offline = false, refresh = false, env = process.env, warn = () => {}, fetchImpl = globalThis.fetch, now = Date.now() } = {}) {
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
122
|
+
await prefetchLevel([...new Set(uris)], new Set(uris), { offline, refresh, env, warn, fetchImpl, now });
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// The documents of one level are fetched together, since one after the other the time, and the timeout of a server that does not answer, is counted once per document.
|
|
126
|
+
// Their warnings are kept until all are there, so they come in the same order whichever answers first.
|
|
127
|
+
async function prefetchLevel(uris, seen, options) {
|
|
128
|
+
if (!uris.length) return;
|
|
129
|
+
const warnings = new Map(uris.map((uri) => [uri, []]));
|
|
130
|
+
const reached = await Promise.all(uris.map((uri) => reachableDocument(uri, { ...options, warn: (text) => warnings.get(uri).push(text) })));
|
|
131
|
+
for (const text of [...warnings.values()].flat()) options.warn(text);
|
|
132
|
+
const next = new Set(reached.flatMap((document, i) => (document ? referencedDocuments(document, uris[i]) : [])).filter((uri) => !seen.has(uri)));
|
|
133
|
+
for (const uri of next) seen.add(uri);
|
|
134
|
+
await prefetchLevel([...next], seen, options);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
async function reachableDocument(uri, options) {
|
|
138
|
+
if (isRemote(locationOf(uri))) {
|
|
139
|
+
const document = await remoteDocument(uri, options);
|
|
140
|
+
if (document) documents.set(uri, document);
|
|
141
|
+
return document;
|
|
142
|
+
}
|
|
143
|
+
if (!locationOf(uri).startsWith('file:') || !hasDocument(uri)) return null;
|
|
144
|
+
try {
|
|
145
|
+
return documentAt(uri);
|
|
146
|
+
} catch {
|
|
147
|
+
return null;
|
|
115
148
|
}
|
|
116
149
|
}
|
|
117
150
|
|
|
@@ -169,5 +202,6 @@ function writeCache(uri, document, env) {
|
|
|
169
202
|
|
|
170
203
|
function age(ms) {
|
|
171
204
|
const hours = Math.round(ms / 3600000);
|
|
172
|
-
|
|
205
|
+
if (hours >= 48) return `${Math.round(hours / 24)} days`;
|
|
206
|
+
return `${hours} hour${hours === 1 ? '' : 's'}`;
|
|
173
207
|
}
|