@turing-machine-js/visuals 7.0.0-alpha.6

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 (42) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/LICENSE +674 -0
  3. package/README.md +21 -0
  4. package/dist/applyHighlight.d.ts +42 -0
  5. package/dist/applyHighlight.js +191 -0
  6. package/dist/format.d.ts +22 -0
  7. package/dist/format.js +46 -0
  8. package/dist/graphIndexes.d.ts +31 -0
  9. package/dist/graphIndexes.js +58 -0
  10. package/dist/graphUtils.d.ts +37 -0
  11. package/dist/graphUtils.js +76 -0
  12. package/dist/highlightOps.d.ts +81 -0
  13. package/dist/highlightOps.js +36 -0
  14. package/dist/index.cjs +514 -0
  15. package/dist/index.d.ts +9 -0
  16. package/dist/index.js +6 -0
  17. package/dist/index.mjs +503 -0
  18. package/dist/recordSnippet.d.ts +35 -0
  19. package/dist/recordSnippet.js +92 -0
  20. package/dist/types.d.ts +92 -0
  21. package/dist/types.js +1 -0
  22. package/docs/graph-highlight-and-breakpoints.md +272 -0
  23. package/package.json +46 -0
  24. package/src/applyHighlight.spec.ts +331 -0
  25. package/src/applyHighlight.ts +217 -0
  26. package/src/fixtures/graphs/post-walk-mark.json +108 -0
  27. package/src/fixtures/graphs/turing-callable-subtree.json +108 -0
  28. package/src/fixtures/graphs/turing-copy-two-tapes.json +87 -0
  29. package/src/fixtures/graphs/turing-replace-b.json +72 -0
  30. package/src/format.spec.ts +100 -0
  31. package/src/format.ts +51 -0
  32. package/src/graphIndexes.ts +84 -0
  33. package/src/graphUtils.spec.ts +112 -0
  34. package/src/graphUtils.ts +74 -0
  35. package/src/highlightOps.ts +94 -0
  36. package/src/index.ts +10 -0
  37. package/src/recordSnippet.spec.ts +275 -0
  38. package/src/recordSnippet.ts +141 -0
  39. package/src/types.ts +96 -0
  40. package/tsconfig.build.json +11 -0
  41. package/tsconfig.build.tsbuildinfo +1 -0
  42. package/tsconfig.json +10 -0
