@delurio/cli 0.10.0 → 0.12.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 (89) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/NOTICE +7 -0
  3. package/README.md +38 -22
  4. package/SPEC.md +8 -1
  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/{dist → js}/graph.d.ts +3 -0
  11. package/js/graph.js +73 -0
  12. package/{dist → js}/html.d.ts +6 -6
  13. package/js/html.js +13 -0
  14. package/js/internal.js +408 -0
  15. package/js/kit.js +54 -0
  16. package/{dist → js}/model.d.ts +2 -2
  17. package/js/model.js +136 -0
  18. package/js/native.cjs +46 -0
  19. package/js/native.d.cts +328 -0
  20. package/{dist → js}/nav.d.ts +1 -1
  21. package/js/nav.js +70 -0
  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 +2 -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 +40 -24
  33. package/schemas/binding.schema.json +2211 -0
  34. package/schemas/ui.schema.json +6 -0
  35. package/dist/anchors.d.ts +0 -29
  36. package/dist/anchors.js +0 -160
  37. package/dist/changes.d.ts +0 -25
  38. package/dist/changes.js +0 -101
  39. package/dist/check.d.ts +0 -23
  40. package/dist/check.js +0 -649
  41. package/dist/cli.d.ts +0 -2
  42. package/dist/cli.js +0 -194
  43. package/dist/compare.d.ts +0 -34
  44. package/dist/compare.js +0 -143
  45. package/dist/diff-flow.d.ts +0 -33
  46. package/dist/diff-flow.js +0 -547
  47. package/dist/diff-nav.d.ts +0 -20
  48. package/dist/diff-nav.js +0 -401
  49. package/dist/diff.d.ts +0 -25
  50. package/dist/diff.js +0 -331
  51. package/dist/domain-names.d.ts +0 -18
  52. package/dist/domain-names.js +0 -124
  53. package/dist/domain.d.ts +0 -25
  54. package/dist/domain.js +0 -110
  55. package/dist/edges.js +0 -120
  56. package/dist/expr.js +0 -157
  57. package/dist/graph.js +0 -236
  58. package/dist/html.js +0 -311
  59. package/dist/index-page.d.ts +0 -12
  60. package/dist/index-page.js +0 -50
  61. package/dist/invokes.d.ts +0 -10
  62. package/dist/invokes.js +0 -67
  63. package/dist/kit.js +0 -711
  64. package/dist/mermaid.d.ts +0 -3
  65. package/dist/mermaid.js +0 -50
  66. package/dist/model.js +0 -608
  67. package/dist/nav-page.d.ts +0 -15
  68. package/dist/nav-page.js +0 -283
  69. package/dist/nav.js +0 -578
  70. package/dist/needs.js +0 -335
  71. package/dist/pan.d.ts +0 -2
  72. package/dist/pan.js +0 -252
  73. package/dist/schemas.d.ts +0 -15
  74. package/dist/schemas.js +0 -316
  75. package/dist/spine.js +0 -156
  76. package/dist/starts.js +0 -88
  77. package/dist/story.js +0 -109
  78. package/dist/tutorial-check.d.ts +0 -9
  79. package/dist/tutorial-check.js +0 -297
  80. package/dist/ui-check.d.ts +0 -8
  81. package/dist/ui-check.js +0 -142
  82. package/dist/watch.d.ts +0 -5
  83. package/dist/watch.js +0 -114
  84. package/dist/wireframe.js +0 -276
  85. package/dist/yaml.d.ts +0 -19
  86. package/dist/yaml.js +0 -134
  87. /package/{dist → js}/expr.d.ts +0 -0
  88. /package/{dist → js}/kit.d.ts +0 -0
  89. /package/{dist → js}/needs.d.ts +0 -0
