@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/mermaid.d.ts DELETED
@@ -1,3 +0,0 @@
1
- import type { Graph } from './graph.ts';
2
- import type { Exploration } from './model.ts';
3
- export declare function renderMermaid(g: Graph, ex: Exploration): string;
package/dist/mermaid.js DELETED
@@ -1,50 +0,0 @@
1
- import { collectEdges, exitLine, kindOf } from './edges.js';
2
- import { titleOf } from './graph.js';
3
- // Mermaid ends a statement at `;` even inside a transition's label: the rest of the label became stray states,
4
- // or, with a `-` or `{` after it, a parse error. A label keeps its words with a comma in its place.
5
- const clean = (s) => s.replace(/"/g, "'").replace(/:/g, ' -').replace(/;/g, ',');
6
- // Mermaid's ids, which take no dot: an exit named `<error>.<cause>` is written `<error>__<cause>`
7
- function mermaidIds(names) {
8
- const ids = new Map();
9
- const taken = new Set(names.filter((n) => !n.includes('.')));
10
- for (const n of names) {
11
- if (!n.includes('.')) {
12
- ids.set(n, n);
13
- continue;
14
- }
15
- let id = n.replace(/\./g, '__');
16
- for (let i = 2; taken.has(id); i++)
17
- id = `${n.replace(/\./g, '__')}_${i}`;
18
- taken.add(id);
19
- ids.set(n, id);
20
- }
21
- return (name) => ids.get(name) ?? name;
22
- }
23
- // Mermaid stateDiagram-v2 text, for PRs and READMEs. The full page is html.ts.
24
- export function renderMermaid(g, ex) {
25
- const lines = ['---', `title: ${clean(g.flow.title ?? g.flow.id)}`, '---', 'stateDiagram-v2', ' direction TB'];
26
- const names = Object.keys(g.flow.states);
27
- const id = mermaidIds(names);
28
- for (const name of names) {
29
- const st = g.flow.states[name];
30
- const detail = st.type === 'final' && st.leavesPage !== true ? ` (${exitLine(st)})` : '';
31
- lines.push(` state "${clean(titleOf(g.flow, name))}${clean(detail)}" as ${id(name)}`);
32
- }
33
- lines.push(` [*] --> ${id(g.flow.initial)}`);
34
- for (const e of collectEdges(g, ex)) {
35
- // "never taken" belongs in the label: after an arrow with no `:` Mermaid read its words as two more states
36
- const said = e.labels.map(clean).join(', ');
37
- const label = e.unused ? `${said} (never taken)`.trim() : said;
38
- lines.push(` ${id(e.from)} --> ${id(e.to)}${label === '' ? '' : `: ${label}`}`);
39
- }
40
- lines.push(' classDef server fill:#eeeeec,stroke:#6b6560,stroke-dasharray:4 3');
41
- lines.push(' classDef screen fill:#ffffff,stroke:#1c1917,stroke-width:2px');
42
- lines.push(' classDef subflow fill:#ffffff,stroke:#1d4ed8,stroke-width:2px');
43
- lines.push(' classDef exit fill:#ffffff,stroke:#6b6560,stroke-width:2px');
44
- for (const kind of ['server', 'screen', 'subflow', 'exit']) {
45
- const members = names.filter((n) => kindOf(g, n) === kind);
46
- if (members.length > 0)
47
- lines.push(` class ${members.map(id).join(',')} ${kind}`);
48
- }
49
- return lines.join('\n') + '\n';
50
- }
package/dist/model.js DELETED
@@ -1,608 +0,0 @@
1
- import { alternatives, placed, transitionPath } from './graph.js';
2
- import { parseExpr } from './expr.js';
3
- // a flow that cannot be explored; `place` says where in flow.yaml, when it is known (SPEC.md §10)
4
- export class ModelError extends Error {
5
- place;
6
- constructor(message, place) {
7
- super(message);
8
- this.place = place;
9
- }
10
- }
11
- const inFlow = (path) => ({ file: 'flow.yaml', path });
12
- // an expression read, or a ModelError that says why it cannot be: a guard or an assertion that does not parse keeps
13
- // the flow from loading, as a name that is not one does
14
- function parsed(src, place) {
15
- try {
16
- return parseExpr(src);
17
- }
18
- catch (err) {
19
- throw new ModelError(err.message, place);
20
- }
21
- }
22
- // The model explores millions of (state, context) pairs on a large flow (QAuth's consent: 5.4 million), so every guard,
23
- // assertion and effect is read once and kept ready, instead of being looked up by name at every pair.
24
- export class Model {
25
- flow;
26
- vars;
27
- domains;
28
- at; // a variable's position in a context
29
- compiled = new Map();
30
- ready = new Map();
31
- ways = new Map();
32
- constructor(flow) {
33
- this.flow = flow;
34
- this.vars = Object.keys(flow.context);
35
- this.domains = this.vars.map((v) => flow.context[v].values);
36
- this.at = new Map(this.vars.map((v, i) => [v, i]));
37
- }
38
- // what evaluate(parseExpr(src), lookup) gave, with the same errors, raised only when the name is reached
39
- // `where`: the named guard being read, so that a name in it that is not one is placed there
40
- compile(e, depth, where) {
41
- switch (e.k) {
42
- case 'lit': {
43
- const v = e.v;
44
- return () => v;
45
- }
46
- case 'id': {
47
- const name = e.name;
48
- if (name === 'state')
49
- return (state) => state;
50
- const i = this.at.get(name);
51
- if (i !== undefined)
52
- return (_, ctx) => ctx[i];
53
- const guard = this.flow.guards[name];
54
- if (guard === undefined)
55
- return (state) => {
56
- throw new ModelError(`unknown name "${name}" (state ${state})`, where);
57
- };
58
- if (depth > 8)
59
- return () => {
60
- throw new ModelError(`guard ${name} nests too deep`, where);
61
- };
62
- const at = inFlow(['guards', name]);
63
- let inner = null; // compiled when first reached, as the lookup read it
64
- return (state, ctx) => (inner ??= this.compile(parsed(guard, at), depth + 1, at))(state, ctx);
65
- }
66
- case 'list': {
67
- const items = e.items.map((x) => this.compile(x, depth, where));
68
- return (state, ctx) => items.map((f) => f(state, ctx));
69
- }
70
- case 'not': {
71
- const f = this.compile(e.e, depth, where);
72
- return (state, ctx) => !f(state, ctx);
73
- }
74
- case 'and': {
75
- const l = this.compile(e.l, depth, where);
76
- const r = this.compile(e.r, depth, where);
77
- return (state, ctx) => Boolean(l(state, ctx)) && Boolean(r(state, ctx));
78
- }
79
- case 'or': {
80
- const l = this.compile(e.l, depth, where);
81
- const r = this.compile(e.r, depth, where);
82
- return (state, ctx) => Boolean(l(state, ctx)) || Boolean(r(state, ctx));
83
- }
84
- case 'cmp': {
85
- const l = this.compile(e.l, depth, where);
86
- const r = this.compile(e.r, depth, where);
87
- if (e.op === '==')
88
- return (state, ctx) => l(state, ctx) === r(state, ctx);
89
- if (e.op === '!=')
90
- return (state, ctx) => l(state, ctx) !== r(state, ctx);
91
- const negate = e.op === 'not in';
92
- // a list of literals, the usual right side, is the same list every time: made once
93
- const fixed = e.r.k === 'list' && e.r.items.every((x) => x.k === 'lit') ? e.r.items.map((x) => x.v) : null;
94
- if (fixed !== null)
95
- return (state, ctx) => {
96
- const x = l(state, ctx);
97
- let inList = false;
98
- for (let j = 0; j < fixed.length && !inList; j++)
99
- inList = fixed[j] === x;
100
- return negate ? !inList : inList;
101
- };
102
- return (state, ctx) => {
103
- const x = l(state, ctx);
104
- const list = r(state, ctx);
105
- const inList = Array.isArray(list) && list.some((y) => y === x);
106
- return negate ? !inList : inList;
107
- };
108
- }
109
- }
110
- }
111
- expr(src) {
112
- let f = this.compiled.get(src);
113
- if (f === undefined) {
114
- f = this.compile(parsed(src), 0);
115
- this.compiled.set(src, f);
116
- }
117
- return f;
118
- }
119
- test(expr, state, ctx) {
120
- return Boolean(this.expr(expr)(state, ctx));
121
- }
122
- /**
123
- * Whether evaluating `src` can never throw: it names only the state, variables, and guards that parse and nest no
124
- * deeper than evaluation allows. Only then may its pairs be tested in another order than the exploration's.
125
- */
126
- pure(src) {
127
- const ok = (e, depth, seen) => {
128
- switch (e.k) {
129
- case 'lit':
130
- return true;
131
- case 'id': {
132
- if (e.name === 'state' || this.at.has(e.name))
133
- return true;
134
- const guard = this.flow.guards[e.name];
135
- if (guard === undefined || depth > 8 || seen.has(e.name))
136
- return false;
137
- try {
138
- return ok(parseExpr(guard), depth + 1, new Set([...seen, e.name]));
139
- }
140
- catch {
141
- return false;
142
- }
143
- }
144
- case 'list':
145
- return e.items.every((x) => ok(x, depth, seen));
146
- case 'not':
147
- return ok(e.e, depth, seen);
148
- default:
149
- return ok(e.l, depth, seen) && ok(e.r, depth, seen);
150
- }
151
- };
152
- try {
153
- return ok(parseExpr(src), 0, new Set());
154
- }
155
- catch {
156
- return false;
157
- }
158
- }
159
- /**
160
- * The value of `src` in `state` whatever the context holds, when the state alone decides it (`state in [...] and
161
- * ...` outside those states); undefined when the context matters. Folds only what evaluation would compute the same
162
- * way: literals, the state, and the side of an `and` / `or` that decides it before the other is read.
163
- */
164
- inState(src, state) {
165
- const fold = (e) => {
166
- switch (e.k) {
167
- case 'lit':
168
- return { v: e.v };
169
- case 'id':
170
- return e.name === 'state' ? { v: state } : undefined;
171
- case 'list': {
172
- const items = e.items.map(fold);
173
- return items.every((x) => x !== undefined) ? { v: items.map((x) => x.v) } : undefined;
174
- }
175
- case 'not': {
176
- const x = fold(e.e);
177
- return x === undefined ? undefined : { v: !x.v };
178
- }
179
- case 'and':
180
- case 'or': {
181
- const l = fold(e.l);
182
- if (l === undefined)
183
- return undefined;
184
- if (e.k === 'and' ? !l.v : Boolean(l.v))
185
- return { v: e.k === 'or' };
186
- const r = fold(e.r);
187
- return r === undefined ? undefined : { v: Boolean(r.v) };
188
- }
189
- case 'cmp': {
190
- const l = fold(e.l);
191
- const r = fold(e.r);
192
- if (l === undefined || r === undefined)
193
- return undefined;
194
- if (e.op === '==')
195
- return { v: l.v === r.v };
196
- if (e.op === '!=')
197
- return { v: l.v !== r.v };
198
- const inList = Array.isArray(r.v) && r.v.some((y) => y === l.v);
199
- return { v: e.op === 'in' ? inList : !inList };
200
- }
201
- }
202
- };
203
- return fold(parseExpr(src))?.v;
204
- }
205
- /** `test` for one expression at many pairs: read once, then run at each. */
206
- tester(expr) {
207
- const f = this.expr(expr);
208
- return (state, ctx) => Boolean(f(state, ctx));
209
- }
210
- value(expr, state, ctx) {
211
- return this.expr(expr)(state, ctx);
212
- }
213
- effect(name) {
214
- let r = this.ready.get(name);
215
- if (r === undefined) {
216
- const effect = this.flow.effects[name];
217
- if (effect === undefined)
218
- throw new ModelError(`unknown effect ${name}`);
219
- r = {
220
- // a name that is not a variable set nothing a context holds
221
- set: Object.entries(effect.set ?? {}).flatMap(([k, v]) => (this.at.has(k) ? [[this.at.get(k), v]] : [])),
222
- havoc: (effect.havoc ?? []).map((h) => {
223
- const i = this.vars.indexOf(h);
224
- return [i, this.domains[i]];
225
- }),
226
- };
227
- this.ready.set(name, r);
228
- }
229
- return r;
230
- }
231
- apply(names, ctx) {
232
- let outs = [ctx];
233
- for (const name of names ?? []) {
234
- const { set, havoc } = this.effect(name);
235
- const next = [];
236
- for (const base of outs) {
237
- const c = base.slice();
238
- for (const [i, v] of set)
239
- c[i] = v;
240
- if (havoc.length === 0) {
241
- next.push(c);
242
- continue;
243
- }
244
- // every combination of the havoc variables' values, the first variable slowest, as the nested lists gave them
245
- let combos = [[]];
246
- for (const [, values] of havoc)
247
- combos = combos.flatMap((p) => values.map((v) => [...p, v]));
248
- for (const combo of combos) {
249
- const c2 = c.slice();
250
- for (let j = 0; j < havoc.length; j++)
251
- c2[havoc[j][0]] = combo[j];
252
- next.push(c2);
253
- }
254
- }
255
- outs = next;
256
- }
257
- return outs;
258
- }
259
- // a state's ways out, read once: `always` as one group tried in order, else one group per event
260
- waysOf(state) {
261
- let w = this.ways.get(state);
262
- if (w === undefined) {
263
- const st = this.flow.states[state];
264
- const way = (event, a, i) => ({
265
- event,
266
- target: a.target,
267
- guard: a.guard,
268
- effect: a.effect,
269
- taken: `${state}|${event ?? 'always'}|${i}`,
270
- path: transitionPath(state, st, event, i),
271
- });
272
- w =
273
- st.type === 'final'
274
- ? { always: false, groups: [] }
275
- : st.always !== undefined
276
- ? { always: true, groups: [st.always.map((a, i) => way(null, a, i))] }
277
- : { always: false, groups: Object.entries(st.on ?? {}).map(([event, spec]) => alternatives(spec).map((a, i) => way(event, a, i))) };
278
- this.ways.set(state, w);
279
- }
280
- return w;
281
- }
282
- steps(state, ctx) {
283
- const { always, groups } = this.waysOf(state);
284
- const out = [];
285
- for (const alts of groups) {
286
- let chosen = false;
287
- for (const a of alts) {
288
- if (a.guard === undefined || this.test(a.guard, state, ctx)) {
289
- for (const c of this.apply(a.effect, ctx))
290
- out.push({ event: a.event, target: a.target, ctx: c, taken: a.taken });
291
- chosen = true;
292
- break;
293
- }
294
- }
295
- if (always && !chosen)
296
- throw new ModelError(`\`always\` in ${state} is not exhaustive for ${JSON.stringify(Object.fromEntries(this.vars.map((v, i) => [v, ctx[i]])))}`, inFlow(['states', state, 'always']));
297
- }
298
- return out;
299
- }
300
- /**
301
- * `err`, thrown by `steps(state, ctx)`, given the place in flow.yaml of the transition that threw it when it has
302
- * none: the ways are tried again as `steps` tries them, and the one whose guard or effect throws is the place; else
303
- * the state. Read only once a step has thrown, so the exploration itself pays nothing for it.
304
- */
305
- placeError(err, state, ctx) {
306
- if (!(err instanceof Error) || err.place !== undefined || this.flow.states[state] === undefined)
307
- return err;
308
- for (const alts of this.waysOf(state).groups) {
309
- for (const a of alts) {
310
- try {
311
- if (a.guard !== undefined && !this.test(a.guard, state, ctx))
312
- continue;
313
- this.apply(a.effect, ctx);
314
- break;
315
- }
316
- catch {
317
- return placed(err, inFlow(a.path));
318
- }
319
- }
320
- }
321
- return placed(err, inFlow(['states', state]));
322
- }
323
- initials() {
324
- // every combination of the starting values, the first variable slowest: the order the nested lists gave
325
- const choices = this.vars.map((v, i) => {
326
- const initial = this.flow.context[v].initial;
327
- return initial === 'any' ? this.domains[i] : [initial];
328
- });
329
- const total = choices.reduce((n, c) => n * c.length, 1);
330
- const out = new Array(total);
331
- for (let k = 0; k < total; k++) {
332
- const c = new Array(choices.length);
333
- let rest = k;
334
- for (let i = choices.length - 1; i >= 0; i--) {
335
- c[i] = choices[i][rest % choices[i].length];
336
- rest = Math.floor(rest / choices[i].length);
337
- }
338
- out[k] = c;
339
- }
340
- return out;
341
- }
342
- scenario(ctx) {
343
- const out = {};
344
- this.vars.forEach((v, i) => {
345
- if (this.flow.context[v].initial === 'any')
346
- out[v] = ctx[i];
347
- });
348
- return out;
349
- }
350
- }
351
- // A (state, context) pair as one number: the state's position, then each variable's value by its position in the
352
- // variable's values, as digits of a mixed radix. A Set keeps numbers far faster than the strings they replace.
353
- // Two pairs are the same exactly when their old keys, `${state}|${ctx.join(',')}`, are: a value is placed by its text,
354
- // as join wrote it. A flow whose pairs do not fit below 2^53, a value or state name that would make the old key
355
- // ambiguous, or a value outside its variable's values, keeps the old key.
356
- function keyer(m) {
357
- const text = (state, ctx) => `${state}|${ctx.join(',')}`;
358
- const written = (v) => (v === null || v === undefined ? '' : String(v));
359
- const names = Object.keys(m.flow.states);
360
- const size = m.domains.reduce((n, values) => n * Math.max(values.length, 1), Math.max(names.length, 1));
361
- if (!Number.isSafeInteger(size) || names.some((s) => s.includes('|')) || m.domains.some((values) => values.some((v) => written(v).includes(','))))
362
- return text;
363
- const states = new Map(names.map((s, i) => [s, i]));
364
- const byText = m.domains.map((values) => {
365
- const d = new Map();
366
- values.forEach((v, i) => {
367
- if (!d.has(written(v)))
368
- d.set(written(v), i);
369
- });
370
- return d;
371
- });
372
- const byValue = m.domains.map((values, i) => new Map(values.map((v) => [v, byText[i].get(written(v))])));
373
- const radix = m.domains.map((values) => Math.max(values.length, 1));
374
- return (state, ctx) => {
375
- let key = states.get(state);
376
- if (key === undefined || ctx.length !== radix.length)
377
- return text(state, ctx);
378
- for (let i = 0; i < radix.length; i++) {
379
- const d = byValue[i].get(ctx[i]) ?? byText[i].get(written(ctx[i]));
380
- if (d === undefined)
381
- return text(state, ctx);
382
- key = key * radix[i] + d;
383
- }
384
- return key;
385
- };
386
- }
387
- // Every reachable (state, context) pair, breadth first, so the first hit of a state is a shortest path to it.
388
- // `from` and `keep` narrow the search: the replay starts only from situations the app is bound to and takes only steps it can drive.
389
- export function explore(m, from = m.initials(), keep) {
390
- const index = new Set();
391
- const key = keyer(m);
392
- const configs = [];
393
- const taken = new Set();
394
- const atState = new Map();
395
- const branchCounts = new Map();
396
- const push = (state, ctx, parent, event) => {
397
- const k = key(state, ctx);
398
- if (index.has(k))
399
- return;
400
- index.add(k);
401
- configs.push({ state, ctx, parent, event });
402
- };
403
- for (const c of from)
404
- push(m.flow.initial, c, -1, null);
405
- const starts = configs.length;
406
- let i = 0;
407
- try {
408
- for (; i < configs.length; i++) {
409
- const { state, ctx } = configs[i];
410
- atState.set(state, (atState.get(state) ?? 0) + 1);
411
- const steps = m.steps(state, ctx);
412
- for (const s of steps) {
413
- if (keep !== undefined && !keep(configs[i], s))
414
- continue;
415
- taken.add(s.taken);
416
- push(s.target, s.ctx, i, s.event);
417
- }
418
- const always = m.flow.states[state].always;
419
- if (always !== undefined && steps.length > 0) {
420
- const counts = branchCounts.get(state) ?? always.map(() => 0);
421
- const taken0 = steps[0].taken;
422
- counts[Number(taken0.slice(taken0.lastIndexOf('|') + 1))] += 1;
423
- branchCounts.set(state, counts);
424
- }
425
- }
426
- }
427
- catch (err) {
428
- // where in flow.yaml the step that threw is written (SPEC.md §10)
429
- throw i < configs.length ? m.placeError(err, configs[i].state, configs[i].ctx) : err;
430
- }
431
- return { configs, starts, taken, atState, branchCounts };
432
- }
433
- export function pathTo(m, ex, index) {
434
- const events = [];
435
- let c = ex.configs[index];
436
- while (c.parent >= 0) {
437
- if (c.event !== null)
438
- events.push(c.event);
439
- c = ex.configs[c.parent];
440
- }
441
- return { events: events.reverse(), start: m.scenario(c.ctx) };
442
- }
443
- // the first pair, in exploration order, where `src` holds; -1 when none does. An assertion that cannot throw is tested
444
- // only in the states where the state alone does not rule it out: the first hit of each such state, the earliest of them.
445
- function firstHit(m, ex, src, byState) {
446
- // read where the exploration reads it, so an expression that throws throws at the same pair as before
447
- if (!m.pure(src))
448
- return ex.configs.findIndex((c) => m.test(src, c.state, c.ctx));
449
- const test = m.tester(src);
450
- let hit = -1;
451
- for (const [state, at] of byState()) {
452
- const fixed = m.inState(src, state);
453
- if (fixed !== undefined && !fixed)
454
- continue;
455
- for (const i of at) {
456
- if (hit >= 0 && i > hit)
457
- break;
458
- if (fixed !== undefined || test(state, ex.configs[i].ctx)) {
459
- hit = i;
460
- break;
461
- }
462
- }
463
- }
464
- return hit;
465
- }
466
- export function checkAssertions(m, ex) {
467
- let groups = null;
468
- const byState = () => {
469
- if (groups === null) {
470
- groups = new Map();
471
- ex.configs.forEach((c, i) => {
472
- const list = groups?.get(c.state);
473
- if (list === undefined)
474
- groups?.set(c.state, [i]);
475
- else
476
- list.push(i);
477
- });
478
- }
479
- return groups;
480
- };
481
- return (m.flow.assertions ?? []).map((a, i) => {
482
- let hit;
483
- try {
484
- hit = firstHit(m, ex, a.never, byState);
485
- }
486
- catch (err) {
487
- throw placed(err, inFlow(['assertions', String(i), 'never']));
488
- }
489
- if (hit < 0)
490
- return { id: a.id, never: a.never, say: a.say };
491
- return { id: a.id, never: a.never, say: a.say, violation: { ...pathTo(m, ex, hit), state: ex.configs[hit].state } };
492
- });
493
- }
494
- export function finalPaths(m, ex) {
495
- const out = [];
496
- for (const [name, st] of Object.entries(m.flow.states)) {
497
- if (st.type !== 'final')
498
- continue;
499
- const hit = ex.configs.findIndex((c) => c.state === name);
500
- if (hit >= 0)
501
- out.push({ state: name, index: hit, ...pathTo(m, ex, hit) });
502
- }
503
- return out;
504
- }
505
- // every transition of the flow, named as a Step's `taken` names it
506
- export function transitionsOf(flow) {
507
- const out = [];
508
- for (const [state, st] of Object.entries(flow.states)) {
509
- if (st.type === 'final')
510
- continue;
511
- if (st.always !== undefined)
512
- st.always.forEach((_, i) => out.push(`${state}|always|${i}`));
513
- else
514
- for (const [event, spec] of Object.entries(st.on ?? {}))
515
- alternatives(spec).forEach((_, i) => out.push(`${state}|${event}|${i}`));
516
- }
517
- return out;
518
- }
519
- // 53 bits of a string, as 14 hex digits (cyrb53): a stable id with no dependency on a platform's crypto
520
- function hash(text) {
521
- let h1 = 0xdeadbeef;
522
- let h2 = 0x41c6ce57;
523
- for (let i = 0; i < text.length; i++) {
524
- const c = text.charCodeAt(i);
525
- h1 = Math.imul(h1 ^ c, 2654435761);
526
- h2 = Math.imul(h2 ^ c, 1597334677);
527
- }
528
- h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909);
529
- h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909);
530
- return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(16).padStart(14, '0');
531
- }
532
- /**
533
- * Event paths that together pass every reachable state (`states`) or take every reachable transition (`transitions`)
534
- * of the flow (#4), from the same starts and through the same steps as `explore(m, from, keep)`. Each is a shortest
535
- * way to the state or transition it is first kept for, so it repeats a state only on the way to something not yet
536
- * covered. The longest are kept first and a path that covers nothing new is left out: a small set, never every path.
537
- * The same flow gives the same paths, in the same order, with the same ids.
538
- */
539
- export function cover(m, by, from = m.initials(), keep) {
540
- const ex = explore(m, from, keep);
541
- const stepsOf = (c) => m.steps(c.state, c.ctx).filter((s) => keep === undefined || keep(c, s));
542
- // the transition that made a situation: the first step of its parent that leads to it, as explore took it
543
- const via = new Map();
544
- const made = (i) => {
545
- let t = via.get(i);
546
- if (t === undefined) {
547
- const c = ex.configs[i];
548
- const p = ex.configs[c.parent];
549
- const s = stepsOf(p).find((x) => x.target === c.state && x.event === c.event && x.ctx.every((v, j) => v === c.ctx[j]));
550
- t = s?.taken ?? `${p.state}|${c.event ?? 'always'}|?`;
551
- via.set(i, t);
552
- }
553
- return t;
554
- };
555
- const chain = (i) => {
556
- const out = [];
557
- for (let k = i; k >= 0; k = ex.configs[k].parent)
558
- out.push(k);
559
- return out.reverse();
560
- };
561
- const candidates = [];
562
- if (by === 'states') {
563
- const first = new Map();
564
- ex.configs.forEach((c, i) => {
565
- if (!first.has(c.state))
566
- first.set(c.state, i);
567
- });
568
- for (const i of first.values())
569
- candidates.push({ at: i, depth: chain(i).length });
570
- }
571
- else {
572
- // the first situation, in exploration order, at which each transition is taken: the end of a shortest way to it
573
- const seen = new Set();
574
- for (let i = 0; i < ex.configs.length && seen.size < ex.taken.size; i++) {
575
- for (const s of stepsOf(ex.configs[i])) {
576
- if (seen.has(s.taken))
577
- continue;
578
- seen.add(s.taken);
579
- candidates.push({ at: i, last: s, depth: chain(i).length + 1 });
580
- }
581
- }
582
- }
583
- const covered = new Set();
584
- const paths = [];
585
- const order = (c) => c.at * 2 + (c.last === undefined ? 0 : 1);
586
- for (const c of [...candidates].sort((a, b) => b.depth - a.depth || order(a) - order(b))) {
587
- const links = chain(c.at);
588
- const states = links.map((k) => ex.configs[k].state);
589
- const transitions = links.slice(1).map(made);
590
- const events = links.slice(1).flatMap((k) => (ex.configs[k].event === null ? [] : [ex.configs[k].event]));
591
- if (c.last !== undefined) {
592
- states.push(c.last.target);
593
- transitions.push(c.last.taken);
594
- if (c.last.event !== null)
595
- events.push(c.last.event);
596
- }
597
- const covers = [...new Set(by === 'states' ? states : transitions)].filter((x) => !covered.has(x));
598
- if (covers.length === 0)
599
- continue;
600
- for (const x of covers)
601
- covered.add(x);
602
- const start = m.scenario(ex.configs[links[0]].ctx);
603
- paths.push({ id: hash(JSON.stringify([start, transitions])), start, events, states, transitions, covers, order: order(c) });
604
- }
605
- paths.sort((a, b) => a.order - b.order);
606
- const all = by === 'states' ? Object.keys(m.flow.states) : transitionsOf(m.flow);
607
- return { by, paths: paths.map(({ order: _, ...p }) => p), unreached: all.filter((x) => !covered.has(x)) };
608
- }
@@ -1,15 +0,0 @@
1
- import type { Finding, Goalcheck, MenuRow, NavGraph, PersonaView, RepoCheck } from './nav.ts';
2
- export interface NavPageInput {
3
- g: NavGraph;
4
- views: PersonaView[];
5
- rows: MenuRow[];
6
- goals: Goalcheck[];
7
- found: Finding[];
8
- repo: {
9
- checks: RepoCheck[];
10
- head: string | null;
11
- } | null;
12
- warnings: string[];
13
- }
14
- export declare function renderNavPage(p: NavPageInput): string;
15
- export declare function renderNavMermaid(g: NavGraph): string;