@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/schemas.js DELETED
@@ -1,266 +0,0 @@
1
- // The JSON Schemas of schemas/ (one per kind of graph file, SPEC.md §12) as `check` applies them: a file is validated
2
- // against its kind's schema, and each failure is placed at its line and column through the YAML document and said in
3
- // words a writer can act on: the key that is not one, the key it was probably meant to be, why an if/then rule exists
4
- // (its `$comment`), and the comma that cut a value inside `{ }`. The schemas are read from the package's own folder,
5
- // beside src/ and dist/ alike.
6
- import { existsSync, readFileSync } from 'node:fs';
7
- import { basename, dirname, join } from 'node:path';
8
- import { Ajv2020 } from 'ajv/dist/2020.js';
9
- import addFormatsModule from 'ajv-formats';
10
- import { isMap, isSeq, LineCounter, parseDocument } from 'yaml';
11
- import { readYaml, unsupported } from './yaml.js';
12
- import { isDomainText, mayBeDomain } from './domain.js';
13
- const FORMAT = 'delurio-graph/0';
14
- const KINDS = ['flow', 'ui', 'domain', 'nav', 'catalog', 'needs', 'gaps'];
15
- // the kind of graph file, by its name, and a domain also by its `kind` (a domain may be split across files, SPEC.md
16
- // §5): null for a file no schema covers (binding, tutorial, kit, anchors.lock)
17
- export function schemaKindOf(file) {
18
- const name = basename(file);
19
- if (name === 'flow.yaml' || name === 'ui.yaml' || name === 'domain.yaml' || name === 'needs.yaml')
20
- return name.slice(0, -'.yaml'.length);
21
- if (name === 'nav.yaml' || name === 'nav.extracted.yaml')
22
- return 'nav';
23
- if (name === 'needs.gaps.yaml')
24
- return 'gaps';
25
- if (name.endsWith('.json') && basename(dirname(file)) === 'catalog')
26
- return 'catalog';
27
- if (mayBeDomain(name) && existsSync(file) && isDomainText(readFileSync(file, 'utf8')))
28
- return 'domain';
29
- return null;
30
- }
31
- let compiled = null;
32
- // compiled once, on first use; strictRequired is off because an if/then names keys its branch does not declare
33
- function schemas() {
34
- if (compiled !== null)
35
- return compiled;
36
- const ajv = new Ajv2020({ allErrors: true, verbose: true, strict: true, strictRequired: false, allowUnionTypes: true });
37
- addFormatsModule.default(ajv);
38
- const roots = {};
39
- const validators = {};
40
- for (const kind of KINDS)
41
- roots[kind] = JSON.parse(readFileSync(new URL(`../schemas/${kind}.schema.json`, import.meta.url), 'utf8'));
42
- for (const kind of KINDS)
43
- validators[kind] = ajv.compile(roots[kind]);
44
- compiled = { roots, validators };
45
- return compiled;
46
- }
47
- const steps = (pointer) => (pointer === '' ? [] : pointer.slice(1).split('/').map((t) => t.replace(/~1/g, '/').replace(/~0/g, '~')));
48
- const escape = (step) => step.replace(/~/g, '~0').replace(/\//g, '~1');
49
- const within = (path, base) => path === base || path.startsWith(`${base}/`);
50
- const keyOf = (pair) => String(pair.key?.value ?? pair.key);
51
- // the YAML node at a JSON pointer; with `name`, the key `name` of the map there, that map and the key's value
52
- function place(doc, pointer, name) {
53
- let node = doc.contents;
54
- for (const t of steps(pointer)) {
55
- const next = isMap(node) ? node.items.find((p) => keyOf(p) === t)?.value : isSeq(node) ? node.items[Number(t)] : undefined;
56
- if (next === undefined || next === null)
57
- break;
58
- node = next;
59
- }
60
- if (name === undefined || !isMap(node))
61
- return { at: node };
62
- const pair = node.items.find((p) => keyOf(p) === name);
63
- return { at: pair?.key ?? node, map: node, value: pair?.value };
64
- }
65
- // a schema and the ones its `$ref`s name, inside the same file
66
- function chain(root, schema) {
67
- const out = [];
68
- for (let s = schema; s !== null && typeof s === 'object' && out.length < 8;) {
69
- const here = s;
70
- out.push(here);
71
- const ref = here.$ref;
72
- s = typeof ref === 'string' && ref.startsWith('#/') ? ref.slice(2).split('/').reduce((x, k) => x?.[k], root) : undefined;
73
- }
74
- return out;
75
- }
76
- // edits between two names, a swap of two neighbours counting as one (titel, title)
77
- function distance(a, b) {
78
- const d = Array.from({ length: a.length + 1 }, (_, i) => [i, ...Array(b.length).fill(0)]);
79
- for (let j = 1; j <= b.length; j++)
80
- d[0][j] = j;
81
- for (let i = 1; i <= a.length; i++) {
82
- for (let j = 1; j <= b.length; j++) {
83
- d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
84
- if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1])
85
- d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
86
- }
87
- }
88
- return d[a.length][b.length];
89
- }
90
- const KIND_WORDS = { object: 'an object', array: 'a list', string: 'a string', integer: 'an integer', number: 'a number', boolean: 'true or false', null: 'null' };
91
- const either = (xs) => (xs.length <= 1 ? xs.join('') : `${xs.slice(0, -1).join(', ')} or ${xs[xs.length - 1]}`);
92
- const quoted = (xs) => either(xs.map((x) => JSON.stringify(x)));
93
- function message(e, root) {
94
- const p = e.params;
95
- switch (e.keyword) {
96
- case 'additionalProperties':
97
- case 'unevaluatedProperties': {
98
- const name = String(p.additionalProperty ?? p.unevaluatedProperty);
99
- const known = chain(root, e.parentSchema).flatMap((x) => Object.keys(x.properties ?? {}));
100
- const near = known.filter((k) => distance(k.toLowerCase(), name.toLowerCase()) <= Math.min(2, Math.max(1, Math.floor(k.length / 3))));
101
- return `"${name}" is not a key here${near.length > 0 ? `; did you mean ${quoted(near)}?` : ''}`;
102
- }
103
- case 'required':
104
- return `${p.missingProperty.map((k) => JSON.stringify(k)).join(' or ')} is missing`;
105
- case 'enum': {
106
- const allowed = p.allowedValues;
107
- return allowed.length <= 12 ? `must be ${quoted(allowed)}` : `${JSON.stringify(e.data)} is not one of its ${allowed.length} values`;
108
- }
109
- case 'const':
110
- return `must be ${JSON.stringify(p.allowedValue)}`;
111
- case 'type':
112
- return `must be ${either(p.type.map((t) => KIND_WORDS[t] ?? t))}`;
113
- case 'pattern':
114
- return `${JSON.stringify(e.data)} does not match ${String(p.pattern)}`;
115
- case 'propertyNames': {
116
- const said = chain(root, e.parentSchema?.propertyNames).find((x) => typeof x.description === 'string')?.description;
117
- return `the name "${String(p.propertyName)}" is not allowed${said === undefined ? '' : `: ${said.split('. ')[0].replace(/\.$/, '')}`}`;
118
- }
119
- case 'false schema':
120
- return 'is not allowed here';
121
- case 'oneOf':
122
- return 'matches more than one of its forms';
123
- case 'minItems':
124
- case 'maxItems':
125
- case 'minProperties':
126
- case 'maxProperties': {
127
- const n = Number(p.limit);
128
- const what = e.keyword.endsWith('Items') ? (n === 1 ? 'item' : 'items') : n === 1 ? 'key' : 'keys';
129
- return e.keyword.startsWith('min') ? `needs at least ${n} ${what}` : `has more than ${n} ${what}`;
130
- }
131
- default:
132
- return e.message ?? e.keyword;
133
- }
134
- }
135
- // Ajv reports every alternative of an anyOf and every rule around a then; keep what the writer can act on
136
- function simplify(errors) {
137
- // the reason for an if/then rule, from its $comment, goes onto the errors its then or else gave (just before it)
138
- errors.forEach((e, i) => {
139
- const comment = e.parentSchema?.$comment;
140
- if (e.keyword !== 'if' || typeof comment !== 'string')
141
- return;
142
- const base = e.schemaPath.slice(0, -'/if'.length);
143
- for (let j = i - 1; j >= 0; j--) {
144
- const x = errors[j];
145
- if (!within(x.instancePath, e.instancePath) || !(x.schemaPath.startsWith(`${base}/then/`) || x.schemaPath.startsWith(`${base}/else/`)))
146
- break;
147
- x.because = comment;
148
- }
149
- });
150
- const wrapper = (x) => ['if', 'anyOf', 'oneOf'].includes(x.keyword);
151
- const explained = (e) => errors.some((x) => x !== e && !wrapper(x) && ((x.instancePath !== e.instancePath && within(x.instancePath, e.instancePath)) || (x.instancePath === e.instancePath && x.keyword !== 'type')));
152
- const kept = errors.filter((e) => {
153
- if (e.keyword === 'if')
154
- return false; // its then or else said it
155
- if (e.keyword === 'anyOf' || (e.keyword === 'oneOf' && e.params.passingSchemas === null)) {
156
- return !explained(e) && !errors.some((x) => x !== e && x.keyword === 'type' && x.instancePath === e.instancePath);
157
- }
158
- if (e.keyword === 'type')
159
- return !explained(e); // an alternative of the right type is there, and failed further in
160
- if (e.propertyName !== undefined)
161
- return false; // the name's own failure; its propertyNames error says it
162
- return true;
163
- });
164
- // what is left at one place in one form is one line: the types the alternatives want, the keys of which one is needed
165
- const out = [];
166
- for (const e of kept) {
167
- const alternative = e.keyword === 'required' && /\/(anyOf|oneOf)\/\d+\/required$/.test(e.schemaPath);
168
- const twin = out.find((x) => x.instancePath === e.instancePath && x.keyword === e.keyword && (e.keyword === 'type' || (alternative && x.alternative === true)));
169
- const p = e.params;
170
- if (twin !== undefined && e.keyword === 'type')
171
- twin.params.type = [...new Set([...twin.params.type, ...[p.type].flat()])];
172
- else if (twin !== undefined)
173
- twin.params.missingProperty.push(p.missingProperty);
174
- else {
175
- const params = e.keyword === 'type' ? { type: [p.type].flat() } : e.keyword === 'required' ? { missingProperty: [p.missingProperty] } : e.params;
176
- out.push({ ...e, alternative, params });
177
- }
178
- }
179
- return out;
180
- }
181
- // the id of the graph a file belongs to, when the file does not say it: the flow, nav or ui graph beside it
182
- function graphIdBeside(dir) {
183
- for (const name of ['flow.yaml', 'nav.yaml', 'ui.yaml']) {
184
- const file = join(dir, name);
185
- if (!existsSync(file))
186
- continue;
187
- try {
188
- const id = readYaml(readFileSync(file, 'utf8'))?.id;
189
- if (typeof id === 'string')
190
- return id;
191
- }
192
- catch {
193
- // a graph file that does not parse names no graph; its own check says why
194
- }
195
- }
196
- return null;
197
- }
198
- // every place where the file does not follow its kind's schema; a file written for another format is left to the
199
- // format check
200
- export function validateFile(file) {
201
- const kind = schemaKindOf(file);
202
- if (kind === null)
203
- return [];
204
- const text = readFileSync(file, 'utf8');
205
- const refused = kind === 'catalog' ? null : unsupported(text);
206
- const lineCounter = new LineCounter();
207
- const doc = parseDocument(text, { lineCounter, prettyErrors: false });
208
- const at = (offset) => {
209
- const { line, col } = lineCounter.linePos(offset ?? 0);
210
- return { line, column: col };
211
- };
212
- const ownFile = kind === 'catalog' ? `catalog/${basename(file)}` : basename(file);
213
- let graph = null;
214
- const failure = (where, said, pointer) => {
215
- graph ??= graphIdBeside(kind === 'catalog' ? dirname(dirname(file)) : dirname(file));
216
- return { ...where, message: said, graph, element: `${ownFile}#${pointer}` };
217
- };
218
- // the first YAML error only: the ones after it mostly follow from it; one before the unsupported place comes first
219
- if (refused !== null && (doc.errors.length === 0 || refused.offset < doc.errors[0].pos[0]))
220
- return [failure(refused, refused.message, '')];
221
- if (doc.errors.length > 0)
222
- return [failure(at(doc.errors[0].pos[0]), `not YAML: ${doc.errors[0].message.split('\n')[0]}`, '')];
223
- let data;
224
- if (kind === 'catalog') {
225
- try {
226
- data = JSON.parse(text);
227
- }
228
- catch (err) {
229
- return [failure({ line: 1, column: 1 }, `not JSON: ${err.message}`, '')];
230
- }
231
- }
232
- else
233
- data = doc.toJS();
234
- const own = data ?? {};
235
- if (kind !== 'catalog' && typeof own.schema === 'string' && own.schema !== FORMAT)
236
- return [];
237
- if (kind !== 'catalog' && typeof own.id === 'string')
238
- graph = own.id;
239
- const { roots, validators } = schemas();
240
- const validate = validators[kind];
241
- if (validate(data))
242
- return [];
243
- const out = [];
244
- for (const e of simplify((validate.errors ?? []))) {
245
- const p = e.params;
246
- const named = p.additionalProperty ?? p.unevaluatedProperty ?? p.propertyName;
247
- const name = named === undefined ? undefined : String(named);
248
- const where = place(doc, e.instancePath, name);
249
- const path = steps(e.instancePath).join('.');
250
- let said = `${path === '' ? 'the file' : path}: ${message(e, roots[kind])}`;
251
- const because = e.because ?? (e.keyword === 'false schema' ? undefined : e.parentSchema?.$comment);
252
- if (typeof because === 'string')
253
- said += ` (${because})`;
254
- // `{ title: Done, and paid }` is a title and a key "and paid": YAML ends a flow mapping's value at the comma
255
- const empty = where.value === null || where.value?.value === null;
256
- if (name !== undefined && where.map?.flow === true && empty)
257
- said += '; a comma inside { } ends the value before it: quote that value';
258
- const missing = e.keyword === 'required' ? p.missingProperty.join('|') : undefined;
259
- const pointer = name !== undefined ? `${e.instancePath}/${escape(name)}` : missing !== undefined ? `${e.instancePath}/${escape(missing)}` : e.instancePath;
260
- const range = where.at?.range;
261
- const finding = failure(at(range?.[0]), said, pointer);
262
- if (!out.some((x) => x.line === finding.line && x.column === finding.column && x.message === finding.message))
263
- out.push(finding);
264
- }
265
- return out;
266
- }
package/dist/spine.js DELETED
@@ -1,156 +0,0 @@
1
- import ElkModule from 'elkjs/lib/elk.bundled.js';
2
- import { collectEdges, kindOf, nodeLine, wrap } from './edges.js';
3
- import { titleOf } from './graph.js';
4
- // elkjs ships CommonJS: under Node ESM the default import is module.exports, which is the constructor
5
- const Elk = ElkModule;
6
- const START = '__start';
7
- const CHAR_TITLE = 8.4; // 14px semibold sans
8
- const CHAR_LINE = 6.9; // 11.5px monospace
9
- const CHAR_LABEL = 7.1; // 13px sans
10
- const LABEL_WRAP = { main: 26, full: 22 };
11
- const esc = (s) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
12
- const r1 = (n) => Math.round(n * 10) / 10;
13
- function labelLines(e, view) {
14
- return e.labels.flatMap((l) => wrap(l, LABEL_WRAP[view]));
15
- }
16
- /**
17
- * The flow's diagram as an SVG. Every state's group carries `data-state`, and every edge and its label `data-from` and
18
- * `data-to`: one edge is drawn per pair of states, its label holding every transition between them. `story`: the
19
- * states to draw as the story (`on-main`), in order.
20
- */
21
- export async function renderSpine(g, ex, view, story) {
22
- const all = collectEdges(g, ex);
23
- // main view: the story without failure branches and without "the user closes the page"
24
- const edges = view === 'full' ? all : all.filter((e) => e.kind !== 'fail' && !e.leave);
25
- const visible = new Set([g.flow.initial]);
26
- for (const e of edges) {
27
- visible.add(e.from);
28
- visible.add(e.to);
29
- }
30
- const names = Object.keys(g.flow.states).filter((n) => visible.has(n));
31
- const mainEdges = new Set();
32
- const mainNodes = new Set();
33
- (story ?? []).forEach((s, k) => {
34
- mainNodes.add(s.state);
35
- if (k > 0)
36
- mainEdges.add(`${story?.[k - 1].state}>${s.state}`);
37
- });
38
- const children = [{ id: START, width: 14, height: 14 }];
39
- for (const name of names) {
40
- const width = Math.ceil(Math.max(150, titleOf(g.flow, name).length * CHAR_TITLE, nodeLine(g, name).length * CHAR_LINE) + 36);
41
- const node = { id: name, width, height: 58 };
42
- if (kindOf(g, name) === 'exit')
43
- node.layoutOptions = { 'elk.layered.layering.layerConstraint': 'LAST' };
44
- children.push(node);
45
- }
46
- const elkEdges = [{ id: 'e_start', sources: [START], targets: [g.flow.initial] }];
47
- edges.forEach((e, i) => {
48
- const lines = labelLines(e, view);
49
- elkEdges.push({
50
- id: `e${i}`,
51
- sources: [e.from],
52
- targets: [e.to],
53
- labels: lines.length === 0
54
- ? []
55
- : [{ text: lines.join('\n'), width: Math.ceil(Math.max(...lines.map((l) => l.length)) * CHAR_LABEL + 14), height: lines.length * 17 + 6 }],
56
- });
57
- });
58
- const root = {
59
- id: 'root',
60
- layoutOptions: {
61
- 'elk.algorithm': 'layered',
62
- 'elk.direction': 'DOWN',
63
- 'elk.edgeRouting': 'ORTHOGONAL',
64
- 'elk.padding': '[top=24,left=24,bottom=24,right=24]',
65
- 'elk.spacing.nodeNode': '36',
66
- 'elk.spacing.edgeNode': '22',
67
- 'elk.spacing.edgeEdge': '16',
68
- 'elk.spacing.edgeLabel': '6',
69
- 'elk.layered.spacing.nodeNodeBetweenLayers': '56',
70
- 'elk.layered.spacing.edgeNodeBetweenLayers': '22',
71
- 'elk.layered.considerModelOrder.strategy': 'NODES_AND_EDGES',
72
- },
73
- children,
74
- edges: elkEdges,
75
- };
76
- const laid = await new Elk().layout(root);
77
- const width = Math.ceil(laid.width ?? 800);
78
- const height = Math.ceil(laid.height ?? 400);
79
- const out = [];
80
- out.push(`<svg class="spine" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${width} ${height}" style="${view === 'full' ? `width:${width}px;max-width:none` : `max-width:${width}px`}" role="img" aria-label="Flowchart of ${esc(g.flow.title ?? g.flow.id)}${view === 'main' ? ' without failure paths' : ' with failure paths'}. The text sections of this page describe every step.">`);
81
- out.push('<defs>');
82
- for (const kind of ['user', 'system', 'route', 'fail', 'main']) {
83
- out.push(`<marker id="arrow-${view}-${kind}" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="8" markerHeight="8" orient="auto-start-reverse"><path class="arrow arrow-${kind}" d="M0 0 L10 5 L0 10 z"/></marker>`);
84
- }
85
- out.push('</defs>');
86
- const byId = new Map();
87
- edges.forEach((e, i) => byId.set(`e${i}`, e));
88
- const drawn = (laid.edges ?? []).filter((e) => e.sections?.[0] !== undefined);
89
- const isMain = (e) => e !== undefined && mainEdges.has(`${e.from}>${e.to}`);
90
- // which states an edge joins, so a tool can find the drawing of a transition: one edge per pair of states
91
- const ends = (e) => `data-from="${esc(e.from)}" data-to="${esc(e.to)}"`;
92
- const path = (e) => {
93
- const section = e.sections?.[0];
94
- if (section === undefined)
95
- return '';
96
- const pts = [section.startPoint, ...(section.bendPoints ?? []), section.endPoint];
97
- return pts.map((p, i) => `${i === 0 ? 'M' : 'L'}${r1(p.x)} ${r1(p.y)}`).join(' ');
98
- };
99
- for (const e of drawn) {
100
- if (e.id === 'e_start')
101
- out.push(`<path class="edge edge-system" d="${path(e)}" marker-end="url(#arrow-${view}-system)"/>`);
102
- }
103
- for (const pass of [false, true]) {
104
- for (const e of drawn) {
105
- const viz = byId.get(e.id);
106
- if (viz === undefined || isMain(viz) !== pass)
107
- continue;
108
- const kind = pass ? 'main' : viz.kind;
109
- out.push(`<path class="edge edge-${kind}${viz.unused ? ' edge-unused' : ''}" ${ends(viz)} d="${path(e)}" marker-end="url(#arrow-${view}-${kind})"/>`);
110
- }
111
- }
112
- for (const e of drawn) {
113
- const viz = byId.get(e.id);
114
- const label = e.labels?.[0];
115
- if (viz === undefined || label === undefined)
116
- continue;
117
- const lines = labelLines(viz, view);
118
- const x = label.x ?? 0;
119
- const y = label.y ?? 0;
120
- out.push(`<g class="elabel${isMain(viz) ? ' elabel-main' : ''}${viz.kind === 'fail' ? ' elabel-fail' : ''}" ${ends(viz)}><rect x="${r1(x)}" y="${r1(y)}" width="${label.width ?? 0}" height="${label.height ?? 0}" rx="4"/>`);
121
- lines.forEach((l, i) => out.push(`<text x="${r1(x + 7)}" y="${r1(y + 17 + i * 17)}">${esc(l)}</text>`));
122
- out.push('</g>');
123
- }
124
- for (const n of laid.children ?? []) {
125
- const x = r1(n.x ?? 0);
126
- const y = r1(n.y ?? 0);
127
- const w = n.width ?? 0;
128
- const h = n.height ?? 0;
129
- if (n.id === START) {
130
- out.push(`<circle class="start" cx="${r1(x + 7)}" cy="${r1(y + 7)}" r="7"><title>start</title></circle>`);
131
- continue;
132
- }
133
- const kind = kindOf(g, n.id);
134
- const st = g.flow.states[n.id];
135
- const exitClass = kind === 'exit' ? ` exit-${st.leavesPage === true ? 'left' : (st.redirect ?? 'error')}` : '';
136
- const unreachable = !ex.atState.has(n.id);
137
- const open = kind === 'screen' ? `<a href="#screen-${esc(n.id)}">` : '';
138
- const close = kind === 'screen' ? '</a>' : '';
139
- const by = st.by === undefined ? '' : ` by-${st.by}`;
140
- const tip = [st.description ?? n.id, ...(st.includes ?? []).map((s) => `+ ${s}`)].join('\n');
141
- out.push(`${open}<g class="node node-${kind}${by}${st.goal === true ? ' goal' : ''}${exitClass}${mainNodes.has(n.id) ? ' on-main' : ''}${unreachable ? ' node-unreachable' : ''}" data-state="${esc(n.id)}"><title>${esc(tip)}</title>`);
142
- const rx = kind === 'exit' || st.by === 'ai' ? 28 : st.by === 'ci' ? 0 : 8;
143
- out.push(`<rect x="${x}" y="${y}" width="${w}" height="${h}" rx="${rx}"/>`);
144
- if (st.by === 'agent')
145
- out.push(`<rect class="inner" x="${r1(x + 4)}" y="${r1(y + 4)}" width="${w - 8}" height="${h - 8}" rx="5"/>`);
146
- if ((st.includes ?? []).length > 0)
147
- out.push(`<text class="nmore" x="${r1(x + w - 8)}" y="${r1(y + 14)}" text-anchor="end">+${st.includes?.length}</text>`);
148
- if (kind === 'subflow')
149
- out.push(`<rect class="inner" x="${r1(x + 4)}" y="${r1(y + 4)}" width="${w - 8}" height="${h - 8}" rx="5"/>`);
150
- out.push(`<text class="nname" x="${r1(x + w / 2)}" y="${r1(y + 25)}" text-anchor="middle">${esc(titleOf(g.flow, n.id))}</text>`);
151
- out.push(`<text class="nline" x="${r1(x + w / 2)}" y="${r1(y + 44)}" text-anchor="middle">${esc(nodeLine(g, n.id))}${unreachable ? ' · unreachable' : ''}</text>`);
152
- out.push(`</g>${close}`);
153
- }
154
- out.push('</svg>');
155
- return out.join('\n');
156
- }
package/dist/starts.js DELETED
@@ -1,88 +0,0 @@
1
- // `starts:` on a transition: this flow starts another one and does not wait for it (SPEC.md §2, "Several flows").
2
- // The started flow is looked up by id among the graphs beside this one. When it is found, every situation in which the
3
- // transition is taken must give it a beginning it accepts; when it is not written yet, that is a note, not a failure.
4
- import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
5
- import { basename, dirname, join } from 'node:path';
6
- import { readYaml } from './yaml.js';
7
- import { alternatives } from './graph.js';
8
- const SKIP = new Set(['viz', 'video', 'node_modules', '.git']);
9
- // the root to search: the nearest folder called `graphs` above the graph, else the graph's parent
10
- function rootOf(dir) {
11
- for (let d = dir, i = 0; i < 5; i++, d = dirname(d))
12
- if (basename(d) === 'graphs')
13
- return d;
14
- return dirname(dir);
15
- }
16
- // every flow under root by its id; a flow.yaml that cannot be read is left out, as its own check reports it
17
- function flowsUnder(root, depth = 4, out = new Map()) {
18
- const file = join(root, 'flow.yaml');
19
- if (existsSync(file)) {
20
- let f = null;
21
- try {
22
- f = readYaml(readFileSync(file, 'utf8'));
23
- }
24
- catch {
25
- f = null;
26
- }
27
- if (typeof f?.id === 'string')
28
- out.set(f.id, { ...f, context: f.context ?? {} });
29
- }
30
- if (depth === 0)
31
- return out;
32
- for (const name of readdirSync(root)) {
33
- if (SKIP.has(name))
34
- continue;
35
- const sub = join(root, name);
36
- if (statSync(sub).isDirectory())
37
- flowsUnder(sub, depth - 1, out);
38
- }
39
- return out;
40
- }
41
- export function checkStarts(g, m, ex) {
42
- const out = [];
43
- let flows = null;
44
- for (const [name, st] of Object.entries(g.flow.states)) {
45
- const ways = [
46
- ...(st.always ?? []).map((t, i) => [null, i, t]),
47
- ...Object.entries(st.on ?? {}).flatMap(([event, spec]) => alternatives(spec).map((t, i) => [event, i, t])),
48
- ];
49
- for (const [event, i, t] of ways) {
50
- if (t.starts === undefined)
51
- continue;
52
- flows ??= flowsUnder(rootOf(g.dir));
53
- const given = t.starts.given ?? {};
54
- const started = flows.get(t.starts.flow);
55
- const hand = { from: name, event, flow: t.starts.flow, given, found: started !== undefined, problems: [] };
56
- out.push(hand);
57
- if (started === undefined)
58
- continue;
59
- const problem = (p) => {
60
- if (!hand.problems.includes(p))
61
- hand.problems.push(p);
62
- };
63
- for (const k of Object.keys(given))
64
- if (started.context[k] === undefined)
65
- problem(`${k} is not a variable of ${started.id}`);
66
- const taken = `${name}|${event ?? 'always'}|${i}`;
67
- for (const c of ex.configs) {
68
- if (c.state !== name)
69
- continue;
70
- for (const s of m.steps(c.state, c.ctx)) {
71
- if (s.taken !== taken)
72
- continue;
73
- for (const [k, expr] of Object.entries(given)) {
74
- const cv = started.context[k];
75
- if (cv === undefined)
76
- continue;
77
- const v = typeof expr === 'string' ? m.value(expr, name, s.ctx) : expr;
78
- if (!cv.values.includes(v))
79
- problem(`${k} would be ${JSON.stringify(v)}, which is not a value of ${started.id}'s ${k}`);
80
- else if (cv.initial !== 'any' && cv.initial !== v)
81
- problem(`${started.id} begins with ${k} = ${String(cv.initial)}, and here it would be ${String(v)}`);
82
- }
83
- }
84
- }
85
- }
86
- }
87
- return out;
88
- }
package/dist/story.js DELETED
@@ -1,109 +0,0 @@
1
- import { alternatives, titleOf } from './graph.js';
2
- import { kindOf, pressLabel } from './edges.js';
3
- export function stepsTo(m, ex, index) {
4
- const chain = [];
5
- for (let i = index; i >= 0; i = ex.configs[i].parent)
6
- chain.push(i);
7
- chain.reverse();
8
- return chain.map((ci, k) => {
9
- const c = ex.configs[ci];
10
- let taken = null;
11
- if (k > 0) {
12
- const prev = ex.configs[chain[k - 1]];
13
- const hit = m.steps(prev.state, prev.ctx).find((s) => s.target === c.state && s.event === c.event && s.ctx.join(',') === c.ctx.join(','));
14
- taken = hit?.taken ?? null;
15
- }
16
- return { state: c.state, ctx: c.ctx, event: c.event, taken };
17
- });
18
- }
19
- // The main story the graph declares: from a starting situation, send the events in order (`always` rules run by themselves).
20
- export function stepsByEvents(m, main) {
21
- const events = Array.isArray(main) ? main : main.events;
22
- const given = Array.isArray(main) ? {} : (main.given ?? {});
23
- for (const init of m.initials()) {
24
- if (Object.entries(given).some(([k, v]) => init[m.vars.indexOf(k)] !== v))
25
- continue;
26
- const path = walk(m, [{ state: m.flow.initial, ctx: init, event: null, taken: null }], events, 0);
27
- if (path !== null)
28
- return path;
29
- }
30
- return null;
31
- }
32
- // Depth first, in document order, so the first walk that sends every event wins; when an effect leaves several
33
- // situations (havoc), one that cannot go on gives way to the next.
34
- function walk(m, path, events, i) {
35
- if (path.length > 500)
36
- return null;
37
- const cur = path[path.length - 1];
38
- const steps = m.steps(cur.state, cur.ctx);
39
- const autos = steps.filter((s) => s.event === null);
40
- const next = autos.length > 0 ? autos : i < events.length ? steps.filter((s) => s.event === events[i]) : [];
41
- if (next.length === 0)
42
- return i === events.length ? path : null;
43
- for (const s of next) {
44
- const found = walk(m, [...path, { state: s.target, ctx: s.ctx, event: s.event, taken: s.taken }], events, autos.length > 0 ? i : i + 1);
45
- if (found !== null)
46
- return found;
47
- }
48
- return null;
49
- }
50
- // The first success exit reachable through at least one screen: the story a person expects to read first.
51
- export function mainStoryIndex(g, ex) {
52
- const viaScreen = [];
53
- ex.configs.forEach((c, i) => {
54
- viaScreen[i] = kindOf(g, c.state) === 'screen' || (c.parent >= 0 && viaScreen[c.parent]);
55
- });
56
- for (const [name, st] of Object.entries(g.flow.states)) {
57
- if (st.type !== 'final' || st.redirect !== 'success')
58
- continue;
59
- const i = ex.configs.findIndex((c, idx) => c.state === name && viaScreen[idx]);
60
- if (i >= 0)
61
- return i;
62
- }
63
- return null;
64
- }
65
- function sayOf(g, taken) {
66
- if (taken === null)
67
- return null;
68
- const [state, event, idx] = taken.split('|');
69
- const st = g.flow.states[state];
70
- const a = event === 'always' ? st.always?.[Number(idx)] : alternatives(st.on?.[event] ?? []).at(Number(idx));
71
- return a?.say ?? null;
72
- }
73
- const capital = (s) => s.charAt(0).toUpperCase() + s.slice(1);
74
- export function narrate(g, m, steps) {
75
- const start = steps[0];
76
- const parts = [];
77
- m.vars.forEach((v, i) => {
78
- const cv = g.flow.context[v];
79
- if (cv.initial !== 'any')
80
- return;
81
- const said = cv.say?.[String(start.ctx[i])];
82
- if (said === undefined)
83
- parts.push(`${v} is ${start.ctx[i]}`);
84
- else if (said !== '')
85
- parts.push(said);
86
- });
87
- const lines = [];
88
- steps.forEach((s, k) => {
89
- if (g.flow.states[s.state].type === 'final')
90
- return;
91
- const next = steps[k + 1];
92
- let line = titleOf(g.flow, s.state);
93
- if (next !== undefined) {
94
- const say = sayOf(g, next.taken);
95
- const press = next.event === null ? null : pressLabel(g, s.state, next.event);
96
- if (press !== null)
97
- line += `: the user presses “${press}”`;
98
- else if (say !== null)
99
- line += next.event?.startsWith('FAIL') === true ? `: it fails, because ${say}` : `: ${say}`;
100
- }
101
- lines.push(line);
102
- });
103
- const last = steps[steps.length - 1];
104
- return {
105
- given: parts.length > 0 ? capital(parts.join(', ')) : 'Any request',
106
- steps: lines,
107
- result: titleOf(g.flow, last.state),
108
- };
109
- }
@@ -1,9 +0,0 @@
1
- import type { Graph } from './graph.ts';
2
- import type { Exploration, Model } from './model.ts';
3
- export interface TutorialProblem {
4
- path: string[];
5
- line?: number;
6
- column?: number;
7
- message: string;
8
- }
9
- export declare function checkTutorial(g: Graph, m: Model, ex: Exploration, text: string): TutorialProblem[];