yamlctl 0.1.4 → 0.1.6

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 CHANGED
@@ -2,6 +2,7 @@
2
2
 
3
3
  [![CI](https://github.com/devpro/yamlctl/actions/workflows/ci.yml/badge.svg)](https://github.com/devpro/yamlctl/actions/workflows/ci.yml)
4
4
  [![npm](https://img.shields.io/npm/v/yamlctl)](https://www.npmjs.com/package/yamlctl)
5
+ [![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=devpro_yamlctl&metric=alert_status)](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 20 or later:
19
+ Node.js 22 or later:
19
20
 
20
21
  ```bash
21
22
  npm install --global yamlctl
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "yamlctl",
3
- "version": "0.1.4",
3
+ "version": "0.1.6",
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": ">=20"
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) => (!existed ? 'created' : changed ? 'configured' : 'unchanged') },
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
- const value = () => {
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
- return argv[++i];
92
- };
93
- if (arg === '-C' || arg === '--dir') options.dir = value();
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
- const [name, verb, ...args] = words;
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: ${e instanceof Error ? e.message : String(e)}\n`);
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 rows = found.map((r) => [r.name ?? '-', display(r.file, cwd), r.entries ?? '-', r.error ? `error: ${r.error}` : r.schema ? display(r.schema, cwd) : '-']);
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, name, args, options, out, err, cwd } = context;
298
- const rules = WRITES[verb];
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
- let changes;
306
+ const changes = options.filename ? changesFromFile(verb, entries, context) : changesFromFields(verb, entries, context);
307
+ checkExistence(WRITES[verb], map, entries, changes);
303
308
 
304
- if (options.filename) {
305
- if (!rules.filename) throw new UsageError('patch takes <key> <field>=<value>..., replace takes -f <file>');
306
- if (args.length) throw new UsageError(verb === 'replace' ? REPLACE_USAGE : `${verb} takes -f <file> without a key`);
307
- const given = readEntries(options.filename, context);
308
- changes = Object.entries(given).map(([key, entry]) => ({ key, entry: verb === 'apply' ? mergePatch(entries[key], entry) : entry }));
309
- } else {
310
- if (!rules.fields) throw new UsageError(REPLACE_USAGE);
311
- const key = needKey(args, verb, rules.filename);
312
- const assignments = args.slice(1);
313
- if (!assignments.length) throw new UsageError(`${verb} needs at least one <field>=<value>${rules.filename ? ', or -f <file>' : ''}`);
314
- const base = isObject(entries[key]) ? entries[key] : {};
315
- changes = [{ key, entry: assign(structuredClone(base), assignments, { schema, map, name }) }];
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
- const next = { ...document.data, [map]: { ...entries } };
325
- for (const { key, entry } of changes) next[map][key] = entry;
326
- let pruned = [];
327
- if (options.prune) {
328
- const owned = (key) => options.all || key.startsWith(options.prefix);
329
- const outside = changes.find(({ key }) => !owned(key));
330
- if (outside) throw new Error(`${options.filename === '-' ? 'standard input' : options.filename} holds ${outside.key}, outside the prefix ${options.prefix} it prunes`);
331
- pruned = Object.keys(entries).filter((key) => owned(key) && !changes.some((change) => change.key === key));
332
- for (const key of pruned) delete next[map][key];
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
- for (const problem of problems) err(`${problem}\n`);
341
- throw new Error(`${options.filename ? display(target.file, cwd) : `${map}/${changes[0].key}`} not written`);
342
- }
343
- for (const key of pruned) {
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
- const lines = [];
349
- for (const { key, entry } of changes) {
350
- const existed = Object.hasOwn(entries, key);
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
- const canonical = (value) => (Array.isArray(value) ? value.map(canonical) : isObject(value) ? Object.fromEntries(Object.keys(value).sort().map((key) => [key, canonical(value[key])])) : value);
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 === '-' ? 'standard input' : filename;
390
- let text;
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: ${e instanceof Error ? e.message : String(e)}`);
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.some((segment) => segment === '')) throw new UsageError(`${path} is not a field path`);
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
- let parent = entry;
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, name, args, options, out } = context;
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
- let keys;
462
- if (options.filename) {
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
- for (const key of present) {
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
- if (!problems.length) out(opened.maps.length ? `${where}: ${entries} ${entries === 1 ? 'entry' : 'entries'}, valid\n` : `${where}: valid\n`);
517
- return !problems.length;
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)}: ${e instanceof Error ? e.message : String(e)}\n`);
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
- if (next === document.text) return false;
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 (!node || node.items === undefined) doc.set(map, doc.createNode({}));
39
- const current = doc.getIn([map, key], true);
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([map, key], doc.createNode(entry));
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
- for (const pair of [...node.items]) {
50
- const key = pair.key?.value ?? pair.key;
51
- if (!Object.hasOwn(value, key)) node.delete(key);
52
- }
53
- for (const [key, next] of Object.entries(value)) {
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
- document.doc.deleteIn([map, key]);
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
- lines.push(`${segments.length ? `FIELD: ${segments.join('.')}` : `RESOURCE: ${map}`} <${describeType(schema, pointer, node)}>`);
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) lines.push(` ${name.padEnd(nameWidth)} ${summary ? `${type.padEnd(typeWidth)} ${summary}` : type}`);
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).filter((type) => type !== 'null')[0] ?? 'any'}`;
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
- return { file, document, schema, schemaPath: schema ? schema.path : found.uri ? displayUri(found.uri) : null, schemaError, maps, singulars };
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
- throw new Error(`${named.map((path) => basename(path)).join(' and ')} ${named.length > 1 ? 'are files' : 'is a file'} rather than a resource, ${maps.length ? `use ${maps.map((map) => `yamlctl ${map} ...`).join(', ')}` : 'and holds no map of entries'}`);
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}${known.length ? `, the resources are ${known.join(', ')}` : files.length ? ', which holds no map of entries' : ', which holds no YAML data file'}`);
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
- if (!same(before, value)) {
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
- for (const rule of fieldRules(schema, other)) {
80
- if (!rule['key-of']) continue;
81
- const targetMap = rule['key-of'] === '.' ? other : rule['key-of'];
82
- if (targetMap !== map) continue;
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).replace(/~1/g, '/').replace(/~0/g, '~'));
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.
@@ -73,11 +84,9 @@ export class Schema {
73
84
  this.bases = new Map([[uri, baseOf(root, uri)]]);
74
85
  this.missing = [];
75
86
  const draft = String(root.$schema ?? '');
76
- const Validator = draft.includes('2020-12') ? Ajv2020 : draft.includes('2019-09') ? Ajv2019 : Ajv;
77
- // Unknown formats and keywords are tolerated rather than refused, since a schema written for an editor carries both and they say nothing about validity.
78
- this.ajv = new Validator({ allErrors: true, strict: false, validateFormats: false });
79
- this.ajv.addKeyword(EXTENSION);
80
- this.ajv.addSchema(root, uri);
87
+ this.Validator = validatorOf(draft);
88
+ this.added = [[root, uri]];
89
+ this.ajv = this.validator({ code: { process: reuseResults } });
81
90
 
82
91
  // 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
92
  const added = new Set([root]);
@@ -95,12 +104,22 @@ export class Schema {
95
104
  this.bases.set(next, baseOf(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
110
  queue.push(...referencedDocuments(document, this.bases.get(next)));
101
111
  }
102
112
  }
103
113
 
114
+ // Unknown formats and keywords are tolerated rather than refused, since a schema written for an editor carries both and they say nothing about validity.
115
+ validator(options) {
116
+ const ajv = new this.Validator({ allErrors: true, strict: false, validateFormats: false, ...options });
117
+ ajv.reuse = reuser(distinct);
118
+ ajv.addKeyword(EXTENSION);
119
+ for (const [document, uri] of this.added) ajv.addSchema(document, uri);
120
+ return ajv;
121
+ }
122
+
104
123
  // A pointer relative to the root, `#/definitions/project`, or absolute, `<uri>#/definitions/project`.
105
124
  absolute(pointer) {
106
125
  return pointer.startsWith('#') ? `${this.uri}${pointer}` : pointer;
@@ -198,28 +217,35 @@ export class Schema {
198
217
  // Every problem in one value, each with the path it was found at.
199
218
  // 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
219
  // ajv reports every branch, which reads as contradictions: a job told both to add `uses` and to drop `steps`.
201
- validate(pointer, value, prefix, depth = 0) {
220
+ validate(pointer, value, prefix) {
221
+ return this.problems(pointer, value, prefix, 0, new Map());
222
+ }
223
+
224
+ // Branches leading back to the same schema ask the same question again, once per combination of branches, so each answer is kept.
225
+ // 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.
226
+ problems(pointer, value, prefix, depth, known) {
227
+ const key = JSON.stringify([pointer, prefix, depth]);
228
+ if (!known.has(key)) known.set(key, new Map());
229
+ const answers = known.get(key);
230
+ if (!answers.has(value)) answers.set(value, this.explained(pointer, value, prefix, depth, known));
231
+ return answers.get(value);
232
+ }
233
+
234
+ explained(pointer, value, prefix, depth, known) {
202
235
  const full = this.absolute(pointer).replace(/#$/, '');
203
- let check;
204
- try {
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 [];
236
+ const found = this.errorsOf(full, value);
237
+ if (!found) return [];
212
238
  // A branch allowing null never explains anything, since the value is not null.
213
- let errors = (check.errors ?? []).filter((error) => !(error.keyword === 'type' && [].concat(error.params.type).join() === 'null'));
239
+ let errors = found.filter((error) => !(error.keyword === 'type' && [error.params.type].flat().join() === 'null'));
214
240
  const closest = [];
215
241
  const handled = [];
216
242
  const alternatives = errors.filter((error) => error.keyword === 'anyOf' || error.keyword === 'oneOf').sort((x, y) => x.instancePath.length - y.instancePath.length);
217
243
  for (const alternative of alternatives) {
218
244
  if (handled.some((path) => within(alternative.instancePath, path))) continue;
219
- const branches = depth < 8 ? this.branches(full.includes('#') ? full : `${full}#`, alternative, value) : null;
245
+ const branches = depth < 8 ? this.branches(full, alternative, value) : null;
220
246
  if (!branches) continue;
221
247
  const here = `${prefix}${dotted(alternative.instancePath)}`;
222
- const results = branches.map((branch) => this.validate(branch.pointer, branch.value, here, depth + 1));
248
+ const results = branches.map((branch) => this.problems(branch.pointer, branch.value, here, depth + 1, known));
223
249
  // A oneOf failing because two branches pass is not a problem any branch can explain, so its own message is kept.
224
250
  if (results.some((result) => !result.length)) continue;
225
251
  // 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 +261,37 @@ export class Schema {
235
261
  return [...new Set([...formatErrors(errors, prefix), ...closest])];
236
262
  }
237
263
 
264
+ // The errors of a value, or null when it is valid.
265
+ // Reusing results takes stack of its own, so a value deeper than that allows is checked again without it.
266
+ errorsOf(full, value) {
267
+ let check = this.compiled(full);
268
+ try {
269
+ if (check(value)) return null;
270
+ } catch (e) {
271
+ if (!(e instanceof RangeError)) throw e;
272
+ this.plain ??= this.validator({});
273
+ check = this.compiled(full, this.plain);
274
+ if (check(value)) return null;
275
+ }
276
+ return check.errors ?? [];
277
+ }
278
+
279
+ compiled(full, ajv = this.ajv) {
280
+ let check;
281
+ try {
282
+ check = ajv.getSchema(full);
283
+ } catch (e) {
284
+ const reason = e instanceof Error ? e.message : String(e);
285
+ 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}`);
286
+ }
287
+ if (!check) throw new Error(`cannot compile the schema at ${full}`);
288
+ return check;
289
+ }
290
+
238
291
  // 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
292
  branches(pointer, error, value) {
240
- const segments = error.instancePath.split('/').slice(1).map((key) => key.replace(/~1/g, '/').replace(/~0/g, '~'));
241
- let here = this.unwrapRef(pointer);
293
+ const segments = error.instancePath.split('/').slice(1).map((key) => key.replaceAll('~1', '/').replaceAll('~0', '~'));
294
+ let here = this.unwrapRef(pointer.includes('#') ? pointer : `${pointer}#`);
242
295
  let data = value;
243
296
  for (const segment of segments) {
244
297
  const { schema } = this.at(here);
@@ -264,7 +317,7 @@ export class Schema {
264
317
  typeMatches(pointer, value) {
265
318
  const allowed = types(this.unwrap(pointer).schema);
266
319
  if (!allowed.length) return true;
267
- const actual = value === null ? 'null' : Array.isArray(value) ? 'array' : typeof value;
320
+ const actual = typeOf(value);
268
321
  if (actual === 'number') return allowed.includes('number') || (allowed.includes('integer') && Number.isInteger(value));
269
322
  return allowed.includes(actual);
270
323
  }
@@ -291,11 +344,11 @@ export class Schema {
291
344
  }
292
345
 
293
346
  // 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).replace(/~/g, '~0').replace(/\//g, '~1'));
347
+ export const escapeKey = (key) => encodeURIComponent(String(key).replaceAll('~', '~0').replaceAll('/', '~1'));
295
348
 
296
349
  export function types(schema) {
297
350
  if (!schema) return [];
298
- if (schema.type) return [].concat(schema.type);
351
+ if (schema.type) return [schema.type].flat();
299
352
  if (schema.properties || schema.additionalProperties !== undefined) return ['object'];
300
353
  if (schema.items) return ['array'];
301
354
  return [];
@@ -333,7 +386,17 @@ function fromEnum(values, text) {
333
386
  }
334
387
 
335
388
  const within = (path, root) => path === root || path.startsWith(`${root}/`);
336
- const dotted = (instancePath) => instancePath.replace(/\//g, '.').replace(/~1/g, '/').replace(/~0/g, '~');
389
+ const dotted = (instancePath) => instancePath.replaceAll('/', '.').replaceAll('~1', '/').replaceAll('~0', '~');
390
+
391
+ // The errors that differ in what is read from them: the keyword, the path and the message.
392
+ function distinct(errors) {
393
+ const found = new Map();
394
+ for (const error of errors) {
395
+ const key = JSON.stringify([error.keyword, error.instancePath, describe(error)]);
396
+ if (!found.has(key)) found.set(key, error);
397
+ }
398
+ return [...found.values()];
399
+ }
337
400
 
338
401
  function formatErrors(errors, prefix) {
339
402
  const seen = new Set();
@@ -356,7 +419,7 @@ function describe(error) {
356
419
  if (keyword === 'enum') return `must be one of ${params.allowedValues.filter((v) => v !== null).map((v) => JSON.stringify(v)).join(', ')}`;
357
420
  if (keyword === 'const') return `must be ${JSON.stringify(params.allowedValue)}`;
358
421
  if (keyword === 'required') return `missing required field ${params.missingProperty}`;
359
- if (keyword === 'type') return `must be ${[].concat(params.type).join(' or ')}`;
422
+ if (keyword === 'type') return `must be ${[params.type].flat().join(' or ')}`;
360
423
  // A pattern can hold a line break, which printed raw splits one message over two lines.
361
424
  if (keyword === 'pattern') return `must match the pattern ${JSON.stringify(params.pattern)}`;
362
425
  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
@@ -63,7 +63,7 @@ export function baseOf(document, uri) {
63
63
  const id = document?.$id ?? document?.id;
64
64
  if (typeof id !== 'string') return uri;
65
65
  try {
66
- return new URL(id, uri).href.replace(/#.*$/, '');
66
+ return new URL(id, uri).href.split('#', 1)[0];
67
67
  } catch {
68
68
  return uri;
69
69
  }
@@ -78,7 +78,7 @@ export function referencedDocuments(document, base) {
78
78
  for (const [key, value] of Object.entries(node)) {
79
79
  if (key === '$ref' && typeof value === 'string' && !value.startsWith('#')) {
80
80
  try {
81
- found.add(new URL(value, base).href.replace(/#.*$/, ''));
81
+ found.add(new URL(value, base).href.split('#', 1)[0]);
82
82
  } catch {
83
83
  // A reference that is not a URL cannot be followed, and validation says so when it reaches it.
84
84
  }
@@ -94,24 +94,32 @@ export function referencedDocuments(document, base) {
94
94
  // A fetch that fails falls back to a cached copy of any age, said in a warning.
95
95
  // 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
96
  export async function prefetch(uris, { offline = false, refresh = false, env = process.env, warn = () => {}, fetchImpl = globalThis.fetch, now = Date.now() } = {}) {
97
- const queue = [...uris];
98
- const seen = new Set();
99
- while (queue.length) {
100
- const uri = queue.shift();
101
- if (seen.has(uri)) continue;
102
- seen.add(uri);
103
- let document = null;
104
- if (isRemote(uri)) {
105
- document = await remoteDocument(uri, { offline, refresh, env, warn, fetchImpl, now });
106
- if (document) documents.set(uri, document);
107
- } else if (uri.startsWith('file:') && hasDocument(uri)) {
108
- try {
109
- document = documentAt(uri);
110
- } catch {
111
- document = null;
112
- }
113
- }
114
- if (document) queue.push(...referencedDocuments(document, baseOf(document, uri)));
97
+ await prefetchLevel([...new Set(uris)], new Set(uris), { offline, refresh, env, warn, fetchImpl, now });
98
+ }
99
+
100
+ // 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.
101
+ // Their warnings are kept until all are there, so they come in the same order whichever answers first.
102
+ async function prefetchLevel(uris, seen, options) {
103
+ if (!uris.length) return;
104
+ const warnings = new Map(uris.map((uri) => [uri, []]));
105
+ const reached = await Promise.all(uris.map((uri) => reachableDocument(uri, { ...options, warn: (text) => warnings.get(uri).push(text) })));
106
+ for (const text of [...warnings.values()].flat()) options.warn(text);
107
+ const next = new Set(reached.flatMap((document, i) => (document ? referencedDocuments(document, baseOf(document, uris[i])) : [])).filter((uri) => !seen.has(uri)));
108
+ for (const uri of next) seen.add(uri);
109
+ await prefetchLevel([...next], seen, options);
110
+ }
111
+
112
+ async function reachableDocument(uri, options) {
113
+ if (isRemote(uri)) {
114
+ const document = await remoteDocument(uri, options);
115
+ if (document) documents.set(uri, document);
116
+ return document;
117
+ }
118
+ if (!uri.startsWith('file:') || !hasDocument(uri)) return null;
119
+ try {
120
+ return documentAt(uri);
121
+ } catch {
122
+ return null;
115
123
  }
116
124
  }
117
125
 
@@ -169,5 +177,6 @@ function writeCache(uri, document, env) {
169
177
 
170
178
  function age(ms) {
171
179
  const hours = Math.round(ms / 3600000);
172
- return hours < 48 ? `${hours} hour${hours === 1 ? '' : 's'}` : `${Math.round(hours / 24)} days`;
180
+ if (hours >= 48) return `${Math.round(hours / 24)} days`;
181
+ return `${hours} hour${hours === 1 ? '' : 's'}`;
173
182
  }