@delurio/cli 0.9.0 → 0.11.0

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.
Files changed (86) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/NOTICE +7 -0
  3. package/README.md +16 -15
  4. package/SPEC.md +37 -11
  5. package/js/changes.d.ts +17 -0
  6. package/js/cli.js +6 -0
  7. package/{dist → js}/edges.d.ts +2 -2
  8. package/js/edges.js +40 -0
  9. package/js/expr.js +25 -0
  10. package/js/graph.js +59 -0
  11. package/{dist → js}/html.d.ts +6 -6
  12. package/js/html.js +13 -0
  13. package/js/internal.js +408 -0
  14. package/js/kit.js +54 -0
  15. package/{dist → js}/model.d.ts +2 -2
  16. package/js/model.js +136 -0
  17. package/js/native.cjs +46 -0
  18. package/js/native.d.cts +322 -0
  19. package/{dist → js}/nav.d.ts +1 -1
  20. package/js/nav.js +70 -0
  21. package/{dist → js}/needs.d.ts +3 -2
  22. package/js/needs.js +30 -0
  23. package/{dist → js}/spine.d.ts +3 -3
  24. package/js/spine.js +22 -0
  25. package/{dist → js}/starts.d.ts +1 -3
  26. package/{dist → js}/story.d.ts +2 -2
  27. package/js/story.js +22 -0
  28. package/{dist → js}/wireframe.d.ts +4 -2
  29. package/js/wireframe.js +29 -0
  30. package/js/yaml.d.ts +20 -0
  31. package/js/yaml.js +40 -0
  32. package/package.json +41 -25
  33. package/schemas/domain.schema.json +3 -0
  34. package/dist/changes.d.ts +0 -25
  35. package/dist/changes.js +0 -101
  36. package/dist/check.d.ts +0 -23
  37. package/dist/check.js +0 -574
  38. package/dist/cli.d.ts +0 -2
  39. package/dist/cli.js +0 -194
  40. package/dist/compare.d.ts +0 -34
  41. package/dist/compare.js +0 -143
  42. package/dist/diff-flow.d.ts +0 -33
  43. package/dist/diff-flow.js +0 -547
  44. package/dist/diff-nav.d.ts +0 -20
  45. package/dist/diff-nav.js +0 -401
  46. package/dist/diff.d.ts +0 -25
  47. package/dist/diff.js +0 -331
  48. package/dist/domain-names.d.ts +0 -18
  49. package/dist/domain-names.js +0 -124
  50. package/dist/domain.d.ts +0 -25
  51. package/dist/domain.js +0 -110
  52. package/dist/edges.js +0 -120
  53. package/dist/expr.js +0 -157
  54. package/dist/graph.js +0 -236
  55. package/dist/html.js +0 -311
  56. package/dist/index-page.d.ts +0 -12
  57. package/dist/index-page.js +0 -50
  58. package/dist/invokes.d.ts +0 -10
  59. package/dist/invokes.js +0 -67
  60. package/dist/kit.js +0 -710
  61. package/dist/mermaid.d.ts +0 -3
  62. package/dist/mermaid.js +0 -50
  63. package/dist/model.js +0 -608
  64. package/dist/nav-page.d.ts +0 -15
  65. package/dist/nav-page.js +0 -283
  66. package/dist/nav.js +0 -578
  67. package/dist/needs.js +0 -311
  68. package/dist/pan.d.ts +0 -2
  69. package/dist/pan.js +0 -252
  70. package/dist/schemas.d.ts +0 -10
  71. package/dist/schemas.js +0 -266
  72. package/dist/spine.js +0 -156
  73. package/dist/starts.js +0 -88
  74. package/dist/story.js +0 -109
  75. package/dist/tutorial-check.d.ts +0 -9
  76. package/dist/tutorial-check.js +0 -297
  77. package/dist/ui-check.d.ts +0 -8
  78. package/dist/ui-check.js +0 -136
  79. package/dist/watch.d.ts +0 -5
  80. package/dist/watch.js +0 -114
  81. package/dist/wireframe.js +0 -273
  82. package/dist/yaml.d.ts +0 -19
  83. package/dist/yaml.js +0 -134
  84. /package/{dist → js}/expr.d.ts +0 -0
  85. /package/{dist → js}/graph.d.ts +0 -0
  86. /package/{dist → js}/kit.d.ts +0 -0