package/dist/index.cjs ADDED
@@ -0,0 +1,514 @@
1
+ 'use strict';
2
+
3
+ var machine = require('@turing-machine-js/machine');
4
+
5
+ /**
6
+ * Contract between the pure highlight logic (`applyHighlight`,
7
+ * `applyIndicator`) and any consumer that actually renders the graph
8
+ * (Svelte component, vanilla embed, server-side snapshot, etc.).
9
+ *
10
+ * The pure functions decide *what* should happen (which node gets a class,
11
+ * which edge lights up, where to pulse); the consumer's `HighlightOps`
12
+ * implementation decides *how* (DOM mutation, recording for tests, etc.).
13
+ *
14
+ * See `docs/graph-highlight-and-breakpoints.md` for the rules each
15
+ * implementation must respect.
16
+ */
17
+ /**
18
+ * Build a recording `HighlightOps` + `IndicatorOps` pair plus the shared
19
+ * `record` array of calls in invocation order. Used by tests to assert
20
+ * what the pure logic would have done without running a real DOM.
21
+ *
22
+ * Snapshot-friendly: the record contains only plain JSON-serializable
23
+ * values (no DOM nodes, no function refs).
24
+ */
25
+ function recordingOps() {
26
+ const record = [];
27
+ return {
28
+ record,
29
+ highlight: {
30
+ addNodeClass(id, cls) { record.push({ op: 'addNodeClass', id, cls }); },
31
+ highlightEdge(fromKey, toKey) { record.push({ op: 'highlightEdge', fromKey, toKey }); },
32
+ markFrameActive(frameId) { record.push({ op: 'markFrameActive', frameId }); },
33
+ pulse(id) { record.push({ op: 'pulse', id }); },
34
+ scrollIntoView(id) { record.push({ op: 'scrollIntoView', id }); },
35
+ },
36
+ indicator: {
37
+ setBreakpoint(id, on) { record.push({ op: 'setBreakpoint', id, on }); },
38
+ },
39
+ };
40
+ }
41
+
42
+ /**
43
+ * Normalize an engine `GraphNode.id` to its canonical representative for
44
+ * breakpoint-class lookups (machines-demo#37). Wrappers produced by
45
+ * `State.withOverriddenHaltState` share `#debugRef` with their bare state
46
+ * engine-side (turing-machine-js v7 `State.ts`: `state.#debugRef =
47
+ * bare.#debugRef`), so they form a single breakpoint from the user's POV.
48
+ * This collapses any wrapper id to its bare's id; non-wrapper ids return
49
+ * self. Used so the demo can store ONE canonical id per equivalence class
50
+ * in its breakpoint set, and expand to all class members for indicator
51
+ * rendering — keeping the worker-side toggle count to one per class
52
+ * (multiple toggles on the shared ref would double-flip).
53
+ */
54
+ function bareIdOf(id, graph) {
55
+ if (!graph)
56
+ return id;
57
+ // Halt markers (negative ids, one per frame) are visualization sentinels;
58
+ // at runtime they all collapse to the haltState singleton (id 0). For
59
+ // breakpoint purposes they're a single class — setting BP on any
60
+ // halt-related node sets it on the global haltState.
61
+ if (id < 0)
62
+ return 0;
63
+ const node = graph.nodes[id];
64
+ if (node && node.isWrapper && node.bareStateId !== null) {
65
+ return node.bareStateId;
66
+ }
67
+ return id;
68
+ }
69
+ /**
70
+ * Asymmetric expansion for the highlight effect (machines-demo#37).
71
+ * Wrapper → `[wrapper, bare]` (the wrapper-entry pause is visually joined
72
+ * to its bare, since the user thinks of them as one call site).
73
+ * Bare → `[bare]` only (when the engine is genuinely on the bare — e.g. a
74
+ * loop iter — the wrapper is not the "active" state and shouldn't get the
75
+ * strong highlight).
76
+ * Non-wrapper / non-bare ids return `[id]`.
77
+ */
78
+ function highlightExpand(id, graph) {
79
+ if (!graph)
80
+ return [id];
81
+ const node = graph.nodes[id];
82
+ if (node?.isWrapper && node.bareStateId !== null) {
83
+ return [id, node.bareStateId];
84
+ }
85
+ return [id];
86
+ }
87
+ /**
88
+ * All GraphNode ids in the same breakpoint equivalence class as `id`.
89
+ * Symmetric — gives consumers the full list of nodes that share an engine
90
+ * breakpoint, regardless of which class member is the input. Used by the
91
+ * context-menu's "Shared with" info line so the user can see at a glance
92
+ * which other nodes flip together.
93
+ *
94
+ * Halt class (canonical id 0): the halt singleton + every halt marker in
95
+ * the graph. Wrapper/bare class: the bare + every wrapper pointing at it.
96
+ * Singleton classes (regular states, idle sentinel proxies) return just
97
+ * the input id.
98
+ */
99
+ function equivalentIds(id, graph) {
100
+ if (!graph)
101
+ return [id];
102
+ const canonical = bareIdOf(id, graph);
103
+ if (canonical === 0) {
104
+ const ids = [0];
105
+ for (const node of Object.values(graph.nodes)) {
106
+ if (node.isHaltMarker)
107
+ ids.push(node.id);
108
+ }
109
+ return ids;
110
+ }
111
+ const result = new Set([canonical]);
112
+ for (const node of Object.values(graph.nodes)) {
113
+ if (node.isWrapper && node.bareStateId === canonical)
114
+ result.add(node.id);
115
+ }
116
+ return [...result];
117
+ }
118
+
119
+ /**
120
+ * Walk the engine graph once and build all derived lookups. Cheap;
121
+ * intended to run on every Build (graph identity changes per build).
122
+ */
123
+ function indexGraph(graph) {
124
+ const nodeFrameMap = new Map();
125
+ const frameWrappersMap = new Map();
126
+ const frameLabelToId = new Map();
127
+ if (!graph)
128
+ return { nodeFrameMap, frameWrappersMap, frameLabelToId };
129
+ for (const node of Object.values(graph.nodes)) {
130
+ if (node.frameId !== null)
131
+ nodeFrameMap.set(node.id, node.frameId);
132
+ }
133
+ // For each wrapper, append to its bare's frame entry. Multiple wrappers
134
+ // can share the same bare with different overrides; we record them all
135
+ // so the return-chain passes can highlight every candidate.
136
+ for (const node of Object.values(graph.nodes)) {
137
+ if (!node.isWrapper || node.bareStateId === null)
138
+ continue;
139
+ const bare = graph.nodes[node.bareStateId];
140
+ if (!bare || bare.frameId === null)
141
+ continue;
142
+ const entry = { wrapperId: node.id, overrideId: node.overriddenHaltStateId };
143
+ const arr = frameWrappersMap.get(bare.frameId);
144
+ if (arr)
145
+ arr.push(entry);
146
+ else
147
+ frameWrappersMap.set(bare.frameId, [entry]);
148
+ }
149
+ // Cluster label reconstruction: mirrors the engine's `toMermaid` emit
150
+ // (`callable subtree of NAME` for single-bare frames, `callable scope:
151
+ // A ∪ B ∪ …` for union frames; bare names sorted by id). Consumers
152
+ // need this to map mermaid's rendered cluster (whose own SVG id is the
153
+ // useless literal `[object Object]`) back to a frameId.
154
+ const bareIds = new Set();
155
+ for (const n of Object.values(graph.nodes)) {
156
+ if (n.isWrapper && n.bareStateId !== null)
157
+ bareIds.add(n.bareStateId);
158
+ }
159
+ const frameToBareNames = new Map();
160
+ for (const n of Object.values(graph.nodes).sort((a, b) => a.id - b.id)) {
161
+ if (n.isWrapper || n.isHaltMarker || n.frameId === null)
162
+ continue;
163
+ if (!bareIds.has(n.id))
164
+ continue;
165
+ const arr = frameToBareNames.get(n.frameId) ?? [];
166
+ arr.push(n.name);
167
+ frameToBareNames.set(n.frameId, arr);
168
+ }
169
+ for (const [frameId, names] of frameToBareNames) {
170
+ const label = names.length > 1
171
+ ? `callable scope: ${names.join(' ∪ ')}`
172
+ : `callable subtree of ${names[0] ?? frameId}`;
173
+ frameLabelToId.set(label, frameId);
174
+ }
175
+ return { nodeFrameMap, frameWrappersMap, frameLabelToId };
176
+ }
177
+
178
+ /**
179
+ * Pure highlight-rule evaluator. Given the current `highlight` (from
180
+ * `MachineView`'s `$derived`), the engine `graph`, derived `indexes`,
181
+ * and the previous strong-id (for pause-revisit pulse detection), emit
182
+ * a sequence of `ops` calls describing the resulting visual state.
183
+ *
184
+ * Strictly additive — the caller is expected to clear previously-applied
185
+ * highlight classes / edge marks / cluster activations BEFORE invoking
186
+ * this function. The function never reads back from the consumer.
187
+ *
188
+ * Returns the new prev-strong-id to thread into the next call. Pulse
189
+ * comparison uses the RAW strong id (not canonical), so wrapper-pause
190
+ * and bare-pause register as different positions and don't pulse each
191
+ * other. Updates only when `highlight.paused === true`; non-paused
192
+ * events (idle / RUNNING_AUTO ticks) leave it untouched. Null highlight
193
+ * resets it to null.
194
+ *
195
+ * See `docs/graph-highlight-and-breakpoints.md` for the 16 rules
196
+ * enumerated.
197
+ */
198
+ function applyHighlight(highlight, graph, indexes, prevStrongId, ops) {
199
+ if (!highlight || !graph) {
200
+ return { nextPrevStrongId: null };
201
+ }
202
+ // §5 Halt-target retargeting: real halt (id 0) reached from an in-frame
203
+ // state retargets to the frame's halt marker (id = -frameId), so the
204
+ // visible edge lands inside the cluster.
205
+ let toId = highlight.toId;
206
+ if (toId === 0 && typeof highlight.fromId === 'number') {
207
+ const fromFrameId = indexes.nodeFrameMap.get(highlight.fromId);
208
+ if (fromFrameId !== undefined)
209
+ toId = -fromFrameId;
210
+ }
211
+ // §2 Equivalence-class expansion (asymmetric, via highlightExpand):
212
+ // wrapper → [wrapper, bare] (joined visual pair for wrapper-entry pause)
213
+ // bare → [bare] (engine genuinely on the bare; no wrapper sync)
214
+ // From-side expansion only fires for positive numeric ids; the 'idle'
215
+ // sentinel is handled directly below. Halt markers / singleton fall
216
+ // through the direct-lookup branches.
217
+ const fromEqIds = typeof highlight.fromId === 'number'
218
+ ? highlightExpand(highlight.fromId, graph)
219
+ : [];
220
+ const toEqIds = toId !== null && toId > 0
221
+ ? highlightExpand(toId, graph)
222
+ : [];
223
+ // §3 Class application — from side.
224
+ if (highlight.fromId === 'idle') {
225
+ ops.addNodeClass('idle', 'mg-highlight-from');
226
+ if (highlight.strong === 'from')
227
+ ops.addNodeClass('idle', 'mg-highlight-strong');
228
+ }
229
+ for (const id of fromEqIds) {
230
+ ops.addNodeClass(id, 'mg-highlight-from');
231
+ if (highlight.strong === 'from')
232
+ ops.addNodeClass(id, 'mg-highlight-strong');
233
+ }
234
+ // §3 + §8 Class application — to side. Halt markers (toId < 0) and the
235
+ // real halt singleton (toId === 0; only possible when §5 didn't retarget)
236
+ // bypass the equivalence-class expansion via direct lookup.
237
+ if (toId !== null && toId <= 0) {
238
+ ops.addNodeClass(toId, 'mg-highlight-to');
239
+ if (highlight.strong === 'to')
240
+ ops.addNodeClass(toId, 'mg-highlight-strong');
241
+ }
242
+ for (const id of toEqIds) {
243
+ ops.addNodeClass(id, 'mg-highlight-to');
244
+ if (highlight.strong === 'to')
245
+ ops.addNodeClass(id, 'mg-highlight-strong');
246
+ }
247
+ // Edge highlight: the data-id token form mermaid emits.
248
+ const fromKey = highlight.fromId === 'idle' ? 'idle' : `s${highlight.fromId}`;
249
+ const toKey = toId === null ? null
250
+ : toId < 0 ? `c${-toId}` // halt marker
251
+ : `s${toId}`;
252
+ if (toKey !== null)
253
+ ops.highlightEdge(fromKey, toKey);
254
+ // §10 Wrapper-entry "call" edge: when to-side expanded to [wrapper, bare],
255
+ // light up the wrapper→bare connector so the joined pair has a visible link.
256
+ if (toEqIds.length > 1) {
257
+ const wrapperId = toEqIds.find((id) => graph.nodes[id]?.isWrapper);
258
+ const bareId = toEqIds.find((id) => !graph.nodes[id]?.isWrapper);
259
+ if (wrapperId !== undefined && bareId !== undefined) {
260
+ ops.highlightEdge(`s${wrapperId}`, `s${bareId}`);
261
+ }
262
+ }
263
+ // §6 Source return chain: just-fired transition landed on a frame's
264
+ // halt marker. Light up the post-pop trajectory before the next iter
265
+ // moves the strong node.
266
+ if (toId !== null && toId < 0) {
267
+ const frameId = -toId;
268
+ const wrappers = indexes.frameWrappersMap.get(frameId) ?? [];
269
+ for (const { wrapperId, overrideId } of wrappers) {
270
+ ops.highlightEdge(`w_${frameId}`, `s${wrapperId}`);
271
+ ops.addNodeClass(wrapperId, 'mg-highlight-to');
272
+ if (overrideId !== null) {
273
+ ops.highlightEdge(`s${wrapperId}`, `s${overrideId}`);
274
+ ops.addNodeClass(overrideId, 'mg-highlight-to');
275
+ }
276
+ }
277
+ }
278
+ // §7 Destination return chain: paused at a positive toId that's some
279
+ // wrapper W's override AND fromId is in W's frame — the engine just
280
+ // popped. The straight bare→override edge doesn't exist in the graph;
281
+ // light up the actual visible path bare → halt-marker → return →
282
+ // wrapper → override, plus the frame cluster.
283
+ if (typeof highlight.fromId === 'number' && toId !== null && toId > 0) {
284
+ const fromFrameId = indexes.nodeFrameMap.get(highlight.fromId);
285
+ if (fromFrameId !== undefined) {
286
+ const wrappers = indexes.frameWrappersMap.get(fromFrameId) ?? [];
287
+ const matching = wrappers.filter((w) => w.overrideId === toId);
288
+ if (matching.length > 0) {
289
+ ops.addNodeClass(-fromFrameId, 'mg-highlight-to');
290
+ ops.highlightEdge(`s${highlight.fromId}`, `c${fromFrameId}`);
291
+ for (const { wrapperId } of matching) {
292
+ ops.highlightEdge(`w_${fromFrameId}`, `s${wrapperId}`);
293
+ ops.addNodeClass(wrapperId, 'mg-highlight-to');
294
+ ops.highlightEdge(`s${wrapperId}`, `s${toId}`);
295
+ }
296
+ ops.markFrameActive(fromFrameId);
297
+ }
298
+ }
299
+ }
300
+ // §9 Frame-active for the strong node. Wrappers are outside any frame
301
+ // so canonicalize via bareIdOf so the wrapper-entry pause still lights
302
+ // up the bare's enclosing cluster.
303
+ const strongId = highlight.strong === 'from' ? highlight.fromId : highlight.toId;
304
+ const strongIdCanonical = typeof strongId === 'number'
305
+ ? bareIdOf(strongId, graph)
306
+ : strongId;
307
+ if (typeof strongIdCanonical === 'number') {
308
+ const frameId = indexes.nodeFrameMap.get(strongIdCanonical);
309
+ if (frameId !== undefined)
310
+ ops.markFrameActive(frameId);
311
+ }
312
+ // §11 Pulse on same-state revisit. Uses RAW strongId — wrapper-pause
313
+ // and bare-pause are visually distinct positions even though they
314
+ // share #debugRef; pausing at wrapper then continuing into bare must
315
+ // not pulse. Idles never pulse and never update prevStrongId.
316
+ if (highlight.paused
317
+ && strongId !== null
318
+ && strongId === prevStrongId
319
+ && strongId !== undefined) {
320
+ ops.pulse(strongId);
321
+ }
322
+ // Scroll-into-view target: for wrapper-entry pauses, scroll to the
323
+ // BARE (not the wrapper) so the focus matches the displayed state
324
+ // name. The worker's `resolveDisplayName` returns the bare's name
325
+ // for wrapper iters (so the log reads "paused at walkToBlank ..."),
326
+ // but `toId` is the wrapper's id and `highlightExpand` lights up
327
+ // both nodes as strong. Without this canonicalization the scroll
328
+ // lands on the wrapper while the log line and user's mental focus
329
+ // are on the bare. Halt-related ids (≤ 0) are scrolled to as-is —
330
+ // `bareIdOf` would collapse them all to the halt singleton, which
331
+ // is structurally separate from the in-frame halt marker the user
332
+ // is paused near.
333
+ if (strongId !== null) {
334
+ let scrollTarget = strongId;
335
+ if (typeof strongId === 'number' && strongId > 0) {
336
+ const node = graph.nodes[strongId];
337
+ if (node?.isWrapper && node.bareStateId !== null) {
338
+ scrollTarget = node.bareStateId;
339
+ }
340
+ }
341
+ ops.scrollIntoView(scrollTarget);
342
+ }
343
+ const nextPrevStrongId = highlight.paused ? strongId : prevStrongId;
344
+ return { nextPrevStrongId };
345
+ }
346
+ /**
347
+ * Pure breakpoint-indicator rule evaluator. For each cached node key,
348
+ * emit `ops.setBreakpoint(key, on)` reflecting whether the node's
349
+ * canonical bare-id is in the `breakpoints` set.
350
+ *
351
+ * The 'idle' string sentinel never carries a breakpoint. All numeric
352
+ * keys are valid BP-class members:
353
+ * - positive id → regular state; canonical via bareIdOf (wrappers
354
+ * collapse to bare)
355
+ * - 0 → haltState singleton (engine-wide; canonical = 0)
356
+ * - negative id → halt marker (per-frame visualization sentinel;
357
+ * bareIdOf maps to 0 — same class as the singleton)
358
+ * Consumers pass their iterable of cached node keys (e.g. `nodeCache.keys()`).
359
+ */
360
+ function applyIndicator(breakpoints, graph, nodeIds, ops) {
361
+ for (const key of nodeIds) {
362
+ const on = typeof key === 'number'
363
+ && graph !== null
364
+ && breakpoints.has(bareIdOf(key, graph));
365
+ ops.setBreakpoint(key, on);
366
+ }
367
+ }
368
+
369
+ const MOVEMENT_LETTER = new Map([
370
+ [machine.movements.left, 'L'],
371
+ [machine.movements.right, 'R'],
372
+ [machine.movements.stay, 'S'],
373
+ ]);
374
+ /**
375
+ * Render a single tape command in `WRITE/MOVE` form.
376
+ * - Write: `'X'` (literal symbol) | `K` (keep) | `E` (erase = write blank).
377
+ * - Move: `L` / `R` / `S` from `movements.*`.
378
+ *
379
+ * Matches the engine's edge-label vocabulary so formatted commands line up
380
+ * with the write/move cells in `toMermaid`-emitted edge labels.
381
+ */
382
+ function formatCommand(tapeCommand) {
383
+ let write;
384
+ if (tapeCommand.symbol === machine.symbolCommands.keep) {
385
+ write = 'K';
386
+ }
387
+ else if (tapeCommand.symbol === machine.symbolCommands.erase) {
388
+ write = 'E';
389
+ }
390
+ else {
391
+ write = `'${tapeCommand.symbol}'`;
392
+ }
393
+ const move = MOVEMENT_LETTER.get(tapeCommand.movement) ?? '?';
394
+ return `${write}/${move}`;
395
+ }
396
+ /**
397
+ * Render one step's edge-label notation: `[reads] → [writes]/[moves]`.
398
+ * Each role is wrapped in a single `[…]`; multi-tape entries are
399
+ * comma-separated inside the brackets.
400
+ *
401
+ * Matches the engine's `toMermaid` emit so logged steps line up with
402
+ * graph edge labels. Note: `nextSymbols` in `MachineState` is already
403
+ * resolved (keep → current symbol, erase → blank) — `K` is inferred
404
+ * by comparing `nextSymbols[i] === currentSymbols[i]`.
405
+ */
406
+ function formatStep(m) {
407
+ const reads = m.currentSymbols.map((s) => `'${s}'`).join(',');
408
+ const writes = m.nextSymbols
409
+ .map((s, i) => (s === m.currentSymbols[i] ? 'K' : `'${s}'`))
410
+ .join(',');
411
+ const moves = m.movements.map((mv) => MOVEMENT_LETTER.get(mv) ?? '?').join(',');
412
+ return `[${reads}] → [${writes}]/[${moves}]`;
413
+ }
414
+
415
+ const DEFAULT_MAX_STEPS = 1000;
416
+ function snapshotTapes(machine) {
417
+ return machine.tapeBlock.tapes.map((t) => ({
418
+ symbols: [...t.symbols],
419
+ position: t.position,
420
+ }));
421
+ }
422
+ function deriveCommands(m) {
423
+ return m.movements.map((mv, i) => ({
424
+ movement: MOVEMENT_LETTER.get(mv) ?? 'S',
425
+ read: m.currentSymbols[i],
426
+ // nextSymbols is already resolved (keep → current symbol, erase → blank);
427
+ // when write === read the command was a keep (UI suppresses the flash).
428
+ write: m.nextSymbols[i],
429
+ }));
430
+ }
431
+ function deriveHighlight(m, graph) {
432
+ return {
433
+ fromId: bareIdOf(m.state.id, graph),
434
+ toId: m.nextState === machine.haltState ? 0 : m.nextState.id,
435
+ strong: 'from',
436
+ paused: false,
437
+ };
438
+ }
439
+ /**
440
+ * Record a full machine run into a `Snippet` — a self-contained playback
441
+ * artifact suitable for embeds, articles, or landing-page panels.
442
+ *
443
+ * The returned snippet contains one frame per iteration plus a frame-0
444
+ * initial-state snapshot. Recording stops when the machine halts or when
445
+ * `maxSteps` iterations have been consumed (default 1000).
446
+ *
447
+ * Tape-timing note: `runStepByStep` yields BEFORE applying its command
448
+ * (the command is applied after the yield resumes). The recorder uses a
449
+ * one-step-delayed snapshot so each frame's `tape` reflects the
450
+ * post-command state for that frame's iter.
451
+ */
452
+ function recordSnippet(opts) {
453
+ const { machine, initialState, graph, alphabets, name, maxSteps = DEFAULT_MAX_STEPS, log, } = opts;
454
+ const frames = [
455
+ { step: 0, tape: snapshotTapes(machine), highlight: null },
456
+ ];
457
+ // pending holds everything for the frame whose tape snapshot is not yet
458
+ // available (because applyCommand hasn't fired yet). It is flushed at the
459
+ // start of the NEXT iter (when the tape reflects the previous command) and
460
+ // after the loop (when the final command has been applied).
461
+ let pending = null;
462
+ let prev = null;
463
+ try {
464
+ for (const m of machine.runStepByStep({ initialState, stepsLimit: maxSteps })) {
465
+ // At this point applyCommand for the PREVIOUS iter has already run
466
+ // (the generator called applyCommand before looping back to yield).
467
+ // So the current tape state = post-command of the previous iter.
468
+ if (pending !== null) {
469
+ frames.push({ ...pending, tape: snapshotTapes(machine) });
470
+ }
471
+ const commands = deriveCommands(m);
472
+ const highlight = deriveHighlight(m, graph);
473
+ const logLine = log ? log(m, prev) : undefined;
474
+ pending = {
475
+ step: m.step,
476
+ commands,
477
+ highlight,
478
+ ...(logLine !== undefined ? { log: logLine } : {}),
479
+ };
480
+ prev = m;
481
+ }
482
+ }
483
+ catch (e) {
484
+ // runStepByStep throws 'Long execution' when stepsLimit is hit.
485
+ // At that point applyCommand for the last yielded iter has run, so the
486
+ // tape is in the post-command state we want for the pending frame.
487
+ if (!(e instanceof Error) || e.message !== 'Long execution') {
488
+ throw e;
489
+ }
490
+ }
491
+ // Flush the last pending frame. After the loop (or after the catch), the
492
+ // tape reflects the post-command state of the final yielded iter.
493
+ if (pending !== null) {
494
+ frames.push({ ...pending, tape: snapshotTapes(machine) });
495
+ }
496
+ return {
497
+ version: 1,
498
+ ...(name !== undefined ? { name } : {}),
499
+ graph,
500
+ alphabets,
501
+ frames,
502
+ };
503
+ }
504
+
505
+ exports.applyHighlight = applyHighlight;
506
+ exports.applyIndicator = applyIndicator;
507
+ exports.bareIdOf = bareIdOf;
508
+ exports.equivalentIds = equivalentIds;
509
+ exports.formatCommand = formatCommand;
510
+ exports.formatStep = formatStep;
511
+ exports.highlightExpand = highlightExpand;
512
+ exports.indexGraph = indexGraph;
513
+ exports.recordSnippet = recordSnippet;
514
+ exports.recordingOps = recordingOps;
@@ -0,0 +1,9 @@
1
+ export type { NodeKey, HighlightClass, HighlightOps, IndicatorOps, RecordedOp } from './highlightOps';
2
+ export { recordingOps } from './highlightOps';
3
+ export { bareIdOf, highlightExpand, equivalentIds } from './graphUtils';
4
+ export type { GraphIndexes } from './graphIndexes';
5
+ export { indexGraph } from './graphIndexes';
6
+ export type { GraphHighlight, TapeSnapshot, Frame, Snippet } from './types';
7
+ export { applyHighlight, applyIndicator } from './applyHighlight';
8
+ export { formatCommand, formatStep } from './format';
9
+ export { recordSnippet, type RecordSnippetOptions } from './recordSnippet';
package/dist/index.js ADDED
@@ -0,0 +1,6 @@
1
+ export { recordingOps } from './highlightOps';
2
+ export { bareIdOf, highlightExpand, equivalentIds } from './graphUtils';
3
+ export { indexGraph } from './graphIndexes';
4
+ export { applyHighlight, applyIndicator } from './applyHighlight';
5
+ export { formatCommand, formatStep } from './format';
6
+ export { recordSnippet } from './recordSnippet';