@intentius/behold 0.30.1 → 0.30.2

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 (56) hide show
  1. package/AGENTS.md +31 -1
  2. package/README.md +11 -6
  3. package/dist/cli.js +1516 -840
  4. package/example-choudoufu-estate/chant.workspace.json +1 -1
  5. package/example-terraform-estate/README.md +1 -1
  6. package/example-terraform-estate/chant.workspace.json +1 -1
  7. package/example-terralith/README.md +1 -1
  8. package/example-three-cloud/package-lock.json +19 -19
  9. package/example-three-cloud/package.json +4 -4
  10. package/package.json +5 -5
  11. package/web/app.js +263 -16
  12. package/web/embed.js +2 -2
  13. package/web/event-help-modal.js +18 -12
  14. package/web/event-help-modal.test.js +28 -1
  15. package/web/index.html +18 -0
  16. package/web/kiosk-ask-layout.js +85 -0
  17. package/web/kiosk-ask-layout.test.js +83 -0
  18. package/web/kiosk-ask-tips.js +467 -0
  19. package/web/kiosk-ask-tips.test.js +359 -0
  20. package/web/kiosk-ask.js +774 -0
  21. package/web/kiosk-ask.test.js +593 -0
  22. package/web/kiosk-banner.js +108 -0
  23. package/web/kiosk-banner.test.js +72 -0
  24. package/web/kiosk-center-cards.test.js +110 -0
  25. package/web/kiosk-estate-scene.js +203 -0
  26. package/web/kiosk-estate-scene.test.js +21 -0
  27. package/web/kiosk-event-help.js +4 -1
  28. package/web/kiosk-graph-pane.js +63 -0
  29. package/web/kiosk-graph-pane.test.js +105 -0
  30. package/web/kiosk-light-frame.js +196 -0
  31. package/web/kiosk-light.js +509 -0
  32. package/web/kiosk-light.test.js +297 -0
  33. package/web/kiosk-metrics.js +7 -4
  34. package/web/kiosk-modal-sticky.test.js +2 -1
  35. package/web/kiosk-refit.test.js +81 -0
  36. package/web/kiosk-reset.js +49 -0
  37. package/web/kiosk-reset.test.js +11 -0
  38. package/web/kiosk-shot.js +40 -2
  39. package/web/kiosk-shot.test.js +23 -1
  40. package/web/kiosk-vendor.js +85 -7
  41. package/web/kiosk-vendor.test.js +9 -9
  42. package/web/kiosk-watch.js +8 -4
  43. package/web/kiosk.html +107 -1
  44. package/web/kiosk.js +149 -23
  45. package/web/kiosk.test.js +25 -1
  46. package/web/small-stage.test.js +4 -0
  47. package/web/terragucci-change.js +30 -13
  48. package/web/tool-mark.js +4 -4
  49. package/web/tool-mark.test.js +1 -1
  50. package/web/vendors/atmos.svg +1 -0
  51. package/web/vendors/chant.svg +1 -0
  52. package/web/vendors/choudoufu.svg +1 -0
  53. package/web/vendors/terragrunt.svg +9 -0
  54. package/web/vendors/terragucci.svg +1 -0
  55. package/web/vendors/choudoufu-128.png +0 -0
  56. package/web/vendors/choudoufu-64.png +0 -0