package/dist/check.js DELETED
@@ -1,649 +0,0 @@
1
- // `check`: every graph under a folder, as a project's CI runs it (graphs/agents/cli.check, SPEC.md §10). It reads the
2
- // files and nothing else, writes no page, and gives each finding as a GNU error line, or as SARIF 2.1.0 with
3
- // --format sarif. Exit 0 when clean, 1 when a graph cannot be loaded or is written for a newer format, 2 when an error
4
- // is found under --strict (and, with --baseline, new since that run).
5
- import { createHash } from 'node:crypto';
6
- import { existsSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
7
- import { basename, dirname, join, relative, resolve } from 'node:path';
8
- import { keyAt, parsingOnce, readYaml } from './yaml.js';
9
- import { alternatives, GraphError, load, placed } from './graph.js';
10
- import { checkAssertions, explore, Model, ModelError } from './model.js';
11
- import { stepsByEvents } from './story.js';
12
- import { renderScreens } from './wireframe.js';
13
- import { checkStarts } from './starts.js';
14
- import { checkChanges, flowDomain } from './changes.js';
15
- import { checkUi } from './ui-check.js';
16
- import { checkInvokes } from './invokes.js';
17
- import { checkTutorial } from './tutorial-check.js';
18
- import { KitError, resolveKit } from './kit.js';
19
- import { checkGoals, findings, loadNav, viewOf } from './nav.js';
20
- import { schemaKindOf, validateFile } from './schemas.js';
21
- import { inReadingOrder, mergeDomain } from './domain.js';
22
- import { checkDomainNames } from './domain-names.js';
23
- import { checkNeeds, planned, readNeeds } from './needs.js';
24
- import { checkAnchors } from './anchors.js';
25
- export const CHECK_USAGE = [
26
- ' node src/cli.ts check <graphs folder>... [--strict] [--baseline <sarif>] [--format sarif --output <file>] [--app <dir> | --no-app]',
27
- ' checks every graph under the folders and writes nothing else: GNU error lines on stdout, or SARIF 2.1.0;',
28
- ' exit 0 clean, 1 a graph cannot be loaded or needs a newer format, 2 an error under --strict (new since --baseline);',
29
- ' the evidence of needs and the source: anchors are found under --app, the application\'s repository root',
30
- ' (default: the working directory); --no-app checks the graphs without the code, and does not look for them',
31
- ].join('\n');
32
- const FORMAT = 'delurio-graph/0';
33
- const SKIP = new Set(['viz', 'video', 'recording', 'node_modules', '.git']);
34
- const RULES = [
35
- { id: 'load', text: 'The graph cannot be loaded', level: 'error' },
36
- { id: 'format-newer', text: 'The graph is written for a newer format than this checker reads', level: 'error' },
37
- { id: 'schema', text: "A graph file does not follow its kind's schema (SPEC.md)", level: 'error' },
38
- { id: 'domain-twice', text: 'A value of a domain is given in two of its files (SPEC.md §5)', level: 'error' },
39
- { id: 'domain-place', text: 'A domain file is not with the rest of its domain (SPEC.md §1)', level: 'error' },
40
- { id: 'server-fn-http', text: 'A server function is given a route, a query or an operationId, which only an HTTP operation has (SPEC.md §5)', level: 'error' },
41
- { id: 'entity-unknown', text: "An action's returns or a references names an entity its domain does not have (SPEC.md §5)", level: 'error' },
42
- { id: 'field-unknown', text: "An entity's key or required names a field the entity does not have (SPEC.md §5)", level: 'error' },
43
- { id: 'assertion-violated', text: 'A guarantee of the flow is broken by a reachable situation', level: 'error' },
44
- { id: 'main-story-unwalkable', text: 'The declared main story cannot be walked', level: 'error' },
45
- { id: 'catalog-key-missing', text: "A catalog key the screens use is missing from a locale's catalog", level: 'error' },
46
- { id: 'sample-missing', text: 'A catalog message has a placeholder with no sample value', level: 'error' },
47
- { id: 'no-renderer', text: 'A component has no renderer', level: 'error' },
48
- { id: 'kit-uncovered', text: "The kit does not cover a component or an intent", level: 'error' },
49
- { id: 'list-item-outside-list', text: 'A list item is drawn outside a list', level: 'error' },
50
- { id: 'hand-over', text: 'A started flow cannot begin with what it is given', level: 'error' },
51
- { id: 'changes-note-missing', text: 'A flow whose steps write has no changes note (SPEC.md §4)', level: 'error' },
52
- { id: 'changes-note-locale', text: "The changes note is missing from a locale's catalog", level: 'error' },
53
- { id: 'changes-note-gap', text: 'A writing flow says why it has no changes note yet: counted, and fails nothing (SPEC.md §4)', level: 'note' },
54
- { id: 'task-locale', text: "The flow's name for its users is missing from a locale's catalog (SPEC.md §4)", level: 'error' },
55
- { id: 'source-missing', text: 'A state of a captured flow names no code (SPEC.md §9)', level: 'error' },
56
- { id: 'source-unresolved', text: 'A source anchor names a file that is not there, or a line past its end (SPEC.md §9)', level: 'error' },
57
- { id: 'citation-unresolved', text: "Words that cite the code name a file that is not there, or a line past its end (SPEC.md §9)", level: 'warning' },
58
- { id: 'focus-not-shown', text: 'A focus or a returnsFocus gives the focus to a node that is not shown there (SPEC.md §4)', level: 'error' },
59
- { id: 'returns-focus-not-dialog', text: 'A returnsFocus does not start at a dialog (SPEC.md §4)', level: 'error' },
60
- { id: 'role-missing', text: 'A field or an action gives no role, by which a screen reader finds it (SPEC.md §4)', level: 'warning' },
61
- { id: 'state-no-way-out', text: 'A state that is not an exit has no way out (SPEC.md §2)', level: 'error' },
62
- { id: 'state-unreachable', text: 'No situation the flow starts in reaches the state (SPEC.md §2)', level: 'error' },
63
- { id: 'tutorial-mismatch', text: 'A tutorial no longer matches its flow (SPEC.md §7)', level: 'error' },
64
- { id: 'evidence-unresolved', text: "A need's evidence names what is not there (SPEC.md §13)", level: 'error' },
65
- { id: 'need-no-evidence', text: 'A need that is not missing names no evidence outside the graph (SPEC.md §13)', level: 'error' },
66
- { id: 'need-names-built', text: 'A missing need names a state that is built as its evidence (SPEC.md §13)', level: 'warning' },
67
- { id: 'need-unlisted', text: "A missing need is not in the product's gaps (SPEC.md §13)", level: 'error' },
68
- { id: 'need-twice', text: "A need's id is given twice in its flow's needs (SPEC.md §13)", level: 'error' },
69
- { id: 'needs-place', text: 'A needs file is beside no flow, or is the needs of another one (SPEC.md §13)', level: 'error' },
70
- { id: 'gap-met', text: 'The gaps list a need that is met (SPEC.md §13)', level: 'error' },
71
- { id: 'gap-unknown', text: 'The gaps list a need that no flow under them has (SPEC.md §13)', level: 'error' },
72
- { id: 'need-gap', text: 'A need that is missing, listed in the gaps: counted, and fails nothing (SPEC.md §13)', level: 'note' },
73
- { id: 'invoke-unknown', text: "An invoke or a failures entry names an action its flow's domain does not have, or the domain is not found (SPEC.md §5)", level: 'error' },
74
- { id: 'refusal-unknown', text: 'A failure class lists a code that is neither a refusal of its action nor a transport code (SPEC.md §2, §5)', level: 'error' },
75
- { id: 'policy-unknown', text: 'A policy names an action or an entity its domain does not have (SPEC.md §5)', level: 'error' },
76
- { id: 'planned-built', text: 'A planned entity or action names its code (SPEC.md §5)', level: 'error' },
77
- { id: 'graph-warning', text: 'Another warning of the graph', level: 'error' },
78
- { id: 'nav-problem', text: 'A problem of the navigation graph', level: 'error' },
79
- { id: 'nav-note', text: 'A note on the navigation graph', level: 'warning' },
80
- ];
81
- const LEVEL = new Map(RULES.map((r) => [r.id, r.level]));
82
- // the rules whose errors stop the run (exit 1) however --strict and --baseline read them
83
- const BREAKING = new Set(['load', 'format-newer']);
84
- export const count = (n, word) => `${n} ${word}${n === 1 ? '' : 's'}`;
85
- // the 1-based line and column of the first occurrence of `needle`, else the file's start
86
- function placeOf(abs, needle) {
87
- if (needle === null || !existsSync(abs))
88
- return { line: 1, column: 1 };
89
- const lines = readFileSync(abs, 'utf8').split('\n');
90
- for (let i = 0; i < lines.length; i++) {
91
- const c = lines[i].indexOf(needle);
92
- if (c >= 0)
93
- return { line: i + 1, column: c + 1 };
94
- }
95
- return { line: 1, column: 1 };
96
- }
97
- // every graph folder at or under root, in path order
98
- export function graphDirs(root, out = []) {
99
- if (existsSync(join(root, 'flow.yaml')) || existsSync(join(root, 'nav.yaml')))
100
- out.push(root);
101
- for (const name of readdirSync(root).sort()) {
102
- if (SKIP.has(name) || name.startsWith('.'))
103
- continue;
104
- const sub = join(root, name);
105
- if (statSync(sub).isDirectory())
106
- graphDirs(sub, out);
107
- }
108
- return out;
109
- }
110
- // every file under root that a schema covers (flow, ui, nav, nav.extracted, domain, catalog), in path order
111
- function graphFiles(root, out = []) {
112
- for (const name of readdirSync(root).sort()) {
113
- if (SKIP.has(name) || name.startsWith('.'))
114
- continue;
115
- const path = join(root, name);
116
- if (statSync(path).isDirectory())
117
- graphFiles(path, out);
118
- else if (schemaKindOf(path) !== null)
119
- out.push(path);
120
- }
121
- return out;
122
- }
123
- // the format the file says it is written in: null when it is this one
124
- function newerFormat(abs) {
125
- const doc = readYaml(readFileSync(abs, 'utf8'));
126
- const s = typeof doc?.schema === 'string' ? doc.schema : FORMAT;
127
- return s === FORMAT ? null : s;
128
- }
129
- function rel(abs) {
130
- return relative(process.cwd(), abs) || '.';
131
- }
132
- function result(rule, file, at, message, graph, element, notes = []) {
133
- return { rule, level: LEVEL.get(rule) ?? 'error', file: rel(file), line: at.line, column: at.column, message, graph, element, notes };
134
- }
135
- // a warning raised while checking a flow, sorted into its rule and placed in its file
136
- function fromWarning(dir, graph, w) {
137
- const flow = join(dir, 'flow.yaml');
138
- const ui = join(dir, 'ui.yaml');
139
- let m;
140
- if ((m = /^catalog key (\S+) is missing/.exec(w)))
141
- return result('catalog-key-missing', ui, placeOf(ui, m[1]), w, graph, m[1]);
142
- if ((m = /^no sample value for \{(\w+)\} in (\S+)/.exec(w)))
143
- return result('sample-missing', ui, placeOf(ui, m[2]), w, graph, `${m[2]}/${m[1]}`);
144
- if ((m = /^(\S+): ListItem outside a List/.exec(w)))
145
- return result('list-item-outside-list', ui, placeOf(ui, `${m[1]}:`), w, graph, m[1]);
146
- if ((m = /\(node (\S+?)\)/.exec(w)) && /^kit /.test(w))
147
- return result('kit-uncovered', ui, placeOf(ui, `${m[1]}:`), w, graph, m[1]);
148
- if ((m = /^(\S+): component .* has no wireframe renderer/.exec(w)))
149
- return result('no-renderer', ui, placeOf(ui, `${m[1]}:`), w, graph, m[1]);
150
- if (/declared main story cannot be walked/.test(w))
151
- return result('main-story-unwalkable', flow, placeOf(flow, 'main:'), w, graph, 'main');
152
- if ((m = /^(\S+) starts (\S+): (.*)$/.exec(w)))
153
- return result('hand-over', flow, placeOf(flow, `flow: ${m[2]}`), w, graph, `${m[1]}->${m[2]}`);
154
- if (/has no changes note/.test(w))
155
- return result('changes-note-missing', ui, placeOf(ui, 'samples:'), w, graph, 'changes');
156
- if ((m = /^the changes note (\S+) is not in the (\w+) catalog/.exec(w)))
157
- return result('changes-note-locale', ui, placeOf(ui, 'changes:'), w, graph, `changes/${m[2]}`);
158
- return result('graph-warning', existsSync(ui) ? ui : flow, { line: 1, column: 1 }, w, graph, w);
159
- }
160
- // the words of the screens in each locale but the one ui.yaml names (SPEC.md §4): a key the screens use that a locale's
161
- // catalog lacks, at the key's line, as for the catalog ui.yaml names; a locale whose catalog is not there, at `locales`
162
- function checkLocales(g, dir) {
163
- if (g.ui.absent === true)
164
- return [];
165
- const ui = join(dir, 'ui.yaml');
166
- const named = join(dir, g.ui.catalog);
167
- const out = [];
168
- for (const locale of g.ui.locales ?? []) {
169
- const name = join(dirname(g.ui.catalog), `${locale}.json`);
170
- const abs = join(dir, name);
171
- if (abs === named)
172
- continue;
173
- let catalog;
174
- try {
175
- catalog = JSON.parse(readFileSync(abs, 'utf8'));
176
- }
177
- catch (err) {
178
- const text = readFileSync(ui, 'utf8');
179
- const why = existsSync(abs) ? `is not JSON: ${err.message}` : 'does not exist';
180
- out.push(result('catalog-key-missing', ui, keyAt(text, ['locales']), `the ${locale} catalog, ${name}, ${why}: every word the screens use is missing in ${locale}`, g.flow.id, `catalog/${locale}`));
181
- continue;
182
- }
183
- const missing = [];
184
- const collect = (m) => {
185
- const key = /^catalog key (\S+) is missing/.exec(m)?.[1];
186
- if (key !== undefined && !missing.includes(key))
187
- missing.push(key);
188
- };
189
- const other = { ...g, catalog: catalog !== null && typeof catalog === 'object' ? catalog : {} };
190
- renderScreens(other, collect, null);
191
- checkUi(other, collect);
192
- for (const key of missing)
193
- out.push(result('catalog-key-missing', ui, placeOf(ui, key), `catalog key ${key} is missing from the ${locale} catalog, ${name}`, g.flow.id, `${key}/${locale}`));
194
- }
195
- return out;
196
- }
197
- // the states that some transition leads to, whatever its guard
198
- function targeted(g) {
199
- const out = new Set();
200
- for (const st of Object.values(g.flow.states)) {
201
- for (const a of st.always ?? [])
202
- out.add(a.target);
203
- for (const spec of Object.values(st.on ?? {}))
204
- for (const a of alternatives(spec))
205
- out.add(a.target);
206
- }
207
- return out;
208
- }
209
- function checkFlow(dir, domains) {
210
- const file = join(dir, 'flow.yaml');
211
- const g = load(dir);
212
- let kit;
213
- try {
214
- kit = resolveKit(dir, g.ui.kit, undefined);
215
- }
216
- catch (err) {
217
- throw g.ui.kit === undefined ? err : placed(err, { file: 'ui.yaml', path: ['kit'] });
218
- }
219
- const model = new Model(g.flow);
220
- const ex = explore(model);
221
- const out = [];
222
- const flowText = readFileSync(file, 'utf8');
223
- // a state the flow stops in for good though it is no exit, and a state no situation reaches (SPEC.md §2)
224
- const led = targeted(g);
225
- for (const [name, st] of Object.entries(g.flow.states)) {
226
- const at = () => keyAt(flowText, ['states', name]);
227
- const element = `states/${name}`;
228
- const ways = Object.keys(st.on ?? {}).length + (st.always ?? []).length;
229
- if (st.type !== 'final' && ways === 0 && st.invoke === undefined) {
230
- out.push(result('state-no-way-out', file, at(), `state ${name} is not an exit and has no way out: it has no on, always or invoke, so the flow stops there; make it an exit (type: final) or give it a transition (SPEC.md §2)`, g.flow.id, element));
231
- }
232
- if (!ex.atState.has(name)) {
233
- const why = led.has(name) ? 'the transitions that lead to it are never taken: the states they leave are not reached, or their guards never hold' : 'no transition leads to it';
234
- out.push(result('state-unreachable', file, at(), `state ${name} is reached by no situation the flow starts in: ${why} (SPEC.md §2)`, g.flow.id, element));
235
- }
236
- }
237
- const warnings = [];
238
- const warn = (m) => {
239
- if (!warnings.includes(m))
240
- warnings.push(m);
241
- };
242
- for (const a of checkAssertions(model, ex)) {
243
- if (a.violation === undefined)
244
- continue;
245
- const at = placeOf(file, `id: ${a.id}`);
246
- const start = Object.entries(a.violation.start).map(([k, v]) => `${k} = ${String(v)}`).join(', ');
247
- const notes = [{ file: rel(file), ...at, message: `start: ${start || 'the initial context'}` }];
248
- a.violation.events.forEach((e, i) => notes.push({ file: rel(file), ...at, message: `step ${i + 1}: ${e}` }));
249
- notes.push({ file: rel(file), ...at, message: `reached: ${a.violation.state}` });
250
- out.push(result('assertion-violated', file, at, `${a.id} is broken: ${a.say ?? a.never}`, g.flow.id, a.id, notes));
251
- }
252
- if (g.flow.main !== undefined && stepsByEvents(model, g.flow.main) === null)
253
- warn('the declared main story cannot be walked: an event is not possible where it is sent');
254
- renderScreens(g, warn, kit);
255
- if (g.ui.absent !== true) {
256
- const ui = join(dir, 'ui.yaml');
257
- const text = readFileSync(ui, 'utf8');
258
- for (const p of checkUi(g, warn))
259
- out.push(result(p.rule, ui, keyAt(text, p.path), p.message, g.flow.id, p.element));
260
- }
261
- out.push(...checkLocales(g, dir));
262
- for (const h of checkStarts(g, model, ex))
263
- for (const p of h.problems)
264
- warn(`${h.from} starts ${h.flow}: ${p}`);
265
- // the flow's domain, looked up once for the rules that read it
266
- let domain;
267
- const domainOf = () => (domain === undefined ? (domain = flowDomain(g, domains)) : domain);
268
- const changes = checkChanges(g, domainOf);
269
- for (const p of changes?.problems ?? [])
270
- warn(p);
271
- for (const w of warnings)
272
- out.push(fromWarning(dir, g.flow.id, w));
273
- // a writing flow whose app has no changes message yet says why: a gap of the flow, at the level note (SPEC.md §4)
274
- if (changes !== null && changes.missing !== null) {
275
- const ui = join(dir, 'ui.yaml');
276
- const message = `its steps write (${changes.writes.join(', ')}), and its changes note is missing: ${changes.missing}; Rehber does not guide its writing steps (SPEC.md §4)`;
277
- out.push(result('changes-note-gap', ui, keyAt(readFileSync(ui, 'utf8'), ['changes', 'missing']), message, g.flow.id, 'changes/missing'));
278
- }
279
- for (const p of checkInvokes(g, domainOf))
280
- out.push(result(p.rule, file, keyAt(flowText, p.path), p.message, g.flow.id, p.element));
281
- const tutorial = join(dir, 'tutorial.yaml');
282
- if (existsSync(tutorial)) {
283
- const text = readFileSync(tutorial, 'utf8');
284
- for (const p of checkTutorial(g, model, ex, text)) {
285
- const at = p.line === undefined ? keyAt(text, p.path) : { line: p.line, column: p.column ?? 1 };
286
- out.push(result('tutorial-mismatch', tutorial, at, p.message, g.flow.id, `tutorial.yaml#/${p.path.join('/')}`));
287
- }
288
- }
289
- // a captured flow is read from code, so every state names the code that makes it true; an exit may leave it out, as
290
- // the transition into it names that code, and so may a state that only missing needs name, which is not built yet
291
- // (SPEC.md §9, §13)
292
- if (g.flow.status === 'captured') {
293
- let needs = null;
294
- try {
295
- needs = readNeeds(dir);
296
- }
297
- catch {
298
- // a needs.yaml that cannot be read plans nothing; its schema check says why
299
- }
300
- const notBuilt = planned(needs).states;
301
- for (const [name, st] of Object.entries(g.flow.states)) {
302
- if (st.source !== undefined || st.type === 'final' || notBuilt.has(name))
303
- continue;
304
- out.push(result('source-missing', file, keyAt(flowText, ['states', name]), `state ${name} names no code: in a captured flow every state but an exit carries source: <path>:<line> (SPEC.md §9)`, g.flow.id, `states/${name}`));
305
- }
306
- }
307
- return out;
308
- }
309
- // what only an HTTP operation has (SPEC.md §5), and why a server function has none of it
310
- const HTTP_ONLY = {
311
- route: 'a route is an operation that others call over HTTP, and a server function is called only by the product\'s own pages: give one of them',
312
- query: 'a server function\'s input is its body, whatever its method',
313
- operationId: 'a server function is no operation of an OpenAPI document',
314
- };
315
- // a server function that is also given what only an HTTP operation has (SPEC.md §5), at its `serverFn` with a note at
316
- // the other key; the two may come from two files of a split domain, so the domain is read as one first
317
- function checkServerFunctions(parts, doc, id) {
318
- const out = [];
319
- const read = parts.map((p) => {
320
- try {
321
- return readYaml(p.text);
322
- }
323
- catch {
324
- return null;
325
- }
326
- });
327
- // the part that gives the action's key, and where in it
328
- const given = (name, key) => {
329
- const i = read.findIndex((d) => d?.actions?.[name]?.[key] !== undefined);
330
- return i < 0 ? null : { file: parts[i].file, ...keyAt(parts[i].text, ['actions', name, key]) };
331
- };
332
- const actions = (doc.actions ?? {});
333
- for (const [name, a] of Object.entries(actions)) {
334
- if (a === null || typeof a !== 'object' || a.serverFn === undefined)
335
- continue;
336
- const at = given(name, 'serverFn');
337
- if (at === null)
338
- continue;
339
- for (const [key, why] of Object.entries(HTTP_ONLY)) {
340
- if (a[key] === undefined)
341
- continue;
342
- const other = given(name, key);
343
- const said = key === 'route' ? `a route, ${String(a.route)}` : key === 'query' ? 'a query' : `an operationId, ${String(a.operationId)}`;
344
- const notes = other === null ? [] : [{ file: rel(other.file), line: other.line, column: other.column, message: `its ${key} is given here` }];
345
- out.push(result('server-fn-http', at.file, at, `the action ${name} is a server function (serverFn: ${String(a.serverFn)}) and has ${said}: ${why} (SPEC.md §5)`, id, `actions/${name}/${key}`, notes));
346
- }
347
- }
348
- return out;
349
- }
350
- // an entity or an action that says it is planned, written before its code, and names its code all the same (SPEC.md
351
- // §5): at its `planned`, with a note where its `source` is given, as the two may come from two files of a split domain
352
- function checkPlanned(parts, doc, id) {
353
- const out = [];
354
- const read = parts.map((p) => {
355
- try {
356
- return readYaml(p.text);
357
- }
358
- catch {
359
- return null;
360
- }
361
- });
362
- const given = (section, name, key) => {
363
- const i = read.findIndex((d) => d?.[section]?.[name]?.[key] !== undefined);
364
- return i < 0 ? null : { file: parts[i].file, ...keyAt(parts[i].text, [section, name, key]) };
365
- };
366
- for (const [section, word] of [['entities', 'entity'], ['actions', 'action']]) {
367
- const items = (doc[section] ?? {});
368
- if (items === null || typeof items !== 'object')
369
- continue;
370
- for (const [name, item] of Object.entries(items)) {
371
- if (item === null || typeof item !== 'object' || typeof item.planned !== 'string' || typeof item.source !== 'string')
372
- continue;
373
- const at = given(section, name, 'planned');
374
- const src = given(section, name, 'source');
375
- if (at === null)
376
- continue;
377
- const notes = src === null ? [] : [{ file: rel(src.file), line: src.line, column: src.column, message: `its source is given here` }];
378
- out.push(result('planned-built', at.file, at, `the ${word} ${name} says it is planned (${item.planned}), and names its code, ${item.source}: a planned ${word} has no code yet; once it is built, take out planned (SPEC.md §5)`, id, `${section}/${name}/planned`, notes));
379
- }
380
- }
381
- return out;
382
- }
383
- // whether a domain's file gives the entity
384
- function givesEntity(text, entity) {
385
- try {
386
- const entities = readYaml(text)?.entities;
387
- return entities !== null && typeof entities === 'object' && Object.hasOwn(entities, entity);
388
- }
389
- catch {
390
- return false;
391
- }
392
- }
393
- // the domains under root, each the domain files of one directory read as one (SPEC.md §5): a value given in two of
394
- // them, a file whose id is not its directory's, a domain whose files sit in two directories, a server function given
395
- // what only an HTTP operation has, and a name of an entity, a field or an action that the domain does not have
396
- function checkDomains(files) {
397
- const byDir = new Map();
398
- for (const f of files)
399
- if (schemaKindOf(f) === 'domain')
400
- byDir.set(dirname(f), [...(byDir.get(dirname(f)) ?? []), f]);
401
- const out = [];
402
- const dirsOf = new Map(); // a domain's id -> the directories that hold it
403
- const domains = [...byDir].map(([dir, list]) => {
404
- const parts = inReadingOrder(list).map((file) => ({ file, text: readFileSync(file, 'utf8') }));
405
- return { dir, parts, merged: mergeDomain(parts) };
406
- });
407
- // an entity of another domain, for the note of a name that this one does not have
408
- const elsewhere = (self) => (entity) => {
409
- for (const { dir, parts, merged } of domains) {
410
- const id = merged.id ?? rel(dir);
411
- const entities = merged.doc.entities;
412
- if (id === self || entities === null || typeof entities !== 'object' || !Object.hasOwn(entities, entity))
413
- continue;
414
- const part = parts.find((p) => givesEntity(p.text, entity)) ?? parts[0];
415
- return { domain: id, file: part.file, ...keyAt(part.text, ['entities', entity]) };
416
- }
417
- return null;
418
- };
419
- for (const { dir, parts, merged } of domains) {
420
- const id = merged.id ?? rel(dir);
421
- for (const p of merged.problems) {
422
- const notes = p.first === undefined ? [] : [{ file: rel(p.first.file), line: p.first.line, column: p.first.column, message: 'given first here' }];
423
- out.push(result(p.rule, p.file, p, p.message, id, p.element, notes));
424
- }
425
- out.push(...checkServerFunctions(parts, merged.doc, id));
426
- out.push(...checkPlanned(parts, merged.doc, id));
427
- for (const p of checkDomainNames(parts, merged.doc, id, elsewhere(id))) {
428
- out.push(result(p.rule, p.file, p, p.message, id, p.element, p.notes.map((n) => ({ ...n, file: rel(n.file) }))));
429
- }
430
- if (merged.id !== null)
431
- dirsOf.set(merged.id, [...(dirsOf.get(merged.id) ?? []), dir]);
432
- }
433
- for (const [id, dirs] of dirsOf) {
434
- for (const dir of dirs.slice(1)) {
435
- const file = inReadingOrder(byDir.get(dir) ?? [])[0];
436
- out.push(result('domain-place', file, placeOf(file, 'id:'), `the domain ${id} is in ${rel(dirs[0])}/ too: a domain sits in one directory, so every flow that names it reads all of it (SPEC.md §1)`, id, `${basename(file)}#/id`));
437
- }
438
- }
439
- return out;
440
- }
441
- function checkNav(dir) {
442
- const file = join(dir, 'nav.yaml');
443
- const { g, warnings } = loadNav(dir, undefined);
444
- const views = g.personas.map((p) => viewOf(g, p));
445
- const found = findings(g, views, checkGoals(g, views));
446
- const out = found.map((f) => result(f.level === 'problem' ? 'nav-problem' : 'nav-note', file, { line: 1, column: 1 }, `${f.say} (${f.code})`, g.id, f.code, f.detail.map((d) => ({ file: rel(file), line: 1, column: 1, message: d }))));
447
- for (const w of warnings)
448
- out.push(result('graph-warning', file, { line: 1, column: 1 }, w, g.id, w));
449
- return out;
450
- }
451
- // the level a finding is printed at, and counted at: an error known from the baseline is a warning, as it fails no
452
- // run, but one that stops the run (it cannot be loaded) is an error however often it was seen
453
- const printedLevel = (r) => (r.level === 'error' && r.baselineState === 'unchanged' && !BREAKING.has(r.rule) ? 'warning' : r.level);
454
- // where a load error is (SPEC.md §10): the place the loader or the model gave it, at the keys it names or the line a
455
- // parser gave, in the file it names; else the line a YAML parser gave; else the start of the graph's own file
456
- function loadPlace(dir, file, err) {
457
- const place = err.place;
458
- const at = place === undefined ? file : join(dir, place.file);
459
- if (place?.line !== undefined)
460
- return { file: at, line: place.line, column: place.column ?? 1 };
461
- const linePos = err.linePos?.[0];
462
- if (linePos !== undefined)
463
- return { file: at, line: linePos.line, column: linePos.col };
464
- if (place?.path !== undefined && existsSync(at))
465
- return { file: at, ...keyAt(readFileSync(at, 'utf8'), place.path) };
466
- return { file: at, line: 1, column: 1 };
467
- }
468
- const fingerprint = (r) => createHash('sha256').update(`${r.rule}|${r.graph}|${r.element}`).digest('hex').slice(0, 32);
469
- function baselinePrints(file) {
470
- const doc = JSON.parse(readFileSync(file, 'utf8'));
471
- const out = new Set();
472
- for (const run of doc.runs ?? [])
473
- for (const r of run.results ?? [])
474
- if (r.fingerprints?.['delurio/v1'] !== undefined)
475
- out.add(r.fingerprints['delurio/v1']);
476
- return out;
477
- }
478
- function toolVersion() {
479
- const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
480
- return pkg.version ?? '0.0.0';
481
- }
482
- function sarif(results, exitCode, said) {
483
- const used = RULES.filter((r) => results.some((x) => x.rule === r.id));
484
- return {
485
- $schema: 'https://json.schemastore.org/sarif-2.1.0.json',
486
- version: '2.1.0',
487
- runs: [
488
- {
489
- tool: {
490
- driver: {
491
- name: 'delurio',
492
- version: toolVersion(),
493
- informationUri: 'https://delur.io',
494
- rules: used.map((r) => ({ id: r.id, shortDescription: { text: r.text }, defaultConfiguration: { level: r.level } })),
495
- },
496
- },
497
- automationDetails: { id: 'delurio/check/' },
498
- invocations: [
499
- {
500
- executionSuccessful: exitCode !== 1,
501
- exitCode,
502
- ...(said.length === 0 ? {} : { toolExecutionNotifications: said.map((text) => ({ level: 'note', message: { text } })) }),
503
- },
504
- ],
505
- results: results.map((r) => ({
506
- ruleId: r.rule,
507
- ruleIndex: used.findIndex((u) => u.id === r.rule),
508
- level: r.level,
509
- message: { text: r.message },
510
- locations: [
511
- {
512
- physicalLocation: { artifactLocation: { uri: r.file.split('\\').join('/') }, region: { startLine: r.line, startColumn: r.column } },
513
- logicalLocations: [{ fullyQualifiedName: `${r.graph}/${r.element}` }],
514
- },
515
- ],
516
- fingerprints: { 'delurio/v1': fingerprint(r) },
517
- ...(r.notes.length > 0 && r.rule === 'assertion-violated'
518
- ? { codeFlows: [{ threadFlows: [{ locations: r.notes.map((n) => ({ location: { message: { text: n.message } } })) }] }] }
519
- : {}),
520
- ...(r.baselineState === undefined ? {} : { baselineState: r.baselineState }),
521
- })),
522
- },
523
- ],
524
- };
525
- }
526
- // every text the check reads is parsed once in it (`parsingOnce`), however many graphs read it
527
- export function checkMain(args) {
528
- return parsingOnce(() => checkRun(args));
529
- }
530
- function checkRun(args) {
531
- const flag = (name) => {
532
- const i = args.indexOf(name);
533
- return i >= 0 ? args[i + 1] : undefined;
534
- };
535
- const withValue = ['--baseline', '--format', '--output', '--app'];
536
- const dirs = args.filter((a, i) => !a.startsWith('--') && !withValue.includes(args[i - 1] ?? ''));
537
- if (dirs.length === 0) {
538
- console.error(`usage:\n${CHECK_USAGE}`);
539
- return 1;
540
- }
541
- const notFolder = dirs.find((d) => !existsSync(d) || !statSync(d).isDirectory());
542
- if (notFolder !== undefined) {
543
- console.error(`${notFolder} is not a folder\nusage:\n${CHECK_USAGE}`);
544
- return 1;
545
- }
546
- // every folder given, each graph and file once though one folder holds another
547
- const roots = dirs.map((d) => resolve(d));
548
- const dirsOfGraphs = [...new Set(roots.flatMap((r) => graphDirs(r)))];
549
- const strict = args.includes('--strict');
550
- const format = flag('--format') ?? 'text';
551
- const output = flag('--output');
552
- const baseline = flag('--baseline');
553
- if (format !== 'text' && format !== 'sarif') {
554
- console.error(`--format is text or sarif, not ${format}`);
555
- return 1;
556
- }
557
- const appGiven = flag('--app');
558
- if (appGiven !== undefined && (!existsSync(appGiven) || !statSync(appGiven).isDirectory())) {
559
- console.error(`--app ${appGiven} is not a folder\nusage:\n${CHECK_USAGE}`);
560
- return 1;
561
- }
562
- // --no-app: the graphs are here without the application's code, so what they name of it is not looked for (SPEC.md §10)
563
- const noApp = args.includes('--no-app');
564
- if (noApp && appGiven !== undefined) {
565
- console.error(`--app names the application's code and --no-app says it is not here: give one of them\nusage:\n${CHECK_USAGE}`);
566
- return 1;
567
- }
568
- const app = noApp ? null : resolve(appGiven ?? '.');
569
- const results = [];
570
- const domains = new Map(); // the domains found, for every flow that names one
571
- let broken = false;
572
- for (const d of dirsOfGraphs) {
573
- const file = existsSync(join(d, 'flow.yaml')) ? join(d, 'flow.yaml') : join(d, 'nav.yaml');
574
- try {
575
- const newer = newerFormat(file);
576
- if (newer !== null) {
577
- broken = true;
578
- results.push(result('format-newer', file, placeOf(file, 'schema:'), `written in ${newer}; this checker reads ${FORMAT}: pin a version that reads it`, rel(d), 'schema'));
579
- continue;
580
- }
581
- results.push(...(file.endsWith('flow.yaml') ? checkFlow(d, domains) : checkNav(d)));
582
- }
583
- catch (err) {
584
- if (!(err instanceof GraphError || err instanceof ModelError || err instanceof KitError || (err instanceof Error && err.name === 'YAMLParseError')))
585
- throw err;
586
- broken = true;
587
- const at = loadPlace(d, file, err);
588
- results.push(result('load', at.file, at, err.message.split('\n')[0], rel(d), 'load'));
589
- }
590
- }
591
- // every graph file against its kind's schema: what an editor with the schemas marks, check reports
592
- const files = [...new Set(roots.flatMap((r) => graphFiles(r)))];
593
- for (const file of files) {
594
- for (const f of validateFile(file))
595
- results.push(result('schema', file, f, f.message, f.graph ?? rel(file), f.element));
596
- }
597
- results.push(...checkDomains(files));
598
- // each flow's needs held to their evidence, and the product's gaps to its needs (SPEC.md §13)
599
- const needs = checkNeeds(files, app);
600
- for (const p of needs.problems)
601
- results.push(result(p.rule, p.file, p, p.message, p.graph, p.element));
602
- // every source anchor, and every citation of the code in a graph's words, held to the application's files (SPEC.md §9)
603
- const anchors = checkAnchors(files, app);
604
- for (const p of anchors.problems)
605
- results.push(result(p.rule, p.file, p, p.message, p.graph, p.element));
606
- results.sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line || a.column - b.column || a.rule.localeCompare(b.rule) || a.message.localeCompare(b.message));
607
- if (baseline !== undefined) {
608
- const prints = baselinePrints(baseline);
609
- for (const r of results)
610
- r.baselineState = prints.has(fingerprint(r)) ? 'unchanged' : 'new';
611
- }
612
- // what --no-app did not look for, said once rather than as a finding each (SPEC.md §10)
613
- const said = [];
614
- if (noApp) {
615
- const of = (n, one, many) => `${n} ${n === 1 ? one : many}`;
616
- const what = [count(anchors.anchors, 'source anchor'), of(anchors.citations, 'citation in words', 'citations in words'), of(needs.notLookedFor, 'piece of evidence', 'pieces of evidence')];
617
- said.push(`--no-app: ${what.slice(0, -1).join(', ')} and ${what[what.length - 1]} name files of the application, which are not here, and were not looked for (SPEC.md §10)`);
618
- }
619
- const failing = results.filter((r) => r.level === 'error' && !BREAKING.has(r.rule) && (r.baselineState === undefined || r.baselineState === 'new'));
620
- const exitCode = broken ? 1 : strict && failing.length > 0 ? 2 : 0;
621
- if (format === 'sarif') {
622
- const text = `${JSON.stringify(sarif(results, exitCode, said), null, 2)}\n`;
623
- if (output === undefined)
624
- process.stdout.write(text);
625
- else
626
- writeFileSync(output, text);
627
- }
628
- if (format === 'text' || output !== undefined) {
629
- for (const r of results) {
630
- console.log(`${r.file}:${r.line}:${r.column}: ${printedLevel(r)}: ${r.message} [${r.rule}]`);
631
- for (const n of r.notes)
632
- console.log(`${n.file}:${n.line}:${n.column}: note: ${n.message}`);
633
- }
634
- const graphs = dirsOfGraphs.length;
635
- const errors = results.filter((r) => printedLevel(r) === 'error').length;
636
- const warnings = results.filter((r) => printedLevel(r) === 'warning').length;
637
- // the gaps, once a flow has needs: every need that is missing, listed or not, and those the base run did not have
638
- const fresh = results.filter((r) => r.rule === 'need-gap' && r.baselineState === 'new').length;
639
- const gaps = needs.files === 0 ? '' : `, ${count(needs.gaps, 'gap')} of ${count(needs.needs, 'need')}${fresh > 0 ? ` (${fresh} new)` : ''}`;
640
- // the changes notes that writing flows say are missing (SPEC.md §4), once there is one
641
- const notes = results.filter((r) => r.rule === 'changes-note-gap');
642
- const newNotes = notes.filter((r) => r.baselineState === 'new').length;
643
- const missingNotes = notes.length === 0 ? '' : `, ${count(notes.length, 'missing changes note')}${newNotes > 0 ? ` (${newNotes} new)` : ''}`;
644
- for (const s of said)
645
- console.error(`delurio check: note: ${s}`);
646
- console.error(`delurio check: ${count(graphs, 'graph')}, ${count(errors, 'error')}, ${count(warnings, 'warning')}${gaps}${missingNotes}; exit ${exitCode}`);
647
- }
648
- return exitCode;
649
- }
package/dist/cli.d.ts DELETED
@@ -1,2 +0,0 @@
1
- #!/usr/bin/env node
2
- export {};