@demlik/tea 0.1.1 → 0.2.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.
- package/dist/agent/index.d.ts +2 -2
- package/dist/agent/index.js +8 -8
- package/dist/authed-call/index.d.ts +3 -3
- package/dist/authed-call/index.js +5 -5
- package/dist/await-terminal/index.d.ts +1 -1
- package/dist/await-terminal/index.js +2 -2
- package/dist/batch-window/index.d.ts +2 -2
- package/dist/batch-window/index.js +4 -4
- package/dist/cache/index.d.ts +2 -2
- package/dist/{chunk-EIZJTYKR.js → chunk-5KVHID6A.js} +4 -4
- package/dist/{chunk-EIZJTYKR.js.map → chunk-5KVHID6A.js.map} +1 -1
- package/dist/{chunk-RVJFGRGK.js → chunk-6GIGQT6C.js} +4 -4
- package/dist/chunk-6GIGQT6C.js.map +1 -0
- package/dist/{chunk-FH5RUIIL.js → chunk-6OUDPSSG.js} +3 -3
- package/dist/{chunk-FH5RUIIL.js.map → chunk-6OUDPSSG.js.map} +1 -1
- package/dist/{chunk-2WZHS4P2.js → chunk-6VDCTR7N.js} +25 -40
- package/dist/chunk-6VDCTR7N.js.map +1 -0
- package/dist/{chunk-BNJYE4AU.js → chunk-DYRKDCJI.js} +46 -16
- package/dist/chunk-DYRKDCJI.js.map +1 -0
- package/dist/{chunk-RGTPPF4U.js → chunk-EGWTT5XJ.js} +3 -3
- package/dist/{chunk-RGTPPF4U.js.map → chunk-EGWTT5XJ.js.map} +1 -1
- package/dist/{chunk-A56GNPI7.js → chunk-EMJTPHI7.js} +5 -23
- package/dist/chunk-EMJTPHI7.js.map +1 -0
- package/dist/{chunk-IFBQJYGI.js → chunk-FOGL3TC7.js} +3 -3
- package/dist/{chunk-IFBQJYGI.js.map → chunk-FOGL3TC7.js.map} +1 -1
- package/dist/{chunk-RVU3RBE6.js → chunk-G2U7DJHL.js} +6 -4
- package/dist/chunk-G2U7DJHL.js.map +1 -0
- package/dist/{chunk-WUV3PSCZ.js → chunk-HCEVHFJ7.js} +2 -2
- package/dist/chunk-HCEVHFJ7.js.map +1 -0
- package/dist/{chunk-EDGDR5XX.js → chunk-IK4S5DJN.js} +3 -3
- package/dist/{chunk-EDGDR5XX.js.map → chunk-IK4S5DJN.js.map} +1 -1
- package/dist/{chunk-EQRUAP2A.js → chunk-J6527VRQ.js} +2 -2
- package/dist/chunk-J6527VRQ.js.map +1 -0
- package/dist/{chunk-TAO4YOLO.js → chunk-M6UZT7HS.js} +3 -3
- package/dist/{chunk-TAO4YOLO.js.map → chunk-M6UZT7HS.js.map} +1 -1
- package/dist/{chunk-QGZW4W3E.js → chunk-SKAMZKTE.js} +3 -3
- package/dist/{chunk-QGZW4W3E.js.map → chunk-SKAMZKTE.js.map} +1 -1
- package/dist/{chunk-TC4HWABA.js → chunk-VFGKTGGC.js} +7 -7
- package/dist/{chunk-TC4HWABA.js.map → chunk-VFGKTGGC.js.map} +1 -1
- package/dist/{chunk-D5EQDLDV.js → chunk-ZDRN3YCE.js} +4 -4
- package/dist/{chunk-D5EQDLDV.js.map → chunk-ZDRN3YCE.js.map} +1 -1
- package/dist/{core-CymXZCeY.d.ts → core-BmlJOvxM.d.ts} +20 -1
- package/dist/deadline/index.d.ts +2 -2
- package/dist/deadline/index.js +3 -3
- package/dist/debounce/index.d.ts +6 -0
- package/dist/debounce/index.js +1 -1
- package/dist/do/index.d.ts +422 -315
- package/dist/do/index.js +173 -149
- package/dist/do/index.js.map +1 -1
- package/dist/{durable-effects-2MDxDs45.d.ts → durable-effects-9LxFpmh3.d.ts} +1 -1
- package/dist/extension/index.d.ts +1 -1
- package/dist/extension/index.js +3 -3
- package/dist/extension/react.js +3 -3
- package/dist/extension/subs/index.d.ts +2 -2
- package/dist/fan-out/index.d.ts +1 -1
- package/dist/idempotent-intake/index.d.ts +1 -1
- package/dist/index.d.ts +20 -3
- package/dist/index.js +2 -2
- package/dist/llm-call/index.d.ts +2 -2
- package/dist/llm-call/index.js +5 -5
- package/dist/machine-viz/index.d.ts +4 -4
- package/dist/machine-viz/index.js +4 -8
- package/dist/machine-viz/index.js.map +1 -1
- package/dist/mem/index.d.ts +1 -1
- package/dist/monitored-run/index.d.ts +2 -2
- package/dist/monitored-run/index.js +5 -5
- package/dist/node/index.d.ts +1 -1
- package/dist/paginated-walk/index.d.ts +2 -2
- package/dist/paginated-walk/index.js +5 -5
- package/dist/parity/index.d.ts +10 -4
- package/dist/parity/index.js +6 -5
- package/dist/parity/index.js.map +1 -1
- package/dist/pbt/arbitraries/index.d.ts +1 -1
- package/dist/pbt/index.d.ts +15 -8
- package/dist/pbt/index.js +5 -11
- package/dist/pbt/index.js.map +1 -1
- package/dist/pbt/runners/index.d.ts +1 -1
- package/dist/pbt/runners/index.js +3 -3
- package/dist/poller/index.d.ts +2 -2
- package/dist/poller/index.js +3 -3
- package/dist/prediction/index.d.ts +23 -2
- package/dist/prediction/index.js +2 -2
- package/dist/pure/index.d.ts +2 -2
- package/dist/pure/index.js +2 -2
- package/dist/react/index.d.ts +1 -1
- package/dist/react/index.js +8 -4
- package/dist/react/index.js.map +1 -1
- package/dist/reconciler/index.d.ts +2 -2
- package/dist/reconciler/index.js +5 -5
- package/dist/recorder/index.d.ts +1 -1
- package/dist/resilient-call/index.d.ts +45 -2
- package/dist/resilient-call/index.js +4 -4
- package/dist/retry-to-success/index.d.ts +109 -0
- package/dist/retry-to-success/index.js +35 -0
- package/dist/retry-to-success/index.js.map +1 -0
- package/dist/saga/index.d.ts +14 -1
- package/dist/saga/index.js.map +1 -1
- package/dist/snapshot/index.d.ts +1 -1
- package/dist/snapshot/index.js +3 -3
- package/dist/subs/index.d.ts +2 -2
- package/dist/testing/index.d.ts +1 -1
- package/dist/testing/index.js +2 -2
- package/dist/throttle/index.d.ts +9 -0
- package/dist/throttle/index.js +1 -1
- package/dist/throttled-input/index.d.ts +10 -2
- package/dist/throttled-input/index.js +6 -6
- package/dist/throttled-input/index.js.map +1 -1
- package/dist/token-refresh/index.d.ts +1 -1
- package/dist/token-refresh/index.js +3 -3
- package/dist/trace-replay/index.d.ts +1 -1
- package/dist/trace-replay/index.js +3 -3
- package/dist/{types-N9LZbdnr.d.ts → types-BoUWgwSm.d.ts} +1 -1
- package/dist/with-deadline/index.d.ts +1 -1
- package/dist/with-deadline/index.js +5 -24
- package/dist/with-deadline/index.js.map +1 -1
- package/dist/with-resilience/index.d.ts +2 -2
- package/dist/with-resilience/index.js +13 -36
- package/dist/with-resilience/index.js.map +1 -1
- package/dist/with-telemetry/index.d.ts +1 -1
- package/dist/with-telemetry/index.js +4 -29
- package/dist/with-telemetry/index.js.map +1 -1
- package/dist/work-queue/adapter.d.ts +1 -1
- package/dist/work-queue/index.d.ts +1 -1
- package/dist/work-queue/ops.d.ts +1 -1
- package/dist/workflow/index.d.ts +16 -10
- package/dist/workflow/index.js.map +1 -1
- package/package.json +8 -20
- package/dist/chunk-2WZHS4P2.js.map +0 -1
- package/dist/chunk-7VEG4KHB.js +0 -202
- package/dist/chunk-7VEG4KHB.js.map +0 -1
- package/dist/chunk-A56GNPI7.js.map +0 -1
- package/dist/chunk-BNJYE4AU.js.map +0 -1
- package/dist/chunk-EQRUAP2A.js.map +0 -1
- package/dist/chunk-RVJFGRGK.js.map +0 -1
- package/dist/chunk-RVU3RBE6.js.map +0 -1
- package/dist/chunk-WUV3PSCZ.js.map +0 -1
- package/dist/chunk-XRXKH7KA.js +0 -268
- package/dist/chunk-XRXKH7KA.js.map +0 -1
- package/dist/raft/demo.d.ts +0 -105
- package/dist/raft/demo.js +0 -172
- package/dist/raft/demo.js.map +0 -1
- package/dist/raft/index.d.ts +0 -548
- package/dist/raft/index.js +0 -7
- package/dist/raft/index.js.map +0 -1
- package/dist/raft/sim.d.ts +0 -222
- package/dist/raft/sim.js +0 -8
- package/dist/raft/sim.js.map +0 -1
- package/dist/raft/timeline.d.ts +0 -46
- package/dist/raft/timeline.js +0 -62
- package/dist/raft/timeline.js.map +0 -1
package/dist/extension/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
export { bridgeClient, bridgeRuntime, bridgeTabClient, passThroughMsg } from '../chunk-
|
|
2
|
-
import '../chunk-
|
|
3
|
-
import '../chunk-
|
|
1
|
+
export { bridgeClient, bridgeRuntime, bridgeTabClient, passThroughMsg } from '../chunk-EGWTT5XJ.js';
|
|
2
|
+
import '../chunk-6VDCTR7N.js';
|
|
3
|
+
import '../chunk-DYRKDCJI.js';
|
|
4
4
|
|
|
5
5
|
// src/extension/index.ts
|
|
6
6
|
var MALFORMED = "chromeStorageStore: stored value is not a string";
|
package/dist/extension/react.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { bridgeClient, passThroughMsg } from '../chunk-
|
|
2
|
-
import '../chunk-
|
|
3
|
-
import '../chunk-
|
|
1
|
+
import { bridgeClient, passThroughMsg } from '../chunk-EGWTT5XJ.js';
|
|
2
|
+
import '../chunk-6VDCTR7N.js';
|
|
3
|
+
import '../chunk-DYRKDCJI.js';
|
|
4
4
|
import { useRef, useSyncExternalStore, useEffect, useCallback, createContext, useMemo, useContext } from 'react';
|
|
5
5
|
import { jsx } from 'react/jsx-runtime';
|
|
6
6
|
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { S as Sub } from '../../core-
|
|
2
|
-
import { S as SubscribeHandler } from '../../types-
|
|
1
|
+
import { S as Sub } from '../../core-BmlJOvxM.js';
|
|
2
|
+
import { S as SubscribeHandler } from '../../types-BoUWgwSm.js';
|
|
3
3
|
|
|
4
4
|
type AlarmSubData = {
|
|
5
5
|
alarmName: string;
|
package/dist/fan-out/index.d.ts
CHANGED
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { C as Cmd, P as Port, S as Sub, M as Machine, T as Transitions, R as Reducer } from './core-
|
|
2
|
-
export { b as ContextFree, I as Interpret, N as NoCtx, c as PortEmitter, a as SubId, d as Subscribe, e as SyncReturn, U as UpdateForm, f as
|
|
1
|
+
import { C as Cmd, P as Port, S as Sub, M as Machine, T as Transitions, R as Reducer } from './core-BmlJOvxM.js';
|
|
2
|
+
export { b as ContextFree, I as Interpret, j as NoCellError, N as NoCtx, c as PortEmitter, a as SubId, d as Subscribe, e as SyncReturn, U as UpdateForm, f as applyCell, g as detectUpdateForm, h as foldMsgs, i as formOf, m as msgKeysOf, s as subId } from './core-BmlJOvxM.js';
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* @demlik/tea — TEA-faithful state machine substrate.
|
|
@@ -68,8 +68,25 @@ declare function __resetPortRegistry(): void;
|
|
|
68
68
|
* throw is catchable in the dispatch loop; the configured `Supervision`
|
|
69
69
|
* strategy decides what the runtime does next (`stop` / `escalate` /
|
|
70
70
|
* `restart`), but the failure is ALWAYS surfaced here as data first.
|
|
71
|
+
*
|
|
72
|
+
* The fanout phases (#277). Every fanout is throw-isolated so one bad
|
|
73
|
+
* consumer never strands its siblings — and the isolated throw routes here
|
|
74
|
+
* rather than to a bare `console.error`, so a sink wired to e.g. Sentry sees
|
|
75
|
+
* every "no caller to reject at" failure:
|
|
76
|
+
*
|
|
77
|
+
* - `"listener"` — a `runtime.subscribe(...)` listener threw during the
|
|
78
|
+
* post-transition fanout.
|
|
79
|
+
* - `"observer"` — a `runtime.observe(...)` observer threw during the
|
|
80
|
+
* post-transition fanout.
|
|
81
|
+
* - `"event"` — the semantic-event path threw: either the `events` projector
|
|
82
|
+
* itself, or an `on(type, ...)` handler.
|
|
83
|
+
* - `"boot"` — an `onBoot` handler threw (at the boot fanout, or on the
|
|
84
|
+
* immediate fire of a late post-boot registration).
|
|
85
|
+
* - `"port-emit"` — a `subscribePort` listener threw during a port emission.
|
|
86
|
+
* - `"sub-cleanup"` — a subscription's cleanup threw (on reconcile-removal,
|
|
87
|
+
* or during `stop()` teardown).
|
|
71
88
|
*/
|
|
72
|
-
type RuntimeErrorPhase = "follow-up" | "stop-save" | "reduce";
|
|
89
|
+
type RuntimeErrorPhase = "follow-up" | "stop-save" | "reduce" | "listener" | "observer" | "event" | "boot" | "port-emit" | "sub-cleanup";
|
|
73
90
|
/** Context handed to an `OnError` sink alongside the error itself. */
|
|
74
91
|
interface RuntimeErrorContext {
|
|
75
92
|
readonly phase: RuntimeErrorPhase;
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { PortNameCollisionError, QuiescenceTimeoutError, __resetPortRegistry, absurd, asReducer, defineMachine, definePort, historyTracker, noop, replay, run, tryInterpret } from './chunk-
|
|
2
|
-
export { Cmd, detectUpdateForm, foldMsgs, formOf, subId } from './chunk-
|
|
1
|
+
export { PortNameCollisionError, QuiescenceTimeoutError, __resetPortRegistry, absurd, asReducer, defineMachine, definePort, historyTracker, noop, replay, run, tryInterpret } from './chunk-6VDCTR7N.js';
|
|
2
|
+
export { Cmd, NoCellError, applyCell, detectUpdateForm, foldMsgs, formOf, msgKeysOf, subId } from './chunk-DYRKDCJI.js';
|
|
3
3
|
//# sourceMappingURL=index.js.map
|
|
4
4
|
//# sourceMappingURL=index.js.map
|
package/dist/llm-call/index.d.ts
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import { C as Cmd } from '../core-
|
|
1
|
+
import { C as Cmd } from '../core-BmlJOvxM.js';
|
|
2
2
|
import { SucceedMsg, FailMsg, RunCmd, ResilientState } from '../resilient-call/index.js';
|
|
3
3
|
import { RetryPolicy } from '../retry-backoff/index.js';
|
|
4
4
|
import { DeadlineExceeded, DeadlineSub } from '../deadline/index.js';
|
|
5
5
|
export { deadlineSub, subscribeDeadline } from '../deadline/index.js';
|
|
6
6
|
import '../cache/index.js';
|
|
7
|
-
import '../types-
|
|
7
|
+
import '../types-BoUWgwSm.js';
|
|
8
8
|
import '../circuit-breaker/index.js';
|
|
9
9
|
import '../protocol-B5YmJr0d.js';
|
|
10
10
|
import '../rate-limit/index.js';
|
package/dist/llm-call/index.js
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
export { createLlmCall, liftLlmCall } from '../chunk-
|
|
2
|
-
import '../chunk-
|
|
1
|
+
export { createLlmCall, liftLlmCall } from '../chunk-M6UZT7HS.js';
|
|
2
|
+
import '../chunk-6GIGQT6C.js';
|
|
3
3
|
import '../chunk-JELSZN25.js';
|
|
4
|
-
export { deadlineSub, subscribeDeadline } from '../chunk-
|
|
4
|
+
export { deadlineSub, subscribeDeadline } from '../chunk-SKAMZKTE.js';
|
|
5
5
|
import '../chunk-5VNWZADP.js';
|
|
6
6
|
import '../chunk-2YOE5PIS.js';
|
|
7
7
|
import '../chunk-SC3FAFZN.js';
|
|
8
8
|
import '../chunk-IN33Q4VJ.js';
|
|
9
9
|
import '../chunk-NSDFA6M6.js';
|
|
10
10
|
import '../chunk-2YFLOCWX.js';
|
|
11
|
-
import '../chunk-
|
|
12
|
-
import '../chunk-
|
|
11
|
+
import '../chunk-6VDCTR7N.js';
|
|
12
|
+
import '../chunk-DYRKDCJI.js';
|
|
13
13
|
//# sourceMappingURL=index.js.map
|
|
14
14
|
//# sourceMappingURL=index.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { C as Cmd, S as Sub, M as Machine } from '../core-
|
|
1
|
+
import { C as Cmd, S as Sub, M as Machine } from '../core-BmlJOvxM.js';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* @demlik/tea/machine-viz — turn a `Machine` into a Mermaid diagram string.
|
|
@@ -14,9 +14,9 @@ import { C as Cmd, S as Sub, M as Machine } from '../core-CymXZCeY.js';
|
|
|
14
14
|
* back to a STRUCTURAL self-edge annotated with `?` — visually distinct from a
|
|
15
15
|
* resolved edge and documented in the diagram's legend.
|
|
16
16
|
*
|
|
17
|
-
* Form detection
|
|
18
|
-
*
|
|
19
|
-
*
|
|
17
|
+
* Form detection is `formOf(machine)` — the same reader `run`/`replay` use,
|
|
18
|
+
* honoring the authoritative `__form` tag `defineMachine` stamps (falling back
|
|
19
|
+
* to the structural heuristic for machines built without it; #275).
|
|
20
20
|
*
|
|
21
21
|
* What we MUST NOT do (these are the effectful paths, off-limits here):
|
|
22
22
|
* - call `interpret[*]` handlers (perform I/O)
|
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
import '../chunk-6VDCTR7N.js';
|
|
2
|
+
import { formOf } from '../chunk-DYRKDCJI.js';
|
|
3
|
+
|
|
1
4
|
// src/machine-viz/index.ts
|
|
2
5
|
function safeId(raw) {
|
|
3
6
|
const cleaned = raw.replace(/[^A-Za-z0-9_]/g, "_");
|
|
@@ -7,19 +10,12 @@ function safeId(raw) {
|
|
|
7
10
|
function safeLabel(raw) {
|
|
8
11
|
return raw.replace(/["\n\r;:]/g, " ").trim();
|
|
9
12
|
}
|
|
10
|
-
function detectMode(update) {
|
|
11
|
-
const keys = Object.keys(update);
|
|
12
|
-
const firstKey = keys[0];
|
|
13
|
-
if (firstKey === void 0) return "reducer";
|
|
14
|
-
const firstValue = update[firstKey];
|
|
15
|
-
return typeof firstValue === "function" ? "reducer" : "transitions";
|
|
16
|
-
}
|
|
17
13
|
function toMermaid(machine, opts = {}) {
|
|
18
14
|
const direction = opts.direction ?? "TB";
|
|
19
15
|
const stateSamples = opts.samples?.states ?? {};
|
|
20
16
|
const msgSamples = opts.samples?.msgs ?? {};
|
|
21
17
|
const hasCtx = opts.samples !== void 0 && "ctx" in opts.samples;
|
|
22
|
-
const mode =
|
|
18
|
+
const mode = formOf(machine);
|
|
23
19
|
const lines = [];
|
|
24
20
|
if (opts.title !== void 0) {
|
|
25
21
|
lines.push("---", `title: ${opts.title}`, "---");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/machine-viz/index.ts"],"names":[],"mappings":";AAmEA,SAAS,OAAO,GAAA,EAAqB;AAGnC,EAAA,MAAM,OAAA,GAAU,GAAA,CAAI,OAAA,CAAQ,gBAAA,EAAkB,GAAG,CAAA;AACjD,EAAA,IAAI,OAAA,KAAY,IAAI,OAAO,QAAA;AAC3B,EAAA,OAAO,SAAS,IAAA,CAAK,OAAO,CAAA,GAAI,CAAA,EAAA,EAAK,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* @demlik/tea/machine-viz — turn a `Machine` into a Mermaid diagram string.\n *\n * PURE. No deps, no AST parsing, no file I/O. The function reads only the\n * `Machine` value it is handed plus optional sample states/msgs/ctx.\n *\n * The trick: TEA update cells are PURE (invariant 2 — they return\n * `[nextState, cmds]` as data, no effects). So we can SAFELY EXECUTE a cell to\n * discover its target state — exactly what `replay` does. That gives us REAL\n * edges (`red --> green : go`) without parsing source. When no sample is\n * provided for a `(state, msg)` pair we cannot resolve the target, so we fall\n * back to a STRUCTURAL self-edge annotated with `?` — visually distinct from a\n * resolved edge and documented in the diagram's legend.\n *\n * Form detection mirrors `run`/`replay` (the `updateMode` logic): inspect the\n * first own key of `update`; a value that is a function ⇒ Reducer form, a value\n * that is a record ⇒ Transitions form. We do NOT add a runtime tag to Machine.\n *\n * What we MUST NOT do (these are the effectful paths, off-limits here):\n * - call `interpret[*]` handlers (perform I/O)\n * - call `subscribe[*]` handlers (install listeners)\n * - call `run` / the runtime\n * We MAY call `init`, `update[*]` cells, and `subscriptions(state)` — all pure\n * by the invariants (same set `replay` is allowed to touch).\n */\n\nimport type { Cmd, Machine, Sub } from \"../index\";\n\n// === Public options ===\n\n/**\n * Options controlling diagram emission.\n *\n * `samples` is the lever that turns STRUCTURAL edges into RESOLVED edges. For a\n * Transitions machine, providing a sample state for `stateType` AND a sample\n * msg for `msgType` lets us execute `update[stateType][msgType](state, msg)` and\n * read the real target `next.type`. Sample maps are keyed by the discriminant\n * string (`state.type` / `msg.type`).\n *\n * `samples.ctx` is the argument to `init(null, ctx)` — provide it to draw the\n * `[*] -->` initial-state edge. Omitted ⇒ no init edge (annotated as such),\n * because `init`'s signature requires a ctx and we will not invent one.\n */\nexport interface MachineVizOptions<S, M> {\n samples?: {\n /** Sample state per `state.type` — unlocks RESOLVED edges + sub annotations. */\n states?: Partial<Record<string, S>>;\n /** Sample msg per `msg.type` — unlocks RESOLVED edges. */\n msgs?: Partial<Record<string, M>>;\n /** Ctx for `init(null, ctx)` — unlocks the `[*] -->` initial-state edge. */\n ctx?: unknown;\n };\n /** Mermaid layout direction. Default `\"TB\"` (top-to-bottom). */\n direction?: \"TB\" | \"LR\";\n /** Optional diagram title, emitted as a Mermaid front-matter `title:` block. */\n title?: string;\n}\n\n// === Mermaid label escaping ===\n//\n// Mermaid state ids must be identifier-safe; arbitrary `type` strings (which\n// CAN contain `:`, spaces, `-`, etc.) are not. We sanitize the id used as the\n// node identifier and carry the human-readable original as a quoted label via\n// `stateId : \"Original\"` when they differ. Edge transition labels (after the\n// `:`) are sanitized to avoid breaking the arrow syntax.\n\n/** Sanitize a discriminant string into a Mermaid-safe node identifier. */\nfunction safeId(raw: string): string {\n // Replace any run of non-identifier chars with `_`; prefix a leading digit so\n // the id is always a valid Mermaid token. Empty ⇒ a stable placeholder.\n const cleaned = raw.replace(/[^A-Za-z0-9_]/g, \"_\");\n if (cleaned === \"\") return \"_empty\";\n return /^[0-9]/.test(cleaned) ? `s_${cleaned}` : cleaned;\n}\n\n/** Sanitize text used as a Mermaid edge/transition label (after the `:`). */\nfunction safeLabel(raw: string): string {\n // Strip the chars that terminate or confuse a transition label: newlines,\n // the `:` that separates label from target, and Mermaid's `\"`/`;` delimiters.\n return raw.replace(/[\"\\n\\r;:]/g, \" \").trim();\n}\n\n// === Form detection (mirrors run/replay updateMode) ===\n\ntype UpdateMode = \"reducer\" | \"transitions\";\n\n/**\n * Detect Reducer-vs-Transitions form from the value shape — identical logic to\n * `run`/`replay`'s `updateMode`. Inspect the first own key: a function value ⇒\n * Reducer (flat `{ [msg.type]: fn }`), a record value ⇒ Transitions (nested\n * `{ [state.type]: { [msg.type]: fn } }`). Empty object ⇒ M is `never`; the\n * mode is moot, default `\"reducer\"`.\n */\nfunction detectMode(update: unknown): UpdateMode {\n const keys = Object.keys(update as object);\n const firstKey = keys[0];\n if (firstKey === undefined) return \"reducer\";\n const firstValue = (update as Record<string, unknown>)[firstKey];\n return typeof firstValue === \"function\" ? \"reducer\" : \"transitions\";\n}\n\n// === Edge model ===\n\ntype Edge =\n // Resolved: we executed the cell with samples and read the real target.\n | { kind: \"resolved\"; from: string; to: string; msg: string }\n // Structural: no samples for the pair → target unknown, drawn as a self-loop.\n | { kind: \"structural\"; from: string; msg: string };\n\n// === toMermaid ===\n\n/**\n * Render a `Machine` as a Mermaid `stateDiagram-v2` string.\n *\n * - **Transitions form** (`update` is a record-of-records): nodes are the\n * `state.type` keys; each `(stateType × msgType)` cell becomes an edge. With\n * samples for both, the edge is RESOLVED by executing the (pure) cell. Without\n * samples it is STRUCTURAL — a `from --> from : msg?` self-loop (the `?`\n * suffix marks \"target unresolved\"). A legend note documents the distinction.\n * The `[*] -->` init edge is drawn only when `samples.ctx` is provided.\n *\n * - **Reducer form** (`update` values are functions): there is no static phase\n * graph (state is not a discriminated union over phases). We emit a single\n * node listing the handled `msg.type`s and an honest note saying so. No edges\n * are invented.\n *\n * Output is deterministic for the same input (keys iterated in insertion order,\n * no clocks, no randomness).\n */\nexport function toMermaid<\n S,\n M extends { type: string },\n C extends Cmd,\n U extends Sub,\n Ctx,\n>(\n machine: Machine<S, M, C, U, Ctx>,\n // `NoInfer` pins S/M to the `machine` argument so sample object literals in\n // `opts` are CHECKED against the machine's State/Msg unions rather than\n // driving inference (which would widen `{ type: \"open\" }` to `{ type: string }`\n // and collide with the machine's discriminated union).\n opts: MachineVizOptions<NoInfer<S>, NoInfer<M>> = {},\n): string {\n const direction = opts.direction ?? \"TB\";\n const stateSamples = opts.samples?.states ?? {};\n const msgSamples = opts.samples?.msgs ?? {};\n const hasCtx = opts.samples !== undefined && \"ctx\" in opts.samples;\n\n const mode = detectMode(machine.update);\n const lines: string[] = [];\n\n // Front matter — Mermaid reads a YAML `title:` block before the diagram.\n if (opts.title !== undefined) {\n lines.push(\"---\", `title: ${opts.title}`, \"---\");\n }\n lines.push(\"stateDiagram-v2\");\n lines.push(` direction ${direction}`);\n\n if (mode === \"reducer\") {\n emitReducer(machine, lines);\n } else {\n emitTransitions(machine, lines, {\n stateSamples,\n msgSamples,\n hasCtx,\n ctx: opts.samples?.ctx,\n });\n }\n\n // Subscriptions annotation — pure call to `subscriptions(sampleState)` per\n // sampled state. Skipped entirely when no state samples are provided (we\n // refuse to invent a state to feed it).\n emitSubscriptions(machine, lines, stateSamples);\n\n return lines.join(\"\\n\");\n}\n\n// === Reducer-form emission ===\n\n/**\n * Reducer form has no phase graph. Emit one node listing the handled msg types\n * plus an honest note. The msg set is the `update` record's keys (the Reducer\n * mapped type guarantees one cell per Msg variant).\n */\nfunction emitReducer(machine: { update: unknown }, lines: string[]): void {\n const msgTypes = Object.keys(machine.update as object);\n lines.push(\" state ReducerMachine {\");\n if (msgTypes.length === 0) {\n lines.push(\" [*] --> NoMsgs\");\n lines.push(' NoMsgs : \"(no msg variants — M is never)\"');\n } else {\n for (const m of msgTypes) {\n lines.push(` ${safeId(m)} : ${safeLabel(m)}`);\n }\n }\n lines.push(\" }\");\n // The note IS the design honesty: no edges, because reducer-form state is not\n // a discriminated union over phases — there is no static target to draw.\n lines.push(\" note right of ReducerMachine\");\n lines.push(\" Reducer-form machine: flat dispatch keyed by msg.type.\");\n lines.push(\n \" No phase graph — state is not a discriminated union over phases.\",\n );\n lines.push(` Handled msg types: ${msgTypes.length}`);\n lines.push(\" end note\");\n}\n\n// === Transitions-form emission ===\n\ninterface TransitionsCtx<S, M> {\n stateSamples: Partial<Record<string, S>>;\n msgSamples: Partial<Record<string, M>>;\n hasCtx: boolean;\n ctx: unknown;\n}\n\n/**\n * Transitions form: walk the `update[stateType][msgType]` table. Execute the\n * (pure) cell when both samples exist → RESOLVED edge; otherwise → STRUCTURAL\n * self-loop. Draw the `[*] -->` init edge only when a ctx sample is given.\n */\nfunction emitTransitions<\n S,\n M extends { type: string },\n C extends Cmd,\n U extends Sub,\n Ctx,\n>(\n machine: Machine<S, M, C, U, Ctx>,\n lines: string[],\n ctx: TransitionsCtx<S, M>,\n): void {\n type CellFn = (state: S, msg: M) => readonly [S, readonly C[]];\n type Table = Record<string, Record<string, CellFn>>;\n const table = machine.update as unknown as Table;\n const stateTypes = Object.keys(table);\n\n // Declare every node up front so even unreachable phases render.\n for (const st of stateTypes) {\n lines.push(` ${safeId(st)}`);\n }\n\n // Init edge — only resolvable with a ctx sample. `init(null, ctx)` is pure\n // (invariant 2: fresh-boot branch returns a starting state). Read `next.type`.\n if (ctx.hasCtx) {\n const [initState] = machine.init(null, ctx.ctx as Ctx);\n const initType = (initState as unknown as { type: string }).type;\n lines.push(` [*] --> ${safeId(initType)}`);\n } else {\n lines.push(\n \" %% init edge omitted: no samples.ctx provided to run init(null, ctx)\",\n );\n }\n\n let anyStructural = false;\n for (const st of stateTypes) {\n const row = table[st];\n if (row === undefined) continue;\n const msgTypes = Object.keys(row);\n for (const mt of msgTypes) {\n const edge = resolveEdge(row, st, mt, ctx);\n if (edge.kind === \"resolved\") {\n lines.push(\n ` ${safeId(edge.from)} --> ${safeId(edge.to)} : ${safeLabel(edge.msg)}`,\n );\n } else {\n anyStructural = true;\n // Structural self-loop with a `?` suffix — target unresolved. Visually\n // distinct from a resolved edge (self-loop + trailing `?`).\n lines.push(\n ` ${safeId(edge.from)} --> ${safeId(edge.from)} : ${safeLabel(edge.msg)}?`,\n );\n }\n }\n }\n\n // Legend — document the resolved-vs-structural distinction in the output.\n lines.push(` note right of ${safeId(stateTypes[0] ?? \"_empty\")}`);\n lines.push(\" Transitions-form machine.\");\n lines.push(\" Edge a --> b : msg = RESOLVED (cell executed with samples).\");\n if (anyStructural) {\n lines.push(\n \" Self-loop a --> a : msg? = STRUCTURAL (no sample; target unresolved).\",\n );\n }\n lines.push(\" end note\");\n}\n\n/**\n * Resolve a single `(stateType, msgType)` cell into an Edge. With both a sample\n * state and a sample msg, EXECUTE the pure cell to read the real target. Any\n * missing sample → structural. A thrown cell (e.g. a sample shaped wrong for\n * the cell) degrades to structural rather than crashing the whole diagram —\n * the diagram is a best-effort visualization, not a correctness gate.\n */\nfunction resolveEdge<S, M extends { type: string }, C extends Cmd>(\n row: Record<string, (state: S, msg: M) => readonly [S, readonly C[]]>,\n stateType: string,\n msgType: string,\n ctx: {\n stateSamples: Partial<Record<string, S>>;\n msgSamples: Partial<Record<string, M>>;\n },\n): Edge {\n const sampleState = ctx.stateSamples[stateType];\n const sampleMsg = ctx.msgSamples[msgType];\n const cell = row[msgType];\n if (\n sampleState === undefined ||\n sampleMsg === undefined ||\n cell === undefined\n ) {\n return { kind: \"structural\", from: stateType, msg: msgType };\n }\n try {\n const [next] = cell(sampleState, sampleMsg);\n const to = (next as unknown as { type: string }).type;\n return { kind: \"resolved\", from: stateType, to, msg: msgType };\n } catch {\n // Mismatched sample → cannot resolve. Fall back to structural.\n return { kind: \"structural\", from: stateType, msg: msgType };\n }\n}\n\n// === Subscriptions annotation ===\n\n/**\n * For each sampled state, call the (pure) `subscriptions(state)` description\n * function and annotate which Sub types are active in that state as a Mermaid\n * note. We call `subscriptions` (the description) but NEVER `subscribe[*]` (the\n * effectful installer) — same boundary `replay` honors. Skipped when no state\n * samples are provided or the machine declares no `subscriptions`.\n */\nfunction emitSubscriptions<\n S,\n M extends { type: string },\n C extends Cmd,\n U extends Sub,\n Ctx,\n>(\n machine: Machine<S, M, C, U, Ctx>,\n lines: string[],\n stateSamples: Partial<Record<string, S>>,\n): void {\n if (machine.subscriptions === undefined) return;\n const stateTypes = Object.keys(stateSamples);\n if (stateTypes.length === 0) return;\n\n for (const st of stateTypes) {\n const sample = stateSamples[st];\n if (sample === undefined) continue;\n const subs = machine.subscriptions(sample);\n const subTypes = subs.map((s) => s.type);\n const body =\n subTypes.length === 0\n ? \"(no active subs)\"\n : `subs: ${subTypes.map(safeLabel).join(\", \")}`;\n lines.push(` note left of ${safeId(st)}`);\n lines.push(` ${body}`);\n lines.push(\" end note\");\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/machine-viz/index.ts"],"names":[],"mappings":";;;;AAoEA,SAAS,OAAO,GAAA,EAAqB;AAGnC,EAAA,MAAM,OAAA,GAAU,GAAA,CAAI,OA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AQ;AAEN,IAAA,OAAO,EAAE,IAAA,EAAM,YAAA,EAAc,IAAA,EAAM,SAAA,EAAW,KAAK,OAAA,EAAQ;AAAA,EAC7D;AACF;AAWA,SAAS,iBAAA,CAOP,OAAA,EACA,KAAA,EACA,YAAA,EACM;AACN,EAAA,IAAI,OAAA,CAAQ,kBAAkB,MAAA,EAAW;AACzC,EAAA,MAAM,UAAA,GAAa,MAAA,CAAO,IAAA,CAAK,YAAY,CAAA;AAC3C,EAAA,IAAI,UAAA,CAAW,WAAW,CAAA,EAAG;AAE7B,EAAA,KAAA,MAAW,MAAM,UAAA,EAAY;AAC3B,IAAA,MAAM,MAAA,GAAS,aAAa,EAAE,CAAA;AAC9B,IAAA,IAAI,WAAW,MAAA,EAAW;AAC1B,IAAA,MAAM,IAAA,GAAO,OAAA,CAAQ,aAAA,CAAc,MAAM,CAAA;AACzC,IAAA,MAAM,WAAW,IAAA,CAAK,GAAA,CAAI,CAAC,CAAA,KAAM,EAAE,IAAI,CAAA;AACvC,IAAA,MAAM,IAAA,GACJ,QAAA,CAAS,MAAA,KAAW,CAAA,GAChB,kBAAA,GACA,CAAA,MAAA,EAAS,QAAA,CAAS,GAAA,CAAI,SAAS,CAAA,CAAE,IAAA,CAAK,IAAI,CAAC,CAAA,CAAA;AACjD,IAAA,KAAA,CAAM,IAAA,CAAK,CAAA,eAAA,EAAkB,MAAA,CAAO,EAAE,CAAC,CAAA,CAAE,CAAA;AACzC,IAAA,KAAA,CAAM,IAAA,CAAK,CAAA,IAAA,EAAO,IAAI,CAAA,CAAE,CAAA;AACxB,IAAA,KAAA,CAAM,KAAK,YAAY,CAAA;AAAA,EACzB;AACF","file":"index.js","sourcesContent":["/**\n * @demlik/tea/machine-viz — turn a `Machine` into a Mermaid diagram string.\n *\n * PURE. No deps, no AST parsing, no file I/O. The function reads only the\n * `Machine` value it is handed plus optional sample states/msgs/ctx.\n *\n * The trick: TEA update cells are PURE (invariant 2 — they return\n * `[nextState, cmds]` as data, no effects). So we can SAFELY EXECUTE a cell to\n * discover its target state — exactly what `replay` does. That gives us REAL\n * edges (`red --> green : go`) without parsing source. When no sample is\n * provided for a `(state, msg)` pair we cannot resolve the target, so we fall\n * back to a STRUCTURAL self-edge annotated with `?` — visually distinct from a\n * resolved edge and documented in the diagram's legend.\n *\n * Form detection is `formOf(machine)` — the same reader `run`/`replay` use,\n * honoring the authoritative `__form` tag `defineMachine` stamps (falling back\n * to the structural heuristic for machines built without it; #275).\n *\n * What we MUST NOT do (these are the effectful paths, off-limits here):\n * - call `interpret[*]` handlers (perform I/O)\n * - call `subscribe[*]` handlers (install listeners)\n * - call `run` / the runtime\n * We MAY call `init`, `update[*]` cells, and `subscriptions(state)` — all pure\n * by the invariants (same set `replay` is allowed to touch).\n */\n\nimport type { Cmd, Machine, Sub } from \"../index\";\nimport { formOf } from \"../index\";\n\n// === Public options ===\n\n/**\n * Options controlling diagram emission.\n *\n * `samples` is the lever that turns STRUCTURAL edges into RESOLVED edges. For a\n * Transitions machine, providing a sample state for `stateType` AND a sample\n * msg for `msgType` lets us execute `update[stateType][msgType](state, msg)` and\n * read the real target `next.type`. Sample maps are keyed by the discriminant\n * string (`state.type` / `msg.type`).\n *\n * `samples.ctx` is the argument to `init(null, ctx)` — provide it to draw the\n * `[*] -->` initial-state edge. Omitted ⇒ no init edge (annotated as such),\n * because `init`'s signature requires a ctx and we will not invent one.\n */\nexport interface MachineVizOptions<S, M> {\n samples?: {\n /** Sample state per `state.type` — unlocks RESOLVED edges + sub annotations. */\n states?: Partial<Record<string, S>>;\n /** Sample msg per `msg.type` — unlocks RESOLVED edges. */\n msgs?: Partial<Record<string, M>>;\n /** Ctx for `init(null, ctx)` — unlocks the `[*] -->` initial-state edge. */\n ctx?: unknown;\n };\n /** Mermaid layout direction. Default `\"TB\"` (top-to-bottom). */\n direction?: \"TB\" | \"LR\";\n /** Optional diagram title, emitted as a Mermaid front-matter `title:` block. */\n title?: string;\n}\n\n// === Mermaid label escaping ===\n//\n// Mermaid state ids must be identifier-safe; arbitrary `type` strings (which\n// CAN contain `:`, spaces, `-`, etc.) are not. We sanitize the id used as the\n// node identifier and carry the human-readable original as a quoted label via\n// `stateId : \"Original\"` when they differ. Edge transition labels (after the\n// `:`) are sanitized to avoid breaking the arrow syntax.\n\n/** Sanitize a discriminant string into a Mermaid-safe node identifier. */\nfunction safeId(raw: string): string {\n // Replace any run of non-identifier chars with `_`; prefix a leading digit so\n // the id is always a valid Mermaid token. Empty ⇒ a stable placeholder.\n const cleaned = raw.replace(/[^A-Za-z0-9_]/g, \"_\");\n if (cleaned === \"\") return \"_empty\";\n return /^[0-9]/.test(cleaned) ? `s_${cleaned}` : cleaned;\n}\n\n/** Sanitize text used as a Mermaid edge/transition label (after the `:`). */\nfunction safeLabel(raw: string): string {\n // Strip the chars that terminate or confuse a transition label: newlines,\n // the `:` that separates label from target, and Mermaid's `\"`/`;` delimiters.\n return raw.replace(/[\"\\n\\r;:]/g, \" \").trim();\n}\n\n// === Edge model ===\n\ntype Edge =\n // Resolved: we executed the cell with samples and read the real target.\n | { kind: \"resolved\"; from: string; to: string; msg: string }\n // Structural: no samples for the pair → target unknown, drawn as a self-loop.\n | { kind: \"structural\"; from: string; msg: string };\n\n// === toMermaid ===\n\n/**\n * Render a `Machine` as a Mermaid `stateDiagram-v2` string.\n *\n * - **Transitions form** (`update` is a record-of-records): nodes are the\n * `state.type` keys; each `(stateType × msgType)` cell becomes an edge. With\n * samples for both, the edge is RESOLVED by executing the (pure) cell. Without\n * samples it is STRUCTURAL — a `from --> from : msg?` self-loop (the `?`\n * suffix marks \"target unresolved\"). A legend note documents the distinction.\n * The `[*] -->` init edge is drawn only when `samples.ctx` is provided.\n *\n * - **Reducer form** (`update` values are functions): there is no static phase\n * graph (state is not a discriminated union over phases). We emit a single\n * node listing the handled `msg.type`s and an honest note saying so. No edges\n * are invented.\n *\n * Output is deterministic for the same input (keys iterated in insertion order,\n * no clocks, no randomness).\n */\nexport function toMermaid<\n S,\n M extends { type: string },\n C extends Cmd,\n U extends Sub,\n Ctx,\n>(\n machine: Machine<S, M, C, U, Ctx>,\n // `NoInfer` pins S/M to the `machine` argument so sample object literals in\n // `opts` are CHECKED against the machine's State/Msg unions rather than\n // driving inference (which would widen `{ type: \"open\" }` to `{ type: string }`\n // and collide with the machine's discriminated union).\n opts: MachineVizOptions<NoInfer<S>, NoInfer<M>> = {},\n): string {\n const direction = opts.direction ?? \"TB\";\n const stateSamples = opts.samples?.states ?? {};\n const msgSamples = opts.samples?.msgs ?? {};\n const hasCtx = opts.samples !== undefined && \"ctx\" in opts.samples;\n\n const mode = formOf(machine);\n const lines: string[] = [];\n\n // Front matter — Mermaid reads a YAML `title:` block before the diagram.\n if (opts.title !== undefined) {\n lines.push(\"---\", `title: ${opts.title}`, \"---\");\n }\n lines.push(\"stateDiagram-v2\");\n lines.push(` direction ${direction}`);\n\n if (mode === \"reducer\") {\n emitReducer(machine, lines);\n } else {\n emitTransitions(machine, lines, {\n stateSamples,\n msgSamples,\n hasCtx,\n ctx: opts.samples?.ctx,\n });\n }\n\n // Subscriptions annotation — pure call to `subscriptions(sampleState)` per\n // sampled state. Skipped entirely when no state samples are provided (we\n // refuse to invent a state to feed it).\n emitSubscriptions(machine, lines, stateSamples);\n\n return lines.join(\"\\n\");\n}\n\n// === Reducer-form emission ===\n\n/**\n * Reducer form has no phase graph. Emit one node listing the handled msg types\n * plus an honest note. The msg set is the `update` record's keys (the Reducer\n * mapped type guarantees one cell per Msg variant).\n */\nfunction emitReducer(machine: { update: unknown }, lines: string[]): void {\n const msgTypes = Object.keys(machine.update as object);\n lines.push(\" state ReducerMachine {\");\n if (msgTypes.length === 0) {\n lines.push(\" [*] --> NoMsgs\");\n lines.push(' NoMsgs : \"(no msg variants — M is never)\"');\n } else {\n for (const m of msgTypes) {\n lines.push(` ${safeId(m)} : ${safeLabel(m)}`);\n }\n }\n lines.push(\" }\");\n // The note IS the design honesty: no edges, because reducer-form state is not\n // a discriminated union over phases — there is no static target to draw.\n lines.push(\" note right of ReducerMachine\");\n lines.push(\" Reducer-form machine: flat dispatch keyed by msg.type.\");\n lines.push(\n \" No phase graph — state is not a discriminated union over phases.\",\n );\n lines.push(` Handled msg types: ${msgTypes.length}`);\n lines.push(\" end note\");\n}\n\n// === Transitions-form emission ===\n\ninterface TransitionsCtx<S, M> {\n stateSamples: Partial<Record<string, S>>;\n msgSamples: Partial<Record<string, M>>;\n hasCtx: boolean;\n ctx: unknown;\n}\n\n/**\n * Transitions form: walk the `update[stateType][msgType]` table. Execute the\n * (pure) cell when both samples exist → RESOLVED edge; otherwise → STRUCTURAL\n * self-loop. Draw the `[*] -->` init edge only when a ctx sample is given.\n */\nfunction emitTransitions<\n S,\n M extends { type: string },\n C extends Cmd,\n U extends Sub,\n Ctx,\n>(\n machine: Machine<S, M, C, U, Ctx>,\n lines: string[],\n ctx: TransitionsCtx<S, M>,\n): void {\n type CellFn = (state: S, msg: M) => readonly [S, readonly C[]];\n type Table = Record<string, Record<string, CellFn>>;\n const table = machine.update as unknown as Table;\n const stateTypes = Object.keys(table);\n\n // Declare every node up front so even unreachable phases render.\n for (const st of stateTypes) {\n lines.push(` ${safeId(st)}`);\n }\n\n // Init edge — only resolvable with a ctx sample. `init(null, ctx)` is pure\n // (invariant 2: fresh-boot branch returns a starting state). Read `next.type`.\n if (ctx.hasCtx) {\n const [initState] = machine.init(null, ctx.ctx as Ctx);\n const initType = (initState as unknown as { type: string }).type;\n lines.push(` [*] --> ${safeId(initType)}`);\n } else {\n lines.push(\n \" %% init edge omitted: no samples.ctx provided to run init(null, ctx)\",\n );\n }\n\n let anyStructural = false;\n for (const st of stateTypes) {\n const row = table[st];\n if (row === undefined) continue;\n const msgTypes = Object.keys(row);\n for (const mt of msgTypes) {\n const edge = resolveEdge(row, st, mt, ctx);\n if (edge.kind === \"resolved\") {\n lines.push(\n ` ${safeId(edge.from)} --> ${safeId(edge.to)} : ${safeLabel(edge.msg)}`,\n );\n } else {\n anyStructural = true;\n // Structural self-loop with a `?` suffix — target unresolved. Visually\n // distinct from a resolved edge (self-loop + trailing `?`).\n lines.push(\n ` ${safeId(edge.from)} --> ${safeId(edge.from)} : ${safeLabel(edge.msg)}?`,\n );\n }\n }\n }\n\n // Legend — document the resolved-vs-structural distinction in the output.\n lines.push(` note right of ${safeId(stateTypes[0] ?? \"_empty\")}`);\n lines.push(\" Transitions-form machine.\");\n lines.push(\" Edge a --> b : msg = RESOLVED (cell executed with samples).\");\n if (anyStructural) {\n lines.push(\n \" Self-loop a --> a : msg? = STRUCTURAL (no sample; target unresolved).\",\n );\n }\n lines.push(\" end note\");\n}\n\n/**\n * Resolve a single `(stateType, msgType)` cell into an Edge. With both a sample\n * state and a sample msg, EXECUTE the pure cell to read the real target. Any\n * missing sample → structural. A thrown cell (e.g. a sample shaped wrong for\n * the cell) degrades to structural rather than crashing the whole diagram —\n * the diagram is a best-effort visualization, not a correctness gate.\n */\nfunction resolveEdge<S, M extends { type: string }, C extends Cmd>(\n row: Record<string, (state: S, msg: M) => readonly [S, readonly C[]]>,\n stateType: string,\n msgType: string,\n ctx: {\n stateSamples: Partial<Record<string, S>>;\n msgSamples: Partial<Record<string, M>>;\n },\n): Edge {\n const sampleState = ctx.stateSamples[stateType];\n const sampleMsg = ctx.msgSamples[msgType];\n const cell = row[msgType];\n if (\n sampleState === undefined ||\n sampleMsg === undefined ||\n cell === undefined\n ) {\n return { kind: \"structural\", from: stateType, msg: msgType };\n }\n try {\n const [next] = cell(sampleState, sampleMsg);\n const to = (next as unknown as { type: string }).type;\n return { kind: \"resolved\", from: stateType, to, msg: msgType };\n } catch {\n // Mismatched sample → cannot resolve. Fall back to structural.\n return { kind: \"structural\", from: stateType, msg: msgType };\n }\n}\n\n// === Subscriptions annotation ===\n\n/**\n * For each sampled state, call the (pure) `subscriptions(state)` description\n * function and annotate which Sub types are active in that state as a Mermaid\n * note. We call `subscriptions` (the description) but NEVER `subscribe[*]` (the\n * effectful installer) — same boundary `replay` honors. Skipped when no state\n * samples are provided or the machine declares no `subscriptions`.\n */\nfunction emitSubscriptions<\n S,\n M extends { type: string },\n C extends Cmd,\n U extends Sub,\n Ctx,\n>(\n machine: Machine<S, M, C, U, Ctx>,\n lines: string[],\n stateSamples: Partial<Record<string, S>>,\n): void {\n if (machine.subscriptions === undefined) return;\n const stateTypes = Object.keys(stateSamples);\n if (stateTypes.length === 0) return;\n\n for (const st of stateTypes) {\n const sample = stateSamples[st];\n if (sample === undefined) continue;\n const subs = machine.subscriptions(sample);\n const subTypes = subs.map((s) => s.type);\n const body =\n subTypes.length === 0\n ? \"(no active subs)\"\n : `subs: ${subTypes.map(safeLabel).join(\", \")}`;\n lines.push(` note left of ${safeId(st)}`);\n lines.push(` ${body}`);\n lines.push(\" end note\");\n }\n}\n"]}
|
package/dist/mem/index.d.ts
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { DeadlineExceeded, DeadlineSub } from '../deadline/index.js';
|
|
2
2
|
export { deadlineSub, subscribeDeadline } from '../deadline/index.js';
|
|
3
|
-
import { I as Interpret, C as Cmd } from '../core-
|
|
3
|
+
import { I as Interpret, C as Cmd } from '../core-BmlJOvxM.js';
|
|
4
4
|
import { SnapshotState, SnapshotWriteCmd, SnapshotStore, SnapshotSavedMsg, SnapshotFailedMsg, SnapshotLoadedMsg, SnapshotLoadFailedMsg, SnapshotLoadCmd } from '../snapshot/index.js';
|
|
5
5
|
import { QueueItem } from '../work-queue/index.js';
|
|
6
|
-
import '../types-
|
|
6
|
+
import '../types-BoUWgwSm.js';
|
|
7
7
|
import '../index.js';
|
|
8
8
|
|
|
9
9
|
/**
|
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
export { createMonitoredRun, liftRun } from '../chunk-
|
|
2
|
-
import '../chunk-
|
|
3
|
-
export { deadlineSub, subscribeDeadline } from '../chunk-
|
|
1
|
+
export { createMonitoredRun, liftRun } from '../chunk-ZDRN3YCE.js';
|
|
2
|
+
import '../chunk-5KVHID6A.js';
|
|
3
|
+
export { deadlineSub, subscribeDeadline } from '../chunk-SKAMZKTE.js';
|
|
4
4
|
import '../chunk-HJO6VNQI.js';
|
|
5
5
|
import '../chunk-TGG26XMK.js';
|
|
6
6
|
import '../chunk-2YFLOCWX.js';
|
|
7
|
-
import '../chunk-
|
|
8
|
-
import '../chunk-
|
|
7
|
+
import '../chunk-6VDCTR7N.js';
|
|
8
|
+
import '../chunk-DYRKDCJI.js';
|
|
9
9
|
//# sourceMappingURL=index.js.map
|
|
10
10
|
//# sourceMappingURL=index.js.map
|
package/dist/node/index.d.ts
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import { C as Cmd } from '../core-
|
|
1
|
+
import { C as Cmd } from '../core-BmlJOvxM.js';
|
|
2
2
|
import { PaginatorState } from '../paginator/index.js';
|
|
3
3
|
import { CircuitConfig, RateLimitConfig, DeadlineConfig, ResilientState, RunCmd, SucceedMsg, FailMsg, ResilientTimerMsg, ResilientPorts } from '../resilient-call/index.js';
|
|
4
4
|
import { RetryPolicy } from '../retry-backoff/index.js';
|
|
5
5
|
import { DeadlineSub } from '../deadline/index.js';
|
|
6
6
|
export { deadlineSub, subscribeDeadline } from '../deadline/index.js';
|
|
7
7
|
import '../cache/index.js';
|
|
8
|
-
import '../types-
|
|
8
|
+
import '../types-BoUWgwSm.js';
|
|
9
9
|
import '../circuit-breaker/index.js';
|
|
10
10
|
import '../protocol-B5YmJr0d.js';
|
|
11
11
|
import '../rate-limit/index.js';
|
|
@@ -1,15 +1,15 @@
|
|
|
1
|
-
export { PAGE_KEY, createPaginatedWalk, liftWalk } from '../chunk-
|
|
1
|
+
export { PAGE_KEY, createPaginatedWalk, liftWalk } from '../chunk-FOGL3TC7.js';
|
|
2
2
|
import '../chunk-SINXE47Y.js';
|
|
3
|
-
import '../chunk-
|
|
3
|
+
import '../chunk-6GIGQT6C.js';
|
|
4
4
|
import '../chunk-JELSZN25.js';
|
|
5
|
-
export { deadlineSub, subscribeDeadline } from '../chunk-
|
|
5
|
+
export { deadlineSub, subscribeDeadline } from '../chunk-SKAMZKTE.js';
|
|
6
6
|
import '../chunk-5VNWZADP.js';
|
|
7
7
|
import '../chunk-2YOE5PIS.js';
|
|
8
8
|
import '../chunk-SC3FAFZN.js';
|
|
9
9
|
import '../chunk-IN33Q4VJ.js';
|
|
10
10
|
import '../chunk-NSDFA6M6.js';
|
|
11
11
|
import '../chunk-2YFLOCWX.js';
|
|
12
|
-
import '../chunk-
|
|
13
|
-
import '../chunk-
|
|
12
|
+
import '../chunk-6VDCTR7N.js';
|
|
13
|
+
import '../chunk-DYRKDCJI.js';
|
|
14
14
|
//# sourceMappingURL=index.js.map
|
|
15
15
|
//# sourceMappingURL=index.js.map
|
package/dist/parity/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { BootingRuntime } from '../index.js';
|
|
2
2
|
import { Trace, RecorderOptions } from '../recorder/index.js';
|
|
3
|
-
import { C as Cmd, S as Sub, M as Machine } from '../core-
|
|
3
|
+
import { C as Cmd, S as Sub, M as Machine } from '../core-BmlJOvxM.js';
|
|
4
4
|
|
|
5
5
|
/**
|
|
6
6
|
* A live parity recording attached to a Runtime — the go/no-go gate's golden
|
|
@@ -71,7 +71,7 @@ interface ParitySchema {
|
|
|
71
71
|
* schema's `stripKeys`, recursively sorts object keys, and stable-key-sorts
|
|
72
72
|
* arrays by the schema's `sortKeys`. Two runs that differ only in generated
|
|
73
73
|
* ids/timestamps or intra-effect ordering normalize to a byte-identical value,
|
|
74
|
-
* so {@link
|
|
74
|
+
* so {@link parityEqual} on the normalized pair reflects behavioural (not incidental)
|
|
75
75
|
* difference.
|
|
76
76
|
*/
|
|
77
77
|
declare function normalizeForParity(schema?: ParitySchema): (value: unknown) => unknown;
|
|
@@ -81,6 +81,12 @@ declare function normalizeForParity(schema?: ParitySchema): (value: unknown) =>
|
|
|
81
81
|
* package owns) rather than adding a second one — feed it the pair produced by
|
|
82
82
|
* {@link normalizeForParity} for the normalized-JSON equality the gate rests on.
|
|
83
83
|
*/
|
|
84
|
-
declare function
|
|
84
|
+
declare function parityEqual(a: unknown, b: unknown): boolean;
|
|
85
|
+
/**
|
|
86
|
+
* @deprecated Inverted name — it returns `true` when the values are EQUAL, so
|
|
87
|
+
* `if (diff(old, new))` reads backwards (#278). Use {@link parityEqual}.
|
|
88
|
+
* Alias kept for one minor, then removed.
|
|
89
|
+
*/
|
|
90
|
+
declare const diff: typeof parityEqual;
|
|
85
91
|
|
|
86
|
-
export { type ParitySchema, type Recording, diff, goldenReplay, normalizeForParity, recordRun };
|
|
92
|
+
export { type ParitySchema, type Recording, diff, goldenReplay, normalizeForParity, parityEqual, recordRun };
|
package/dist/parity/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { recorder } from '../chunk-UYWUVEP6.js';
|
|
2
|
-
import { deepEqual } from '../chunk-
|
|
3
|
-
import { replay } from '../chunk-
|
|
4
|
-
import '../chunk-
|
|
2
|
+
import { deepEqual } from '../chunk-IK4S5DJN.js';
|
|
3
|
+
import { replay } from '../chunk-6VDCTR7N.js';
|
|
4
|
+
import '../chunk-DYRKDCJI.js';
|
|
5
5
|
|
|
6
6
|
// src/parity/index.ts
|
|
7
7
|
function recordRun(runtime, opts) {
|
|
@@ -68,10 +68,11 @@ function compareStrings(a, b) {
|
|
|
68
68
|
function isPlainObject(value) {
|
|
69
69
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
70
70
|
}
|
|
71
|
-
function
|
|
71
|
+
function parityEqual(a, b) {
|
|
72
72
|
return deepEqual(a, b);
|
|
73
73
|
}
|
|
74
|
+
var diff = parityEqual;
|
|
74
75
|
|
|
75
|
-
export { diff, goldenReplay, normalizeForParity, recordRun };
|
|
76
|
+
export { diff, goldenReplay, normalizeForParity, parityEqual, recordRun };
|
|
76
77
|
//# sourceMappingURL=index.js.map
|
|
77
78
|
//# sourceMappingURL=index.js.map
|
package/dist/parity/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["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Ac,QAAA,IACrB,OAAO,cAAc,QAAA,IACrB,OAAO,cAAc,SAAA,EACrB;AACA,MAAA,OAAO,OAAO,SAAS,CAAA;AAAA,IACzB;AAAA,EACF;AACA,EAAA,OAAO,EAAA;AACT;AAEA,SAAS,cAAA,CAAe,GAAW,CAAA,EAAmB;AACpD,EAAA,OAAO,CAAA,GAAI,CAAA,GAAI,EAAA,GAAK,CAAA,GAAI,IAAI,CAAA,GAAI,CAAA;AAClC;AAEA,SAAS,cAAc,KAAA,EAAkD;AACvE,EAAA,OAAO,OAAO,UAAU,QAAA,IAAY,KAAA,KAAU,QAAQ,CAAC,KAAA,CAAM,QAAQ,KAAK,CAAA;AAC5E;AAQO,SAAS,IAAA,CAAK,GAAY,CAAA,EAAqB;AACpD,EAAA,OAAO,SAAA,CAAU,GAAG,CAAC,CAAA;AACvB","file":"index.js","sourcesContent":["// ---------------------------------------------------------------------------\n// parity — the record → replay → normalized-diff go/no-go gate.\n//\n// The parity spike proved the mechanism already composes from in-tree\n// primitives: `recorder` captures a run's Msg sequence (the recording), `replay`\n// re-folds it purely, and `trace-replay`'s order-insensitive deep-equal diffs\n// the result. Non-determinism is a RECORD-TIME property — ids/timestamps freeze\n// into the recording, `replay` never re-mints them — so the same recording\n// replays byte-identical every time.\n//\n// This module is the thin packaging over that substrate plus the one genuinely\n// new helper, `normalizeForParity`: the finding-normalizer that strips\n// record-time non-determinism (generated ids/timestamps) and stable-key-sorts\n// collections, so an OLD-engine golden run and a NEW-engine run diff as equal\n// exactly when they are behaviourally equivalent. Every domain (audit, auth,\n// ingest, …) gets its old-vs-new parity check without reinventing the capture,\n// the normalization, and the diff.\n//\n// recordRun(runtime) → Recording // wraps the recorder\n// goldenReplay(machine, rec) → State // wraps replay\n// normalizeForParity(schema) → (finding) => norm // strip + stable-sort\n// diff(a, b) → boolean // normalized deep-equal\n// ---------------------------------------------------------------------------\n\nimport type { BootingRuntime, Cmd, Machine, Sub } from \"../index\";\nimport { replay } from \"../index\";\nimport { type RecorderOptions, recorder, type Trace } from \"../recorder\";\nimport { deepEqual } from \"../trace-replay\";\n\n/**\n * A live parity recording attached to a Runtime — the go/no-go gate's golden\n * artifact. Wraps a {@link recorder}: drive the runtime, then snapshot with\n * {@link Recording.trace} (or hand the live `Recording` straight to\n * {@link goldenReplay}, which snapshots for you).\n *\n * @typeParam S - the machine's State type.\n * @typeParam M - the machine's Msg union.\n */\nexport interface Recording<S, M> {\n /**\n * Snapshot the recording so far as a replayable {@link Trace} — `loaded`\n * (boot state), the ordered non-null `msgs`, and `finalState`. Sufficient to\n * reproduce the run via {@link goldenReplay}. Fresh object each call.\n */\n trace(): Trace<S, M>;\n /** Serialize the recording as JSONL (see {@link recorder}'s `toJSONL`). */\n toJSONL(): string;\n /** Detach the underlying observer. Idempotent. */\n stop(): void;\n}\n\n/**\n * Attach a parity recording to a Runtime, reusing the `recorder`/`historyTracker`\n * capture (the boot observe for `loaded` + every non-null msg in order) rather\n * than a fresh observer path.\n *\n * Attach on the synchronous `run()` handle so the boot transition is captured\n * as `loaded`; drive the runtime; then `trace()` (or pass the handle to\n * {@link goldenReplay}). See {@link RecorderOptions} for `captureSteps` (needed\n * only for the per-step / resume-cache-prefix inspection, not for replay).\n */\nexport function recordRun<S, M extends { type: string }>(\n runtime: BootingRuntime<S, M>,\n opts?: RecorderOptions,\n): Recording<S, M> {\n const rec = recorder(runtime, opts);\n return {\n trace: () => rec.dump(),\n toJSONL: () => rec.toJSONL(),\n stop: () => rec.stop(),\n };\n}\n\n/**\n * Reproduce a recording's final state by folding its msgs through the pure\n * `replay` — `init(loaded, ctx)` then `update` per msg, never `interpret`,\n * never a `Store`, never a live subscription. Accepts a live {@link Recording}\n * (snapshotted here) or a bare {@link Trace}.\n *\n * `ctx` is the ENVIRONMENT supplied fresh at replay time (the trace is the\n * INPUT: `loaded` + `msgs`), mirroring `replayTrace`. It is optional so a\n * void-ctx machine can call `goldenReplay(machine, rec)`; a machine that reads\n * ctx passes it explicitly.\n */\nexport function goldenReplay<\n S,\n M extends { type: string },\n C extends Cmd,\n U extends Sub,\n Ctx,\n>(\n machine: Machine<S, M, C, U, Ctx>,\n recording: Recording<S, M> | Trace<S, M>,\n ctx?: Ctx,\n): S {\n const trace = asTrace(recording);\n const { state } = replay(machine, {\n msgs: trace.msgs,\n ctx: ctx as Ctx,\n loaded: trace.loaded,\n });\n return state;\n}\n\n/** Narrow a `Recording | Trace` to a `Trace`, snapshotting a live recording. */\nfunction asTrace<S, M>(recording: Recording<S, M> | Trace<S, M>): Trace<S, M> {\n return typeof (recording as Recording<S, M>).trace === \"function\"\n ? (recording as Recording<S, M>).trace()\n : (recording as Trace<S, M>);\n}\n\n/** Configuration for {@link normalizeForParity}. */\nexport interface ParitySchema {\n /**\n * Object keys stripped wherever they appear — the record-time\n * non-determinism `replay` never re-mints. Default: `id`, `runId`,\n * `timestamp`.\n */\n readonly stripKeys?: readonly string[];\n /**\n * Candidate keys used to stable-sort arrays of objects. For each array the\n * first candidate present (as a primitive) on the items decides the order;\n * arrays with no candidate fall back to canonical-JSON order. Default:\n * `ruleId`, `selector`, `url`.\n */\n readonly sortKeys?: readonly string[];\n}\n\n// Defaults proven by the spike: strip the generated id/runId/timestamp,\n// stable-key-sort by ruleId | selector | url. Fan-out ordering is already\n// deterministic on this substrate (array order); the sort only defends against\n// intra-effect concurrency (Promise.all / Set).\nconst DEFAULT_STRIP_KEYS: readonly string[] = [\"id\", \"runId\", \"timestamp\"];\nconst DEFAULT_SORT_KEYS: readonly string[] = [\"ruleId\", \"selector\", \"url\"];\n\n/**\n * Build a finding-normalizer: a pure `(value) => normalized` that strips the\n * schema's `stripKeys`, recursively sorts object keys, and stable-key-sorts\n * arrays by the schema's `sortKeys`. Two runs that differ only in generated\n * ids/timestamps or intra-effect ordering normalize to a byte-identical value,\n * so {@link diff} on the normalized pair reflects behavioural (not incidental)\n * difference.\n */\nexport function normalizeForParity(\n schema?: ParitySchema,\n): (value: unknown) => unknown {\n const stripKeys = new Set(schema?.stripKeys ?? DEFAULT_STRIP_KEYS);\n const sortKeys = schema?.sortKeys ?? DEFAULT_SORT_KEYS;\n\n const normalize = (value: unknown): unknown => {\n if (Array.isArray(value)) {\n const items = value.map(normalize);\n // Decorate-sort-undecorate: primary key = first present sortKey value,\n // secondary = canonical JSON (items are already normalized so keys are\n // sorted), original index last for a stable total order.\n return items\n .map((item, index) => ({\n item,\n index,\n primary: primarySortKey(item, sortKeys),\n json: JSON.stringify(item) ?? \"\",\n }))\n .sort(\n (a, b) =>\n compareStrings(a.primary, b.primary) ||\n compareStrings(a.json, b.json) ||\n a.index - b.index,\n )\n .map((decorated) => decorated.item);\n }\n if (isPlainObject(value)) {\n const out: Record<string, unknown> = {};\n for (const key of Object.keys(value)\n .filter((key) => !stripKeys.has(key))\n .sort()) {\n out[key] = normalize(value[key]);\n }\n return out;\n }\n return value;\n };\n\n return normalize;\n}\n\n/** The first present `sortKeys` candidate on `item` as a string, or `\"\"`. */\nfunction primarySortKey(item: unknown, sortKeys: readonly string[]): string {\n if (!isPlainObject(item)) return \"\";\n for (const key of sortKeys) {\n const candidate = item[key];\n if (\n typeof candidate === \"string\" ||\n typeof candidate === \"number\" ||\n typeof candidate === \"boolean\"\n ) {\n return String(candidate);\n }\n }\n return \"\";\n}\n\nfunction compareStrings(a: string, b: string): number {\n return a < b ? -1 : a > b ? 1 : 0;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * The parity verdict: `true` iff `a` and `b` are structurally equal. Reuses\n * `trace-replay`'s order-insensitive deep-equal (the single comparator this\n * package owns) rather than adding a second one — feed it the pair produced by\n * {@link normalizeForParity} for the normalized-JSON equality the gate rests on.\n */\nexport function diff(a: unknown, b: unknown): boolean {\n return deepEqual(a, b);\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/parity/index.ts"],"names":["key"],"mappings":";;;;;;AA6DO,SAAS,SAAA,CACd,SACA,IAAA,EACiB;A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,OAAO,SAAS,CAAA;AAAA,IACzB;AAAA,EACF;AACA,EAAA,OAAO,EAAA;AACT;AAEA,SAAS,cAAA,CAAe,GAAW,CAAA,EAAmB;AACpD,EAAA,OAAO,CAAA,GAAI,CAAA,GAAI,EAAA,GAAK,CAAA,GAAI,IAAI,CAAA,GAAI,CAAA;AAClC;AAEA,SAAS,cAAc,KAAA,EAAkD;AACvE,EAAA,OAAO,OAAO,UAAU,QAAA,IAAY,KAAA,KAAU,QAAQ,CAAC,KAAA,CAAM,QAAQ,KAAK,CAAA;AAC5E;AAQO,SAAS,WAAA,CAAY,GAAY,CAAA,EAAqB;AAC3D,EAAA,OAAO,SAAA,CAAU,GAAG,CAAC,CAAA;AACvB;AAOO,IAAM,IAAA,GAAO","file":"index.js","sourcesContent":["// ---------------------------------------------------------------------------\n// parity — the record → replay → normalized-diff go/no-go gate.\n//\n// The parity spike proved the mechanism already composes from in-tree\n// primitives: `recorder` captures a run's Msg sequence (the recording), `replay`\n// re-folds it purely, and `trace-replay`'s order-insensitive deep-equal diffs\n// the result. Non-determinism is a RECORD-TIME property — ids/timestamps freeze\n// into the recording, `replay` never re-mints them — so the same recording\n// replays byte-identical every time.\n//\n// This module is the thin packaging over that substrate plus the one genuinely\n// new helper, `normalizeForParity`: the finding-normalizer that strips\n// record-time non-determinism (generated ids/timestamps) and stable-key-sorts\n// collections, so an OLD-engine golden run and a NEW-engine run diff as equal\n// exactly when they are behaviourally equivalent. Every domain (audit, auth,\n// ingest, …) gets its old-vs-new parity check without reinventing the capture,\n// the normalization, and the diff.\n//\n// recordRun(runtime) → Recording // wraps the recorder\n// goldenReplay(machine, rec) → State // wraps replay\n// normalizeForParity(schema) → (finding) => norm // strip + stable-sort\n// parityEqual(a, b) → boolean // normalized deep-equal\n// ---------------------------------------------------------------------------\n\nimport type { BootingRuntime, Cmd, Machine, Sub } from \"../index\";\nimport { replay } from \"../index\";\nimport { type RecorderOptions, recorder, type Trace } from \"../recorder\";\nimport { deepEqual } from \"../trace-replay\";\n\n/**\n * A live parity recording attached to a Runtime — the go/no-go gate's golden\n * artifact. Wraps a {@link recorder}: drive the runtime, then snapshot with\n * {@link Recording.trace} (or hand the live `Recording` straight to\n * {@link goldenReplay}, which snapshots for you).\n *\n * @typeParam S - the machine's State type.\n * @typeParam M - the machine's Msg union.\n */\nexport interface Recording<S, M> {\n /**\n * Snapshot the recording so far as a replayable {@link Trace} — `loaded`\n * (boot state), the ordered non-null `msgs`, and `finalState`. Sufficient to\n * reproduce the run via {@link goldenReplay}. Fresh object each call.\n */\n trace(): Trace<S, M>;\n /** Serialize the recording as JSONL (see {@link recorder}'s `toJSONL`). */\n toJSONL(): string;\n /** Detach the underlying observer. Idempotent. */\n stop(): void;\n}\n\n/**\n * Attach a parity recording to a Runtime, reusing the `recorder`/`historyTracker`\n * capture (the boot observe for `loaded` + every non-null msg in order) rather\n * than a fresh observer path.\n *\n * Attach on the synchronous `run()` handle so the boot transition is captured\n * as `loaded`; drive the runtime; then `trace()` (or pass the handle to\n * {@link goldenReplay}). See {@link RecorderOptions} for `captureSteps` (needed\n * only for the per-step / resume-cache-prefix inspection, not for replay).\n */\nexport function recordRun<S, M extends { type: string }>(\n runtime: BootingRuntime<S, M>,\n opts?: RecorderOptions,\n): Recording<S, M> {\n const rec = recorder(runtime, opts);\n return {\n trace: () => rec.dump(),\n toJSONL: () => rec.toJSONL(),\n stop: () => rec.stop(),\n };\n}\n\n/**\n * Reproduce a recording's final state by folding its msgs through the pure\n * `replay` — `init(loaded, ctx)` then `update` per msg, never `interpret`,\n * never a `Store`, never a live subscription. Accepts a live {@link Recording}\n * (snapshotted here) or a bare {@link Trace}.\n *\n * `ctx` is the ENVIRONMENT supplied fresh at replay time (the trace is the\n * INPUT: `loaded` + `msgs`), mirroring `replayTrace`. It is optional so a\n * void-ctx machine can call `goldenReplay(machine, rec)`; a machine that reads\n * ctx passes it explicitly.\n */\nexport function goldenReplay<\n S,\n M extends { type: string },\n C extends Cmd,\n U extends Sub,\n Ctx,\n>(\n machine: Machine<S, M, C, U, Ctx>,\n recording: Recording<S, M> | Trace<S, M>,\n ctx?: Ctx,\n): S {\n const trace = asTrace(recording);\n const { state } = replay(machine, {\n msgs: trace.msgs,\n ctx: ctx as Ctx,\n loaded: trace.loaded,\n });\n return state;\n}\n\n/** Narrow a `Recording | Trace` to a `Trace`, snapshotting a live recording. */\nfunction asTrace<S, M>(recording: Recording<S, M> | Trace<S, M>): Trace<S, M> {\n return typeof (recording as Recording<S, M>).trace === \"function\"\n ? (recording as Recording<S, M>).trace()\n : (recording as Trace<S, M>);\n}\n\n/** Configuration for {@link normalizeForParity}. */\nexport interface ParitySchema {\n /**\n * Object keys stripped wherever they appear — the record-time\n * non-determinism `replay` never re-mints. Default: `id`, `runId`,\n * `timestamp`.\n */\n readonly stripKeys?: readonly string[];\n /**\n * Candidate keys used to stable-sort arrays of objects. For each array the\n * first candidate present (as a primitive) on the items decides the order;\n * arrays with no candidate fall back to canonical-JSON order. Default:\n * `ruleId`, `selector`, `url`.\n */\n readonly sortKeys?: readonly string[];\n}\n\n// Defaults proven by the spike: strip the generated id/runId/timestamp,\n// stable-key-sort by ruleId | selector | url. Fan-out ordering is already\n// deterministic on this substrate (array order); the sort only defends against\n// intra-effect concurrency (Promise.all / Set).\nconst DEFAULT_STRIP_KEYS: readonly string[] = [\"id\", \"runId\", \"timestamp\"];\nconst DEFAULT_SORT_KEYS: readonly string[] = [\"ruleId\", \"selector\", \"url\"];\n\n/**\n * Build a finding-normalizer: a pure `(value) => normalized` that strips the\n * schema's `stripKeys`, recursively sorts object keys, and stable-key-sorts\n * arrays by the schema's `sortKeys`. Two runs that differ only in generated\n * ids/timestamps or intra-effect ordering normalize to a byte-identical value,\n * so {@link parityEqual} on the normalized pair reflects behavioural (not incidental)\n * difference.\n */\nexport function normalizeForParity(\n schema?: ParitySchema,\n): (value: unknown) => unknown {\n const stripKeys = new Set(schema?.stripKeys ?? DEFAULT_STRIP_KEYS);\n const sortKeys = schema?.sortKeys ?? DEFAULT_SORT_KEYS;\n\n const normalize = (value: unknown): unknown => {\n if (Array.isArray(value)) {\n const items = value.map(normalize);\n // Decorate-sort-undecorate: primary key = first present sortKey value,\n // secondary = canonical JSON (items are already normalized so keys are\n // sorted), original index last for a stable total order.\n return items\n .map((item, index) => ({\n item,\n index,\n primary: primarySortKey(item, sortKeys),\n json: JSON.stringify(item) ?? \"\",\n }))\n .sort(\n (a, b) =>\n compareStrings(a.primary, b.primary) ||\n compareStrings(a.json, b.json) ||\n a.index - b.index,\n )\n .map((decorated) => decorated.item);\n }\n if (isPlainObject(value)) {\n const out: Record<string, unknown> = {};\n for (const key of Object.keys(value)\n .filter((key) => !stripKeys.has(key))\n .sort()) {\n out[key] = normalize(value[key]);\n }\n return out;\n }\n return value;\n };\n\n return normalize;\n}\n\n/** The first present `sortKeys` candidate on `item` as a string, or `\"\"`. */\nfunction primarySortKey(item: unknown, sortKeys: readonly string[]): string {\n if (!isPlainObject(item)) return \"\";\n for (const key of sortKeys) {\n const candidate = item[key];\n if (\n typeof candidate === \"string\" ||\n typeof candidate === \"number\" ||\n typeof candidate === \"boolean\"\n ) {\n return String(candidate);\n }\n }\n return \"\";\n}\n\nfunction compareStrings(a: string, b: string): number {\n return a < b ? -1 : a > b ? 1 : 0;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * The parity verdict: `true` iff `a` and `b` are structurally equal. Reuses\n * `trace-replay`'s order-insensitive deep-equal (the single comparator this\n * package owns) rather than adding a second one — feed it the pair produced by\n * {@link normalizeForParity} for the normalized-JSON equality the gate rests on.\n */\nexport function parityEqual(a: unknown, b: unknown): boolean {\n return deepEqual(a, b);\n}\n\n/**\n * @deprecated Inverted name — it returns `true` when the values are EQUAL, so\n * `if (diff(old, new))` reads backwards (#278). Use {@link parityEqual}.\n * Alias kept for one minor, then removed.\n */\nexport const diff = parityEqual;\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import * as fc from 'fast-check';
|
|
2
|
-
import { C as Cmd, S as Sub, M as Machine } from '../../core-
|
|
2
|
+
import { C as Cmd, S as Sub, M as Machine } from '../../core-BmlJOvxM.js';
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* Build a Ctx value whose every property access throws. Use as the `ctx`
|
package/dist/pbt/index.d.ts
CHANGED
|
@@ -1,12 +1,16 @@
|
|
|
1
1
|
export { MsgArbitraryTable, arbConstantMsg, arbGuidedSequence, arbMsg, arbMsgSequence, arbRecordMsg, stubCtxThrowingProxy } from './arbitraries/index.js';
|
|
2
2
|
export { Step, foldEvents, propertyInvariant, propertyTerminates, propertyTrace } from './runners/index.js';
|
|
3
|
-
import { C as Cmd, R as Reducer, T as Transitions } from '../core-
|
|
3
|
+
import { C as Cmd, R as Reducer, T as Transitions, U as UpdateForm } from '../core-BmlJOvxM.js';
|
|
4
4
|
import 'fast-check';
|
|
5
5
|
|
|
6
6
|
/**
|
|
7
|
-
* Extract the Msg discriminant set at runtime from a
|
|
8
|
-
*
|
|
9
|
-
*
|
|
7
|
+
* Extract the Msg discriminant set at runtime from a machine. Useful for
|
|
8
|
+
* asserting that a user-supplied `MsgArbitraryTable<M>` covers every variant
|
|
9
|
+
* the reducer can handle.
|
|
10
|
+
*
|
|
11
|
+
* Takes the MACHINE (not the bare `update` record) so the reducer-vs-
|
|
12
|
+
* transitions branch honors the authoritative `__form` tag via `msgKeysOf` —
|
|
13
|
+
* the same classification production `run` uses (#275).
|
|
10
14
|
*
|
|
11
15
|
* - **Reducer form** — keys of the top-level record ARE the Msg variants.
|
|
12
16
|
* - **Transitions form** — keys of any single state's inner record. Every
|
|
@@ -16,13 +20,16 @@ import 'fast-check';
|
|
|
16
20
|
*
|
|
17
21
|
* @example
|
|
18
22
|
* import { auditBackgroundMachine } from "./reducer";
|
|
19
|
-
* msgTypeKeys(auditBackgroundMachine
|
|
23
|
+
* msgTypeKeys(auditBackgroundMachine);
|
|
20
24
|
* // → ["start_audit", "stop_audit", "window_created", ...]
|
|
21
25
|
*/
|
|
22
26
|
declare function msgTypeKeys<S, M extends {
|
|
23
27
|
type: string;
|
|
24
|
-
}, C extends Cmd>(
|
|
25
|
-
|
|
26
|
-
|
|
28
|
+
}, C extends Cmd>(machine: {
|
|
29
|
+
update: Reducer<S, M, C> | ([S] extends [{
|
|
30
|
+
type: string;
|
|
31
|
+
}] ? Transitions<S, M, C> : never);
|
|
32
|
+
__form?: UpdateForm;
|
|
33
|
+
}): readonly string[];
|
|
27
34
|
|
|
28
35
|
export { msgTypeKeys };
|
package/dist/pbt/index.js
CHANGED
|
@@ -1,17 +1,11 @@
|
|
|
1
1
|
export { arbConstantMsg, arbGuidedSequence, arbMsg, arbMsgSequence, arbRecordMsg, stubCtxThrowingProxy } from '../chunk-7FYQGDMF.js';
|
|
2
|
-
export { foldEvents, propertyInvariant, propertyTerminates, propertyTrace } from '../chunk-
|
|
3
|
-
import '../chunk-
|
|
4
|
-
import '../chunk-
|
|
2
|
+
export { foldEvents, propertyInvariant, propertyTerminates, propertyTrace } from '../chunk-EMJTPHI7.js';
|
|
3
|
+
import '../chunk-6VDCTR7N.js';
|
|
4
|
+
import { msgKeysOf } from '../chunk-DYRKDCJI.js';
|
|
5
5
|
|
|
6
6
|
// src/pbt/util/msg-keys.ts
|
|
7
|
-
function msgTypeKeys(
|
|
8
|
-
|
|
9
|
-
if (keys.length === 0) return [];
|
|
10
|
-
const firstValue = update[keys[0] ?? ""];
|
|
11
|
-
if (typeof firstValue === "function") {
|
|
12
|
-
return keys;
|
|
13
|
-
}
|
|
14
|
-
return Object.keys(firstValue);
|
|
7
|
+
function msgTypeKeys(machine) {
|
|
8
|
+
return msgKeysOf(machine);
|
|
15
9
|
}
|
|
16
10
|
|
|
17
11
|
export { msgTypeKeys };
|
package/dist/pbt/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/pbt/util/msg-keys.ts"],"names":[],"mappings":";;;;;;
|
|
1
|
+
{"version":3,"sources":["../../src/pbt/util/msg-keys.ts"],"names":[],"mappings":";;;;;;AA2CO,SAAS,YAId,OAAA,EAKoB;AACpB,EAAA,OAAO,UAAU,OAAO,CAAA;AAC1B","file":"index.js","sourcesContent":["// ---------------------------------------------------------------------------\n// msgTypeKeys — read the Msg discriminant set at runtime from a machine's\n// Reducer record or Transitions table.\n//\n// TS Msg unions only exist at the type level; the discriminant strings are\n// erased at runtime. The reducer record / transitions table is the load-\n// bearing artifact that DOES carry the discriminants at runtime — its keys\n// (for Reducer) or any one cell's inner keys (for Transitions) are exactly\n// the set we need to build an `arbMsg` table without hand-listing them.\n//\n// Used by `arbMsg` to assert (in dev) that the user-supplied table covers\n// every Msg variant the reducer claims to handle. Strict drift detection\n// without runtime introspection of the type system.\n// ---------------------------------------------------------------------------\n\nimport {\n type Cmd,\n msgKeysOf,\n type Reducer,\n type Transitions,\n type UpdateForm,\n} from \"../../index\";\n\n/**\n * Extract the Msg discriminant set at runtime from a machine. Useful for\n * asserting that a user-supplied `MsgArbitraryTable<M>` covers every variant\n * the reducer can handle.\n *\n * Takes the MACHINE (not the bare `update` record) so the reducer-vs-\n * transitions branch honors the authoritative `__form` tag via `msgKeysOf` —\n * the same classification production `run` uses (#275).\n *\n * - **Reducer form** — keys of the top-level record ARE the Msg variants.\n * - **Transitions form** — keys of any single state's inner record. Every\n * state's inner record must cover every Msg variant (mapped-type\n * discipline), so reading the first state's keys is equivalent to reading\n * the union.\n *\n * @example\n * import { auditBackgroundMachine } from \"./reducer\";\n * msgTypeKeys(auditBackgroundMachine);\n * // → [\"start_audit\", \"stop_audit\", \"window_created\", ...]\n */\nexport function msgTypeKeys<\n S,\n M extends { type: string },\n C extends Cmd,\n>(machine: {\n update:\n | Reducer<S, M, C>\n | ([S] extends [{ type: string }] ? Transitions<S, M, C> : never);\n __form?: UpdateForm;\n}): readonly string[] {\n return msgKeysOf(machine);\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
export { foldEvents, propertyInvariant, propertyTerminates, propertyTrace } from '../../chunk-
|
|
2
|
-
import '../../chunk-
|
|
3
|
-
import '../../chunk-
|
|
1
|
+
export { foldEvents, propertyInvariant, propertyTerminates, propertyTrace } from '../../chunk-EMJTPHI7.js';
|
|
2
|
+
import '../../chunk-6VDCTR7N.js';
|
|
3
|
+
import '../../chunk-DYRKDCJI.js';
|
|
4
4
|
//# sourceMappingURL=index.js.map
|
|
5
5
|
//# sourceMappingURL=index.js.map
|