package/dist/diff.js DELETED
@@ -1,331 +0,0 @@
1
- import { execFileSync } from 'node:child_process';
2
- import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
3
- import { isAbsolute, join, posix, relative, resolve, sep } from 'node:path';
4
- import { GraphError, humanize, load } from './graph.js';
5
- import { loadNav } from './nav.js';
6
- import { joinWords } from './compare.js';
7
- import { flowBehaviour, flowSameBehaviour, flowStructure, runSide } from './diff-flow.js';
8
- import { navBehaviour, navSameBehaviour, navStructure, runNav } from './diff-nav.js';
9
- import { inReadingOrder, isDomainText, mayBeDomain, mergeDomain } from './domain.js';
10
- // `node src/cli.ts diff`: what a revision of a graph changes, for a PR description. Each side is a graph directory on disk
11
- // or the same directory at a git revision (read with `git show <commit>:<path>`, nothing is checked out). No model, no
12
- // network: the same two revisions give the same bytes.
13
- export const DIFF_USAGE = [
14
- ' node src/cli.ts diff <old dir> <new dir> [--base <rev>] [--head <rev>] [--json] [--fail-on-behaviour] [--fail-on-regression]',
15
- ' node src/cli.ts diff <graph dir> --base <rev> [--head <rev>] ...',
16
- ' what the new revision changes, as markdown for a PR description (--json: for machines); --base reads the old side',
17
- ' from a git revision, --head the new one (default: the directory on disk). Works for flow and navigation graphs.',
18
- ' --fail-on-behaviour: exit 2 when what the graph does changed; --fail-on-regression: exit 2 when a guarantee newly',
19
- ' fails, a goal newly fails or a problem is new',
20
- ].join('\n');
21
- // a directory inside the repository is named from its root, as a PR reader knows it; one outside as given
22
- function shown(dir) {
23
- const top = git(['rev-parse', '--show-toplevel'], process.cwd())?.trim();
24
- if (top === undefined || top === '')
25
- return dir;
26
- const rel = relative(top, resolve(dir)).split(sep).join('/');
27
- return rel.startsWith('..') || isAbsolute(rel) ? dir : rel === '' ? '.' : rel;
28
- }
29
- function dirSource(dir) {
30
- const texts = new Map();
31
- if (!existsSync(dir))
32
- throw new GraphError(`${dir} does not exist`);
33
- return {
34
- where: shown(dir),
35
- rev: null,
36
- texts,
37
- exists: (file) => existsSync(join(dir, file)),
38
- read: (file) => {
39
- const path = join(dir, file);
40
- if (!existsSync(path))
41
- throw new GraphError(`${path} does not exist`);
42
- const text = readFileSync(path, 'utf8');
43
- texts.set(posix.normalize(file), text);
44
- return text;
45
- },
46
- peek: (file) => readFileSync(join(dir, file), 'utf8'),
47
- list: (sub) => {
48
- const path = join(dir, sub);
49
- return existsSync(path) && statSync(path).isDirectory() ? readdirSync(path).filter((n) => statSync(join(path, n)).isFile()).sort() : [];
50
- },
51
- };
52
- }
53
- function git(args, cwd) {
54
- try {
55
- return execFileSync('git', args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], maxBuffer: 1 << 28 });
56
- }
57
- catch {
58
- return null;
59
- }
60
- }
61
- function gitSource(rev, dir) {
62
- const top = git(['rev-parse', '--show-toplevel'], process.cwd())?.trim();
63
- if (top === undefined || top === '')
64
- throw new GraphError(`--base and --head read a git revision, and ${process.cwd()} is not in a git repository`);
65
- const commit = git(['rev-parse', '--verify', '--quiet', `${rev}^{commit}`], top)?.trim();
66
- if (commit === undefined || commit === '')
67
- throw new GraphError(`${rev} is not a revision of ${top}`);
68
- const rel = relative(top, resolve(dir)).split(sep).join('/');
69
- if (rel.startsWith('..') || isAbsolute(rel))
70
- throw new GraphError(`${dir} is outside the repository ${top}`);
71
- const short = commit.slice(0, 7); // fixed length, so the output does not change as the repository grows
72
- const path = (file) => {
73
- const p = posix.normalize(posix.join(rel, file));
74
- if (p.startsWith('../'))
75
- throw new GraphError(`${file} is outside the repository`);
76
- return p;
77
- };
78
- const texts = new Map();
79
- const shownRev = commit.startsWith(rev) ? short : `${rev} (${short})`;
80
- if (git(['cat-file', '-e', `${commit}:${rel === '' ? '.' : rel}`], top) === null)
81
- throw new GraphError(`${rel} does not exist at ${shownRev}; a new graph has no diff, render it instead`);
82
- return {
83
- where: rel === '' ? '.' : rel,
84
- rev: shownRev,
85
- texts,
86
- exists: (file) => git(['cat-file', '-e', `${commit}:${path(file)}`], top) !== null,
87
- read: (file) => {
88
- const text = git(['show', `${commit}:${path(file)}`], top);
89
- if (text === null)
90
- throw new GraphError(`${path(file)} does not exist at ${short}`);
91
- texts.set(posix.normalize(file), text);
92
- return text;
93
- },
94
- peek: (file) => git(['show', `${commit}:${path(file)}`], top) ?? '',
95
- list: (sub) => {
96
- // blobs only: `ls-tree` names a directory a tree
97
- const tree = git(['ls-tree', `${commit}:${path(sub)}`], top);
98
- if (tree === null)
99
- return [];
100
- return tree.split('\n').filter((l) => /^\d+ blob /.test(l)).map((l) => l.slice(l.indexOf('\t') + 1)).sort();
101
- },
102
- };
103
- }
104
- // The API description of a flow: the domain beside it, else the shared ../domain/ of a capture layout, else
105
- // ../../domain/ of graphs/ (graphs/<part>/<flow>); all its files read as one (SPEC.md §5). When the flow names its
106
- // domain, the files must be that domain.
107
- function findDomain(src, g) {
108
- for (const dir of ['.', '../domain', '../../domain']) {
109
- const files = inReadingOrder(src.list(dir).filter(mayBeDomain).map((n) => (dir === '.' ? n : `${dir}/${n}`))).filter((f) => isDomainText(src.peek(f)));
110
- if (files.length === 0)
111
- continue;
112
- const { id, doc } = mergeDomain(files.map((file) => ({ file, text: src.read(file) })));
113
- const named = g.flow.domain;
114
- if (typeof named === 'string' && id !== named)
115
- throw new GraphError(`flow.yaml names the domain ${named}, but ${files.join(', ')} ${files.length === 1 ? 'is' : 'are'} ${String(id)}`);
116
- return { file: files.join(', '), doc };
117
- }
118
- return null;
119
- }
120
- function loadSide(src, name, locale) {
121
- try {
122
- if (src.exists('flow.yaml')) {
123
- const g = load(src.where, src.read, src.exists);
124
- return { kind: 'flow', side: { g, domain: findDomain(src, g) } };
125
- }
126
- if (src.exists('nav.yaml'))
127
- return { kind: 'nav', side: loadNav(src.where, locale, src.read) };
128
- }
129
- catch (err) {
130
- throw new GraphError(`${name} (${label(src)}): ${err.message}`);
131
- }
132
- throw new GraphError(`${name} (${label(src)}) has neither flow.yaml nor nav.yaml`);
133
- }
134
- const label = (s) => (s.rev === null ? s.where : `${s.where} at ${s.rev}`);
135
- const HEADINGS = {
136
- flow: 'The flow',
137
- graph: 'The graph',
138
- scope: 'What this view shows',
139
- main: 'The main story',
140
- steps: 'Steps',
141
- ways: 'How it moves on',
142
- guarantees: 'Guarantees',
143
- situations: 'What it keeps track of',
144
- conditions: 'Conditions and effects',
145
- screens: 'What the user sees',
146
- people: 'Kinds of user',
147
- pages: 'Pages',
148
- entries: 'Menus, links and buttons',
149
- goals: 'Goals',
150
- frames: 'Frames',
151
- facts: 'Facts and conditions',
152
- notModeled: 'Not modeled',
153
- wording: 'Wording',
154
- domain: 'The API it calls (its domain)',
155
- other: 'Other keys',
156
- citations: 'Source citations',
157
- };
158
- // markdown: escape what would turn plain words into markup
159
- const md = (s) => s.replace(/([\\`*_[\]<])/g, '\\$1');
160
- function tick(s) {
161
- const longest = Math.max(0, ...(s.match(/`+/g) ?? []).map((r) => r.length));
162
- const fence = '`'.repeat(longest + 1);
163
- const pad = s.startsWith('`') || s.endsWith('`') ? ' ' : '';
164
- return `${fence}${pad}${s}${pad}${fence}`;
165
- }
166
- const value = (v) => (v === undefined ? '(none)' : tick(JSON.stringify(v)));
167
- function exactLine(c) {
168
- const what = c.field === undefined ? c.key : `${c.key} › ${c.field}`;
169
- const short = (v) => {
170
- if (v === undefined)
171
- return '';
172
- const text = JSON.stringify(v);
173
- return text.length <= 160 ? `: ${tick(text)}` : '';
174
- };
175
- if (c.op === 'added')
176
- return `- ${tick(what)} added${short(c.after)}`;
177
- if (c.op === 'removed')
178
- return `- ${tick(what)} removed${short(c.before)}`;
179
- if (c.op === 'moved')
180
- return `- ${tick(what)} moved from ${String(c.before)} to ${String(c.after)}`;
181
- return `- ${tick(what)}: ${value(c.before)} → ${value(c.after)}`;
182
- }
183
- // the line that stands for the changes of an area that have no sentence of their own
184
- function summaryLine(area, items) {
185
- const n = items.length;
186
- const plural = (k, w) => `${k} ${w}${k === 1 ? '' : 's'}`;
187
- const distinct = (xs) => [...new Set(xs)];
188
- if (area === 'conditions' || area === 'facts') {
189
- const guards = items.filter((c) => c.key.startsWith('guard ')).length;
190
- const other = n - guards;
191
- const parts = [guards > 0 ? plural(guards, 'named condition') : '', other > 0 ? plural(other, area === 'facts' ? 'fact' : 'effect') : ''].filter((x) => x !== '');
192
- return `${joinWords(parts)} changed; the exact text is under the exact changes.`;
193
- }
194
- if (area === 'domain') {
195
- const one = { entities: 'entity', actions: 'action', policies: 'policy', invariants: 'invariant', relations: 'relation', helpers: 'helper', permissions: 'permission', jobs: 'job' };
196
- const where = (c) => {
197
- const [section, name] = (c.field ?? '').split('.');
198
- return name === undefined ? section : `${one[section] ?? section} ${name}`;
199
- };
200
- return `${plural(n, 'change')} in the API description: ${joinWords(distinct(items.map(where)))}.`;
201
- }
202
- if (area === 'ways')
203
- return `${plural(n, 'way')} on from removed steps, under the exact changes.`;
204
- if (area === 'citations')
205
- return `${plural(n, 'source citation')} changed.`;
206
- if (area === 'other')
207
- return `${plural(n, 'change')} in keys this tool does not read: ${distinct(items.map((c) => (c.field ?? c.key).split('.')[0])).join(', ')}.`;
208
- return `${plural(n, 'more change')}, under the exact changes.`;
209
- }
210
- export function renderMarkdown(r) {
211
- const out = [];
212
- out.push(`## ${md(r.title)}: what this revision changes`, '');
213
- const kind = r.kind === 'flow' ? 'Flow graph' : 'Navigation graph';
214
- const at = (s) => (s.rev === null ? 'the directory on disk' : tick(s.rev));
215
- out.push(r.before.where === r.after.where ? `${kind} ${tick(r.after.where)}: ${at(r.before)} → ${at(r.after)}.` : `${kind}: ${tick(label(r.before))} → ${tick(label(r.after))}.`);
216
- const files = [...new Set([...r.after.texts.keys(), ...r.before.texts.keys()])];
217
- const changed = files.filter((f) => r.before.texts.get(f) !== r.after.texts.get(f));
218
- out.push(`Compared ${files.join(', ')}; ${changed.length === 0 ? 'no file differs' : `changed: ${changed.join(', ')}`}.`, '');
219
- out.push('### What it does differently', '');
220
- if (r.behaviour.length === 0)
221
- out.push(md(r.same));
222
- else if (r.kind === 'flow')
223
- for (const s of r.behaviour)
224
- out.push(...item(s));
225
- else {
226
- const people = [...new Set(r.behaviour.filter((s) => s.persona !== undefined).map((s) => s.persona))];
227
- for (const who of people) {
228
- const items = r.behaviour.filter((s) => s.persona === who);
229
- if (items.length > 8)
230
- out.push(`<details><summary><b>${md(who)}</b>: ${items.length} changes</summary>`, '', ...items.flatMap(item), '', '</details>', '');
231
- else
232
- out.push(`**${md(who)}**`, '', ...items.flatMap(item), '');
233
- }
234
- const rest = r.behaviour.filter((s) => s.persona === undefined);
235
- if (rest.length > 0)
236
- out.push('**Findings**', '', ...rest.flatMap(item));
237
- }
238
- out.push('');
239
- out.push('### What changed in the graph', '');
240
- if (r.structure.length === 0)
241
- out.push(changed.length === 0 ? 'Nothing.' : 'Nothing: the files differ only in comments, layout or key order.');
242
- for (const area of Object.keys(HEADINGS)) {
243
- const items = r.structure.filter((c) => c.area === area);
244
- if (items.length === 0)
245
- continue;
246
- const said = items.filter((c) => c.say !== null);
247
- const silent = items.filter((c) => c.say === null);
248
- out.push(`**${HEADINGS[area]}**`, '');
249
- for (const c of said)
250
- out.push(`- ${md(c.say)}`);
251
- if (silent.length > 0)
252
- out.push(`- ${md(summaryLine(area, silent))}`);
253
- out.push('');
254
- }
255
- if (r.structure.length > 0) {
256
- out.push(`<details><summary>Exact changes, by id (${r.structure.length})</summary>`, '');
257
- for (const c of r.structure)
258
- out.push(exactLine(c));
259
- out.push('', '</details>');
260
- }
261
- return `${out.join('\n').replace(/\n{3,}/g, '\n\n').trimEnd()}\n`;
262
- }
263
- function item(s) {
264
- return [`- ${s.worse ? `**${md(s.say)}**` : md(s.say)}`, ...s.detail.map((d) => ` ${md(d)}`)];
265
- }
266
- export function renderJson(r) {
267
- const side = (s) => ({ path: s.where, revision: s.rev, files: [...s.texts.keys()] });
268
- const files = [...new Set([...r.after.texts.keys(), ...r.before.texts.keys()])];
269
- return `${JSON.stringify({
270
- schema: 'delurio-graph-diff/0',
271
- kind: r.kind,
272
- title: r.title,
273
- before: side(r.before),
274
- after: side(r.after),
275
- changedFiles: files.filter((f) => r.before.texts.get(f) !== r.after.texts.get(f)),
276
- behaviourChanged: r.behaviour.length > 0,
277
- regressions: r.behaviour.filter((s) => s.worse).length,
278
- behaviour: r.behaviour,
279
- structure: r.structure,
280
- }, null, 2)}\n`;
281
- }
282
- export function compare(before, after, locale) {
283
- const b = loadSide(before, 'before', locale);
284
- const a = loadSide(after, 'after', locale);
285
- if (b.kind === 'flow' && a.kind === 'flow') {
286
- const s = flowStructure(b.side, a.side);
287
- const rb = runSide(b.side.g, `before (${label(before)})`);
288
- const ra = runSide(a.side.g, `after (${label(after)})`);
289
- return { kind: 'flow', title: a.side.g.flow.title ?? humanize(a.side.g.flow.id), before, after, structure: s.changes, behaviour: flowBehaviour(rb, ra, s), same: flowSameBehaviour(ra) };
290
- }
291
- if (b.kind === 'nav' && a.kind === 'nav') {
292
- for (const w of b.side.warnings)
293
- console.error(`warning: before: ${w}`);
294
- for (const w of a.side.warnings)
295
- console.error(`warning: after: ${w}`);
296
- const s = navStructure(b.side, a.side);
297
- const rb = runNav(b.side.g, `before (${label(before)})`);
298
- const ra = runNav(a.side.g, `after (${label(after)})`);
299
- return { kind: 'nav', title: a.side.g.title, before, after, structure: s.changes, behaviour: navBehaviour(rb, ra, s), same: navSameBehaviour(ra) };
300
- }
301
- throw new GraphError(`before (${label(before)}) is a ${b.kind} graph and after (${label(after)}) a ${a.kind} graph`);
302
- }
303
- export async function diffMain(args) {
304
- const withValue = ['--base', '--head', '--locale'];
305
- const dirs = args.filter((x, i) => !x.startsWith('--') && !withValue.includes(args[i - 1] ?? ''));
306
- const flag = (name) => {
307
- const i = args.indexOf(name);
308
- return i >= 0 ? args[i + 1] : undefined;
309
- };
310
- const base = flag('--base');
311
- const head = flag('--head');
312
- for (const name of withValue)
313
- if (args.includes(name) && (flag(name) === undefined || flag(name)?.startsWith('--') === true))
314
- throw new GraphError(`${name} needs a value`);
315
- if (dirs.length === 0 || dirs.length > 2 || (dirs.length === 1 && base === undefined && head === undefined)) {
316
- console.error(`usage:\n${DIFF_USAGE}`);
317
- return 1;
318
- }
319
- const [oldDir, newDir] = dirs.length === 2 ? dirs : [dirs[0], dirs[0]];
320
- const before = base === undefined ? dirSource(oldDir) : gitSource(base, oldDir);
321
- const after = head === undefined ? dirSource(newDir) : gitSource(head, newDir);
322
- const report = compare(before, after, flag('--locale'));
323
- const text = args.includes('--json') ? renderJson(report) : renderMarkdown(report);
324
- await new Promise((done) => process.stdout.write(text, () => done())); // all of it, before the process exits
325
- const regressions = report.behaviour.filter((s) => s.worse).length;
326
- if (args.includes('--fail-on-regression') && regressions > 0)
327
- return 2;
328
- if (args.includes('--fail-on-behaviour') && report.behaviour.length > 0)
329
- return 2;
330
- return 0;
331
- }
@@ -1,18 +0,0 @@
1
- import type { DomainPart } from './domain.ts';
2
- export interface NamePlace {
3
- file: string;
4
- line: number;
5
- column: number;
6
- }
7
- export interface NameProblem extends NamePlace {
8
- rule: 'entity-unknown' | 'field-unknown' | 'policy-unknown';
9
- message: string;
10
- element: string;
11
- notes: Array<NamePlace & {
12
- message: string;
13
- }>;
14
- }
15
- export type EntityElsewhere = (entity: string) => (NamePlace & {
16
- domain: string;
17
- }) | null;
18
- export declare function checkDomainNames(parts: DomainPart[], doc: Record<string, unknown>, id: string, elsewhere?: EntityElsewhere): NameProblem[];
@@ -1,124 +0,0 @@
1
- // The names a domain gives one another (SPEC.md §5), each held to what the domain has, all its files read as one: an
2
- // action's `returns` and every `references` (on an entity's field, or in a body, a query, a result or a refusal's body)
3
- // name an entity; an entity's `key` and `required` name its own fields; a policy's `do` names actions, and its `read`
4
- // and `write` entities. A name that the domain does not have is an error, as a flow's `invoke` names are (decided on
5
- // 16 Nov 2026, d-1116-10). Each finding is given in the file that gives the name, at its line, with a note where another
6
- // domain beside it has the entity: a domain names only its own, and one domain may be split across files instead.
7
- import { readYaml, keyAt } from './yaml.js';
8
- const isObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
9
- // the keywords of JSON Schema 2020-12 whose value is a schema, a list of schemas, or schemas by name; a value of any
10
- // other keyword (`examples`, `default`, `const`, `enum`) is data, never read for `references`
11
- const ONE = ['items', 'contains', 'not', 'if', 'then', 'else', 'additionalProperties', 'propertyNames', 'unevaluatedItems', 'unevaluatedProperties', 'contentSchema'];
12
- const LIST = ['allOf', 'anyOf', 'oneOf', 'prefixItems'];
13
- const BY_NAME = ['properties', 'patternProperties', '$defs', 'dependentSchemas'];
14
- // every `references` in a schema, with the path to the schema that gives it
15
- function referencesIn(schema, path, out = []) {
16
- if (!isObject(schema))
17
- return out;
18
- if (schema.references !== undefined)
19
- out.push({ path, name: schema.references });
20
- for (const k of ONE)
21
- referencesIn(schema[k], [...path, k], out);
22
- for (const k of LIST)
23
- if (Array.isArray(schema[k]))
24
- schema[k].forEach((s, i) => referencesIn(s, [...path, k, String(i)], out));
25
- for (const k of BY_NAME)
26
- if (isObject(schema[k]))
27
- for (const [name, s] of Object.entries(schema[k]))
28
- referencesIn(s, [...path, k, name], out);
29
- return out;
30
- }
31
- // a schema's path inside the value it sits in, for a message: properties.address.properties.city -> address.city
32
- const inside = (path) => path.map((s, i) => (path[i - 1] === 'properties' ? s : s === 'properties' ? '' : s)).filter((s) => s !== '').join('.');
33
- // `doc` is the domain's files read as one (mergeDomain); `parts` the files, each read again here for where it gives a name
34
- export function checkDomainNames(parts, doc, id, elsewhere = () => null) {
35
- const entities = isObject(doc.entities) ? doc.entities : {};
36
- const actions = isObject(doc.actions) ? doc.actions : {};
37
- const isEntity = (name) => Object.hasOwn(entities, name);
38
- const isAction = (name) => Object.hasOwn(actions, name);
39
- const fieldsOf = (entity) => {
40
- const e = entities[entity];
41
- return isObject(e) && isObject(e.fields) ? e.fields : null;
42
- };
43
- const out = [];
44
- for (const part of parts) {
45
- let data;
46
- try {
47
- data = readYaml(part.text);
48
- }
49
- catch {
50
- continue;
51
- }
52
- // a file that is not a map, or is another domain's (domain-place), is no part of this one
53
- if (!isObject(data) || (typeof data.id === 'string' && data.id !== id))
54
- continue;
55
- const at = (rule, path, message, element, entity) => {
56
- const other = entity === undefined ? null : elsewhere(entity);
57
- const notes = other === null ? [] : [{ file: other.file, line: other.line, column: other.column, message: `${entity} is an entity of the domain ${other.domain}: a domain names only its own entities, and one domain may be split across the files of its directory (SPEC.md §5)` }];
58
- out.push({ rule, file: part.file, ...keyAt(part.text, path), message, element, notes });
59
- };
60
- const references = (schema, path, where) => {
61
- for (const r of referencesIn(schema, path)) {
62
- if (typeof r.name !== 'string' || isEntity(r.name))
63
- continue;
64
- const rest = inside(r.path.slice(path.length));
65
- at('entity-unknown', [...r.path, 'references'], `${where(rest)} references ${r.name}, which is not an entity of the domain ${id} (SPEC.md §5)`, `${r.path.join('/')}/references`, r.name);
66
- }
67
- };
68
- for (const [entity, e] of Object.entries(isObject(data.entities) ? data.entities : {})) {
69
- if (!isObject(e))
70
- continue;
71
- // an entity whose fields no file gives yet is not held to them
72
- const fields = fieldsOf(entity);
73
- for (const key of ['key', 'required']) {
74
- if (fields === null || !Array.isArray(e[key]))
75
- continue;
76
- e[key].forEach((name, i) => {
77
- if (typeof name !== 'string' || Object.hasOwn(fields, name))
78
- return;
79
- const said = key === 'key' ? `the key of the entity ${entity} names ${name}` : `the entity ${entity} requires ${name}`;
80
- at('field-unknown', ['entities', entity, key, String(i)], `${said}, which is not one of its fields (SPEC.md §5)`, `entities/${entity}/${key}/${name}`);
81
- });
82
- }
83
- for (const [field, schema] of Object.entries(isObject(e.fields) ? e.fields : {})) {
84
- references(schema, ['entities', entity, 'fields', field], (rest) => `the field ${entity}.${field}${rest === '' ? '' : `, at ${rest},`}`);
85
- }
86
- }
87
- for (const [action, a] of Object.entries(isObject(data.actions) ? data.actions : {})) {
88
- if (!isObject(a))
89
- continue;
90
- const result = a.result;
91
- if (isObject(result) && typeof result.returns === 'string' && !isEntity(result.returns)) {
92
- at('entity-unknown', ['actions', action, 'result', 'returns'], `the action ${action} returns ${result.returns}, which is not an entity of the domain ${id} (SPEC.md §5)`, `actions/${action}/result/returns`, result.returns);
93
- }
94
- for (const section of ['query', 'body', 'result']) {
95
- references(a[section], ['actions', action, section], (rest) => `the ${section} of the action ${action}${rest === '' ? '' : `, at ${rest},`}`);
96
- }
97
- for (const [code, r] of Object.entries(isObject(a.refusals) ? a.refusals : {})) {
98
- if (isObject(r))
99
- references(r.body, ['actions', action, 'refusals', code, 'body'], (rest) => `the body of the refusal ${code} of the action ${action}${rest === '' ? '' : `, at ${rest},`}`);
100
- }
101
- }
102
- // the policies of this file, by their place in it; the element names the policy by its actor, as the list's order
103
- // across files is no part of what it is
104
- (Array.isArray(data.policies) ? data.policies : []).forEach((p, i) => {
105
- if (!isObject(p))
106
- return;
107
- const actor = typeof p.actor === 'string' ? p.actor : String(i);
108
- for (const key of ['do', 'read', 'write']) {
109
- if (!Array.isArray(p[key]))
110
- continue;
111
- p[key].forEach((name, j) => {
112
- if (typeof name !== 'string')
113
- return;
114
- const known = key === 'do' ? isAction(name) : isEntity(name);
115
- if (known)
116
- return;
117
- const what = key === 'do' ? 'an action' : 'an entity';
118
- at('policy-unknown', ['policies', String(i), key, String(j)], `the policy for ${actor} names ${name} in ${key}, which is not ${what} of the domain ${id} (SPEC.md §5)`, `policies/${actor}/${key}/${name}`, key === 'do' ? undefined : name);
119
- });
120
- }
121
- });
122
- }
123
- return out;
124
- }
package/dist/domain.d.ts DELETED
@@ -1,25 +0,0 @@
1
- export interface DomainPart {
2
- file: string;
3
- text: string;
4
- }
5
- export interface DomainPlace {
6
- file: string;
7
- line: number;
8
- column: number;
9
- }
10
- export interface DomainProblem extends DomainPlace {
11
- rule: 'domain-twice' | 'domain-place';
12
- message: string;
13
- element: string;
14
- first?: DomainPlace;
15
- }
16
- export interface MergedDomain {
17
- id: string | null;
18
- doc: Record<string, unknown>;
19
- problems: DomainProblem[];
20
- }
21
- export declare const OTHER_KINDS: Set<string>;
22
- export declare const mayBeDomain: (name: string) => boolean;
23
- export declare const isDomainText: (text: string) => boolean;
24
- export declare function inReadingOrder(names: string[]): string[];
25
- export declare function mergeDomain(parts: DomainPart[]): MergedDomain;
package/dist/domain.js DELETED
@@ -1,110 +0,0 @@
1
- // A domain (SPEC.md §1, §5) is every file in its directory that says `kind: domain`, read as one: `domain.yaml` first,
2
- // then the others by name. `schema`, `kind` and `id` open every file and the id is the same in all; maps merge key by
3
- // key at any depth; the top-level lists `policies` and `invariants` join in that order; any other value (a string, a
4
- // number, a list) is given in one file only. A split lets a generated part and a hand-written part sit side by side.
5
- import { keyAt, readYaml } from './yaml.js';
6
- // the files whose name says another kind (SPEC.md §1); only the others are read to see whether they are a domain
7
- export const OTHER_KINDS = new Set(['flow.yaml', 'ui.yaml', 'nav.yaml', 'nav.extracted.yaml', 'binding.yaml', 'tutorial.yaml', 'kit.yaml', 'needs.yaml', 'needs.gaps.yaml', 'anchors.lock.yaml']);
8
- const OWN = new Set(['schema', 'kind', 'id']);
9
- const JOINED = new Set(['policies', 'invariants']);
10
- // a file that may be part of a domain, by its name
11
- export const mayBeDomain = (name) => name === 'domain.yaml' || (name.endsWith('.yaml') && !OTHER_KINDS.has(name));
12
- // `kind: domain` at the top of the file; read from the text, so a file that is not YAML is still found and its own
13
- // schema check says why
14
- export const isDomainText = (text) => /^kind:[ \t]*(domain|'domain'|"domain")[ \t]*(#.*)?$/m.test(text);
15
- // the reading order of a domain's files: domain.yaml, then the others by name
16
- export function inReadingOrder(names) {
17
- const base = (n) => n.slice(n.lastIndexOf('/') + 1);
18
- return [...names].sort((a, b) => (base(a) === 'domain.yaml' ? -1 : base(b) === 'domain.yaml' ? 1 : a < b ? -1 : a > b ? 1 : 0));
19
- }
20
- const isObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
21
- const pointer = (path) => path.map((s) => `/${s.replace(/~/g, '~0').replace(/\//g, '~1')}`).join('');
22
- const nameOf = (file) => file.slice(file.lastIndexOf('/') + 1);
23
- // the files of one directory, read as one domain; a file that is not YAML, or not a map, is left to its schema check
24
- export function mergeDomain(parts) {
25
- const doc = {};
26
- const problems = [];
27
- const origin = new Map(); // the pointer of a value given -> the part that gave it
28
- const invariants = new Map();
29
- let id = null;
30
- let idFrom = -1;
31
- const where = (i, path) => ({ file: parts[i].file, ...keyAt(parts[i].text, path) });
32
- // the part that gave the value at `path`, or the map it sits in
33
- const giver = (path) => {
34
- for (let n = path.length; n > 0; n--) {
35
- const o = origin.get(pointer(path.slice(0, n)));
36
- if (o !== undefined)
37
- return o;
38
- }
39
- return 0;
40
- };
41
- const twice = (i, path, first, said) => {
42
- const at = where(i, path);
43
- const firstAt = where(first, path);
44
- problems.push({ rule: 'domain-twice', ...at, first: firstAt, message: `${said} is given in ${nameOf(parts[first].file)}:${firstAt.line} too: a domain's files give each value once (SPEC.md §5)`, element: `${nameOf(parts[i].file)}#${pointer(path)}` });
45
- };
46
- const put = (target, key, value, path, i) => {
47
- if (!(key in target)) {
48
- target[key] = value;
49
- origin.set(pointer(path), i);
50
- return;
51
- }
52
- const here = target[key];
53
- if (isObject(here) && isObject(value)) {
54
- for (const [k, v] of Object.entries(value))
55
- put(here, k, v, [...path, k], i);
56
- return;
57
- }
58
- twice(i, path, giver(path), path.join('.'));
59
- };
60
- parts.forEach((part, i) => {
61
- let data;
62
- try {
63
- data = readYaml(part.text);
64
- }
65
- catch {
66
- return;
67
- }
68
- if (!isObject(data))
69
- return;
70
- if (typeof data.id === 'string') {
71
- if (id === null) {
72
- id = data.id;
73
- idFrom = i;
74
- }
75
- else if (data.id !== id) {
76
- problems.push({ rule: 'domain-place', ...where(i, ['id']), message: `the id is ${data.id}, and ${nameOf(parts[idFrom].file)} beside it is ${id}: a directory holds one domain, every file of it with its id (SPEC.md §1)`, element: `${nameOf(part.file)}#/id` });
77
- return;
78
- }
79
- }
80
- for (const [key, value] of Object.entries(data)) {
81
- if (OWN.has(key)) {
82
- doc[key] ??= value;
83
- continue;
84
- }
85
- if (JOINED.has(key) && Array.isArray(value) && (doc[key] === undefined || Array.isArray(doc[key]))) {
86
- if (doc[key] === undefined)
87
- origin.set(pointer([key]), i);
88
- doc[key] = [...(doc[key] ?? []), ...value];
89
- if (key !== 'invariants')
90
- continue;
91
- value.forEach((inv, index) => {
92
- const name = isObject(inv) && typeof inv.id === 'string' ? inv.id : null;
93
- if (name === null)
94
- return;
95
- const seen = invariants.get(name);
96
- if (seen === undefined)
97
- invariants.set(name, { part: i, index });
98
- else if (seen.part !== i) {
99
- const at = where(i, ['invariants', String(index), 'id']);
100
- const firstAt = where(seen.part, ['invariants', String(seen.index), 'id']);
101
- problems.push({ rule: 'domain-twice', ...at, first: firstAt, message: `the invariant ${name} is given in ${nameOf(parts[seen.part].file)}:${firstAt.line} too: a domain's files give each invariant once (SPEC.md §5)`, element: `${nameOf(part.file)}#/invariants/${index}` });
102
- }
103
- });
104
- continue;
105
- }
106
- put(doc, key, value, [key], i);
107
- }
108
- });
109
- return { id, doc, problems };
110
- }