@@ -0,0 +1,509 @@
1
+ // behold#937: what a demo step's `ask` does to the graph. Pure logic here (what to
2
+ // light, how many depend on it, each state's file and look, the unknown slot and
3
+ // when it fills); web/kiosk-light-frame.js draws it in the graph frame, and
4
+ // startKioskLight wires the pane's events (behold#936) to both.
5
+ //
6
+ // The contract with the pane (behold#936):
7
+ // behold:ask-hold a step began: the graph holds still (nothing changes on its own) until a turn replies.
8
+ // behold:ask-start detail { ask, step, scenario } before the reply types; we set
9
+ // window.beholdAskTokens = { dependents } so the reply can fill it.
10
+ // behold:ask-light same detail, as the reply starts to print; we light the graph.
11
+ // behold:ask-done same detail, after the reply; lit here only if ask-light did not already light this beat.
12
+ // behold:ask-status a step that carries only a status (no prompt), as its busy line shows: lit like ask-light.
13
+ // behold:ask-clear a new step with no ask; the lighting goes.
14
+ //
15
+ // Everything is read from what the kiosk already holds: /api/terragucci (the
16
+ // reports joined onto the cards: `cards`, `roots`, `unmatched`, `pull_request`)
17
+ // and the run view (`progress`: `states`, `reads`). Nothing here fetches.
18
+
19
+ /**
20
+ * Whether a run is one composed apply across estates, not waves: any of the docs (the terragucci read, its pull request,
21
+ * a run's metrics, the run view) carries `compose.estate` or `compose.roots`, an estate scene, or a composed wave.
22
+ * Text for such a run never counts or names waves.
23
+ */
24
+ export function composedRun(...docs) {
25
+ const one = (d) => {
26
+ if (!d || typeof d !== "object") return false;
27
+ const c = d.compose;
28
+ if (c && (c.estate === true || (Array.isArray(c.roots) && c.roots.length))) return true;
29
+ if (d.estateScene && Array.isArray(d.estateScene.roots) && d.estateScene.roots.length) return true;
30
+ if (Array.isArray(d.states) && d.states.some((w) => w && w.composed)) return true;
31
+ return !!(d.pull_request && one(d.pull_request)) || !!(d.run && d.run !== d && one(d.run));
32
+ };
33
+ return docs.some(one);
34
+ }
35
+
36
+ export const COMPOSED_WORDS = "applied together in one apply";
37
+ /** behold#969: a chant composed run's re-plan that the first approval covered (chant#4419): said on the stack it re-planned. */
38
+ export const COVERED_WORDS = "one approval covered the re-plan";
39
+
40
+ /** An address with its instance keys dropped: `aws_x.y["a"]` is `aws_x.y`. */
41
+ export const bare = (address) => String(address || "").replace(/\[(?:"(?:[^"\\]|\\.)*"|[^\]])*\]/g, "");
42
+
43
+ /** The key a step names a resource by: `<root>/<address>`. */
44
+ export const lightKey = (root, address) => `${root}/${address}`;
45
+
46
+ /** A resource's name and type, for a card that leads with its name: `terraform_data.subnet` is `subnet` over `terraform_data`. */
47
+ export function cardTitle(address) {
48
+ const tokens = bare(address).split(".");
49
+ let i = 0;
50
+ while (tokens[i] === "module" && i + 1 < tokens.length) i += 2;
51
+ if (tokens[i] === "data") i += 1;
52
+ const type = tokens[i] || "";
53
+ const name = tokens.slice(i + 1).join(".");
54
+ const inst = (String(address).match(/(\[[^\]]*\])$/) || [])[1] || "";
55
+ return name ? { name: name + inst, type } : { name: bare(address) + inst, type: "" };
56
+ }
57
+
58
+ /** The block a card id names after its `<member>/<root>/` prefix, as an address. */
59
+ function addressOfBlock(block) {
60
+ return String(block).split("/").join(".");
61
+ }
62
+
63
+ /**
64
+ * The roots a step can light: the checkout's, then every estate the composed run names that the checkout does not list
65
+ * (the scene carries those). Each is `{ member, name, path }`.
66
+ */
67
+ export function rootsOf(answer) {
68
+ const base = answer && Array.isArray(answer.roots) ? answer.roots : [];
69
+ const scene = answer && answer.estateScene && Array.isArray(answer.estateScene.roots) ? answer.estateScene.roots : [];
70
+ const extra = scene.filter((r) => r && !base.some((b) => b.path === r.path));
71
+ return [...base, ...extra];
72
+ }
73
+
74
+ /**
75
+ * The plan as the kiosk's terragucci read holds it: the changed resources by
76
+ * `<root>/<address>` (with the card each is, when the checkout has one), the
77
+ * reads edges between roots, and the blast radius' resource reaches.
78
+ */
79
+ export function planOf(answer, progress = null) {
80
+ const out = { roots: [], resources: new Map(), edges: [], reaches: new Map(), reads: [] };
81
+ if (!answer || answer.error || !Array.isArray(answer.roots)) return out;
82
+ out.roots = rootsOf(answer).map((r) => ({ path: r.path, member: r.member, name: r.name }));
83
+ const rootAt = (id) => {
84
+ let best = null;
85
+ for (const r of answer.roots) {
86
+ const prefix = `${r.member}/${r.name}/`;
87
+ if (String(id).startsWith(prefix) && (!best || prefix.length > best.prefix.length)) best = { prefix, root: r };
88
+ }
89
+ return best;
90
+ };
91
+ const add = (root, address, extra) => {
92
+ const key = lightKey(root, address);
93
+ const had = out.resources.get(key);
94
+ if (had) {
95
+ if (extra.cardId && !had.cardId) had.cardId = extra.cardId;
96
+ if (extra.values && extra.values.length && !had.values.length) had.values = extra.values;
97
+ return;
98
+ }
99
+ out.resources.set(key, { key, root, address, ...cardTitle(address), cardId: null, action: null, values: [], ...extra });
100
+ };
101
+ // behold#940: a composed choudoufu run's resources, as its reports state them (an estate keeps no state file, and the graph's cards are as of the base).
102
+ const scene = answer.estateScene && Array.isArray(answer.estateScene.roots) ? answer.estateScene.roots : [];
103
+ for (const r of scene) {
104
+ for (const res of r.resources || []) add(r.path, res.address, { cardId: `${r.member}/${r.name}/${res.address}`, action: res.action || null, values: Array.isArray(res.values) ? res.values : [] });
105
+ }
106
+ for (const [id, marks] of Object.entries(answer.cards || {})) {
107
+ const at = rootAt(id);
108
+ if (!at) continue;
109
+ const mark = (marks || []).find((m) => m.verdict === "wave") || (marks || []).find((m) => m.verdict === "plan");
110
+ if (!mark) continue;
111
+ const addresses = mark.addresses && mark.addresses.length ? mark.addresses : [addressOfBlock(id.slice(at.prefix.length))];
112
+ for (const address of addresses) {
113
+ const values = (mark.values || []).filter((v) => !v.address || v.address === address);
114
+ add(at.root.path, address, { cardId: id, action: mark.action || null, values });
115
+ }
116
+ }
117
+ for (const c of (answer.unmatched && answer.unmatched.changes) || []) {
118
+ if (c.verdict === "drift") continue;
119
+ add(c.root, c.address, { action: c.action || null });
120
+ }
121
+ const pr = answer.pull_request;
122
+ const seen = new Set();
123
+ const edge = (from, to) => {
124
+ const k = `${from}\u0000${to}`;
125
+ if (from && to && from !== to && !seen.has(k)) {
126
+ seen.add(k);
127
+ out.edges.push({ from, to }); // from the upstream to the root that reads it
128
+ }
129
+ };
130
+ if (pr) {
131
+ for (const r of pr.reads || []) {
132
+ edge(r.upstream, r.root);
133
+ out.reads.push(r);
134
+ }
135
+ for (const [root, ups] of Object.entries(pr.upstreams || {})) for (const u of ups || []) edge(u, root);
136
+ for (const res of (pr.blast && pr.blast.resources) || []) out.reaches.set(lightKey(res.root, res.address), res.reaches || []);
137
+ }
138
+ if (progress && Array.isArray(progress.reads)) for (const r of progress.reads) for (const u of r.reads || []) edge(u, r.root);
139
+ // A composed run's members come in the order it applies them. When no read names an order, each reads the one before.
140
+ if (!out.edges.length) {
141
+ const members = pr && Array.isArray(pr.waves) ? (pr.waves.map((w) => w.composed && w.composed.members).find((m) => Array.isArray(m) && m.length > 1) || []) : [];
142
+ for (let i = 1; i < members.length; i++) edge(members[i - 1].root, members[i].root);
143
+ }
144
+ return out;
145
+ }
146
+
147
+ const TAG_PATHS = new Set(["tags", "tags_all"]);
148
+
149
+ /**
150
+ * Whether a changed resource of a downstream root is one that depends on what the root reads: a resource the apply
151
+ * creates or replaces, or one whose changed attributes are more than its tags. A tag-only update (the estate's own
152
+ * bookkeeping, unknown at plan) depends on nothing upstream.
153
+ */
154
+ export function dependsOnUpstream(res) {
155
+ if (res.action !== "update") return true;
156
+ const values = Array.isArray(res.values) ? res.values : [];
157
+ return !values.length || values.some((v) => !TAG_PATHS.has(v.path));
158
+ }
159
+
160
+ /**
161
+ * Which resources a step lights. `ask.light` names seeds as `<root>/<address>`
162
+ * (an unmatched one is skipped, never an error); `ask.paths` adds what is
163
+ * downstream: every changed resource of a root that reads a lit root, through
164
+ * the reads and dependency edges, and what the blast radius says refers to a
165
+ * seed inside its root. Null when the step lights nothing.
166
+ */
167
+ export function selectLight(plan, ask) {
168
+ if (!ask || typeof ask !== "object") return null;
169
+ const wanted = Array.isArray(ask.light) ? ask.light.filter((x) => typeof x === "string") : [];
170
+ if (!wanted.length) return null;
171
+ const seeds = [];
172
+ const skipped = [];
173
+ for (const w of wanted) {
174
+ const hit = plan.resources.has(w) ? w : [...plan.resources.keys()].find((k) => bare(k) === bare(w));
175
+ if (hit) {
176
+ if (!seeds.includes(hit)) seeds.push(hit);
177
+ } else skipped.push(w);
178
+ }
179
+ if (!seeds.length) return null;
180
+ const downstream = new Set();
181
+ if (ask.paths === true && seeds.length) {
182
+ for (const s of seeds) for (const r of plan.reaches.get(s) || []) {
183
+ const k = lightKey(r.root, r.address);
184
+ if (plan.resources.has(k)) downstream.add(k);
185
+ }
186
+ // The roots that read a seed's root, and the roots that read those.
187
+ const queue = [...new Set(seeds.map((s) => plan.resources.get(s).root))];
188
+ const roots = new Set(queue);
189
+ while (queue.length) {
190
+ const up = queue.shift();
191
+ for (const e of plan.edges) if (e.from === up && !roots.has(e.to)) {
192
+ roots.add(e.to);
193
+ queue.push(e.to);
194
+ }
195
+ }
196
+ for (const r of plan.resources.values()) if (roots.has(r.root) && !seeds.includes(r.key) && !seeds.some((s) => plan.resources.get(s).root === r.root) && dependsOnUpstream(r)) downstream.add(r.key);
197
+ }
198
+ const lit = [...seeds, ...[...downstream].filter((k) => !seeds.includes(k))];
199
+ const cards = lit.map((k) => plan.resources.get(k).cardId).filter(Boolean);
200
+ const rootsLit = [...new Set(lit.map((k) => plan.resources.get(k).root))];
201
+ return { seeds, lit, dependents: lit.length - seeds.length, cardIds: cards, roots: rootsLit, skipped };
202
+ }
203
+
204
+ /** `{dependents}` for the pane's reply: the number of nodes the step's `paths` lights, beyond the ones it names. */
205
+ export function dependentsOf(answer, progress, ask) {
206
+ if (!ask || ask.paths !== true) return null;
207
+ const sel = selectLight(planOf(answer, progress), ask);
208
+ return sel ? sel.dependents : 0;
209
+ }
210
+
211
+ // ---------------------------------------------------------------------------
212
+ // The states: a file name each, a written mark, and one of three looks.
213
+ // ---------------------------------------------------------------------------
214
+
215
+ const lastSegment = (path) => String(path || "").split("/").filter(Boolean).pop() || String(path || "");
216
+
217
+ /** A root's state file name: its backend's key from the run view, else the root's path with `.tfstate`. */
218
+ export function stateFile(root, progress) {
219
+ const r = progress && Array.isArray(progress.reads) ? progress.reads.find((x) => x.root === root) : null;
220
+ if (r && typeof r.stateKey === "string" && r.stateKey) return { file: r.stateKey, from: "run" };
221
+ return { file: `${lastSegment(root)}.tfstate`, from: "path" };
222
+ }
223
+
224
+ /** A composed member's, or a plain wave root's, apply outcome from the run view. */
225
+ export function applyOf(root, progress) {
226
+ const states = progress && Array.isArray(progress.states) ? progress.states : [];
227
+ for (const w of states) {
228
+ const m = w.composed && Array.isArray(w.composed.members) ? w.composed.members.find((x) => x.root === root) : null;
229
+ if (m) return { apply: m.apply || null, state: m.state || null, wave: w.number, waveState: w.state, ...(m.covered ? { covered: m.covered } : {}) };
230
+ }
231
+ for (const w of states) {
232
+ if (!Array.isArray(w.roots) || !w.roots.includes(root)) continue;
233
+ const changed = !Array.isArray(w.changed) || w.changed.includes(root);
234
+ if (w.state === "applied") return { apply: changed ? "applied" : "no-changes", state: changed ? "written" : "unchanged", wave: w.number, waveState: w.state };
235
+ if (w.state === "failed") return { apply: "partial", state: "written", wave: w.number, waveState: w.state };
236
+ if (w.state === "refused" || w.state === "blocked" || w.state === "not-started") return { apply: "not-started", state: "unchanged", wave: w.number, waveState: w.state };
237
+ return { apply: null, state: null, wave: w.number, waveState: w.state };
238
+ }
239
+ return null;
240
+ }
241
+
242
+ /**
243
+ * The words on a root's badge in ask mode: no wave (a viewer has no use for one), and the step's own word. Follows the
244
+ * run view's outcome for the root when it has one, so the badge and the state label under the box agree.
245
+ * `st` is the root's state from rootStates; null when it has nothing to say.
246
+ */
247
+ export function badgeWords(st, root, progress) {
248
+ if (!st) return null;
249
+ if (st.state === "unchanged" || st.state === "outside") return st.words.replace(/^wave \d+ \u00b7 /, "");
250
+ const together = /composed/.test(st.words) ? " together" : "";
251
+ const a = applyOf(root, progress);
252
+ const apply = a && a.apply ? a.apply : st.state === "applied" ? "applied" : st.state === "failed" ? "partial" : st.state === "applying" ? "applying" : null;
253
+ if (apply === "applied" || apply === "no-changes") return `applied${together}`;
254
+ if (apply === "partial" || apply === "failed") return "partly applied";
255
+ if (apply === "not-started") return "not applied";
256
+ if (apply === "applying") return `applying${together}`;
257
+ return `planned${together}`;
258
+ }
259
+
260
+ export const LOOK_WORDS = { applied: "applied", partial: "partly applied", "not-applied": "not applied" };
261
+ const LOOK_OF = { applied: "applied", "no-changes": "applied", partial: "partial", failed: "partial", "not-started": "not-applied" };
262
+
263
+ /** Each root's state: `{ file, from, written, look }`. `look` is applied, partial, not-applied, or null while nothing is decided. */
264
+ export function stateMarks(answer, progress) {
265
+ const roots = answer && Array.isArray(answer.roots) ? rootsOf(answer).map((r) => r.path) : progress && Array.isArray(progress.reads) ? progress.reads.map((r) => r.root) : [];
266
+ // behold#940: an estate of choudoufu's has no state file: it holds records, one per resource, written as each applies.
267
+ const estate = !!(answer && answer.estateScene && Array.isArray(answer.estateScene.roots) && answer.estateScene.roots.length);
268
+ const out = {};
269
+ for (const root of roots) {
270
+ const a = applyOf(root, progress);
271
+ const file = estate ? { file: lastSegment(root), from: "estate", estate: true } : stateFile(root, progress);
272
+ out[root] = { ...file, written: !!a && a.state === "written", look: a && a.apply ? LOOK_OF[a.apply] || null : null, covered: !!(a && a.covered) };
273
+ }
274
+ return out;
275
+ }
276
+
277
+ /** The words of a state's label: its file (or an estate's name), its look, and that it was written. */
278
+ export function stateWords(m) {
279
+ return [m.estate ? m.file : `state ${m.file}`, m.look ? LOOK_WORDS[m.look] : null, m.written ? (m.estate ? "records written" : "written") : null, m.covered ? COVERED_WORDS : null].filter(Boolean).join(" \u00b7 ");
280
+ }
281
+
282
+ // ---------------------------------------------------------------------------
283
+ // The unknown value: a marked empty slot, and when it fills.
284
+ // ---------------------------------------------------------------------------
285
+
286
+ /**
287
+ * The resource whose creation makes a card's unknown input known: the blast
288
+ * radius' reach into it through an output, else a created resource of the root
289
+ * it reads, else itself (an output that is its own).
290
+ */
291
+ export function producerOf(plan, res) {
292
+ for (const [seed, reaches] of plan.reaches) {
293
+ if ((reaches || []).some((r) => r.root === res.root && r.address === res.address && r.through)) {
294
+ const p = plan.resources.get(seed);
295
+ if (p && p.key !== res.key) return p;
296
+ }
297
+ }
298
+ for (const r of plan.reads) {
299
+ if (r.root !== res.root || !(r.unknown && r.unknown.length)) continue;
300
+ const created = [...plan.resources.values()].filter((x) => x.root === r.upstream && x.action === "create");
301
+ const owner = created.find((x) => x.values.some((v) => v.unknown)) || created[0];
302
+ if (owner) return owner;
303
+ }
304
+ return res;
305
+ }
306
+
307
+ /** Every unknown attribute of the planned resources: `{ key, cardId, path, producer, text }`. */
308
+ export function unknownSlots(plan) {
309
+ const slots = [];
310
+ for (const res of plan.resources.values()) {
311
+ for (const v of res.values) {
312
+ if (!v.unknown) continue;
313
+ const producer = producerOf(plan, res);
314
+ slots.push({ key: res.key, cardId: res.cardId, root: res.root, address: res.address, path: v.path, producer: producer.key, producerRoot: producer.root, text: `not known until ${producer.name} exists` });
315
+ }
316
+ }
317
+ return slots;
318
+ }
319
+
320
+ /** The most attribute lines a card shows in ask mode. */
321
+ export const MAX_CARD_LINES = 2;
322
+
323
+ const isEmptyValue = (v) => v === undefined || v === null || v === "" || (Array.isArray(v) && !v.length);
324
+ const show = (v) => (typeof v === "string" ? v : JSON.stringify(v));
325
+
326
+ /**
327
+ * The attribute lines a card shows in ask mode, at most MAX_CARD_LINES for each card id: the attributes that were
328
+ * unknown at plan and read another estate's value (the ones the root's reads name, `subnet_id`, `vpc_id`, and any
329
+ * attribute an `ask.light` address names as `<root>/<address>.<attribute>`), then the attributes whose known value
330
+ * changed. Every other attribute is left out. Each line is `{ key, cardId, root, address, path, kind, producer,
331
+ * producerRoot, producerName, before, after }` with kind `unknown` or `changed`.
332
+ */
333
+ export function cardLines(plan, light = []) {
334
+ const lit = new Set((Array.isArray(light) ? light : []).filter((w) => typeof w === "string"));
335
+ const named = new Map();
336
+ for (const w of Array.isArray(light) ? light : []) {
337
+ if (typeof w !== "string") continue;
338
+ for (const res of plan.resources.values()) if (w.startsWith(`${res.key}.`) || w.startsWith(`${bare(res.key)}.`)) {
339
+ const tail = w.slice(w.indexOf(res.key) === 0 ? res.key.length + 1 : bare(res.key).length + 1);
340
+ if (!named.has(res.key)) named.set(res.key, new Set());
341
+ named.get(res.key).add(tail);
342
+ }
343
+ }
344
+ const lines = [];
345
+ for (const res of plan.resources.values()) {
346
+ if (!res.cardId) continue;
347
+ const readNames = new Set(plan.reads.filter((r) => r.root === res.root).flatMap((r) => r.unknown || []));
348
+ const asked = named.get(res.key) || new Set();
349
+ const reads = res.values.filter((v) => v.unknown && v.path !== "id" && (!("before" in v) || isEmptyValue(v.before)) && (readNames.has(v.path) || asked.has(v.path) || v.path === "subnet_id" || v.path === "vpc_id"));
350
+ const rank = (v) => (asked.has(v.path) ? 0 : readNames.has(v.path) ? 1 : v.path === "subnet_id" ? 2 : 3);
351
+ reads.sort((a, b) => rank(a) - rank(b));
352
+ // Rule 5: never a false or empty default (a created resource's `assign_ipv6_address_on_creation: false`): the before is a real value.
353
+ const changed = res.values.filter((v) => !v.unknown && v.path !== "id" && "before" in v && "after" in v && !isEmptyValue(v.before) && JSON.stringify(v.before) !== JSON.stringify(v.after));
354
+ // A report that names the property an update touches but states neither value (chant's change-set entries: property
355
+ // names only) still shows the line, as "Value: updated".
356
+ const touched = res.action === "update" ? res.values.filter((v) => !v.unknown && v.path !== "id" && !("before" in v) && !("after" in v)) : [];
357
+ const producer = reads.length ? producerOf(plan, res) : res;
358
+ // A lit resource, or a created one with nothing else to show, is never a blank card: it shows its id.
359
+ const isLit = lit.has(res.key) || lit.has(bare(res.key));
360
+ // Rule 1: a lit resource, or any created one whose id is unknown at plan, leads with its id.
361
+ const idKnown = res.values.some((v) => v.path === "id" && !v.unknown && "after" in v && !isEmptyValue(v.after));
362
+ const idUnknownAtPlan = res.action === "create" && !idKnown;
363
+ const idLine = !idKnown && (isLit || idUnknownAtPlan) ? [[{ path: "id", unknown: true }, "unknown", res]] : [];
364
+ const row = (v, kind, prod) => ({ key: res.key, cardId: res.cardId, root: res.root, address: res.address, path: v.path, kind, producer: prod.key, producerRoot: prod.root, producerName: prod.name, before: v.before, after: v.after });
365
+ for (const v of [...idLine, ...reads.map((x) => [x, "unknown"]), ...changed.map((x) => [x, "changed"]), ...touched.map((x) => [x, "changed"])].slice(0, MAX_CARD_LINES)) lines.push(row(v[0], v[1], v[2] || producer));
366
+ }
367
+ return lines;
368
+ }
369
+
370
+ /**
371
+ * A card line's look and words: unknown reads "known after apply" (amber, dashed); applied reads the real value (green),
372
+ * or the producer it was filled from when the apply report gives no value; a changed value reads `before -> after`.
373
+ * `{ state: "unknown" | "applied" | "changed", text }`.
374
+ */
375
+ export function lineState(line, answer, progress) {
376
+ if (line.kind === "unknown") {
377
+ const st = slotState({ key: line.key, cardId: line.cardId, path: line.path, producer: line.producer, producerRoot: line.producerRoot }, answer, progress);
378
+ if (!st.filled) return { state: "unknown", text: `${line.path}: known after apply` };
379
+ const path = st.path || line.path;
380
+ // "filled from" only when the apply report states no value. A resource that is its own producer was simply created.
381
+ if (st.value !== undefined) return { state: "applied", text: `${path}: ${show(st.value)}` };
382
+ return { state: "applied", text: line.producer === line.key ? `${line.path}: created` : `${line.path}: filled from ${line.producerName}` };
383
+ }
384
+ const a = applyOf(line.root, progress);
385
+ const done = !!a && (a.apply === "applied" || a.apply === "no-changes");
386
+ const stated = "before" in line && "after" in line && (line.before !== undefined || line.after !== undefined);
387
+ return { state: done ? "applied" : "changed", text: stated ? `${line.path}: ${show(line.before)} -> ${show(line.after)}` : `${line.path}: updated` };
388
+ }
389
+
390
+ /**
391
+ * Whether a slot has been filled, and with what. Filled once the producer's root
392
+ * has applied (the run view's member or wave). Its value is shown only when an
393
+ * apply-time report states one (`answer.applied`, what the root's newest applied
394
+ * wave wrote); run.json states none, so otherwise the slot is filled with no value.
395
+ */
396
+ export function slotState(slot, answer, progress) {
397
+ const a = applyOf(slot.producerRoot, progress);
398
+ const filled = !!a && (a.apply === "applied" || a.apply === "no-changes");
399
+ const wrote = slot.cardId && answer && answer.applied ? answer.applied[slot.cardId] : null;
400
+ const known = filled && wrote ? (wrote.values || []).filter((x) => !x.unknown && "after" in x) : [];
401
+ let v = known.find((x) => x.path === slot.path);
402
+ // behold#940: a resource that is its own producer (the subnet) shows what it exported when the exact attribute is not stated: its id, else its first value.
403
+ let path = slot.path;
404
+ if (!v && slot.producer === slot.key && slot.path !== "id") {
405
+ v = known.find((x) => x.path === "id") || known[0];
406
+ if (v) path = v.path;
407
+ }
408
+ return v ? { filled, value: v.after, ...(path !== slot.path ? { path } : {}) } : { filled };
409
+ }
410
+
411
+ // ---------------------------------------------------------------------------
412
+ // Wiring.
413
+ // ---------------------------------------------------------------------------
414
+
415
+ /** The message the frame takes: what to light, whether to ghost the second approval, and a token that changes with each beat (so the pulse plays once). */
416
+ export function lightMessage(sel, ask, token) {
417
+ return {
418
+ type: "behold:light",
419
+ labels: true, // the frame labels each state with its file once any step has had an ask
420
+ ids: sel ? sel.cardIds : [],
421
+ roots: sel ? sel.roots : [],
422
+ lit: !!sel,
423
+ ghost: !!(ask && ask.ghost === true),
424
+ light: ask && Array.isArray(ask.light) ? ask.light.filter((x) => typeof x === "string") : [],
425
+ token,
426
+ };
427
+ }
428
+
429
+ /** How long after a beat's reply to look again for the reads a step lights, while they are not in. */
430
+ export const RETRY_MS = [400, 800, 1600, 3200];
431
+
432
+ /**
433
+ * Listen for the pane's events and tell the frame. `post` sends a message to the
434
+ * frame; `getAnswer` and `getProgress` give the kiosk's current reads.
435
+ * Returns a stop function.
436
+ */
437
+ export function startKioskLight({ post, getAnswer, getProgress, win = typeof window !== "undefined" ? window : null }) {
438
+ if (!win) return () => {};
439
+ let last = null;
440
+ let n = 0;
441
+ const send = (m) => {
442
+ last = m;
443
+ post(m);
444
+ };
445
+ const askOf = (e) => (e && e.detail && e.detail.ask && typeof e.detail.ask === "object" ? e.detail.ask : null);
446
+ // Every step holds the graph the moment it begins, so a status-only step cannot let progress through before its busy line has shown.
447
+ const onHold = () => post({ type: "behold:hold" });
448
+ const onStart = (e) => {
449
+ const ask = askOf(e);
450
+ const d = ask ? dependentsOf(getAnswer(), getProgress(), ask) : null;
451
+ win.beholdAskTokens = d === null ? {} : { dependents: d };
452
+ // The graph holds still until this step's reply is done (or its status shows): progress is queued meanwhile.
453
+ post({ type: "behold:hold" });
454
+ };
455
+ // behold#940: the lit state is drawn the moment the reply starts (it used to wait for the reply to be done). When the reads the step lights are not in yet
456
+ // (the kiosk's own poll is behind the frame's), it asks again soon, never waiting for a poll's turn.
457
+ let litAsk = null;
458
+ const onLight = (e) => {
459
+ const ask = askOf(e);
460
+ litAsk = ask;
461
+ const wants = !!(ask && Array.isArray(ask.light) && ask.light.length);
462
+ const attempt = (k) => {
463
+ const sel = ask ? selectLight(planOf(getAnswer(), getProgress()), ask) : null;
464
+ n += 1;
465
+ const mine = n;
466
+ send(lightMessage(sel, ask, mine));
467
+ if (!sel && wants && k < RETRY_MS.length && typeof win.setTimeout === "function") {
468
+ win.setTimeout(() => {
469
+ if (n === mine) attempt(k + 1);
470
+ }, RETRY_MS[k]);
471
+ }
472
+ };
473
+ attempt(0);
474
+ };
475
+ // The reply has printed: already lit as it started, unless that word never came.
476
+ const onDone = (e) => {
477
+ const ask = askOf(e);
478
+ if (ask && ask === litAsk) return;
479
+ onLight(e);
480
+ };
481
+ // A step that carries only a status has no reply to wait for: it lights as soon as the pane says so.
482
+ const onStatus = (e) => onLight(e);
483
+ const onClear = () => {
484
+ n += 1;
485
+ litAsk = null;
486
+ win.beholdAskTokens = {};
487
+ send(lightMessage(null, null, n));
488
+ };
489
+ // A frame that reloaded asks nothing; it is told again when it says it has drawn.
490
+ const onMessage = (e) => {
491
+ if (last && e && e.data && e.data.type === "behold:drawn") post(last);
492
+ };
493
+ win.addEventListener("behold:ask-hold", onHold);
494
+ win.addEventListener("behold:ask-start", onStart);
495
+ win.addEventListener("behold:ask-light", onLight);
496
+ win.addEventListener("behold:ask-done", onDone);
497
+ win.addEventListener("behold:ask-status", onStatus);
498
+ win.addEventListener("behold:ask-clear", onClear);
499
+ win.addEventListener("message", onMessage);
500
+ return () => {
501
+ win.removeEventListener("behold:ask-hold", onHold);
502
+ win.removeEventListener("behold:ask-start", onStart);
503
+ win.removeEventListener("behold:ask-light", onLight);
504
+ win.removeEventListener("behold:ask-done", onDone);
505
+ win.removeEventListener("behold:ask-status", onStatus);
506
+ win.removeEventListener("behold:ask-clear", onClear);
507
+ win.removeEventListener("message", onMessage);
508
+ };
509
+ }