@demlik/tea 0.21.0 → 0.22.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 +32 -19
- package/dist/agent/index.js +12 -10
- package/dist/{chunk-VM7PMFV5.js → chunk-2A5XTKQQ.js} +142 -19
- package/dist/chunk-2A5XTKQQ.js.map +1 -0
- package/dist/{chunk-EB5OMOXX.js → chunk-7K7SEYCH.js} +16 -15
- package/dist/chunk-7K7SEYCH.js.map +1 -0
- package/dist/{chunk-GAVLND5C.js → chunk-A3QPMX5M.js} +17 -10
- package/dist/chunk-A3QPMX5M.js.map +1 -0
- package/dist/{chunk-VHKDUBXC.js → chunk-BVFS3ICC.js} +3 -3
- package/dist/{chunk-VHKDUBXC.js.map → chunk-BVFS3ICC.js.map} +1 -1
- package/dist/{chunk-4I2LCQKB.js → chunk-CPE5ZQXQ.js} +3 -3
- package/dist/{chunk-4I2LCQKB.js.map → chunk-CPE5ZQXQ.js.map} +1 -1
- package/dist/chunk-DEAPNMKO.js +11 -0
- package/dist/chunk-DEAPNMKO.js.map +1 -0
- package/dist/{chunk-BFSZ4L6Y.js → chunk-ETRNSJCR.js} +4 -4
- package/dist/{chunk-BFSZ4L6Y.js.map → chunk-ETRNSJCR.js.map} +1 -1
- package/dist/chunk-FXWDDNGD.js +98 -0
- package/dist/chunk-FXWDDNGD.js.map +1 -0
- package/dist/chunk-GFGOQIEC.js +10 -0
- package/dist/chunk-GFGOQIEC.js.map +1 -0
- package/dist/{chunk-YDF6P74H.js → chunk-IAHEYPYJ.js} +3 -3
- package/dist/{chunk-YDF6P74H.js.map → chunk-IAHEYPYJ.js.map} +1 -1
- package/dist/{chunk-YCJPLPQQ.js → chunk-J5JNLXO7.js} +3 -3
- package/dist/{chunk-YCJPLPQQ.js.map → chunk-J5JNLXO7.js.map} +1 -1
- package/dist/{chunk-MBQR3LFW.js → chunk-NFOGYDRS.js} +5 -5
- package/dist/{chunk-MBQR3LFW.js.map → chunk-NFOGYDRS.js.map} +1 -1
- package/dist/{chunk-Z7IL735U.js → chunk-R2YNDRGL.js} +3 -3
- package/dist/{chunk-Z7IL735U.js.map → chunk-R2YNDRGL.js.map} +1 -1
- package/dist/{chunk-ZV4WGW74.js → chunk-R5NXOPL2.js} +3 -3
- package/dist/{chunk-ZV4WGW74.js.map → chunk-R5NXOPL2.js.map} +1 -1
- package/dist/chunk-RMBZ7YH7.js +52 -0
- package/dist/chunk-RMBZ7YH7.js.map +1 -0
- package/dist/{chunk-HU3Y2AZY.js → chunk-SHXUSTHM.js} +62 -15
- package/dist/chunk-SHXUSTHM.js.map +1 -0
- package/dist/{chunk-QIE4Y6BK.js → chunk-UGTC33VH.js} +4 -4
- package/dist/{chunk-QIE4Y6BK.js.map → chunk-UGTC33VH.js.map} +1 -1
- package/dist/{chunk-6NIQIUGR.js → chunk-VH5MYJ2K.js} +4 -4
- package/dist/{chunk-6NIQIUGR.js.map → chunk-VH5MYJ2K.js.map} +1 -1
- package/dist/{chunk-W6XWI6QE.js → chunk-WZEDIUWR.js} +8 -7
- package/dist/chunk-WZEDIUWR.js.map +1 -0
- package/dist/{chunk-TMYUDZLE.js → chunk-ZRRET3RP.js} +11 -11
- package/dist/chunk-ZRRET3RP.js.map +1 -0
- package/dist/{core-BKJW1Kmq.d.ts → core-DNDAEhO2.d.ts} +7 -10
- package/dist/devtools/index.d.ts +4 -4
- package/dist/do/index.d.ts +98 -35
- package/dist/do/index.js +40 -21
- package/dist/do/index.js.map +1 -1
- package/dist/{drive-loop-Dc6Z8Vbs.d.ts → drive-loop-DlOEv49c.d.ts} +2 -2
- package/dist/{durable-effects-CgrLNccA.d.ts → durable-effects-wLWEdy9H.d.ts} +1 -1
- package/dist/effect/index.d.ts +52 -26
- package/dist/effect/index.js +7 -31
- package/dist/effect/index.js.map +1 -1
- package/dist/extension/index.d.ts +3 -3
- package/dist/extension/index.js +2 -2
- package/dist/flow/index.d.ts +13 -13
- package/dist/flow/index.js +13 -11
- package/dist/flow/index.js.map +1 -1
- package/dist/idempotency/index.d.ts +3 -3
- package/dist/idempotency/index.js +3 -3
- package/dist/{index-1hit3dJ9.d.ts → index-9P1PaXIV.d.ts} +2 -2
- package/dist/{index-Cuy1_xTh.d.ts → index-BBLI2WWN.d.ts} +1 -1
- package/dist/{index-Z6Uw7C9t.d.ts → index-C1WhBZ6a.d.ts} +4 -5
- package/dist/{index-B-VC4qjx.d.ts → index-C92SgNWz.d.ts} +2 -2
- package/dist/{index-CYrUWi1c.d.ts → index-CAsUE_d1.d.ts} +4 -4
- package/dist/{index-BjwRcjBi.d.ts → index-CO34esWT.d.ts} +2 -2
- package/dist/{index-DB8Yn0-K.d.ts → index-COeX9Bmz.d.ts} +11 -9
- package/dist/{index-Diyo8WBO.d.ts → index-Cg0QXnzf.d.ts} +2 -2
- package/dist/index.d.ts +5 -5
- package/dist/index.js +2 -2
- package/dist/jev/index.d.ts +8 -8
- package/dist/jev/index.js +5 -5
- package/dist/laws-DTtCDDlU.d.ts +135 -0
- package/dist/loop-DReKGV1X.d.ts +70 -0
- package/dist/{machine-BuPTS1QH.d.ts → machine-C0WhOAyB.d.ts} +5 -5
- package/dist/machine-viz/index.d.ts +1 -1
- package/dist/machine-viz/index.js +2 -2
- package/dist/mem/index.d.ts +4 -3
- package/dist/mem/index.js +2 -2
- package/dist/mem/index.js.map +1 -1
- package/dist/node/index.d.ts +57 -9
- package/dist/node/index.js +175 -68
- package/dist/node/index.js.map +1 -1
- package/dist/otel/index.d.ts +28 -12
- package/dist/otel/index.js +25 -21
- package/dist/otel/index.js.map +1 -1
- package/dist/paginate/index.d.ts +4 -4
- package/dist/paginate/index.js +5 -5
- package/dist/parity/index.d.ts +11 -15
- package/dist/parity/index.js +4 -9
- package/dist/parity/index.js.map +1 -1
- package/dist/pbt/index.d.ts +279 -67
- package/dist/pbt/index.js +299 -58
- package/dist/pbt/index.js.map +1 -1
- package/dist/persistence/index.d.ts +10 -12
- package/dist/persistence/index.js +4 -4
- package/dist/promise/index.d.ts +95 -13
- package/dist/promise/index.js +6 -4
- package/dist/react/index.d.ts +34 -22
- package/dist/react/index.js +271 -42
- package/dist/react/index.js.map +1 -1
- package/dist/resilience/index.d.ts +6 -6
- package/dist/resilience/index.js +5 -5
- package/dist/{run-D0sxbyno.d.ts → run-Cnw4qXj2.d.ts} +86 -17
- package/dist/{runtime-types-BPKp2bGo.d.ts → runtime-types-CP-ykwgf.d.ts} +120 -31
- package/dist/testing/effect/index.d.ts +162 -9
- package/dist/testing/effect/index.js +110 -10
- package/dist/testing/effect/index.js.map +1 -1
- package/dist/testing/index.d.ts +6 -8
- package/dist/testing/index.js +4 -24
- package/dist/testing/index.js.map +1 -1
- package/dist/testing/promise/index.d.ts +4 -4
- package/dist/testing/promise/index.js +5 -5
- package/dist/timing/index.d.ts +4 -4
- package/dist/timing/index.js +4 -4
- package/dist/{types-BiXj7k_k.d.ts → types-S53WDy_h.d.ts} +1 -1
- package/dist/work-queue/index.d.ts +4 -4
- package/dist/work-queue/index.js +2 -2
- package/package.json +18 -18
- package/dist/chunk-7Z2IDZ7R.js +0 -34
- package/dist/chunk-7Z2IDZ7R.js.map +0 -1
- package/dist/chunk-EB5OMOXX.js.map +0 -1
- package/dist/chunk-GAVLND5C.js.map +0 -1
- package/dist/chunk-HU3Y2AZY.js.map +0 -1
- package/dist/chunk-TMYUDZLE.js.map +0 -1
- package/dist/chunk-VM7PMFV5.js.map +0 -1
- package/dist/chunk-W6XWI6QE.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/internal/paginate/paginator/index.ts","../src/internal/paginate/paginated-walk/index.ts"],"names":["start","drain","resume"],"mappings":";;;AAmJO,IAAM,sBAAA,GAAkD;AAAA,EAC7D,WAAA,EAAa,CAAA;AAAA,EACb,aAAA,EAAe;AACjB;AAqCO,SAAS,aAAA,GAAgD;AAC9D,EAAA,OAAO,EAAE,KAAA,EAAO,MAAA,EAAQ,IAAA,EAAM,CAA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EAAA,CAAG,GAAA;AAAA,IACV,IAAA;AAAA,IACA,KAAA,EAAAF,MAAAA;AAAA,IACA,MAAA;AAAA,IACA,OAAA;AAAA,IACA,OAAA;AAAA,IACA,KAAA,EAAAC,MAAAA;AAAA,IACA,MAAA,EAAAC,OAAAA;AAAA,IACA,UAAA;AAAA,IACA,OAAA;AAAA,IACA,OAAA;AAAA,IACA,SAAA;AAAA,IACA;AAAA,GACF;AACF;AAQO,SAAS,QAAA,CAMd,KAAA,EACA,CAAC,KAAA,EAAO,IAAI,CAAA,EACgB;AAC5B,EAAA,OAAO,CAAC,EAAE,GAAG,OAAO,IAAA,EAAM,KAAA,IAAS,IAAI,CAAA;AACzC","file":"chunk-4I2LCQKB.js","sourcesContent":["/**\n * internal/paginate/paginator — the cursor/offset/page-token walk loop as pure\n * state + ops.\n *\n * Same shape as `../../../retry-backoff`, `../../resilience/circuit-breaker`,\n * and `../../resilience/rate-limit`: a state type plus pure transition functions,\n * host-agnostic by construction. Nothing here reads the clock, the RNG, or any\n * I/O on its own behalf — the consumer fetches a page out-of-band and folds the\n * *result* back in through `recordPage`. That keeps every function inside TEA's\n * invariant 2 (transitions are pure: same inputs → same outputs) so a consumer\n * can thread the walk through `update` and exercise it with `replay` / the pbt\n * fold without a fake network.\n *\n * Every op returns a NEW state value and never mutates its input (invariant 1 —\n * state is a value, not a place). All fields are `readonly` and plain data, so\n * the whole walk is trivially JSON-serializable into a consumer's `Store<S>`\n * and survives a Durable-Object eviction / reload mid-walk: the cursor lives in\n * the Model, not a closure (the durability + replay non-negotiables every TEA\n * knob preserves).\n *\n * ## The cursor is opaque, and the consumer advances it\n *\n * A paginated API hands back a *next cursor* however it likes: an offset\n * (`?offset=40`), a page token (`?pageToken=ey…`), a \"next\" URL, or `null` at\n * the end. This module is generic in `Cursor` and never inspects it — it only\n * carries it forward. The consumer (who alone knows the API's shape) reads the\n * next cursor off the just-fetched page and passes it to `recordPage`:\n *\n * const next = page.nextPageToken ?? null; // consumer-specific extraction\n * const walk = recordPage(state.walk, page.items.length, next);\n *\n * Passing `next: null` (or a missing `undefined` cursor — the op compares with\n * loose `== null`) means \"the API said there is no next page\" → the walk\n * finishes (`done`). Passing a `Cursor` means \"fetch this one next\" → the walk\n * either keeps `fetching` or `pauses` for backpressure (below). Decoupling the\n * extraction from the op is the same discipline `circuit-breaker` uses for the\n * clock: the impure / domain-specific bit (`nextCursor(page)`) lives at the\n * call site; the op stays a pure fold over the extracted value.\n *\n * ## The phase machine\n *\n * Four phases, each a discriminated-union arm carrying ONLY the data that phase\n * needs so impossible states are unrepresentable (pattern 11):\n *\n * - **idle** — created, not started. No cursor is armed yet; `start` arms the\n * first one. Carries the running `seen` / `pages` counters (both 0 here, but\n * present on every phase so a consumer reads them uniformly).\n *\n * - **fetching** — a page request for `cursor` is outstanding. The walk sits\n * here while the consumer's fetch is in flight; `recordPage` resolves it.\n * Carries the `cursor` being fetched so a post-eviction resume re-issues the\n * SAME request (idempotent retry) rather than skipping a page.\n *\n * - **paused** — backpressure tripped. The API still has more pages (a non-null\n * next cursor), but `seen` has reached `highWaterMark` and the consumer has\n * not drained yet. Carries the `cursor` to resume from. No fetch is\n * outstanding — the loop is deliberately idle until `resume`. This is the\n * valve that stops a fast producer (the API) from outrunning a slow consumer\n * (whatever processes each page) and blowing memory.\n *\n * - **done** — the API returned a null next cursor; the walk is exhausted. A\n * terminal phase: `start` / `recordPage` / `resume` are all no-ops on it\n * (idempotent completion — a late duplicate result can't un-finish a walk).\n *\n * ### Transition table\n *\n * Rows are the current phase; columns are the op. `→` denotes the next phase;\n * `self` means unchanged (a no-op for that (phase × op) pair). `next` is the\n * cursor the consumer extracted from the page; `hwm` is `highWaterMark`.\n *\n * | from \\ op | start | recordPage(count, next) | resume |\n * | ----------- | -------------- | -------------------------------------------------------------------- | ------------------------------ |\n * | idle | → fetching(c0) | self *(¹)* | self |\n * | fetching | self | seen=max(0,seen+count), pages+=1; next==null → done; seen≥hwm → paused(next); else → fetching(next) | self |\n * | paused | self | self *(¹)* | seen<hwm → fetching(cursor) *(²)* |\n * | done | self | self | self |\n *\n * *(¹)* `recordPage` only makes sense while `fetching` (a page was outstanding).\n * On any other phase it is a no-op: a result that arrives when no fetch was in\n * flight (a late duplicate, a double-dispatch) must not advance the cursor or\n * double-count `seen`. The walk is a coordination aid, not a correctness gate —\n * it absorbs the stray rather than corrupting the count.\n *\n * *(²)* `resume` re-arms the paused cursor ONLY once `seen` has dropped below\n * `highWaterMark` (the consumer drained, lowering `seen` via `drain`). Calling\n * `resume` while still over the mark is a no-op — the valve stays shut until\n * there is real headroom, so a consumer that resumes optimistically can't\n * defeat the backpressure. Resuming a walk that isn't `paused` is likewise a\n * no-op.\n *\n * ## Backpressure\n *\n * `seen` is the count of items the API has produced that the consumer has not\n * yet acknowledged as processed. `recordPage` adds each page's item count to it;\n * `drain(n)` subtracts what the consumer finished. When `seen` reaches\n * `highWaterMark`, `recordPage` parks the walk in `paused` instead of issuing\n * the next fetch — the producer stops until `drain` + `resume` re-open the\n * valve. A `highWaterMark` of `0` (or any non-positive value) disables\n * backpressure: the comparison `seen >= hwm` is satisfied vacuously only when\n * `hwm <= 0` would pause immediately, so we treat `hwm <= 0` as \"unbounded\" and\n * never pause. The walk then runs flat-out, `fetching → fetching` until `done`.\n *\n * Internal since #47 — not published on any subpath; reached from inside the\n * package as `internal/paginate/paginator`. Same one-shape-per-package rule as `work-queue`, `retry-backoff`,\n * `circuit-breaker`, and `rate-limit`. It is the L1 escape hatch the\n * `paginated-walk` composition builds its walk loop on.\n */\n\n/**\n * Paginator policy — pure configuration, no mutable state. One policy is shared\n * across the whole walk (often a module-scope const). `PaginatorState` carries\n * the cursor + counters; this carries the knobs they're compared against.\n *\n * Generic in `Cursor` so `firstCursor` matches whatever the API's cursor shape\n * is — an offset `number`, a page-token `string`, a `{ after: string }` record,\n * etc. The module never inspects the cursor; the type just threads through.\n */\nexport interface PaginatorPolicy<Cursor> {\n /**\n * The cursor the walk fetches first, armed by `start`. For an offset API this\n * is typically `0`; for a token API, `null`-or-empty-meaning-\"first page\" is\n * the API's call, so pass whatever sentinel the API treats as page one.\n */\n readonly firstCursor: Cursor;\n /**\n * Backpressure threshold: the number of un-drained items at which the walk\n * pauses instead of fetching the next page. `recordPage` parks in `paused`\n * once `seen >= highWaterMark`; `drain` + `resume` re-open the valve.\n *\n * A non-positive value (`<= 0`) disables backpressure — the walk never pauses\n * and runs `fetching → fetching` until the API exhausts. Use that when the\n * consumer processes each page synchronously inside `recordPage` and there is\n * nothing to back up.\n */\n readonly highWaterMark: number;\n}\n\n/**\n * Sensible defaults: start from a numeric offset of `0`, pause after 1000\n * un-drained items. Tuned for an offset-paginated REST API whose consumer\n * processes pages asynchronously; override per call site (especially\n * `firstCursor`, which is API-specific) rather than mutating this shared const.\n *\n * Typed as `PaginatorPolicy<number>` because the only honest default cursor is\n * the numeric offset `0`; a token-based API supplies its own `firstCursor` and\n * its own `PaginatorPolicy<string>`.\n */\nexport const defaultPaginatorPolicy: PaginatorPolicy<number> = {\n firstCursor: 0,\n highWaterMark: 1000,\n};\n\n/**\n * The walk's phase. A discriminated union on `phase` so each phase carries ONLY\n * its own data and impossible combinations are unrepresentable (pattern 11):\n * there is no `done` state that still holds a pending cursor, no `idle` state\n * mid-fetch. Every field is `readonly` so the whole value is trivially\n * JSON-serializable into a consumer's `Store<S>` and safe to thread through a\n * pure reducer / a Durable-Object reload.\n *\n * Two counters ride on every phase so a consumer reads them uniformly without\n * narrowing first:\n * - `seen` — items produced by the API but not yet drained (backpressure gauge).\n * - `pages` — total pages recorded so far (progress / observability).\n *\n * - `idle` — not started; `start` arms `firstCursor`.\n * - `fetching` — a page request for `cursor` is outstanding.\n * - `paused` — backpressure tripped; `cursor` is the page to resume from.\n * - `done` — API exhausted (null next cursor); terminal.\n */\nexport type PaginatorState<Cursor> =\n | { readonly phase: \"idle\"; readonly seen: number; readonly pages: number }\n | {\n readonly phase: \"fetching\";\n readonly cursor: Cursor;\n readonly seen: number;\n readonly pages: number;\n }\n | {\n readonly phase: \"paused\";\n readonly cursor: Cursor;\n readonly seen: number;\n readonly pages: number;\n }\n | { readonly phase: \"done\"; readonly seen: number; readonly pages: number };\n\n/** The starting state: idle, nothing seen, no pages recorded. */\nexport function initPaginator<Cursor>(): PaginatorState<Cursor> {\n return { phase: \"idle\", seen: 0, pages: 0 };\n}\n\n/**\n * Arm the first fetch. PURE — returns a new state; the input is never mutated.\n *\n * - `idle` → `fetching(firstCursor)`. This is the only phase `start` acts on.\n * - any other phase → unchanged. Re-arming a walk that has already begun (or\n * finished) would skip back to page one and double-count; a stray `start`\n * after launch is absorbed, not honored. Use `initPaginator()` to begin a\n * genuinely fresh walk.\n */\nexport function start<Cursor>(\n state: PaginatorState<Cursor>,\n policy: PaginatorPolicy<Cursor>,\n): PaginatorState<Cursor> {\n if (state.phase !== \"idle\") return state;\n return {\n phase: \"fetching\",\n cursor: policy.firstCursor,\n seen: state.seen,\n pages: state.pages,\n };\n}\n\n/**\n * Record the result of the outstanding fetch and decide what comes next. PURE —\n * returns a new state; the input is never mutated.\n *\n * `count` is how many items the just-fetched page yielded (added to `seen` for\n * backpressure accounting). `next` is the cursor the consumer extracted from the\n * page — a `Cursor` to fetch next, or `null`/`undefined` (a missing optional\n * cursor field) if the API signalled the end.\n *\n * - `fetching` → `seen = max(0, seen + count)`, `pages += 1`, then branch on\n * `next`:\n * - `next == null` → `done` (API exhausted; loose-null so a\n * missing/`undefined` cursor also finishes).\n * - `seen >= highWaterMark` → `paused(next)` (backpressure; `hwm <= 0`\n * disables this branch — see policy docs).\n * - otherwise → `fetching(next)` (keep walking).\n * - any other phase → unchanged. A result with no fetch outstanding (a late\n * duplicate, a double-dispatch) must not advance the cursor or double-count;\n * it is absorbed. See the module header's note ¹.\n *\n * `count` is floored into the gauge: a non-finite `count` (`NaN`/`Infinity`) is\n * treated as `0`, and the additive sum is clamped at `0`. A record can only hold\n * or raise `seen`; only `drain` lowers it. This keeps a stray negative or\n * non-finite count from poisoning the `seen >= highWaterMark` comparison and\n * silently defeating backpressure.\n *\n * The new `seen` total — not the pre-page value — is what the backpressure check\n * reads, so a single page large enough to cross the mark pauses immediately\n * rather than fetching one more first.\n */\nexport function recordPage<Cursor>(\n state: PaginatorState<Cursor>,\n count: number,\n next: Cursor | null | undefined,\n policy: PaginatorPolicy<Cursor>,\n): PaginatorState<Cursor> {\n if (state.phase !== \"fetching\") return state;\n // A page's item count must be a finite, non-negative addition to `seen`. A\n // negative count would drive `seen` down (a record can never lower the gauge —\n // only `drain` does) and a non-finite count (`NaN` / `Infinity`) would poison\n // every later `seen >= highWaterMark` comparison, permanently defeating\n // backpressure (NaN compares false, so the valve never trips). Floor the\n // CONTRIBUTION (not just the sum) at 0: clamp a non-finite count to 0\n // (mirroring retry-backoff's `Number.isNaN` discipline at backoffDelay ~:119)\n // and a negative count to 0. Flooring the contribution — rather than the sum —\n // is what makes a record strictly monotonic: `Math.max(0, seen + count)` only\n // catches a count that drags the *sum* below zero, so a small negative count\n // (e.g. `seen=10, count=-3 → 7`) would still silently lower the gauge and\n // break \"only `drain` lowers `seen`\". Clamping `count` first guarantees the\n // additive step can only hold or raise the gauge.\n const safeCount = Number.isFinite(count) ? Math.max(0, count) : 0;\n const seen = state.seen + safeCount;\n const pages = state.pages + 1;\n // Loose `== null` so a *missing* next cursor (`undefined`, common for an\n // optional API field the consumer extracted as `page.nextPageToken`) finishes\n // the walk exactly like an explicit `null`. Strict `=== null` would route an\n // `undefined` cursor into the fetching/paused branch and carry a cursor-less\n // (malformed) state forward.\n if (next == null) {\n return { phase: \"done\", seen, pages };\n }\n // `hwm <= 0` disables backpressure entirely (unbounded walk); only a positive\n // mark can park the loop. `seen >= hwm` is the half-open edge — reaching the\n // mark exactly pauses, matching the `>=` window edges `rate-limit` /\n // `circuit-breaker` use.\n if (policy.highWaterMark > 0 && seen >= policy.highWaterMark) {\n return { phase: \"paused\", cursor: next, seen, pages };\n }\n return { phase: \"fetching\", cursor: next, seen, pages };\n}\n\n/**\n * Acknowledge that the consumer finished processing `n` items, lowering the\n * backpressure gauge. PURE — returns a new state; the input is never mutated.\n *\n * Subtracts `n` from `seen`, floored at 0 (a consumer that over-acks, or acks a\n * page recorded before a reload, can never drive `seen` negative). `n <= 0` is a\n * no-op on the count. `drain` does NOT change the phase — it only frees\n * headroom; `resume` is the separate, explicit decision to re-issue a fetch once\n * the headroom exists. Splitting \"I drained\" from \"I want to continue\" lets a\n * consumer drain in several steps and resume once.\n *\n * Works on every phase: a consumer may drain while still `fetching` (the gauge\n * just drops, no pause was reached) or while `paused` (freeing room for a later\n * `resume`). On `done` the gauge can still be drained for accurate final\n * accounting, though it no longer gates anything.\n */\nexport function drain<Cursor>(\n state: PaginatorState<Cursor>,\n n: number,\n): PaginatorState<Cursor> {\n if (n <= 0) return state;\n const seen = Math.max(0, state.seen - n);\n if (seen === state.seen) return state;\n return { ...state, seen };\n}\n\n/**\n * Re-open the backpressure valve after a `drain`. PURE — returns a new state;\n * the input is never mutated.\n *\n * - `paused` AND `seen < highWaterMark` → `fetching(cursor)`: the consumer has\n * drained below the mark, so re-issue the parked fetch.\n * - `paused` but `seen >= highWaterMark` → unchanged. There is still no\n * headroom; the valve stays shut until a `drain` lowers `seen`. A consumer\n * that resumes optimistically can't defeat the backpressure. (When `hwm <=\n * 0` backpressure is disabled, so the walk never reaches `paused` and this\n * branch is unreachable — but the guard reads `< hwm` consistently, and a\n * non-positive `hwm` makes `seen < hwm` false for any non-negative `seen`,\n * correctly refusing to resume a state that should never have paused.)\n * - any other phase → unchanged. Resuming a walk that isn't paused (idle,\n * fetching, done) is a no-op.\n *\n * See the module header's note ².\n */\nexport function resume<Cursor>(\n state: PaginatorState<Cursor>,\n policy: PaginatorPolicy<Cursor>,\n): PaginatorState<Cursor> {\n if (state.phase !== \"paused\") return state;\n if (state.seen < policy.highWaterMark) {\n return {\n phase: \"fetching\",\n cursor: state.cursor,\n seen: state.seen,\n pages: state.pages,\n };\n }\n return state;\n}\n\n/**\n * Whether the walk has finished (the API returned a null next cursor). PURE,\n * read-only. A derived predicate so a consumer's reducer can branch\n * (`if (isDone(walk)) return [doneState, [joinCmd]]`) without re-checking the\n * `phase` discriminant by hand at every call site.\n */\nexport function isDone<Cursor>(state: PaginatorState<Cursor>): boolean {\n return state.phase === \"done\";\n}\n","/**\n * internal/paginate/paginated-walk — traverse a paginated API / sitemap end to end\n * WITHOUT a fake clock, without 429s, and resumable across a Durable-Object\n * eviction. The L2 composition that bolts `../resilient-call`'s resilience onto\n * `../paginator`'s cursor walk: each page is fetched as ONE keyed resilient\n * call (retry + backoff + rate-limit gate), and the cursor advances only once a\n * page settles `ok`.\n *\n * ## The recipe (the two siblings it composes)\n *\n * - **`../paginator`** owns the walk loop: the opaque `Cursor`, the `seen` /\n * `pages` counters, and the `idle → fetching → … → done` phase machine.\n * `paginated-walk` never re-implements cursor advancement — it folds each\n * settled page through `recordPage`, letting the paginator decide\n * `done` / `fetching(next)` / `paused`. Backpressure is a TWO-way valve:\n * `recordPage` parks the walk in `paused` once `seen >= highWaterMark`, and\n * the `drain` / `resume` verbs (delegating to the paginator's own\n * `drain` / `resume`) lower the gauge and re-open the parked fetch — without\n * them `highWaterMark` would be a one-way valve that strands a paused walk.\n * - **`../resilient-call`** owns the page fetch: the single `resilient_run`\n * effect per page is gated through that knob's cache → circuit → rate-limit\n * → retry pipeline. A transient page failure backs off and re-issues the\n * SAME cursor (idempotent retry); the walk does not advance until the page\n * genuinely settles.\n *\n * Those are the only two siblings this module calls into. The resilience knobs\n * (`retry` / `circuit` / `rateLimit` / `deadline`) are NOT separate bricks\n * `paginated-walk` composes — they belong to `resilient-call`, which owns the\n * rate-limit gate internally. This module merely passes them through to\n * `createResilientCall` and re-uses two config TYPES at the boundary:\n * `RateLimitConfig` (re-exported by `resilient-call`) and `RetryPolicy` (from\n * `../retry-backoff`). Pass a `rateLimit` and `resilient-call`'s token bucket\n * throttles page fetches (\"don't 429 the upstream\"); omit it and the walk runs\n * as fast as the upstream answers.\n *\n * Because the page-fetch resilience IS a `resilient-call` slice, this knob\n * **inherits that knob's contract verbatim**: the slice is a flat record, every\n * verb returns `readonly [State, Cmd[]]`, time is always an `at` parameter, and\n * the jitter RNG is injected once at `createPaginatedWalk(config, rng)` — never\n * read inside a verb (per the spec, `paginated-walk` *extends* `resilient-call`).\n *\n * ## The two non-negotiables (canon)\n *\n * - **Durable** — the slice is plain data: the paginator phase + counters, and\n * the resilient-call brick states (all JSON-serializable). The cursor lives\n * in the Model, not a closure, so a walk survives eviction mid-traversal and\n * resumes from the exact page it was fetching.\n * - **Replayable** — every transition is a verb returning new state + Cmds.\n * `nextCursor` / `onPage` are pure config functions applied at the verb\n * boundary; the Cmds they yield are plain data. `replay` reconstructs the\n * whole walk exactly.\n *\n * ## Where the clock / RNG live\n *\n * Inside the verbs: nowhere. `at` arrives on `start` / `resume`, on the settled\n * Msg `pageOk` / `pageErr` read (stamped by the engine), and on the timer Msg\n * `onTimer` reads, and is threaded straight into the underlying resilient-call\n * gate (so a rate-limited or retried page measures backoff from that `at`). The\n * jitter RNG is injected at construction. The knob ships no I/O: the page\n * fetch is resilient-call's `Cmd.define`d run Cmd, and its handler is yours.\n *\n * ## The fixed fetch key\n *\n * A walk fetches one page at a time, so the resilient-call layer tracks exactly\n * one logical call under the constant key `PAGE_KEY`. The cursor being fetched\n * is the resilient call's `input`, so a post-eviction resume re-issues the same\n * page request. (`resilient-call` is keyed to support N concurrent calls; a walk\n * deliberately uses a single key — the paginator is the sequencer.)\n *\n * ## Typical wiring\n *\n * const walk = createPaginatedWalk<PageToken, ApiPage>({\n * firstPage: null, // the API's \"page one\" sentinel\n * nextCursor: (page) => page.nextToken ?? null,\n * onPage: (page) => [{ type: \"index_rows\", rows: page.items }],\n * rateLimit: { capacity: 10, refillPerSec: 5 },\n * retry: defaultRetryPolicy,\n * });\n *\n * // in the machine:\n * cmds: [walk.fetch],\n * init: () => [{ walk: walk.init() }, []],\n * update: {\n * start: (s, m) => lift(s, walk.start(s.walk, m.at)),\n * resilient_run_ok: (s, m) => lift(s, walk.pageOk(s.walk, m)),\n * resilient_run_err: (s, m) => lift(s, walk.pageErr(s.walk, m)),\n * deadline_exceeded: (s, m) => lift(s, walk.onTimer(s.walk, m)),\n * drained: (s, m) => lift(s, walk.drain(s.walk, m.n)),\n * resume: (s, m) => lift(s, walk.resume(s.walk, m.at)),\n * },\n * subs: [{ type: \"timer\", deps: (s) => walk.timer(s.walk) }],\n *\n * // and where it runs — the page fetch is the handler you write:\n * run(machine, {\n * interpret: {\n * resilient_run: async (cmd, { ok, err }) => {\n * try { return ok(await api.fetchPage(cmd.input)); }\n * catch (cause) { return err({ _tag: \"port_rejected\", cause }); }\n * },\n * },\n * });\n */\n\nimport type { Cmd } from \"../../../index\";\nimport type { RetryPolicy } from \"../../../retry-backoff\";\nimport type { DeadlineSub } from \"../../resilience/deadline\";\nimport {\n type CircuitConfig,\n createResilientCall,\n type DeadlineConfig,\n type FailMsg,\n type RateLimitConfig,\n type ResilientState,\n type ResilientTimerMsg,\n type RunCmd,\n type SucceedMsg,\n} from \"../../resilience/resilient-call\";\nimport {\n drain as drainWalk,\n initPaginator,\n isDone,\n type PaginatorPolicy,\n type PaginatorState,\n recordPage,\n resume as resumeWalk,\n start as startWalk,\n} from \"../paginator\";\n\n// ===========================================================================\n// Config — the knob. `firstPage` / `nextCursor` / `onPage` describe the walk;\n// the resilience bricks are inherited from resilient-call (every one optional —\n// omit a brick, omit its gate).\n// ===========================================================================\n\n/**\n * The paginated-walk knob. Generic in `Cursor` (the opaque page handle the\n * upstream API hands back — offset, page token, \"next\" URL, …) and `Page` (the\n * shape your fetch port resolves with).\n *\n * `nextCursor` and `onPage` are PURE config functions applied at the verb\n * boundary, never stored in the slice or in a Cmd (invariant 3 — Cmds are\n * plain data, not closures). `nextCursor(page)` extracts the API's next-page\n * handle (or `null` at the end); `onPage(page)` yields the Cmds the consumer\n * wants emitted for each successfully fetched page (index rows, write to R2,\n * dispatch a downstream Msg — whatever; an empty array is fine).\n *\n * The resilience bricks (`retry` / `circuit` / `rateLimit` / `deadline`) are\n * the SAME optional knobs `resilient-call` exposes — paginated-walk extends it.\n * `rateLimit` is the brick that keeps the walk from 429-ing the upstream.\n */\nexport interface PaginatedWalkConfig<Cursor, Page, EmittedCmd extends Cmd> {\n /**\n * The cursor the walk fetches first. For an offset API this is typically `0`;\n * for a token API, whatever sentinel the API treats as \"page one\" (often\n * `null` or `\"\"`). Threaded into `paginator`'s `firstCursor`.\n */\n readonly firstPage: Cursor;\n /**\n * Extract the next cursor from a just-fetched page. Return a `Cursor` to keep\n * walking, or `null` when the API signalled the end (the walk finishes). PURE\n * + consumer-specific (only the consumer knows the API's pagination shape).\n */\n readonly nextCursor: (page: Page) => Cursor | null;\n /**\n * The Cmds to emit for each successfully fetched page — the consumer's work\n * per page (index, persist, fan out, …). Returns plain-data Cmds; `[]` is a\n * valid \"I process the page synchronously elsewhere\" answer. PURE.\n */\n readonly onPage: (page: Page) => readonly EmittedCmd[];\n /**\n * How many items a page contributes to the paginator's backpressure gauge\n * (`seen`). Defaults to `1` per page (count pages, not items) when omitted; a\n * consumer that wants per-item backpressure returns `page.items.length`. PURE.\n */\n readonly pageSize?: (page: Page) => number;\n /**\n * Backpressure threshold handed to the paginator. `seen >= highWaterMark`\n * parks the walk in `paused` instead of fetching the next page. Non-positive\n * (the default `0`) disables backpressure — the walk runs flat out until the\n * API exhausts. See `../paginator`'s `highWaterMark` docs.\n */\n readonly highWaterMark?: number;\n\n // --- resilience bricks, inherited from resilient-call (all optional) ---\n /** Exponential-backoff retry policy for a transient page-fetch failure. */\n readonly retry?: RetryPolicy;\n /** Circuit breaker around the page fetch (one upstream → one breaker). */\n readonly circuit?: CircuitConfig;\n /** Token-bucket rate limit — the \"don't 429 the upstream\" knob. */\n readonly rateLimit?: RateLimitConfig;\n /** Overall wall-clock deadline per individual page fetch. */\n readonly deadline?: DeadlineConfig;\n}\n\n// ===========================================================================\n// Slice — the Model field this knob owns. The paginator walk state + the\n// resilient-call slice for the page fetch. Both are flat plain data.\n// ===========================================================================\n\n/**\n * The slice. `walk` is the cursor/phase/counters from `../paginator`;\n * `resilience` is the `../resilient-call` slice that gates the page fetch.\n * Every field is JSON-serializable, so the whole walk survives a reload.\n *\n * The two move in lockstep: `walk` decides WHICH cursor to fetch next, while\n * `resilience` decides HOW that fetch is attempted (gated, retried, backed\n * off). `pageOk` advances `walk`; `pageErr` defers to `resilience` and leaves\n * `walk` parked on the same cursor until the page truly settles.\n */\nexport interface PaginatedWalkState<Cursor, Page> {\n readonly walk: PaginatorState<Cursor>;\n readonly resilience: ResilientState<Cursor, Page>;\n}\n\n// ===========================================================================\n// Cmds + Msgs the knob speaks.\n// ===========================================================================\n\n/**\n * The page-fetch effect this knob emits: the inherited `resilient_run` Cmd from\n * resilient-call, whose `input` is the `Cursor` to fetch and whose `key` is the\n * fixed `PAGE_KEY`. It is `Cmd.define`d; the handler you write for it fetches\n * one page and returns `ok(page)` or `err({ _tag: \"port_rejected\", … })`.\n */\nexport type FetchPageCmd<Cursor> = RunCmd<Cursor>;\n\n/** The page-settled Msgs the engine mints from that handler's outcome. */\nexport type PageOkMsg<Page> = SucceedMsg<Page>;\n/** The Msg the engine mints when the page-fetch handler fails. */\nexport type PageErrMsg = FailMsg;\n\n/** The retry / deadline timer Msg — inherited from resilient-call. */\nexport type PaginatedWalkTimerMsg = ResilientTimerMsg;\n\n// ===========================================================================\n// The fixed key. A walk fetches one page at a time → exactly one logical\n// resilient call. The paginator is the sequencer; resilient-call's keying is\n// pinned to this single key.\n// ===========================================================================\n\n/** The single resilient-call key every page fetch runs under. */\nexport const PAGE_KEY = \"page\";\n\n// ===========================================================================\n// The knob factory.\n// ===========================================================================\n\n/**\n * Build a paginated-walk knob from `config`. `rng` is injected for the\n * underlying retry jitter — pass a fixed `() => 0` in tests to pin backoff;\n * defaults to `Math.random` (read at the verb boundary inside resilient-call,\n * never in a `paginated-walk` verb). Inherited straight from resilient-call.\n *\n * Returns plain functions: `init()`, the verbs `start` / `pageOk` / `pageErr`\n * / `onTimer`, `deadlines(state)` / `timer(state)`, and the page-fetch Cmd def\n * (`fetch`) to list in the machine's `cmds`. `Cursor` is\n * the page handle, `Page` the fetch result, `EmittedCmd` the consumer's\n * per-page Cmds plus the inherited `FetchPageCmd`.\n */\nexport function createPaginatedWalk<Cursor, Page, EmittedCmd extends Cmd = Cmd>(\n config: PaginatedWalkConfig<Cursor, Page, EmittedCmd>,\n rng: () => number = Math.random,\n) {\n // The page fetch is a resilient call keyed by Cursor input → Page result.\n // We feed it only the resilience bricks; the walk-loop knobs are ours.\n const rc = createResilientCall<Cursor, Page>(\n {\n retry: config.retry,\n circuit: config.circuit,\n rateLimit: config.rateLimit,\n deadline: config.deadline,\n },\n rng,\n );\n\n // The paginator policy: our firstPage is the paginator's firstCursor; the\n // high-water mark gates backpressure (0 / omitted → unbounded).\n const paginatorPolicy: PaginatorPolicy<Cursor> = {\n firstCursor: config.firstPage,\n highWaterMark: config.highWaterMark ?? 0,\n };\n\n // The combined Cmd type the verbs can emit: the inherited page-fetch effect\n // plus whatever `onPage` yields.\n type OutCmd = FetchPageCmd<Cursor> | EmittedCmd;\n\n /** Replace the resilience slice, leaving `walk` untouched. */\n function withSlice(\n s: PaginatedWalkState<Cursor, Page>,\n resilience: ResilientState<Cursor, Page>,\n ): PaginatedWalkState<Cursor, Page> {\n return { ...s, resilience };\n }\n\n /** The starting slice: an idle paginator + a fresh resilient-call slice. */\n function init(): PaginatedWalkState<Cursor, Page> {\n return {\n walk: initPaginator<Cursor>(),\n resilience: rc.init(),\n };\n }\n\n /**\n * Issue a resilient page fetch for `cursor` at `at`. The cursor is the\n * resilient call's `input` (so a retry / resume re-fetches the same page) and\n * `PAGE_KEY` is the fixed key. Returns the advanced resilience slice + the\n * `resilient_run` Cmd (or none, if the gate cached / fast-failed / backed off).\n * PURE — `at` is the only clock. Shared by `start` and `pageOk`'s advance.\n */\n function fetch(\n s: PaginatedWalkState<Cursor, Page>,\n cursor: Cursor,\n at: number,\n ): readonly [\n PaginatedWalkState<Cursor, Page>,\n readonly FetchPageCmd<Cursor>[],\n ] {\n const [resilience, cmds] = rc.attempt(s.resilience, PAGE_KEY, cursor, at);\n return [withSlice(s, resilience), cmds];\n }\n\n /**\n * Issue the page fetch for a freshly-armed paginator transition, else a pure\n * no-op. `walk` is the result of a paginator verb (`startWalk` / `resumeWalk`)\n * applied to `s.walk`; this states the arm-and-fetch contract ONCE for the two\n * verbs that share it (`start`, `resume`).\n *\n * A paginator verb is a pure no-op on any phase it does not act on — it returns\n * the SAME state object. Reference identity (not phase) is the honest \"did the\n * verb arm a fresh fetch?\" check: a walk already `fetching` would also satisfy\n * `phase === \"fetching\"` yet must NOT re-issue a fetch (page-one skip /\n * double-fetch). So we proceed ONLY when the verb produced a fresh state. The\n * `phase === \"fetching\"` narrow that follows is therefore always true here\n * (both verbs only ever produce a `fetching` arm), and also narrows `.cursor`\n * for the type checker. PURE — `at` threads into the fetch gate.\n */\n function armAndFetch(\n s: PaginatedWalkState<Cursor, Page>,\n walk: PaginatorState<Cursor>,\n at: number,\n ): readonly [PaginatedWalkState<Cursor, Page>, readonly OutCmd[]] {\n if (walk === s.walk || walk.phase !== \"fetching\") {\n return [s, []];\n }\n return fetch({ ...s, walk }, walk.cursor, at);\n }\n\n // === Verb: start =========================================================\n\n /**\n * Begin the walk: arm the paginator's first cursor and issue the first page\n * fetch (gated through resilience). On any non-`idle` paginator phase this is\n * a no-op — re-starting a walk in flight would skip back to page one and\n * double-count, so a stray `start` after launch is absorbed (the paginator's\n * own `start` guard). PURE — `at` threads into the fetch gate.\n */\n function start(\n s: PaginatedWalkState<Cursor, Page>,\n at: number,\n ): readonly [PaginatedWalkState<Cursor, Page>, readonly OutCmd[]] {\n // `startWalk` is a pure no-op on any non-`idle` phase (same reference); a\n // fresh `fetching(firstCursor)` arm → issue the first page fetch.\n return armAndFetch(s, startWalk(s.walk, paginatorPolicy), at);\n }\n\n // === Verb: pageOk ========================================================\n\n /**\n * Record a successfully fetched page (the engine-minted `msg.value`) and\n * decide what comes next. PURE — `msg.at` is the cache / next-fetch clock.\n *\n * 1. Settle the resilient call OK (closes the breaker, fills the cache,\n * resets the page-fetch retry counter) — inherited from resilient-call.\n * 2. Fold the page through the paginator: add `pageSize(page)` to `seen`,\n * bump `pages`, and branch on `nextCursor(page)`:\n * - `null` → the API is exhausted → paginator goes `done`.\n * - a cursor → advance, then either fetch it (backpressure room) or\n * park in `paused` (high-water mark reached).\n * 3. Emit the consumer's `onPage(page)` Cmds either way, PLUS the next\n * page-fetch effect when the paginator stays `fetching`.\n *\n * A `pageOk` that arrives when the paginator is not `fetching` (a late\n * duplicate, a double-dispatch) is absorbed by `recordPage` — the cursor does\n * not advance and `seen` is not double-counted; only the resilient settle +\n * `onPage` Cmds happen. The walk is a coordination aid, not a correctness\n * gate.\n */\n function pageOk(\n s: PaginatedWalkState<Cursor, Page>,\n msg: PageOkMsg<Page>,\n ): readonly [PaginatedWalkState<Cursor, Page>, readonly OutCmd[]] {\n const { value: page, at } = msg;\n // 1) Settle the underlying resilient call as a success.\n const { call: resilience } = rc.settle(s.resilience, msg);\n\n // 2) Advance the paginator with the page's contribution + the next cursor.\n const count = config.pageSize ? config.pageSize(page) : 1;\n const next = config.nextCursor(page);\n const walk = recordPage(s.walk, count, next, paginatorPolicy);\n\n const advanced: PaginatedWalkState<Cursor, Page> = { walk, resilience };\n\n // 3) The consumer's per-page work, always emitted on a successful page.\n const pageCmds: readonly EmittedCmd[] = config.onPage(page);\n\n // If the paginator stayed `fetching`, issue the next page fetch (gated).\n if (walk.phase === \"fetching\") {\n const [withFetch, fetchCmds] = fetch(advanced, walk.cursor, at);\n return [withFetch, [...pageCmds, ...fetchCmds]];\n }\n\n // `done` (exhausted) or `paused` (backpressure) → no further fetch now.\n return [advanced, pageCmds];\n }\n\n // === Verb: pageErr =======================================================\n\n /**\n * Record a failed page fetch and back off via resilience. PURE — `at` stamps\n * the breaker trip + the retry-delay base.\n *\n * Defers to the resilient-call `settle` verb: it trips the breaker and either\n * schedules a retry (paginator stays parked on the SAME cursor — no advance)\n * or settles the resilient call `failed` once retries are exhausted. The\n * paginator is deliberately untouched: a failed fetch must NOT advance the\n * cursor or skip a page. When the retry timer later fires, `onTimer` re-issues\n * the same page fetch.\n *\n * GUARDED by the paginator phase, exactly as `pageOk` is guarded by\n * `recordPage`'s `fetching`-only check. A `pageErr` only makes sense while a\n * page fetch is outstanding (`walk.phase === \"fetching\"`). A stray `pageErr`\n * that arrives after the walk has settled — `done` (exhausted), `paused`\n * (backpressure), or `idle` (not started) — has NO outstanding fetch to fail.\n * Without this guard it would still call `rc.settle`, which trips the SHARED\n * circuit breaker (dinging a healthy upstream) and overwrites the settled\n * `PAGE_KEY` resilient slot with `failed` (clobbering the succeeded result a\n * resume would otherwise observe). So a stray `pageErr` is absorbed as a pure\n * no-op — identity preserved — matching `pageOk`'s \"the walk is a coordination\n * aid, not a correctness gate\" stance.\n */\n function pageErr(\n s: PaginatedWalkState<Cursor, Page>,\n msg: PageErrMsg,\n ): readonly [PaginatedWalkState<Cursor, Page>, readonly OutCmd[]] {\n // Only a `fetching` paginator has an outstanding page fetch to fail. On any\n // other phase the fail would corrupt shared resilience state for a fetch\n // that is not in flight — absorb it as a pure no-op.\n if (s.walk.phase !== \"fetching\") {\n return [s, []];\n }\n const { call: resilience, cmds } = rc.settle(s.resilience, msg);\n return [withSlice(s, resilience), cmds];\n }\n\n // === Verb: onTimer =======================================================\n\n /**\n * A retry / deadline timer fired. Defers to resilient-call's `onTimer`: a\n * retry timer re-runs the gate for the page-fetch's remembered cursor (re-\n * issuing the SAME page); a deadline timer settles the resilient call failed.\n * The paginator stays parked on its cursor throughout — only `pageOk` advances\n * it. A stale fire is a no-op (inherited). PURE.\n *\n * GUARDED by the paginator phase, for the same reason as `pageErr`. A timer is\n * only meaningful while a page fetch is outstanding (`walk.phase ===\n * \"fetching\"`). A stray timer that fires after the walk has settled (`done` /\n * `paused` / `idle`) would otherwise re-enter `rc.onTimer` — re-issuing a fetch\n * the paginator no longer wants (a deadline timer could even overwrite the\n * settled `PAGE_KEY` slot with a deadline `failed`). On any non-`fetching`\n * phase the timer is absorbed as a pure no-op.\n */\n function onTimer(\n s: PaginatedWalkState<Cursor, Page>,\n msg: PaginatedWalkTimerMsg,\n ): readonly [PaginatedWalkState<Cursor, Page>, readonly OutCmd[]] {\n if (s.walk.phase !== \"fetching\") {\n return [s, []];\n }\n const [resilience, cmds] = rc.onTimer(s.resilience, msg);\n return [withSlice(s, resilience), cmds];\n }\n\n // === Verb: drain =========================================================\n\n /**\n * Acknowledge that the consumer finished processing `n` items, lowering the\n * paginator's backpressure gauge (`seen`). PURE — no clock. Delegates to\n * `paginator.drain`: subtracts `n` (floored at 0), leaves the phase untouched.\n *\n * The OTHER half of the backpressure valve `highWaterMark` opens: `recordPage`\n * parks the walk in `paused` once `seen >= highWaterMark`, and `drain` is how a\n * consumer lowers `seen` back below the mark so `resume` can re-open the fetch.\n * Without it `highWaterMark` would be a one-way valve — a walk could pause but\n * never continue. Emits no Cmds: draining only frees headroom; `resume` is the\n * separate, explicit \"continue now\" decision.\n */\n function drain(\n s: PaginatedWalkState<Cursor, Page>,\n n: number,\n ): readonly [PaginatedWalkState<Cursor, Page>, readonly OutCmd[]] {\n const walk = drainWalk(s.walk, n);\n if (walk === s.walk) {\n // Pure no-op identity (n <= 0, or seen already at floor).\n return [s, []];\n }\n return [{ ...s, walk }, []];\n }\n\n // === Verb: resume ========================================================\n\n /**\n * Re-open the backpressure valve after a `drain`: if the walk is `paused` and\n * `seen` has dropped below `highWaterMark`, re-arm the parked cursor and issue\n * its page fetch (gated through resilience). PURE — `at` threads into the fetch\n * gate. Delegates the phase decision to `paginator.resume`:\n *\n * - `paused` AND `seen < highWaterMark` → `fetching(cursor)` → emit the fetch.\n * - `paused` but still over the mark → no-op (the valve stays shut until a\n * further `drain` frees real headroom).\n * - any other phase → no-op (nothing to resume).\n *\n * Together with `drain` this completes the valve: `recordPage` shuts it\n * (`paused`), `drain` lowers the gauge, `resume` re-opens it and fires the next\n * page fetch — the same `fetch` helper `start` / `pageOk` use, so a resumed\n * fetch is gated identically (cache / circuit / rate-limit / retry).\n */\n function resume(\n s: PaginatedWalkState<Cursor, Page>,\n at: number,\n ): readonly [PaginatedWalkState<Cursor, Page>, readonly OutCmd[]] {\n // `resumeWalk` is a pure no-op (same reference) on any phase but `paused`, or\n // when `seen` is still at/over the mark. Only a fresh `fetching` arm means\n // the valve actually re-opened — issue the page fetch only then.\n return armAndFetch(s, resumeWalk(s.walk, paginatorPolicy), at);\n }\n\n // === Derived predicates ==================================================\n\n /**\n * Whether the walk has finished — the API returned a null next cursor and the\n * paginator is `done`. PURE, read-only. Lets a consumer's reducer fire a\n * \"walk complete\" Cmd (`if (walk.isDone(s.walk)) …`) without re-checking the\n * paginator phase by hand.\n */\n function isComplete(s: PaginatedWalkState<Cursor, Page>): boolean {\n return isDone(s.walk);\n }\n\n /**\n * The terminal page-fetch failure that stranded the walk, or `undefined` if no\n * page has terminally failed. PURE, read-only. Errors are data: a page that\n * exhausts its retries (or trips the deadline) settles the `PAGE_KEY` resilient\n * slot to `failed` while the paginator stays parked on its cursor — the walk is\n * stuck and will never advance on its own. Without a way to read that phase the\n * failure is unobservable: the walk simply stops emitting fetches with no\n * signal. `failure(s)` surfaces the settled error (the same plain-data sentinel\n * resilient-call records) so a consumer can fire a \"walk dead\" Cmd, alert, or\n * re-`start` a fresh walk.\n */\n function failure(s: PaginatedWalkState<Cursor, Page>): unknown {\n const call = s.resilience.calls[PAGE_KEY];\n return call?.phase === \"failed\" ? call.error : undefined;\n }\n\n /**\n * Whether the walk is STUCK: a page fetch has terminally `failed` yet the\n * paginator is still parked on a cursor (not `done`), so no further fetch will\n * ever be issued without intervention. PURE, read-only.\n *\n * This is the dead-walk predicate the consumer polls (`if (walk.isStuck(s)) …`)\n * to distinguish a healthy finish (`isComplete`) from a silent death. A walk is\n * stuck precisely when the resilient slot settled `failed` AND the paginator\n * has NOT reached `done` — a terminal failure on the final page that also\n * finished the walk is `isComplete`, not stuck. Pairs with `failure(s)`, which\n * hands back the error that stuck it.\n */\n function isStuck(s: PaginatedWalkState<Cursor, Page>): boolean {\n return s.resilience.calls[PAGE_KEY]?.phase === \"failed\" && !isDone(s.walk);\n }\n\n // === Timers ==============================================================\n\n /**\n * The page fetch's deadlines — exactly resilient-call's: a retry timer while\n * the fetch is `waiting_retry`, and (with the `deadline` brick) a per-fetch\n * deadline timer while it is active.\n */\n function deadlines(\n s: PaginatedWalkState<Cursor, Page>,\n ): readonly DeadlineSub[] {\n return rc.deadlines(s.resilience);\n }\n\n /**\n * The built-in `timer` Sub's deps: resilient-call's `timer` over the fetch's\n * slice. Declare `{ type: \"timer\", deps: (s) => walk.timer(s.walk) }`.\n */\n function timer(s: PaginatedWalkState<Cursor, Page>) {\n return rc.timer(s.resilience);\n }\n\n return {\n /** The page-fetch Cmd def — list it in the machine's `cmds`. */\n fetch: rc.run,\n init,\n start,\n pageOk,\n pageErr,\n onTimer,\n drain,\n resume,\n isComplete,\n failure,\n isStuck,\n deadlines,\n timer,\n };\n}\n\n/**\n * Lift a knob result `[slice, cmds]` into a host `[State, cmds]` where the slice\n * lives at `state.walk`. A convenience for the common single-slice host;\n * consumers with a differently-named field spread by hand. Pure — a thin record\n * rebuild, no clock / RNG.\n */\nexport function liftWalk<\n S extends { walk: PaginatedWalkState<Cursor, Page> },\n Cursor,\n Page,\n C extends Cmd,\n>(\n state: S,\n [slice, cmds]: readonly [PaginatedWalkState<Cursor, Page>, readonly C[]],\n): readonly [S, readonly C[]] {\n return [{ ...state, walk: slice }, cmds];\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/internal/paginate/paginator/index.ts","../src/internal/paginate/paginated-walk/index.ts"],"names":["start","drain","resume"],"mappings":";;;AAmJO,IAAM,sBAAA,GAAkD;AAAA,EAC7D,WAAA,EAAa,CAAA;AAAA,EACb,aAAA,EAAe;AACjB;AAqCO,SAAS,aAAA,GAAgD;AAC9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CAAA;AAAA,EAC9B;AAEA,EAAA,OAAO;AAAA;AAAA,IAEL,OAAO,EAAA,CAAG,GAAA;AAAA,IACV,IAAA;AAAA,IACA,KAAA,EAAAF,MAAAA;AAAA,IACA,MAAA;AAAA,IACA,OAAA;AAAA,IACA,OAAA;AAAA,IACA,KAAA,EAAAC,MAAAA;AAAA,IACA,MAAA,EAAAC,OAAAA;AAAA,IACA,UAAA;AAAA,IACA,OAAA;AAAA,IACA,OAAA;AAAA,IACA,SAAA;AAAA,IACA;AAAA,GACF;AACF;AAQO,SAAS,QAAA,CAMd,KAAA,EACA,CAAC,KAAA,EAAO,IAAI,CAAA,EACgB;AAC5B,EAAA,OAAO,CAAC,EAAE,GAAG,OAAO,IAAA,EAAM,KAAA,IAAS,IAAI,CAAA;AACzC","file":"chunk-CPE5ZQXQ.js","sourcesContent":["/**\n * internal/paginate/paginator — the cursor/offset/page-token walk loop as pure\n * state + ops.\n *\n * Same shape as `../../../retry-backoff`, `../../resilience/circuit-breaker`,\n * and `../../resilience/rate-limit`: a state type plus pure transition functions,\n * host-agnostic by construction. Nothing here reads the clock, the RNG, or any\n * I/O on its own behalf — the consumer fetches a page out-of-band and folds the\n * *result* back in through `recordPage`. That keeps every function inside TEA's\n * invariant 2 (transitions are pure: same inputs → same outputs) so a consumer\n * can thread the walk through `update` and exercise it with `replay` / the pbt\n * fold without a fake network.\n *\n * Every op returns a NEW state value and never mutates its input (invariant 1 —\n * state is a value, not a place). All fields are `readonly` and plain data, so\n * the whole walk is trivially JSON-serializable into a consumer's `Store<S>`\n * and survives a Durable-Object eviction / reload mid-walk: the cursor lives in\n * the Model, not a closure (the durability + replay non-negotiables every TEA\n * knob preserves).\n *\n * ## The cursor is opaque, and the consumer advances it\n *\n * A paginated API hands back a *next cursor* however it likes: an offset\n * (`?offset=40`), a page token (`?pageToken=ey…`), a \"next\" URL, or `null` at\n * the end. This module is generic in `Cursor` and never inspects it — it only\n * carries it forward. The consumer (who alone knows the API's shape) reads the\n * next cursor off the just-fetched page and passes it to `recordPage`:\n *\n * const next = page.nextPageToken ?? null; // consumer-specific extraction\n * const walk = recordPage(state.walk, page.items.length, next);\n *\n * Passing `next: null` (or a missing `undefined` cursor — the op compares with\n * loose `== null`) means \"the API said there is no next page\" → the walk\n * finishes (`done`). Passing a `Cursor` means \"fetch this one next\" → the walk\n * either keeps `fetching` or `pauses` for backpressure (below). Decoupling the\n * extraction from the op is the same discipline `circuit-breaker` uses for the\n * clock: the impure / domain-specific bit (`nextCursor(page)`) lives at the\n * call site; the op stays a pure fold over the extracted value.\n *\n * ## The phase machine\n *\n * Four phases, each a discriminated-union arm carrying ONLY the data that phase\n * needs so impossible states are unrepresentable (pattern 11):\n *\n * - **idle** — created, not started. No cursor is armed yet; `start` arms the\n * first one. Carries the running `seen` / `pages` counters (both 0 here, but\n * present on every phase so a consumer reads them uniformly).\n *\n * - **fetching** — a page request for `cursor` is outstanding. The walk sits\n * here while the consumer's fetch is in flight; `recordPage` resolves it.\n * Carries the `cursor` being fetched so a post-eviction resume re-issues the\n * SAME request (idempotent retry) rather than skipping a page.\n *\n * - **paused** — backpressure tripped. The API still has more pages (a non-null\n * next cursor), but `seen` has reached `highWaterMark` and the consumer has\n * not drained yet. Carries the `cursor` to resume from. No fetch is\n * outstanding — the loop is deliberately idle until `resume`. This is the\n * valve that stops a fast producer (the API) from outrunning a slow consumer\n * (whatever processes each page) and blowing memory.\n *\n * - **done** — the API returned a null next cursor; the walk is exhausted. A\n * terminal phase: `start` / `recordPage` / `resume` are all no-ops on it\n * (idempotent completion — a late duplicate result can't un-finish a walk).\n *\n * ### Transition table\n *\n * Rows are the current phase; columns are the op. `→` denotes the next phase;\n * `self` means unchanged (a no-op for that (phase × op) pair). `next` is the\n * cursor the consumer extracted from the page; `hwm` is `highWaterMark`.\n *\n * | from \\ op | start | recordPage(count, next) | resume |\n * | ----------- | -------------- | -------------------------------------------------------------------- | ------------------------------ |\n * | idle | → fetching(c0) | self *(¹)* | self |\n * | fetching | self | seen=max(0,seen+count), pages+=1; next==null → done; seen≥hwm → paused(next); else → fetching(next) | self |\n * | paused | self | self *(¹)* | seen<hwm → fetching(cursor) *(²)* |\n * | done | self | self | self |\n *\n * *(¹)* `recordPage` only makes sense while `fetching` (a page was outstanding).\n * On any other phase it is a no-op: a result that arrives when no fetch was in\n * flight (a late duplicate, a double-dispatch) must not advance the cursor or\n * double-count `seen`. The walk is a coordination aid, not a correctness gate —\n * it absorbs the stray rather than corrupting the count.\n *\n * *(²)* `resume` re-arms the paused cursor ONLY once `seen` has dropped below\n * `highWaterMark` (the consumer drained, lowering `seen` via `drain`). Calling\n * `resume` while still over the mark is a no-op — the valve stays shut until\n * there is real headroom, so a consumer that resumes optimistically can't\n * defeat the backpressure. Resuming a walk that isn't `paused` is likewise a\n * no-op.\n *\n * ## Backpressure\n *\n * `seen` is the count of items the API has produced that the consumer has not\n * yet acknowledged as processed. `recordPage` adds each page's item count to it;\n * `drain(n)` subtracts what the consumer finished. When `seen` reaches\n * `highWaterMark`, `recordPage` parks the walk in `paused` instead of issuing\n * the next fetch — the producer stops until `drain` + `resume` re-open the\n * valve. A `highWaterMark` of `0` (or any non-positive value) disables\n * backpressure: the comparison `seen >= hwm` is satisfied vacuously only when\n * `hwm <= 0` would pause immediately, so we treat `hwm <= 0` as \"unbounded\" and\n * never pause. The walk then runs flat-out, `fetching → fetching` until `done`.\n *\n * Internal since #47 — not published on any subpath; reached from inside the\n * package as `internal/paginate/paginator`. Same one-shape-per-package rule as `work-queue`, `retry-backoff`,\n * `circuit-breaker`, and `rate-limit`. It is the L1 escape hatch the\n * `paginated-walk` composition builds its walk loop on.\n */\n\n/**\n * Paginator policy — pure configuration, no mutable state. One policy is shared\n * across the whole walk (often a module-scope const). `PaginatorState` carries\n * the cursor + counters; this carries the knobs they're compared against.\n *\n * Generic in `Cursor` so `firstCursor` matches whatever the API's cursor shape\n * is — an offset `number`, a page-token `string`, a `{ after: string }` record,\n * etc. The module never inspects the cursor; the type just threads through.\n */\nexport interface PaginatorPolicy<Cursor> {\n /**\n * The cursor the walk fetches first, armed by `start`. For an offset API this\n * is typically `0`; for a token API, `null`-or-empty-meaning-\"first page\" is\n * the API's call, so pass whatever sentinel the API treats as page one.\n */\n readonly firstCursor: Cursor;\n /**\n * Backpressure threshold: the number of un-drained items at which the walk\n * pauses instead of fetching the next page. `recordPage` parks in `paused`\n * once `seen >= highWaterMark`; `drain` + `resume` re-open the valve.\n *\n * A non-positive value (`<= 0`) disables backpressure — the walk never pauses\n * and runs `fetching → fetching` until the API exhausts. Use that when the\n * consumer processes each page synchronously inside `recordPage` and there is\n * nothing to back up.\n */\n readonly highWaterMark: number;\n}\n\n/**\n * Sensible defaults: start from a numeric offset of `0`, pause after 1000\n * un-drained items. Tuned for an offset-paginated REST API whose consumer\n * processes pages asynchronously; override per call site (especially\n * `firstCursor`, which is API-specific) rather than mutating this shared const.\n *\n * Typed as `PaginatorPolicy<number>` because the only honest default cursor is\n * the numeric offset `0`; a token-based API supplies its own `firstCursor` and\n * its own `PaginatorPolicy<string>`.\n */\nexport const defaultPaginatorPolicy: PaginatorPolicy<number> = {\n firstCursor: 0,\n highWaterMark: 1000,\n};\n\n/**\n * The walk's phase. A discriminated union on `phase` so each phase carries ONLY\n * its own data and impossible combinations are unrepresentable (pattern 11):\n * there is no `done` state that still holds a pending cursor, no `idle` state\n * mid-fetch. Every field is `readonly` so the whole value is trivially\n * JSON-serializable into a consumer's `Store<S>` and safe to thread through a\n * pure reducer / a Durable-Object reload.\n *\n * Two counters ride on every phase so a consumer reads them uniformly without\n * narrowing first:\n * - `seen` — items produced by the API but not yet drained (backpressure gauge).\n * - `pages` — total pages recorded so far (progress / observability).\n *\n * - `idle` — not started; `start` arms `firstCursor`.\n * - `fetching` — a page request for `cursor` is outstanding.\n * - `paused` — backpressure tripped; `cursor` is the page to resume from.\n * - `done` — API exhausted (null next cursor); terminal.\n */\nexport type PaginatorState<Cursor> =\n | { readonly phase: \"idle\"; readonly seen: number; readonly pages: number }\n | {\n readonly phase: \"fetching\";\n readonly cursor: Cursor;\n readonly seen: number;\n readonly pages: number;\n }\n | {\n readonly phase: \"paused\";\n readonly cursor: Cursor;\n readonly seen: number;\n readonly pages: number;\n }\n | { readonly phase: \"done\"; readonly seen: number; readonly pages: number };\n\n/** The starting state: idle, nothing seen, no pages recorded. */\nexport function initPaginator<Cursor>(): PaginatorState<Cursor> {\n return { phase: \"idle\", seen: 0, pages: 0 };\n}\n\n/**\n * Arm the first fetch. PURE — returns a new state; the input is never mutated.\n *\n * - `idle` → `fetching(firstCursor)`. This is the only phase `start` acts on.\n * - any other phase → unchanged. Re-arming a walk that has already begun (or\n * finished) would skip back to page one and double-count; a stray `start`\n * after launch is absorbed, not honored. Use `initPaginator()` to begin a\n * genuinely fresh walk.\n */\nexport function start<Cursor>(\n state: PaginatorState<Cursor>,\n policy: PaginatorPolicy<Cursor>,\n): PaginatorState<Cursor> {\n if (state.phase !== \"idle\") return state;\n return {\n phase: \"fetching\",\n cursor: policy.firstCursor,\n seen: state.seen,\n pages: state.pages,\n };\n}\n\n/**\n * Record the result of the outstanding fetch and decide what comes next. PURE —\n * returns a new state; the input is never mutated.\n *\n * `count` is how many items the just-fetched page yielded (added to `seen` for\n * backpressure accounting). `next` is the cursor the consumer extracted from the\n * page — a `Cursor` to fetch next, or `null`/`undefined` (a missing optional\n * cursor field) if the API signalled the end.\n *\n * - `fetching` → `seen = max(0, seen + count)`, `pages += 1`, then branch on\n * `next`:\n * - `next == null` → `done` (API exhausted; loose-null so a\n * missing/`undefined` cursor also finishes).\n * - `seen >= highWaterMark` → `paused(next)` (backpressure; `hwm <= 0`\n * disables this branch — see policy docs).\n * - otherwise → `fetching(next)` (keep walking).\n * - any other phase → unchanged. A result with no fetch outstanding (a late\n * duplicate, a double-dispatch) must not advance the cursor or double-count;\n * it is absorbed. See the module header's note ¹.\n *\n * `count` is floored into the gauge: a non-finite `count` (`NaN`/`Infinity`) is\n * treated as `0`, and the additive sum is clamped at `0`. A record can only hold\n * or raise `seen`; only `drain` lowers it. This keeps a stray negative or\n * non-finite count from poisoning the `seen >= highWaterMark` comparison and\n * silently defeating backpressure.\n *\n * The new `seen` total — not the pre-page value — is what the backpressure check\n * reads, so a single page large enough to cross the mark pauses immediately\n * rather than fetching one more first.\n */\nexport function recordPage<Cursor>(\n state: PaginatorState<Cursor>,\n count: number,\n next: Cursor | null | undefined,\n policy: PaginatorPolicy<Cursor>,\n): PaginatorState<Cursor> {\n if (state.phase !== \"fetching\") return state;\n // A page's item count must be a finite, non-negative addition to `seen`. A\n // negative count would drive `seen` down (a record can never lower the gauge —\n // only `drain` does) and a non-finite count (`NaN` / `Infinity`) would poison\n // every later `seen >= highWaterMark` comparison, permanently defeating\n // backpressure (NaN compares false, so the valve never trips). Floor the\n // CONTRIBUTION (not just the sum) at 0: clamp a non-finite count to 0\n // (mirroring retry-backoff's `Number.isNaN` discipline at backoffDelay ~:119)\n // and a negative count to 0. Flooring the contribution — rather than the sum —\n // is what makes a record strictly monotonic: `Math.max(0, seen + count)` only\n // catches a count that drags the *sum* below zero, so a small negative count\n // (e.g. `seen=10, count=-3 → 7`) would still silently lower the gauge and\n // break \"only `drain` lowers `seen`\". Clamping `count` first guarantees the\n // additive step can only hold or raise the gauge.\n const safeCount = Number.isFinite(count) ? Math.max(0, count) : 0;\n const seen = state.seen + safeCount;\n const pages = state.pages + 1;\n // Loose `== null` so a *missing* next cursor (`undefined`, common for an\n // optional API field the consumer extracted as `page.nextPageToken`) finishes\n // the walk exactly like an explicit `null`. Strict `=== null` would route an\n // `undefined` cursor into the fetching/paused branch and carry a cursor-less\n // (malformed) state forward.\n if (next == null) {\n return { phase: \"done\", seen, pages };\n }\n // `hwm <= 0` disables backpressure entirely (unbounded walk); only a positive\n // mark can park the loop. `seen >= hwm` is the half-open edge — reaching the\n // mark exactly pauses, matching the `>=` window edges `rate-limit` /\n // `circuit-breaker` use.\n if (policy.highWaterMark > 0 && seen >= policy.highWaterMark) {\n return { phase: \"paused\", cursor: next, seen, pages };\n }\n return { phase: \"fetching\", cursor: next, seen, pages };\n}\n\n/**\n * Acknowledge that the consumer finished processing `n` items, lowering the\n * backpressure gauge. PURE — returns a new state; the input is never mutated.\n *\n * Subtracts `n` from `seen`, floored at 0 (a consumer that over-acks, or acks a\n * page recorded before a reload, can never drive `seen` negative). `n <= 0` is a\n * no-op on the count. `drain` does NOT change the phase — it only frees\n * headroom; `resume` is the separate, explicit decision to re-issue a fetch once\n * the headroom exists. Splitting \"I drained\" from \"I want to continue\" lets a\n * consumer drain in several steps and resume once.\n *\n * Works on every phase: a consumer may drain while still `fetching` (the gauge\n * just drops, no pause was reached) or while `paused` (freeing room for a later\n * `resume`). On `done` the gauge can still be drained for accurate final\n * accounting, though it no longer gates anything.\n */\nexport function drain<Cursor>(\n state: PaginatorState<Cursor>,\n n: number,\n): PaginatorState<Cursor> {\n if (n <= 0) return state;\n const seen = Math.max(0, state.seen - n);\n if (seen === state.seen) return state;\n return { ...state, seen };\n}\n\n/**\n * Re-open the backpressure valve after a `drain`. PURE — returns a new state;\n * the input is never mutated.\n *\n * - `paused` AND `seen < highWaterMark` → `fetching(cursor)`: the consumer has\n * drained below the mark, so re-issue the parked fetch.\n * - `paused` but `seen >= highWaterMark` → unchanged. There is still no\n * headroom; the valve stays shut until a `drain` lowers `seen`. A consumer\n * that resumes optimistically can't defeat the backpressure. (When `hwm <=\n * 0` backpressure is disabled, so the walk never reaches `paused` and this\n * branch is unreachable — but the guard reads `< hwm` consistently, and a\n * non-positive `hwm` makes `seen < hwm` false for any non-negative `seen`,\n * correctly refusing to resume a state that should never have paused.)\n * - any other phase → unchanged. Resuming a walk that isn't paused (idle,\n * fetching, done) is a no-op.\n *\n * See the module header's note ².\n */\nexport function resume<Cursor>(\n state: PaginatorState<Cursor>,\n policy: PaginatorPolicy<Cursor>,\n): PaginatorState<Cursor> {\n if (state.phase !== \"paused\") return state;\n if (state.seen < policy.highWaterMark) {\n return {\n phase: \"fetching\",\n cursor: state.cursor,\n seen: state.seen,\n pages: state.pages,\n };\n }\n return state;\n}\n\n/**\n * Whether the walk has finished (the API returned a null next cursor). PURE,\n * read-only. A derived predicate so a consumer's reducer can branch\n * (`if (isDone(walk)) return [doneState, [joinCmd]]`) without re-checking the\n * `phase` discriminant by hand at every call site.\n */\nexport function isDone<Cursor>(state: PaginatorState<Cursor>): boolean {\n return state.phase === \"done\";\n}\n","/**\n * internal/paginate/paginated-walk — traverse a paginated API / sitemap end to end\n * WITHOUT a fake clock, without 429s, and resumable across a Durable-Object\n * eviction. The L2 composition that bolts `../resilient-call`'s resilience onto\n * `../paginator`'s cursor walk: each page is fetched as ONE keyed resilient\n * call (retry + backoff + rate-limit gate), and the cursor advances only once a\n * page settles `ok`.\n *\n * ## The recipe (the two siblings it composes)\n *\n * - **`../paginator`** owns the walk loop: the opaque `Cursor`, the `seen` /\n * `pages` counters, and the `idle → fetching → … → done` phase machine.\n * `paginated-walk` never re-implements cursor advancement — it folds each\n * settled page through `recordPage`, letting the paginator decide\n * `done` / `fetching(next)` / `paused`. Backpressure is a TWO-way valve:\n * `recordPage` parks the walk in `paused` once `seen >= highWaterMark`, and\n * the `drain` / `resume` verbs (delegating to the paginator's own\n * `drain` / `resume`) lower the gauge and re-open the parked fetch — without\n * them `highWaterMark` would be a one-way valve that strands a paused walk.\n * - **`../resilient-call`** owns the page fetch: the single `resilient_run`\n * effect per page is gated through that knob's cache → circuit → rate-limit\n * → retry pipeline. A transient page failure backs off and re-issues the\n * SAME cursor (idempotent retry); the walk does not advance until the page\n * genuinely settles.\n *\n * Those are the only two siblings this module calls into. The resilience knobs\n * (`retry` / `circuit` / `rateLimit` / `deadline`) are NOT separate bricks\n * `paginated-walk` composes — they belong to `resilient-call`, which owns the\n * rate-limit gate internally. This module merely passes them through to\n * `createResilientCall` and re-uses two config TYPES at the boundary:\n * `RateLimitConfig` (re-exported by `resilient-call`) and `RetryPolicy` (from\n * `../retry-backoff`). Pass a `rateLimit` and `resilient-call`'s token bucket\n * throttles page fetches (\"don't 429 the upstream\"); omit it and the walk runs\n * as fast as the upstream answers.\n *\n * Because the page-fetch resilience IS a `resilient-call` slice, this knob\n * **inherits that knob's contract verbatim**: the slice is a flat record, every\n * verb returns `readonly [State, Cmd[]]`, time is always an `at` parameter, and\n * the jitter RNG is injected once at `createPaginatedWalk(config, rng)` — never\n * read inside a verb (per the spec, `paginated-walk` *extends* `resilient-call`).\n *\n * ## The two non-negotiables (canon)\n *\n * - **Durable** — the slice is plain data: the paginator phase + counters, and\n * the resilient-call brick states (all JSON-serializable). The cursor lives\n * in the Model, not a closure, so a walk survives eviction mid-traversal and\n * resumes from the exact page it was fetching.\n * - **Replayable** — every transition is a verb returning new state + Cmds.\n * `nextCursor` / `onPage` are pure config functions applied at the verb\n * boundary; the Cmds they yield are plain data. `replay` reconstructs the\n * whole walk exactly.\n *\n * ## Where the clock / RNG live\n *\n * Inside the verbs: nowhere. `at` arrives on `start` / `resume`, on the settled\n * Msg `pageOk` / `pageErr` read (stamped by the engine), and on the timer Msg\n * `onTimer` reads, and is threaded straight into the underlying resilient-call\n * gate (so a rate-limited or retried page measures backoff from that `at`). The\n * jitter RNG is injected at construction. The knob ships no I/O: the page\n * fetch is resilient-call's `Cmd.define`d run Cmd, and its handler is yours.\n *\n * ## The fixed fetch key\n *\n * A walk fetches one page at a time, so the resilient-call layer tracks exactly\n * one logical call under the constant key `PAGE_KEY`. The cursor being fetched\n * is the resilient call's `input`, so a post-eviction resume re-issues the same\n * page request. (`resilient-call` is keyed to support N concurrent calls; a walk\n * deliberately uses a single key — the paginator is the sequencer.)\n *\n * ## Typical wiring\n *\n * const walk = createPaginatedWalk<PageToken, ApiPage>({\n * firstPage: null, // the API's \"page one\" sentinel\n * nextCursor: (page) => page.nextToken ?? null,\n * onPage: (page) => [{ type: \"index_rows\", rows: page.items }],\n * rateLimit: { capacity: 10, refillPerSec: 5 },\n * retry: defaultRetryPolicy,\n * });\n *\n * // in the machine:\n * cmds: [walk.fetch],\n * init: () => [{ walk: walk.init() }, []],\n * update: {\n * start: (s, m) => lift(s, walk.start(s.walk, m.at)),\n * resilient_run_ok: (s, m) => lift(s, walk.pageOk(s.walk, m)),\n * resilient_run_err: (s, m) => lift(s, walk.pageErr(s.walk, m)),\n * deadline_exceeded: (s, m) => lift(s, walk.onTimer(s.walk, m)),\n * drained: (s, m) => lift(s, walk.drain(s.walk, m.n)),\n * resume: (s, m) => lift(s, walk.resume(s.walk, m.at)),\n * },\n * subs: [{ type: \"timer\", deps: (s) => walk.timer(s.walk) }],\n *\n * // and where it runs — the page fetch is the handler you write:\n * run(machine, {\n * interpret: {\n * resilient_run: async (cmd, { ok, err }) => {\n * try { return ok(await api.fetchPage(cmd.input)); }\n * catch (cause) { return err({ _tag: \"port_rejected\", cause }); }\n * },\n * },\n * });\n */\n\nimport type { Cmd } from \"../../../index\";\nimport type { RetryPolicy } from \"../../../retry-backoff\";\nimport type { DeadlineSub } from \"../../resilience/deadline\";\nimport {\n type CircuitConfig,\n createResilientCall,\n type DeadlineConfig,\n type FailMsg,\n type RateLimitConfig,\n type ResilientState,\n type ResilientTimerMsg,\n type RunCmd,\n type SucceedMsg,\n} from \"../../resilience/resilient-call\";\nimport {\n drain as drainWalk,\n initPaginator,\n isDone,\n type PaginatorPolicy,\n type PaginatorState,\n recordPage,\n resume as resumeWalk,\n start as startWalk,\n} from \"../paginator\";\n\n// ===========================================================================\n// Config — the knob. `firstPage` / `nextCursor` / `onPage` describe the walk;\n// the resilience bricks are inherited from resilient-call (every one optional —\n// omit a brick, omit its gate).\n// ===========================================================================\n\n/**\n * The paginated-walk knob. Generic in `Cursor` (the opaque page handle the\n * upstream API hands back — offset, page token, \"next\" URL, …) and `Page` (the\n * shape your fetch port resolves with).\n *\n * `nextCursor` and `onPage` are PURE config functions applied at the verb\n * boundary, never stored in the slice or in a Cmd (invariant 3 — Cmds are\n * plain data, not closures). `nextCursor(page)` extracts the API's next-page\n * handle (or `null` at the end); `onPage(page)` yields the Cmds the consumer\n * wants emitted for each successfully fetched page (index rows, write to R2,\n * dispatch a downstream Msg — whatever; an empty array is fine).\n *\n * The resilience bricks (`retry` / `circuit` / `rateLimit` / `deadline`) are\n * the SAME optional knobs `resilient-call` exposes — paginated-walk extends it.\n * `rateLimit` is the brick that keeps the walk from 429-ing the upstream.\n */\nexport interface PaginatedWalkConfig<Cursor, Page, EmittedCmd extends Cmd> {\n /**\n * The cursor the walk fetches first. For an offset API this is typically `0`;\n * for a token API, whatever sentinel the API treats as \"page one\" (often\n * `null` or `\"\"`). Threaded into `paginator`'s `firstCursor`.\n */\n readonly firstPage: Cursor;\n /**\n * Extract the next cursor from a just-fetched page. Return a `Cursor` to keep\n * walking, or `null` when the API signalled the end (the walk finishes). PURE\n * + consumer-specific (only the consumer knows the API's pagination shape).\n */\n readonly nextCursor: (page: Page) => Cursor | null;\n /**\n * The Cmds to emit for each successfully fetched page — the consumer's work\n * per page (index, persist, fan out, …). Returns plain-data Cmds; `[]` is a\n * valid \"I process the page synchronously elsewhere\" answer. PURE.\n */\n readonly onPage: (page: Page) => readonly EmittedCmd[];\n /**\n * How many items a page contributes to the paginator's backpressure gauge\n * (`seen`). Defaults to `1` per page (count pages, not items) when omitted; a\n * consumer that wants per-item backpressure returns `page.items.length`. PURE.\n */\n readonly pageSize?: (page: Page) => number;\n /**\n * Backpressure threshold handed to the paginator. `seen >= highWaterMark`\n * parks the walk in `paused` instead of fetching the next page. Non-positive\n * (the default `0`) disables backpressure — the walk runs flat out until the\n * API exhausts. See `../paginator`'s `highWaterMark` docs.\n */\n readonly highWaterMark?: number;\n\n // --- resilience bricks, inherited from resilient-call (all optional) ---\n /** Exponential-backoff retry policy for a transient page-fetch failure. */\n readonly retry?: RetryPolicy;\n /** Circuit breaker around the page fetch (one upstream → one breaker). */\n readonly circuit?: CircuitConfig;\n /** Token-bucket rate limit — the \"don't 429 the upstream\" knob. */\n readonly rateLimit?: RateLimitConfig;\n /** Overall wall-clock deadline per individual page fetch. */\n readonly deadline?: DeadlineConfig;\n}\n\n// ===========================================================================\n// Slice — the Model field this knob owns. The paginator walk state + the\n// resilient-call slice for the page fetch. Both are flat plain data.\n// ===========================================================================\n\n/**\n * The slice. `walk` is the cursor/phase/counters from `../paginator`;\n * `resilience` is the `../resilient-call` slice that gates the page fetch.\n * Every field is JSON-serializable, so the whole walk survives a reload.\n *\n * The two move in lockstep: `walk` decides WHICH cursor to fetch next, while\n * `resilience` decides HOW that fetch is attempted (gated, retried, backed\n * off). `pageOk` advances `walk`; `pageErr` defers to `resilience` and leaves\n * `walk` parked on the same cursor until the page truly settles.\n */\nexport interface PaginatedWalkState<Cursor, Page> {\n readonly walk: PaginatorState<Cursor>;\n readonly resilience: ResilientState<Cursor, Page>;\n}\n\n// ===========================================================================\n// Cmds + Msgs the knob speaks.\n// ===========================================================================\n\n/**\n * The page-fetch effect this knob emits: the inherited `resilient_run` Cmd from\n * resilient-call, whose `input` is the `Cursor` to fetch and whose `key` is the\n * fixed `PAGE_KEY`. It is `Cmd.define`d; the handler you write for it fetches\n * one page and returns `ok(page)` or `err({ _tag: \"port_rejected\", … })`.\n */\nexport type FetchPageCmd<Cursor> = RunCmd<Cursor>;\n\n/** The page-settled Msgs the engine mints from that handler's outcome. */\nexport type PageOkMsg<Page> = SucceedMsg<Page>;\n/** The Msg the engine mints when the page-fetch handler fails. */\nexport type PageErrMsg = FailMsg;\n\n/** The retry / deadline timer Msg — inherited from resilient-call. */\nexport type PaginatedWalkTimerMsg = ResilientTimerMsg;\n\n// ===========================================================================\n// The fixed key. A walk fetches one page at a time → exactly one logical\n// resilient call. The paginator is the sequencer; resilient-call's keying is\n// pinned to this single key.\n// ===========================================================================\n\n/** The single resilient-call key every page fetch runs under. */\nexport const PAGE_KEY = \"page\";\n\n// ===========================================================================\n// The knob factory.\n// ===========================================================================\n\n/**\n * Build a paginated-walk knob from `config`. `rng` is injected for the\n * underlying retry jitter — pass a fixed `() => 0` in tests to pin backoff;\n * defaults to `Math.random` (read at the verb boundary inside resilient-call,\n * never in a `paginated-walk` verb). Inherited straight from resilient-call.\n *\n * Returns plain functions: `init()`, the verbs `start` / `pageOk` / `pageErr`\n * / `onTimer`, `deadlines(state)` / `timer(state)`, and the page-fetch Cmd def\n * (`fetch`) to list in the machine's `cmds`. `Cursor` is\n * the page handle, `Page` the fetch result, `EmittedCmd` the consumer's\n * per-page Cmds plus the inherited `FetchPageCmd`.\n */\nexport function createPaginatedWalk<Cursor, Page, EmittedCmd extends Cmd = Cmd>(\n config: PaginatedWalkConfig<Cursor, Page, EmittedCmd>,\n rng: () => number = Math.random,\n) {\n // The page fetch is a resilient call keyed by Cursor input → Page result.\n // We feed it only the resilience bricks; the walk-loop knobs are ours.\n const rc = createResilientCall<Cursor, Page>(\n {\n retry: config.retry,\n circuit: config.circuit,\n rateLimit: config.rateLimit,\n deadline: config.deadline,\n },\n rng,\n );\n\n // The paginator policy: our firstPage is the paginator's firstCursor; the\n // high-water mark gates backpressure (0 / omitted → unbounded).\n const paginatorPolicy: PaginatorPolicy<Cursor> = {\n firstCursor: config.firstPage,\n highWaterMark: config.highWaterMark ?? 0,\n };\n\n // The combined Cmd type the verbs can emit: the inherited page-fetch effect\n // plus whatever `onPage` yields.\n type OutCmd = FetchPageCmd<Cursor> | EmittedCmd;\n\n /** Replace the resilience slice, leaving `walk` untouched. */\n function withSlice(\n s: PaginatedWalkState<Cursor, Page>,\n resilience: ResilientState<Cursor, Page>,\n ): PaginatedWalkState<Cursor, Page> {\n return { ...s, resilience };\n }\n\n /** The starting slice: an idle paginator + a fresh resilient-call slice. */\n function init(): PaginatedWalkState<Cursor, Page> {\n return {\n walk: initPaginator<Cursor>(),\n resilience: rc.init(),\n };\n }\n\n /**\n * Issue a resilient page fetch for `cursor` at `at`. The cursor is the\n * resilient call's `input` (so a retry / resume re-fetches the same page) and\n * `PAGE_KEY` is the fixed key. Returns the advanced resilience slice + the\n * `resilient_run` Cmd (or none, if the gate cached / fast-failed / backed off).\n * PURE — `at` is the only clock. Shared by `start` and `pageOk`'s advance.\n */\n function fetch(\n s: PaginatedWalkState<Cursor, Page>,\n cursor: Cursor,\n at: number,\n ): readonly [\n PaginatedWalkState<Cursor, Page>,\n readonly FetchPageCmd<Cursor>[],\n ] {\n const [resilience, cmds] = rc.attempt(s.resilience, PAGE_KEY, cursor, at);\n return [withSlice(s, resilience), cmds];\n }\n\n /**\n * Issue the page fetch for a freshly-armed paginator transition, else a pure\n * no-op. `walk` is the result of a paginator verb (`startWalk` / `resumeWalk`)\n * applied to `s.walk`; this states the arm-and-fetch contract ONCE for the two\n * verbs that share it (`start`, `resume`).\n *\n * A paginator verb is a pure no-op on any phase it does not act on — it returns\n * the SAME state object. Reference identity (not phase) is the honest \"did the\n * verb arm a fresh fetch?\" check: a walk already `fetching` would also satisfy\n * `phase === \"fetching\"` yet must NOT re-issue a fetch (page-one skip /\n * double-fetch). So we proceed ONLY when the verb produced a fresh state. The\n * `phase === \"fetching\"` narrow that follows is therefore always true here\n * (both verbs only ever produce a `fetching` arm), and also narrows `.cursor`\n * for the type checker. PURE — `at` threads into the fetch gate.\n */\n function armAndFetch(\n s: PaginatedWalkState<Cursor, Page>,\n walk: PaginatorState<Cursor>,\n at: number,\n ): readonly [PaginatedWalkState<Cursor, Page>, readonly OutCmd[]] {\n if (walk === s.walk || walk.phase !== \"fetching\") {\n return [s, []];\n }\n return fetch({ ...s, walk }, walk.cursor, at);\n }\n\n // === Verb: start =========================================================\n\n /**\n * Begin the walk: arm the paginator's first cursor and issue the first page\n * fetch (gated through resilience). On any non-`idle` paginator phase this is\n * a no-op — re-starting a walk in flight would skip back to page one and\n * double-count, so a stray `start` after launch is absorbed (the paginator's\n * own `start` guard). PURE — `at` threads into the fetch gate.\n */\n function start(\n s: PaginatedWalkState<Cursor, Page>,\n at: number,\n ): readonly [PaginatedWalkState<Cursor, Page>, readonly OutCmd[]] {\n // `startWalk` is a pure no-op on any non-`idle` phase (same reference); a\n // fresh `fetching(firstCursor)` arm → issue the first page fetch.\n return armAndFetch(s, startWalk(s.walk, paginatorPolicy), at);\n }\n\n // === Verb: pageOk ========================================================\n\n /**\n * Record a successfully fetched page (the engine-minted `msg.value`) and\n * decide what comes next. PURE — `msg.at` is the cache / next-fetch clock.\n *\n * 1. Settle the resilient call OK (closes the breaker, fills the cache,\n * resets the page-fetch retry counter) — inherited from resilient-call.\n * 2. Fold the page through the paginator: add `pageSize(page)` to `seen`,\n * bump `pages`, and branch on `nextCursor(page)`:\n * - `null` → the API is exhausted → paginator goes `done`.\n * - a cursor → advance, then either fetch it (backpressure room) or\n * park in `paused` (high-water mark reached).\n * 3. Emit the consumer's `onPage(page)` Cmds either way, PLUS the next\n * page-fetch effect when the paginator stays `fetching`.\n *\n * A `pageOk` that arrives when the paginator is not `fetching` (a late\n * duplicate, a double-dispatch) is absorbed by `recordPage` — the cursor does\n * not advance and `seen` is not double-counted; only the resilient settle +\n * `onPage` Cmds happen. The walk is a coordination aid, not a correctness\n * gate.\n */\n function pageOk(\n s: PaginatedWalkState<Cursor, Page>,\n msg: PageOkMsg<Page>,\n ): readonly [PaginatedWalkState<Cursor, Page>, readonly OutCmd[]] {\n const { value: page, at } = msg;\n // 1) Settle the underlying resilient call as a success.\n const { call: resilience } = rc.settle(s.resilience, msg);\n\n // 2) Advance the paginator with the page's contribution + the next cursor.\n const count = config.pageSize ? config.pageSize(page) : 1;\n const next = config.nextCursor(page);\n const walk = recordPage(s.walk, count, next, paginatorPolicy);\n\n const advanced: PaginatedWalkState<Cursor, Page> = { walk, resilience };\n\n // 3) The consumer's per-page work, always emitted on a successful page.\n const pageCmds: readonly EmittedCmd[] = config.onPage(page);\n\n // If the paginator stayed `fetching`, issue the next page fetch (gated).\n if (walk.phase === \"fetching\") {\n const [withFetch, fetchCmds] = fetch(advanced, walk.cursor, at);\n return [withFetch, [...pageCmds, ...fetchCmds]];\n }\n\n // `done` (exhausted) or `paused` (backpressure) → no further fetch now.\n return [advanced, pageCmds];\n }\n\n // === Verb: pageErr =======================================================\n\n /**\n * Record a failed page fetch and back off via resilience. PURE — `at` stamps\n * the breaker trip + the retry-delay base.\n *\n * Defers to the resilient-call `settle` verb: it trips the breaker and either\n * schedules a retry (paginator stays parked on the SAME cursor — no advance)\n * or settles the resilient call `failed` once retries are exhausted. The\n * paginator is deliberately untouched: a failed fetch must NOT advance the\n * cursor or skip a page. When the retry timer later fires, `onTimer` re-issues\n * the same page fetch.\n *\n * GUARDED by the paginator phase, exactly as `pageOk` is guarded by\n * `recordPage`'s `fetching`-only check. A `pageErr` only makes sense while a\n * page fetch is outstanding (`walk.phase === \"fetching\"`). A stray `pageErr`\n * that arrives after the walk has settled — `done` (exhausted), `paused`\n * (backpressure), or `idle` (not started) — has NO outstanding fetch to fail.\n * Without this guard it would still call `rc.settle`, which trips the SHARED\n * circuit breaker (dinging a healthy upstream) and overwrites the settled\n * `PAGE_KEY` resilient slot with `failed` (clobbering the succeeded result a\n * resume would otherwise observe). So a stray `pageErr` is absorbed as a pure\n * no-op — identity preserved — matching `pageOk`'s \"the walk is a coordination\n * aid, not a correctness gate\" stance.\n */\n function pageErr(\n s: PaginatedWalkState<Cursor, Page>,\n msg: PageErrMsg,\n ): readonly [PaginatedWalkState<Cursor, Page>, readonly OutCmd[]] {\n // Only a `fetching` paginator has an outstanding page fetch to fail. On any\n // other phase the fail would corrupt shared resilience state for a fetch\n // that is not in flight — absorb it as a pure no-op.\n if (s.walk.phase !== \"fetching\") {\n return [s, []];\n }\n const { call: resilience, cmds } = rc.settle(s.resilience, msg);\n return [withSlice(s, resilience), cmds];\n }\n\n // === Verb: onTimer =======================================================\n\n /**\n * A retry / deadline timer fired. Defers to resilient-call's `onTimer`: a\n * retry timer re-runs the gate for the page-fetch's remembered cursor (re-\n * issuing the SAME page); a deadline timer settles the resilient call failed.\n * The paginator stays parked on its cursor throughout — only `pageOk` advances\n * it. A stale fire is a no-op (inherited). PURE.\n *\n * GUARDED by the paginator phase, for the same reason as `pageErr`. A timer is\n * only meaningful while a page fetch is outstanding (`walk.phase ===\n * \"fetching\"`). A stray timer that fires after the walk has settled (`done` /\n * `paused` / `idle`) would otherwise re-enter `rc.onTimer` — re-issuing a fetch\n * the paginator no longer wants (a deadline timer could even overwrite the\n * settled `PAGE_KEY` slot with a deadline `failed`). On any non-`fetching`\n * phase the timer is absorbed as a pure no-op.\n */\n function onTimer(\n s: PaginatedWalkState<Cursor, Page>,\n msg: PaginatedWalkTimerMsg,\n ): readonly [PaginatedWalkState<Cursor, Page>, readonly OutCmd[]] {\n if (s.walk.phase !== \"fetching\") {\n return [s, []];\n }\n const [resilience, cmds] = rc.onTimer(s.resilience, msg);\n return [withSlice(s, resilience), cmds];\n }\n\n // === Verb: drain =========================================================\n\n /**\n * Acknowledge that the consumer finished processing `n` items, lowering the\n * paginator's backpressure gauge (`seen`). PURE — no clock. Delegates to\n * `paginator.drain`: subtracts `n` (floored at 0), leaves the phase untouched.\n *\n * The OTHER half of the backpressure valve `highWaterMark` opens: `recordPage`\n * parks the walk in `paused` once `seen >= highWaterMark`, and `drain` is how a\n * consumer lowers `seen` back below the mark so `resume` can re-open the fetch.\n * Without it `highWaterMark` would be a one-way valve — a walk could pause but\n * never continue. Emits no Cmds: draining only frees headroom; `resume` is the\n * separate, explicit \"continue now\" decision.\n */\n function drain(\n s: PaginatedWalkState<Cursor, Page>,\n n: number,\n ): readonly [PaginatedWalkState<Cursor, Page>, readonly OutCmd[]] {\n const walk = drainWalk(s.walk, n);\n if (walk === s.walk) {\n // Pure no-op identity (n <= 0, or seen already at floor).\n return [s, []];\n }\n return [{ ...s, walk }, []];\n }\n\n // === Verb: resume ========================================================\n\n /**\n * Re-open the backpressure valve after a `drain`: if the walk is `paused` and\n * `seen` has dropped below `highWaterMark`, re-arm the parked cursor and issue\n * its page fetch (gated through resilience). PURE — `at` threads into the fetch\n * gate. Delegates the phase decision to `paginator.resume`:\n *\n * - `paused` AND `seen < highWaterMark` → `fetching(cursor)` → emit the fetch.\n * - `paused` but still over the mark → no-op (the valve stays shut until a\n * further `drain` frees real headroom).\n * - any other phase → no-op (nothing to resume).\n *\n * Together with `drain` this completes the valve: `recordPage` shuts it\n * (`paused`), `drain` lowers the gauge, `resume` re-opens it and fires the next\n * page fetch — the same `fetch` helper `start` / `pageOk` use, so a resumed\n * fetch is gated identically (cache / circuit / rate-limit / retry).\n */\n function resume(\n s: PaginatedWalkState<Cursor, Page>,\n at: number,\n ): readonly [PaginatedWalkState<Cursor, Page>, readonly OutCmd[]] {\n // `resumeWalk` is a pure no-op (same reference) on any phase but `paused`, or\n // when `seen` is still at/over the mark. Only a fresh `fetching` arm means\n // the valve actually re-opened — issue the page fetch only then.\n return armAndFetch(s, resumeWalk(s.walk, paginatorPolicy), at);\n }\n\n // === Derived predicates ==================================================\n\n /**\n * Whether the walk has finished — the API returned a null next cursor and the\n * paginator is `done`. PURE, read-only. Lets a consumer's reducer fire a\n * \"walk complete\" Cmd (`if (walk.isDone(s.walk)) …`) without re-checking the\n * paginator phase by hand.\n */\n function isComplete(s: PaginatedWalkState<Cursor, Page>): boolean {\n return isDone(s.walk);\n }\n\n /**\n * The terminal page-fetch failure that stranded the walk, or `undefined` if no\n * page has terminally failed. PURE, read-only. Errors are data: a page that\n * exhausts its retries (or trips the deadline) settles the `PAGE_KEY` resilient\n * slot to `failed` while the paginator stays parked on its cursor — the walk is\n * stuck and will never advance on its own. Without a way to read that phase the\n * failure is unobservable: the walk simply stops emitting fetches with no\n * signal. `failure(s)` surfaces the settled error (the same plain-data sentinel\n * resilient-call records) so a consumer can fire a \"walk dead\" Cmd, alert, or\n * re-`start` a fresh walk.\n */\n function failure(s: PaginatedWalkState<Cursor, Page>): unknown {\n const call = s.resilience.calls[PAGE_KEY];\n return call?.phase === \"failed\" ? call.error : undefined;\n }\n\n /**\n * Whether the walk is STUCK: a page fetch has terminally `failed` yet the\n * paginator is still parked on a cursor (not `done`), so no further fetch will\n * ever be issued without intervention. PURE, read-only.\n *\n * This is the dead-walk predicate the consumer polls (`if (walk.isStuck(s)) …`)\n * to distinguish a healthy finish (`isComplete`) from a silent death. A walk is\n * stuck precisely when the resilient slot settled `failed` AND the paginator\n * has NOT reached `done` — a terminal failure on the final page that also\n * finished the walk is `isComplete`, not stuck. Pairs with `failure(s)`, which\n * hands back the error that stuck it.\n */\n function isStuck(s: PaginatedWalkState<Cursor, Page>): boolean {\n return s.resilience.calls[PAGE_KEY]?.phase === \"failed\" && !isDone(s.walk);\n }\n\n // === Timers ==============================================================\n\n /**\n * The page fetch's deadlines — exactly resilient-call's: a retry timer while\n * the fetch is `waiting_retry`, and (with the `deadline` brick) a per-fetch\n * deadline timer while it is active.\n */\n function deadlines(\n s: PaginatedWalkState<Cursor, Page>,\n ): readonly DeadlineSub[] {\n return rc.deadlines(s.resilience);\n }\n\n /**\n * The built-in `timer` Sub's deps: resilient-call's `timer` over the fetch's\n * slice. Declare `{ type: \"timer\", deps: (s) => walk.timer(s.walk) }`.\n */\n function timer(s: PaginatedWalkState<Cursor, Page>) {\n return rc.timer(s.resilience);\n }\n\n return {\n /** The page-fetch Cmd def — list it in the machine's `cmds`. */\n fetch: rc.run,\n init,\n start,\n pageOk,\n pageErr,\n onTimer,\n drain,\n resume,\n isComplete,\n failure,\n isStuck,\n deadlines,\n timer,\n };\n}\n\n/**\n * Lift a knob result `[slice, cmds]` into a host `[State, cmds]` where the slice\n * lives at `state.walk`. A convenience for the common single-slice host;\n * consumers with a differently-named field spread by hand. Pure — a thin record\n * rebuild, no clock / RNG.\n */\nexport function liftWalk<\n S extends { walk: PaginatedWalkState<Cursor, Page> },\n Cursor,\n Page,\n C extends Cmd,\n>(\n state: S,\n [slice, cmds]: readonly [PaginatedWalkState<Cursor, Page>, readonly C[]],\n): readonly [S, readonly C[]] {\n return [{ ...state, walk: slice }, cmds];\n}\n"]}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
// src/internal/engine/installed-state.ts
|
|
2
|
+
var installedState = /* @__PURE__ */ Symbol(
|
|
3
|
+
"demlik-tea.installedState"
|
|
4
|
+
);
|
|
5
|
+
function readInstalledState(handle) {
|
|
6
|
+
return handle[installedState]?.();
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export { installedState, readInstalledState };
|
|
10
|
+
//# sourceMappingURL=chunk-DEAPNMKO.js.map
|
|
11
|
+
//# sourceMappingURL=chunk-DEAPNMKO.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/internal/engine/installed-state.ts"],"names":[],"mappings":";AAYO,IAAM,cAAA,mBAAgC,MAAA;AAAA,EAC3C;AACF;AAaO,SAAS,mBAAsB,MAAA,EAA+B;AACnE,EAAA,OAAQ,MAAA,CAA0C,cAAc,CAAA,IAAI;AACtE","file":"chunk-DEAPNMKO.js","sourcesContent":["/**\n * The one read a view needs before `ready`: the State a `subscribe` listener was\n * last told about. `ready` waits for boot's Cmds, so a store-backed machine whose\n * `init` starts work has told its listeners a State the booted handle cannot\n * serve yet (#695).\n *\n * `RunHandle` still has no `getState`: a caller reading State before boot stays a\n * compile error, and the export map does not change. Symbol-keyed so it reaches\n * no export, and enumerable so it survives the spread a wrapper does over the\n * handle, as `liveWork` is. Its own file so `/react` reads it without importing\n * an engine.\n */\nexport const installedState: unique symbol = Symbol(\n \"demlik-tea.installedState\",\n);\n\n/** A run handle a view can read the installed State of. */\nexport interface InstalledStateRead<S> {\n /** `undefined` until the first State is past its save and listeners heard it. */\n readonly [installedState]: () => S | undefined;\n}\n\n/**\n * The State `handle` last told its listeners about, or `undefined` when it has\n * told them none yet or carries no such read. An engine typed only to `RunHandle`\n * carries none, and a view on it waits for `ready`.\n */\nexport function readInstalledState<S>(handle: object): S | undefined {\n return (handle as Partial<InstalledStateRead<S>>)[installedState]?.();\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { bindMachine } from './chunk-
|
|
2
|
-
import { cmdContractOver, followUps, subEntriesOf, desiredSub } from './chunk-
|
|
1
|
+
import { bindMachine } from './chunk-RMBZ7YH7.js';
|
|
2
|
+
import { cmdContractOver, followUps, subEntriesOf, desiredSub } from './chunk-A3QPMX5M.js';
|
|
3
3
|
|
|
4
4
|
// src/testing/drive-loop.ts
|
|
5
5
|
var DEFAULT_MAX_ROUNDS = 100;
|
|
@@ -115,5 +115,5 @@ function desiredSubs(machine, state) {
|
|
|
115
115
|
}
|
|
116
116
|
|
|
117
117
|
export { DEFAULT_MAX_ROUNDS, DriveNoHandlerError, DriveRoundsExceededError, annotateTrace, desiredSubs, driveContractOf, driveLoop, driveTraceOf };
|
|
118
|
-
//# sourceMappingURL=chunk-
|
|
119
|
-
//# sourceMappingURL=chunk-
|
|
118
|
+
//# sourceMappingURL=chunk-ETRNSJCR.js.map
|
|
119
|
+
//# sourceMappingURL=chunk-ETRNSJCR.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/testing/drive-loop.ts"],"names":[],"mappings":";;;;AAmDO,IAAM,kBAAA,GAAqB;AAqE3B,IAAM,wBAAA,GAAN,cAA6C,KAAA,CAAM;AAAA,EAGxD,WAAA,CAEkB,SAAA,EAEA,MAAA,EAEA,KAAA,EAChB;AACA,IAAA,KAAA;AAAA,MACE,CAAA,yCAAA,EAA4C,SAAS,CAAA,8DAAA,EACP,MAAM,CAAA,qBAAA,EACxC,KAAA,CAAM,MAAM,CAAA,KAAA,EAAQ,KAAA,CAAM,MAAA,KAAW,CAAA,GAAI,GAAA,GAAM,KAAK,CAAA,oCAAA;AAAA,KAElE;AAXgB,IAAA,IAAA,CAAA,SAAA,GAAA,SAAA;AAEA,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AAEA,IAAA,IAAA,CAAA,KAAA,GAAA,KAAA;AAAA,EAQlB;AAAA,EAZkB,SAAA;AAAA,EAEA,MAAA;AAAA,EAEA,KAAA;AAAA,EARA,IAAA,GAAO,0BAAA;AAAA,EAChB,IAAA,GAAO,0BAAA;AAgBlB;AAQO,IAAM,mBAAA,GAAN,cAAwC,KAAA,CAAM;AAAA,EAGnD,WAAA,CAEkB,SAEA,KAAA,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AA,EAC3C;AACA,EAAA,OAAO,OAAA;AACT","file":"chunk-BFSZ4L6Y.js","sourcesContent":["// ---------------------------------------------------------------------------\n// The round loop both `drive`s run — `@demlik/tea/testing/promise` and\n// `@demlik/tea/testing/effect` — said once, so the two cannot drift.\n//\n// `bindMachine` hands back the Cmds a fold emitted and stops there; performing\n// them is the caller's. So every consumer test that exercises a Cmd-emitting\n// machine hand-writes the same fixture: step the Msg, await the real interpret\n// handler over each emitted Cmd, feed the settle Msg back, repeat until quiet,\n// with a hand-picked guard bound in the loop header. `drive` is that fixture as\n// one call, and this file is its loop. It composes `bindMachine`'s synchronous\n// 2-arg `step` and adds NO second reducer path.\n//\n// What differs per engine is only how one Cmd is performed and whether Subs\n// run, so an engine hands this loop a `cellFor` lookup and, optionally, a\n// `subs` driver. Everything else — the rounds, the trace, the `maxRounds`\n// bound, the `Cmd.define` edge and its dispatch check (#304) — is here.\n//\n// **It returns the history, not just the endpoint.** `{ state, trace }`, where\n// `trace` is every Msg folded and every Cmd dispatched in order, lets a test\n// assert on the SEQUENCE as well as the settled state, and the same trace's\n// Msgs replayed through `replay` from the same initial state reproduce the\n// returned state exactly.\n//\n// **Exhausting `maxRounds` fails the drive.** A driver that quietly returns a\n// half-driven state lets a test assert green on a machine that never settled.\n//\n// Strengthens invariant 9 (the testing surface is named and small).\n// ---------------------------------------------------------------------------\n\nimport {\n type AnyCmdDef,\n type Cmd,\n type CmdContract,\n cmdContractOver,\n desiredSub,\n followUps,\n type Machine,\n type Sub,\n subEntriesOf,\n} from \"../pure/core\";\nimport type { CtxArg } from \"../runtime-types\";\nimport { bindMachine } from \"./bind-machine\";\n\n/**\n * The default round bound when `opts.maxRounds` is omitted: **100**.\n *\n * A round is one drain of the pending Msgs plus one drain of the Cmds those\n * folds emitted, so a settling machine costs a handful; 100 is loose enough\n * that a legitimate retry ladder finishes inside it and tight enough that a\n * genuine cycle stops rather than hangs.\n */\nexport const DEFAULT_MAX_ROUNDS = 100;\n\n/**\n * One entry of a driven run's history, in dispatch order.\n *\n * - `msg` — a Msg folded through the machine's reducer. The seed Msg is the\n * first entry of every trace; every later one is a settle Msg a handler\n * returned (or fired through its injected `dispatch`), or a Msg a running\n * Sub emitted.\n * - `cmd` — a Cmd handed to an interpret handler. It is recorded BEFORE the\n * handler runs, so a trace recovered from a failed handler names the Cmd\n * that failed as its last entry.\n */\nexport type DriveTraceEntry<M, C> =\n | { readonly kind: \"msg\"; readonly msg: M }\n | { readonly kind: \"cmd\"; readonly cmd: C };\n\n/** What a settled `drive` hands back. */\nexport interface DriveResult<S, M, C> {\n /** The state after the machine went quiet — no Msg pending, no Cmd unperformed. */\n readonly state: S;\n /**\n * Every Msg folded and every Cmd dispatched, in order. Filtering it to its\n * `msg` entries and replaying those through `replay` from the same initial\n * state reproduces {@link DriveResult.state}.\n */\n readonly trace: readonly DriveTraceEntry<M, C>[];\n}\n\n/**\n * `drive`'s `ctx` field. `CtxArg` widened by exactly one case: a machine\n * declaring `ctx: undefined` in its `types` block — the pure shape every\n * how-to on this package writes — may omit it too. `CtxArg` alone keeps `ctx`\n * REQUIRED there, because `{}` is not assignable to `undefined`, which would\n * make the common pure call site spell `{ ctx: undefined }` to say nothing.\n * A machine whose `Ctx` carries a field a handler reads still requires it.\n */\nexport type DriveCtxArg<Ctx> = [undefined] extends [Ctx]\n ? { readonly ctx?: Ctx }\n : CtxArg<Ctx>;\n\n/**\n * The options both `drive`s take. `ctx` is conditionally optional (see\n * {@link DriveCtxArg}).\n */\nexport type DriveOptions<Ctx> = DriveCtxArg<Ctx> & {\n /**\n * The round bound. Exceeding it fails the drive with\n * {@link DriveRoundsExceededError}; `drive` never returns a half-driven\n * state. Defaults to {@link DEFAULT_MAX_ROUNDS} (100).\n */\n readonly maxRounds?: number;\n /**\n * The clock that stamps `at` on a `Cmd.define`d Cmd's minted `_ok` / `_err`\n * Msg — the one `run` takes. Defaults to `Date.now`; pin it for a test that\n * asserts on `at`.\n */\n readonly clock?: () => number;\n};\n\n/**\n * Raised when a driven machine is still emitting work after `maxRounds` rounds.\n * Follows the tea error dialect (`override readonly name`) and carries a `_tag`\n * discriminant, so a test branches on it by `instanceof` or on the tag.\n *\n * It carries the round count it stopped at and the PARTIAL trace up to that\n * point, which is what a test needs to see the cycle — the bound alone says\n * only that one exists.\n */\nexport class DriveRoundsExceededError<M, C> extends Error {\n override readonly name = \"DriveRoundsExceededError\";\n readonly _tag = \"DriveRoundsExceededError\" as const;\n constructor(\n /** The bound that was exceeded. */\n public readonly maxRounds: number,\n /** The round the driver stopped at — always `maxRounds + 1`. */\n public readonly rounds: number,\n /** Every Msg folded and Cmd dispatched before the driver gave up. */\n public readonly trace: readonly DriveTraceEntry<M, C>[],\n ) {\n super(\n `@demlik/tea: drive did not settle within ${maxRounds} round(s) — the ` +\n `machine was still emitting work at round ${rounds}. The partial ` +\n `trace (${trace.length} entr${trace.length === 1 ? \"y\" : \"ies\"}) is ` +\n `on the error's \\`trace\\` field.`,\n );\n }\n}\n\n/**\n * Raised when a Cmd reaches `drive` with no handler for its `type` in the\n * handler record. The record's mapped type makes that a compile error at a\n * well-typed call site; this is the runtime arm for a handler record assembled\n * dynamically or cast.\n */\nexport class DriveNoHandlerError<M, C> extends Error {\n override readonly name = \"DriveNoHandlerError\";\n readonly _tag = \"DriveNoHandlerError\" as const;\n constructor(\n /** The Cmd `type` nothing in the handler record answered. */\n public readonly cmdType: string,\n /** Every Msg folded and Cmd dispatched before the miss. */\n public readonly trace: readonly DriveTraceEntry<M, C>[],\n ) {\n super(\n `@demlik/tea: drive found no interpret handler for Cmd type ` +\n `\"${cmdType}\" — the handlers record must answer every Cmd the ` +\n `machine emits.`,\n );\n }\n}\n\n/** The key `drive` hangs a partial trace off a failure under. */\nconst TRACE_KEY = \"driveTrace\";\n\n/**\n * Hang `trace` off `err` on a non-enumerable property, so {@link driveTraceOf}\n * reads it back without changing how the error prints or serializes. A\n * non-object failure carries nothing.\n */\nexport function annotateTrace(err: unknown, trace: readonly unknown[]): void {\n if (typeof err !== \"object\" || err === null) return;\n Object.defineProperty(err, TRACE_KEY, {\n value: [...trace],\n enumerable: false,\n configurable: true,\n writable: true,\n });\n}\n\n/**\n * Read back the partial trace `drive` attached to an error a handler failed\n * with. Returns `undefined` for anything `drive` did not annotate.\n *\n * A failing handler's error leaves `drive` UNSWALLOWED — same value, same\n * `instanceof`, same `_tag` — so a test that already branches on the handler's\n * own error type keeps doing so. The trace rides along on a non-enumerable\n * property so it is recoverable without changing how the error prints or\n * serializes.\n */\nexport function driveTraceOf<M, C>(\n err: unknown,\n): readonly DriveTraceEntry<M, C>[] | undefined {\n if (typeof err !== \"object\" || err === null) return undefined;\n const carried = (err as Record<string, unknown>)[TRACE_KEY];\n return Array.isArray(carried)\n ? (carried as readonly DriveTraceEntry<M, C>[])\n : undefined;\n}\n\n// === The loop ===\n\n/**\n * Perform one Cmd and resolve with the handler's raw return, before the\n * `Cmd.define` edge reads it. The `dispatch` it is handed is already checked\n * (#304).\n */\nexport type DriveCell<M, C> = (\n cmd: C,\n dispatch: (msg: M) => void,\n) => Promise<unknown>;\n\n/** The Subs a drive runs, as the loop sees them. */\nexport interface DriveSubs<S, M> {\n /**\n * Start every Sub `state` wants that is not running, and stop every running\n * one it no longer wants — the engine's reconcile, after each fold.\n */\n readonly reconcile: (state: S) => void;\n /**\n * Wait for the next Msgs a running Sub emits. Resolves with every Msg\n * buffered by then, or with `undefined` once no Sub is left running; rejects\n * when a Sub failed.\n */\n readonly next: () => Promise<readonly M[] | undefined>;\n /** Stop every Sub still running. */\n readonly close: () => Promise<void>;\n}\n\n/** What one engine hands the shared loop. */\nexport interface DriveEngine<S, M, C> {\n /**\n * The edge and dispatch check over the machine's `Cmd.define` list. The\n * engine builds it (see {@link driveContractOf}) so a handler that settles\n * through `cmdEdgeOf(ctx)` mints into the same record the check reads.\n */\n readonly contract: CmdContract;\n /** The cell that performs a Cmd of `type`, or `undefined` when none does. */\n readonly cellFor: (type: string) => DriveCell<M, C> | undefined;\n /** The Subs to run beside the Cmds; an engine that runs none omits it. */\n readonly subs?: DriveSubs<S, M>;\n}\n\n/** The contract both `drive`s hold a machine's Cmds to (ADR 0021). */\nexport function driveContractOf(\n machine: { readonly cmds?: readonly AnyCmdDef[] },\n clock: () => number,\n): CmdContract {\n return cmdContractOver(machine.cmds ?? [], clock);\n}\n\n/**\n * Drive `machine` from `initial` through `msg`, performing every emitted Cmd\n * through `engine.cellFor`, until the machine goes quiet.\n *\n * One round is: fold every pending Msg, then perform every Cmd those folds\n * emitted, in order. A Msg a cell returns or dispatches is pending for the next\n * round. When nothing is pending and Subs are running, the loop waits for the\n * next Msgs they emit; it settles once no Msg is pending, no Cmd is unperformed\n * and no Sub is left running.\n *\n * Every error that leaves the loop carries the partial trace (see\n * {@link driveTraceOf}).\n */\nexport async function driveLoop<\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 initial: S,\n msg: M,\n ctx: Ctx,\n maxRounds: number,\n engine: DriveEngine<S, M, C>,\n): Promise<DriveResult<S, M, C>> {\n const bound = bindMachine(machine, ctx);\n const { contract, cellFor, subs } = engine;\n\n const trace: DriveTraceEntry<M, C>[] = [];\n let state = initial;\n let pending: M[] = [msg];\n let round = 0;\n\n try {\n subs?.reconcile(state);\n while (pending.length > 0) {\n round += 1;\n if (round > maxRounds) {\n throw new DriveRoundsExceededError<M, C>(maxRounds, round, trace);\n }\n\n // Drain the round's Msgs first, THEN its Cmds. Swapping the buffer before\n // the fold is what keeps a settle Msg out of the round that produced it.\n const folding = pending;\n pending = [];\n const emitted: C[] = [];\n for (const next of folding) {\n trace.push({ kind: \"msg\", msg: next });\n const [advanced, cmds] = bound.step(state, next);\n state = advanced;\n emitted.push(...cmds);\n subs?.reconcile(state);\n }\n\n for (const cmd of emitted) {\n trace.push({ kind: \"cmd\", cmd });\n const cell = cellFor(cmd.type);\n if (cell === undefined) {\n throw new DriveNoHandlerError<M, C>(cmd.type, trace);\n }\n // The dispatch half of ADR 0021, as the engine applies it (#304): a\n // `Cmd.define`d handler may not send a `_ok` / `_err` it built itself.\n // That Msg is dropped, never folded, and the refusal fails the drive\n // once the cell settles, so a handler that catches it cannot hide it.\n let refused: { readonly error: unknown } | undefined;\n const dispatch = (fired: M): void => {\n try {\n contract.checkDispatch(cmd, fired);\n } catch (error) {\n refused ??= { error };\n return;\n }\n pending.push(fired);\n };\n const settled = contract.settle(cmd, await cell(cmd, dispatch));\n if (refused !== undefined) throw refused.error;\n // A returned list lands in order, as `run`'s loop enqueues it.\n pending.push(...followUps<M>(settled));\n }\n\n if (pending.length === 0 && subs !== undefined) {\n pending = [...((await subs.next()) ?? [])];\n }\n }\n } catch (err) {\n // Unswallowed: the failure's own value is what leaves the loop, so a\n // test's `instanceof` / `_tag` branch still lands.\n annotateTrace(err, trace);\n throw err;\n } finally {\n await subs?.close();\n }\n\n return { state, trace };\n}\n\n/** The Subs `machine` wants at `state`, keyed by the id the engines derive. */\nexport function desiredSubs<S>(\n machine: { readonly subs?: ReadonlyArray<unknown> },\n state: S,\n): ReadonlyMap<string, Sub> {\n const desired = new Map<string, Sub>();\n for (const entry of subEntriesOf<S>(machine)) {\n const sub = desiredSub(entry, state);\n if (sub !== null) desired.set(sub.id, sub);\n }\n return desired;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/testing/drive-loop.ts"],"names":[],"mappings":";;;;AAmDO,IAAM,kBAAA,GAAqB;AAqE3B,IAAM,wBAAA,GAAN,cAA6C,KAAA,CAAM;AAAA,EAGxD,WAAA,CAEkB,SAAA,EAEA,MAAA,EAEA,KAAA,EAChB;AACA,IAAA,KAAA;AAAA,MACE,CAAA,yCAAA,EAA4C,SAAS,CAAA,8DAAA,EACP,MAAM,CAAA,qBAAA,EACxC,KAAA,CAAM,MAAM,CAAA,KAAA,EAAQ,KAAA,CAAM,MAAA,KAAW,CAAA,GAAI,GAAA,GAAM,KAAK,CAAA,oCAAA;AAAA,KAElE;AAXgB,IAAA,IAAA,C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EAAM;AACxB;AAGO,SAAS,WAAA,CACd,SACA,KAAA,EAC0B;AAC1B,EAAA,MAAM,OAAA,uBAAc,GAAA,EAAiB;AACrC,EAAA,KAAA,MAAW,KAAA,IAAS,YAAA,CAAgB,OAAO,CAAA,EAAG;AAC5C,IAAA,MAAM,GAAA,GAAM,UAAA,CAAW,KAAA,EAAO,KAAK,CAAA;AACnC,IAAA,IAAI,QAAQ,IAAA,EAAM,OAAA,CAAQ,GAAA,CAAI,GAAA,CAAI,IAAI,GAAG,CAAA;AAAA,EAC3C;AACA,EAAA,OAAO,OAAA;AACT","file":"chunk-ETRNSJCR.js","sourcesContent":["// ---------------------------------------------------------------------------\n// The round loop both `drive`s run — `@demlik/tea/testing/promise` and\n// `@demlik/tea/testing/effect` — said once, so the two cannot drift.\n//\n// `bindMachine` hands back the Cmds a fold emitted and stops there; performing\n// them is the caller's. So every consumer test that exercises a Cmd-emitting\n// machine hand-writes the same fixture: step the Msg, await the real interpret\n// handler over each emitted Cmd, feed the settle Msg back, repeat until quiet,\n// with a hand-picked guard bound in the loop header. `drive` is that fixture as\n// one call, and this file is its loop. It composes `bindMachine`'s synchronous\n// 2-arg `step` and adds NO second reducer path.\n//\n// What differs per engine is only how one Cmd is performed and whether Subs\n// run, so an engine hands this loop a `cellFor` lookup and, optionally, a\n// `subs` driver. Everything else — the rounds, the trace, the `maxRounds`\n// bound, the `Cmd.define` edge and its dispatch check (#304) — is here.\n//\n// **It returns the history, not just the endpoint.** `{ state, trace }`, where\n// `trace` is every Msg folded and every Cmd dispatched in order, lets a test\n// assert on the SEQUENCE as well as the settled state, and the same trace's\n// Msgs replayed through `replay` from the same initial state reproduce the\n// returned state exactly.\n//\n// **Exhausting `maxRounds` fails the drive.** A driver that quietly returns a\n// half-driven state lets a test assert green on a machine that never settled.\n//\n// Strengthens invariant 9 (the testing surface is named and small).\n// ---------------------------------------------------------------------------\n\nimport {\n type AnyCmdDef,\n type Cmd,\n type CmdContract,\n cmdContractOver,\n desiredSub,\n followUps,\n type Machine,\n type Sub,\n subEntriesOf,\n} from \"../pure/core\";\nimport type { CtxArg } from \"../runtime-types\";\nimport { bindMachine } from \"./bind-machine\";\n\n/**\n * The default round bound when `opts.maxRounds` is omitted: **100**.\n *\n * A round is one drain of the pending Msgs plus one drain of the Cmds those\n * folds emitted, so a settling machine costs a handful; 100 is loose enough\n * that a legitimate retry ladder finishes inside it and tight enough that a\n * genuine cycle stops rather than hangs.\n */\nexport const DEFAULT_MAX_ROUNDS = 100;\n\n/**\n * One entry of a driven run's history, in dispatch order.\n *\n * - `msg` — a Msg folded through the machine's reducer. The seed Msg is the\n * first entry of every trace; every later one is a settle Msg a handler\n * returned (or fired through its injected `dispatch`), or a Msg a running\n * Sub emitted.\n * - `cmd` — a Cmd handed to an interpret handler. It is recorded BEFORE the\n * handler runs, so a trace recovered from a failed handler names the Cmd\n * that failed as its last entry.\n */\nexport type DriveTraceEntry<M, C> =\n | { readonly kind: \"msg\"; readonly msg: M }\n | { readonly kind: \"cmd\"; readonly cmd: C };\n\n/** What a settled `drive` hands back. */\nexport interface DriveResult<S, M, C> {\n /** The state after the machine went quiet — no Msg pending, no Cmd unperformed. */\n readonly state: S;\n /**\n * Every Msg folded and every Cmd dispatched, in order. Filtering it to its\n * `msg` entries and replaying those through `replay` from the same initial\n * state reproduces {@link DriveResult.state}.\n */\n readonly trace: readonly DriveTraceEntry<M, C>[];\n}\n\n/**\n * `drive`'s `ctx` field. `CtxArg` widened by exactly one case: a machine\n * declaring `ctx: undefined` in its `types` block — the pure shape every\n * how-to on this package writes — may omit it too. `CtxArg` alone keeps `ctx`\n * REQUIRED there, because `{}` is not assignable to `undefined`, which would\n * make the common pure call site spell `{ ctx: undefined }` to say nothing.\n * A machine whose `Ctx` carries a field a handler reads still requires it.\n */\nexport type DriveCtxArg<Ctx> = [undefined] extends [Ctx]\n ? { readonly ctx?: Ctx }\n : CtxArg<Ctx>;\n\n/**\n * The options both `drive`s take. `ctx` is conditionally optional (see\n * {@link DriveCtxArg}).\n */\nexport type DriveOptions<Ctx> = DriveCtxArg<Ctx> & {\n /**\n * The round bound. Exceeding it fails the drive with\n * {@link DriveRoundsExceededError}; `drive` never returns a half-driven\n * state. Defaults to {@link DEFAULT_MAX_ROUNDS} (100).\n */\n readonly maxRounds?: number;\n /**\n * The clock that stamps `at` on a `Cmd.define`d Cmd's minted `_ok` / `_err`\n * Msg — the one `run` takes. Defaults to `Date.now`; pin it for a test that\n * asserts on `at`.\n */\n readonly clock?: () => number;\n};\n\n/**\n * Raised when a driven machine is still emitting work after `maxRounds` rounds.\n * Follows the tea error dialect (`override readonly name`) and carries a `_tag`\n * discriminant, so a test branches on it by `instanceof` or on the tag.\n *\n * It carries the round count it stopped at and the PARTIAL trace up to that\n * point, which is what a test needs to see the cycle — the bound alone says\n * only that one exists.\n */\nexport class DriveRoundsExceededError<M, C> extends Error {\n override readonly name = \"DriveRoundsExceededError\";\n readonly _tag = \"DriveRoundsExceededError\" as const;\n constructor(\n /** The bound that was exceeded. */\n public readonly maxRounds: number,\n /** The round the driver stopped at — always `maxRounds + 1`. */\n public readonly rounds: number,\n /** Every Msg folded and Cmd dispatched before the driver gave up. */\n public readonly trace: readonly DriveTraceEntry<M, C>[],\n ) {\n super(\n `@demlik/tea: drive did not settle within ${maxRounds} round(s) — the ` +\n `machine was still emitting work at round ${rounds}. The partial ` +\n `trace (${trace.length} entr${trace.length === 1 ? \"y\" : \"ies\"}) is ` +\n `on the error's \\`trace\\` field.`,\n );\n }\n}\n\n/**\n * Raised when a Cmd reaches `drive` with no handler for its `type` in the\n * handler record. The record's mapped type makes that a compile error at a\n * well-typed call site; this is the runtime arm for a handler record assembled\n * dynamically or cast.\n */\nexport class DriveNoHandlerError<M, C> extends Error {\n override readonly name = \"DriveNoHandlerError\";\n readonly _tag = \"DriveNoHandlerError\" as const;\n constructor(\n /** The Cmd `type` nothing in the handler record answered. */\n public readonly cmdType: string,\n /** Every Msg folded and Cmd dispatched before the miss. */\n public readonly trace: readonly DriveTraceEntry<M, C>[],\n ) {\n super(\n `@demlik/tea: drive found no interpret handler for Cmd type ` +\n `\"${cmdType}\" — the handlers record must answer every Cmd the ` +\n `machine emits.`,\n );\n }\n}\n\n/** The key `drive` hangs a partial trace off a failure under. */\nconst TRACE_KEY = \"driveTrace\";\n\n/**\n * Hang `trace` off `err` on a non-enumerable property, so {@link driveTraceOf}\n * reads it back without changing how the error prints or serializes. A\n * non-object failure carries nothing.\n */\nexport function annotateTrace(err: unknown, trace: readonly unknown[]): void {\n if (typeof err !== \"object\" || err === null) return;\n Object.defineProperty(err, TRACE_KEY, {\n value: [...trace],\n enumerable: false,\n configurable: true,\n writable: true,\n });\n}\n\n/**\n * Read back the partial trace `drive` attached to an error a handler failed\n * with. Returns `undefined` for anything `drive` did not annotate.\n *\n * A failing handler's error leaves `drive` UNSWALLOWED — same value, same\n * `instanceof`, same `_tag` — so a test that already branches on the handler's\n * own error type keeps doing so. The trace rides along on a non-enumerable\n * property so it is recoverable without changing how the error prints or\n * serializes.\n */\nexport function driveTraceOf<M, C>(\n err: unknown,\n): readonly DriveTraceEntry<M, C>[] | undefined {\n if (typeof err !== \"object\" || err === null) return undefined;\n const carried = (err as Record<string, unknown>)[TRACE_KEY];\n return Array.isArray(carried)\n ? (carried as readonly DriveTraceEntry<M, C>[])\n : undefined;\n}\n\n// === The loop ===\n\n/**\n * Perform one Cmd and resolve with the handler's raw return, before the\n * `Cmd.define` edge reads it. The `dispatch` it is handed is already checked\n * (#304).\n */\nexport type DriveCell<M, C> = (\n cmd: C,\n dispatch: (msg: M) => void,\n) => Promise<unknown>;\n\n/** The Subs a drive runs, as the loop sees them. */\nexport interface DriveSubs<S, M> {\n /**\n * Start every Sub `state` wants that is not running, and stop every running\n * one it no longer wants — the engine's reconcile, after each fold.\n */\n readonly reconcile: (state: S) => void;\n /**\n * Wait for the next Msgs a running Sub emits. Resolves with every Msg\n * buffered by then, or with `undefined` once no Sub is left running; rejects\n * when a Sub failed.\n */\n readonly next: () => Promise<readonly M[] | undefined>;\n /** Stop every Sub still running. */\n readonly close: () => Promise<void>;\n}\n\n/** What one engine hands the shared loop. */\nexport interface DriveEngine<S, M, C> {\n /**\n * The edge and dispatch check over the machine's `Cmd.define` list. The\n * engine builds it (see {@link driveContractOf}) so a handler that settles\n * through `cmdEdgeOf(ctx)` mints into the same record the check reads.\n */\n readonly contract: CmdContract;\n /** The cell that performs a Cmd of `type`, or `undefined` when none does. */\n readonly cellFor: (type: string) => DriveCell<M, C> | undefined;\n /** The Subs to run beside the Cmds; an engine that runs none omits it. */\n readonly subs?: DriveSubs<S, M>;\n}\n\n/** The contract both `drive`s hold a machine's Cmds to (ADR 0021). */\nexport function driveContractOf(\n machine: { readonly cmds?: readonly AnyCmdDef[] },\n clock: () => number,\n): CmdContract {\n return cmdContractOver(machine.cmds ?? [], clock);\n}\n\n/**\n * Drive `machine` from `initial` through `msg`, performing every emitted Cmd\n * through `engine.cellFor`, until the machine goes quiet.\n *\n * One round is: fold every pending Msg, then perform every Cmd those folds\n * emitted, in order. A Msg a cell returns or dispatches is pending for the next\n * round. When nothing is pending and Subs are running, the loop waits for the\n * next Msgs they emit; it settles once no Msg is pending, no Cmd is unperformed\n * and no Sub is left running.\n *\n * Every error that leaves the loop carries the partial trace (see\n * {@link driveTraceOf}).\n */\nexport async function driveLoop<\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 initial: S,\n msg: M,\n ctx: Ctx,\n maxRounds: number,\n engine: DriveEngine<S, M, C>,\n): Promise<DriveResult<S, M, C>> {\n const bound = bindMachine(machine, ctx);\n const { contract, cellFor, subs } = engine;\n\n const trace: DriveTraceEntry<M, C>[] = [];\n let state = initial;\n let pending: M[] = [msg];\n let round = 0;\n\n try {\n subs?.reconcile(state);\n while (pending.length > 0) {\n round += 1;\n if (round > maxRounds) {\n throw new DriveRoundsExceededError<M, C>(maxRounds, round, trace);\n }\n\n // Drain the round's Msgs first, THEN its Cmds. Swapping the buffer before\n // the fold is what keeps a settle Msg out of the round that produced it.\n const folding = pending;\n pending = [];\n const emitted: C[] = [];\n for (const next of folding) {\n trace.push({ kind: \"msg\", msg: next });\n const [advanced, cmds] = bound.step(state, next);\n state = advanced;\n emitted.push(...cmds);\n subs?.reconcile(state);\n }\n\n for (const cmd of emitted) {\n trace.push({ kind: \"cmd\", cmd });\n const cell = cellFor(cmd.type);\n if (cell === undefined) {\n throw new DriveNoHandlerError<M, C>(cmd.type, trace);\n }\n // The dispatch half of ADR 0021, as the engine applies it (#304): a\n // `Cmd.define`d handler may not send a `_ok` / `_err` it built itself.\n // That Msg is dropped, never folded, and the refusal fails the drive\n // once the cell settles, so a handler that catches it cannot hide it.\n let refused: { readonly error: unknown } | undefined;\n const dispatch = (fired: M): void => {\n try {\n contract.checkDispatch(cmd, fired);\n } catch (error) {\n refused ??= { error };\n return;\n }\n pending.push(fired);\n };\n const settled = contract.settle(cmd, await cell(cmd, dispatch));\n if (refused !== undefined) throw refused.error;\n // A returned list lands in order, as `run`'s loop enqueues it.\n pending.push(...followUps<M>(settled));\n }\n\n if (pending.length === 0 && subs !== undefined) {\n pending = [...((await subs.next()) ?? [])];\n }\n }\n } catch (err) {\n // Unswallowed: the failure's own value is what leaves the loop, so a\n // test's `instanceof` / `_tag` branch still lands.\n annotateTrace(err, trace);\n throw err;\n } finally {\n await subs?.close();\n }\n\n return { state, trace };\n}\n\n/** The Subs `machine` wants at `state`, keyed by the id the engines derive. */\nexport function desiredSubs<S>(\n machine: { readonly subs?: ReadonlyArray<unknown> },\n state: S,\n): ReadonlyMap<string, Sub> {\n const desired = new Map<string, Sub>();\n for (const entry of subEntriesOf<S>(machine)) {\n const sub = desiredSub(entry, state);\n if (sub !== null) desired.set(sub.id, sub);\n }\n return desired;\n}\n"]}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { replay, applyCell, acceptedTypes } from './chunk-A3QPMX5M.js';
|
|
2
|
+
|
|
3
|
+
// src/pbt/laws.ts
|
|
4
|
+
function verdict(answer, report) {
|
|
5
|
+
if (answer === true || answer === null) return null;
|
|
6
|
+
const reason = answer === false || answer === "" ? null : answer;
|
|
7
|
+
return { report: report(), reason };
|
|
8
|
+
}
|
|
9
|
+
function lawTerminates(fold, terminal) {
|
|
10
|
+
if (terminal(fold.finalState, fold.initCmds)) return null;
|
|
11
|
+
return {
|
|
12
|
+
report: `final state did not match terminal predicate. Final: ${JSON.stringify(fold.finalState)}`,
|
|
13
|
+
reason: null
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
function lawInvariant(fold, invariant) {
|
|
17
|
+
for (const step of fold.steps) {
|
|
18
|
+
const broken = verdict(
|
|
19
|
+
invariant(step, fold.initCmds),
|
|
20
|
+
() => `failed at step msg=${JSON.stringify(step.msg)} prev=${JSON.stringify(step.prev)} next=${JSON.stringify(step.next)} cmds=${JSON.stringify(step.cmds)}`
|
|
21
|
+
);
|
|
22
|
+
if (broken !== null) return broken;
|
|
23
|
+
}
|
|
24
|
+
return null;
|
|
25
|
+
}
|
|
26
|
+
function lawTrace(fold, predicate) {
|
|
27
|
+
return verdict(
|
|
28
|
+
predicate(fold.steps, fold.finalState, fold.initCmds),
|
|
29
|
+
() => `predicate failed on trace length=${fold.steps.length}, final=${JSON.stringify(fold.finalState)}`
|
|
30
|
+
);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// src/pbt/runners/replay-fold.ts
|
|
34
|
+
function foldEvents(machine, ctx, loaded, msgs) {
|
|
35
|
+
const { state: initialState, cmds: initCmds } = replay(machine, {
|
|
36
|
+
msgs: [],
|
|
37
|
+
ctx,
|
|
38
|
+
loaded: loaded ?? null
|
|
39
|
+
});
|
|
40
|
+
const states = [initialState];
|
|
41
|
+
const steps = [];
|
|
42
|
+
let current = initialState;
|
|
43
|
+
for (const msg of msgs) {
|
|
44
|
+
const [next, emitted] = applyCell(machine, current, msg);
|
|
45
|
+
steps.push({ prev: current, msg, next, cmds: [...emitted] });
|
|
46
|
+
states.push(next);
|
|
47
|
+
current = next;
|
|
48
|
+
}
|
|
49
|
+
return { states, steps, finalState: current, initCmds };
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// src/pbt/arbitraries/guided-fold.ts
|
|
53
|
+
var MAX_PICK = 5039;
|
|
54
|
+
function resolveGuided(machine, ctx, loaded, answerers, events) {
|
|
55
|
+
const index = new Map(answerers.map(({ cmdType }, at) => [cmdType, at]));
|
|
56
|
+
const read = (event, waiting2) => {
|
|
57
|
+
if (event.kind === "outside") return { msg: event.msg, answers: null };
|
|
58
|
+
if (waiting2.length === 0) {
|
|
59
|
+
return event.otherwise === void 0 ? null : { msg: event.otherwise, answers: null };
|
|
60
|
+
}
|
|
61
|
+
const at = event.pick % waiting2.length;
|
|
62
|
+
const cmd = waiting2[at];
|
|
63
|
+
const cell = index.get(cmd.type);
|
|
64
|
+
const answerer = answerers[cell];
|
|
65
|
+
return { msg: answerer.make(cmd, event.values[cell]), answers: at };
|
|
66
|
+
};
|
|
67
|
+
const answerable = (cmds) => cmds.filter((cmd) => index.has(cmd.type));
|
|
68
|
+
const msgs = [];
|
|
69
|
+
const waiting = [];
|
|
70
|
+
let state;
|
|
71
|
+
try {
|
|
72
|
+
const boot = replay(machine, { msgs: [], ctx, loaded });
|
|
73
|
+
state = boot.state;
|
|
74
|
+
waiting.push(...answerable(boot.cmds));
|
|
75
|
+
} catch {
|
|
76
|
+
return msgs;
|
|
77
|
+
}
|
|
78
|
+
for (const event of events) {
|
|
79
|
+
const meant = read(event, waiting);
|
|
80
|
+
if (meant === null) continue;
|
|
81
|
+
const { msg, answers } = meant;
|
|
82
|
+
if (!acceptedTypes(machine, state).includes(msg.type)) continue;
|
|
83
|
+
if (answers !== null) waiting.splice(answers, 1);
|
|
84
|
+
msgs.push(msg);
|
|
85
|
+
try {
|
|
86
|
+
const [next, sent] = applyCell(machine, state, msg);
|
|
87
|
+
state = next;
|
|
88
|
+
waiting.push(...answerable(sent));
|
|
89
|
+
} catch {
|
|
90
|
+
return msgs;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
return msgs;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export { MAX_PICK, foldEvents, lawInvariant, lawTerminates, lawTrace, resolveGuided };
|
|
97
|
+
//# sourceMappingURL=chunk-FXWDDNGD.js.map
|
|
98
|
+
//# sourceMappingURL=chunk-FXWDDNGD.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/pbt/laws.ts","../src/pbt/runners/replay-fold.ts","../src/pbt/arbitraries/guided-fold.ts"],"names":["waiting"],"mappings":";;;AA+BA,SAAS,OAAA,CACP,QACA,MAAA,EACiB;AACjB,EAAA,IAAI,MAAA,KAAW,IAAA,IAAQ,MAAA,KAAW,IAAA,EAAM,OAAO,IAAA;AAC/C,EAAA,MAAM,MAAA,GAAS,MAAA,KAAW,KAAA,IAAS,MAAA,KAAW,KAAK,IAAA,GAAO,MAAA;AAC1D,EAAA,OAAO,EAAE,MAAA,EAAQ,MAAA,EAAO,EAAG,MAAA,EAAO;AACpC;AAqBO,SAAS,aAAA,CACd,MACA,QAAA,EACiB;AACjB,EAAA,IAAI,SAAS,IAAA,CAAK,UAAA,EAAY,IAAA,CAAK,QAAQ,GAAG,OAAO,IAAA;AACrD,EAAA,OAAO;AAAA,IACL,QACE,CAAA,qDAAA,EACU,IAAA,CAAK,SAAA,CAAU,IAAA,CAAK,UAAU,CAAC,CAAA,CAAA;AAAA,IAC3C,MAAA,EAAQ;AAAA,GACV;AACF;AAuBO,SAAS,YAAA,CACd,MACA,SAAA,EAIiB;AACjB,EAAA,KAAA,MAAW,IAAA,IAAQ,KAAK,KAAA,EAAO;AAC7B,IAAA,MAAM,MAAA,GAAS,OAAA;AAAA,MACb,SAAA,CAAU,IAAA,EAAM,IAAA,CAAK,QAAQ,CAAA;AAAA,MAC7B,MACE,CAAA,mBAAA,EAAsB,IAAA,CAAK,SAAA,CAAU,IAAA,CAAK,G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AAAA,IACT;AAAA,EACF;AACA,EAAA,OAAO,IAAA;AACT","file":"chunk-FXWDDNGD.js","sourcesContent":["// ---------------------------------------------------------------------------\n// The laws, as plain check functions over one fold (#749).\n//\n// A law reads what `foldEvents` handed back and answers `null` when it holds, or\n// a `LawBreak` saying what broke. It draws nothing and throws nothing of its\n// own, so any checker can run it: fast-check through `propertyTerminates`,\n// `propertyInvariant` and `propertyTrace`, which call these, or Effect's\n// `Arbitrary.checkEffect`, through `@demlik/tea/testing/effect`.\n//\n// This file imports neither `fast-check` nor `effect`, and\n// `src/entry-points.import-graph.test.ts` keeps it that way, so both entries\n// export it. The ruling: https://github.com/kamp-us/demlik/issues/749#issuecomment-6564369809\n// ---------------------------------------------------------------------------\n\nimport type { Fold, Step } from \"./runners/replay-fold\";\n\n/**\n * What a broken law says. `report` names the fold that broke it. `reason` is the\n * string the check returned to say why, or `null` when it returned `false`.\n *\n * @experimental\n */\nexport interface LawBreak {\n readonly report: string;\n readonly reason: string | null;\n}\n\n/**\n * Read what a check answered: `true` and `null` hold, `false` and any string\n * break. An empty string breaks with nothing to say, so it reads as `false`.\n */\nfunction verdict(\n answer: boolean | string | null,\n report: () => string,\n): LawBreak | null {\n if (answer === true || answer === null) return null;\n const reason = answer === false || answer === \"\" ? null : answer;\n return { report: report(), reason };\n}\n\n/**\n * The law `propertyTerminates` runs: the fold's final state is one `terminal`\n * accepts. `terminal` also gets the Cmds `init` sent.\n *\n * @example\n * ```ts\n * import type { Machine } from \"@demlik/tea\";\n * import { foldEvents, lawTerminates } from \"@demlik/tea/pbt\";\n *\n * type State = { type: \"idle\" } | { type: \"done\" };\n * type Msg = { type: \"finish\" };\n * declare const machine: Machine<State, Msg, never, never, object>;\n *\n * const fold = foldEvents(machine, {}, null, [{ type: \"finish\" }]);\n * lawTerminates(fold, (s) => s.type === \"done\"); // null when it holds\n * ```\n *\n * @experimental\n */\nexport function lawTerminates<S, M, C>(\n fold: Fold<S, M, C>,\n terminal: (state: NoInfer<S>, initCmds: readonly NoInfer<C>[]) => boolean,\n): LawBreak | null {\n if (terminal(fold.finalState, fold.initCmds)) return null;\n return {\n report:\n `final state did not match terminal predicate. ` +\n `Final: ${JSON.stringify(fold.finalState)}`,\n reason: null,\n };\n}\n\n/**\n * The law `propertyInvariant` runs: `invariant` holds on every step of the fold.\n * Return `true` or `null` to accept, `false` or a string saying why to break. It\n * stops at the first step that breaks, and the report names that step. The second\n * argument is the Cmds `init` sent.\n *\n * @example\n * ```ts\n * import type { Machine } from \"@demlik/tea\";\n * import { foldEvents, lawInvariant } from \"@demlik/tea/pbt\";\n *\n * type State = { readonly n: number };\n * type Msg = { type: \"inc\" };\n * declare const machine: Machine<State, Msg, never, never, object>;\n *\n * const fold = foldEvents(machine, {}, null, [{ type: \"inc\" }]);\n * lawInvariant(fold, ({ prev, next }) => next.n > prev.n || \"n did not grow\");\n * ```\n *\n * @experimental\n */\nexport function lawInvariant<S, M, C>(\n fold: Fold<S, M, C>,\n invariant: (\n step: Step<NoInfer<S>, NoInfer<M>, NoInfer<C>>,\n initCmds: readonly NoInfer<C>[],\n ) => boolean | string | null,\n): LawBreak | null {\n for (const step of fold.steps) {\n const broken = verdict(\n invariant(step, fold.initCmds),\n () =>\n `failed at step msg=${JSON.stringify(step.msg)} ` +\n `prev=${JSON.stringify(step.prev)} next=${JSON.stringify(step.next)} ` +\n `cmds=${JSON.stringify(step.cmds)}`,\n );\n if (broken !== null) return broken;\n }\n return null;\n}\n\n/**\n * The law `propertyTrace` runs: `predicate` holds on the fold's steps and final\n * state together. Return `true` or `null` to accept, `false` or a string saying\n * why to break. The last argument is the Cmds `init` sent.\n *\n * @example\n * ```ts\n * import type { Machine } from \"@demlik/tea\";\n * import { foldEvents, lawTrace } from \"@demlik/tea/pbt\";\n *\n * type State = { type: \"open\" } | { type: \"done\" };\n * type Msg = { type: \"close\" };\n * declare const machine: Machine<State, Msg, never, never, object>;\n *\n * const fold = foldEvents(machine, {}, null, [{ type: \"close\" }]);\n * lawTrace(fold, (steps, final) => final.type !== \"done\" || steps.length > 0);\n * ```\n *\n * @experimental\n */\nexport function lawTrace<S, M, C>(\n fold: Fold<S, M, C>,\n predicate: (\n steps: readonly Step<NoInfer<S>, NoInfer<M>, NoInfer<C>>[],\n finalState: NoInfer<S>,\n initCmds: readonly NoInfer<C>[],\n ) => boolean | string | null,\n): LawBreak | null {\n return verdict(\n predicate(fold.steps, fold.finalState, fold.initCmds),\n () =>\n `predicate failed on trace length=${fold.steps.length}, ` +\n `final=${JSON.stringify(fold.finalState)}`,\n );\n}\n","// ---------------------------------------------------------------------------\n// `foldEvents` — pure deterministic fold over a Msg sequence.\n//\n// PBT needs the per-step (prev/msg/next/cmds) structure to assert\n// step-shaped invariants. The substrate's `replay(machine, opts)` returns\n// only final state + cumulative cmds — insufficient. We use `replay` for\n// the boot step (calls `machine.init(loaded, ctx)` faithfully) then walk\n// msgs ourselves through `applyCell`, the substrate's own cell dispatch.\n//\n// Why walk cells directly instead of looping `replay` once per msg with\n// `loaded: prevState`? Because `init(loaded)` runs every call, and on\n// machines with non-trivial init transforms (e.g. the audit machine's\n// `auditing → attach_debugger` resume cell) that would either (a) re-fire\n// the transform on every step, or (b) require fragile cmd-subtraction to\n// isolate this step's cmds. Calling the cells directly keeps the fold pure\n// and the cmds per-step exactly.\n//\n// Dispatches through `applyCell` — the single primitive `run`/`replay` use —\n// so form classification agrees with production by construction (#275).\n//\n// `foldEvents` does NOT call `interpret`, does NOT touch a Store, does NOT\n// start Subs. The reducer surface is the contract.\n// ---------------------------------------------------------------------------\n\nimport {\n applyCell,\n type Cmd,\n type Machine,\n replay,\n type Sub,\n} from \"../../index\";\n\n/**\n * One unit in a fold trace — the four pieces of data a property\n * invariant typically asserts on. `prev` is the state before the msg\n * applied; `next` is the state after; `cmds` is the cmds emitted by this\n * single step (NOT the running total).\n */\nexport interface Step<S, M, C> {\n readonly prev: S;\n readonly msg: M;\n readonly next: S;\n readonly cmds: readonly C[];\n}\n\n/**\n * What {@link foldEvents} hands back: every state in order, one {@link Step} per\n * Msg, the final state, and the Cmds `init` sent. A law reads one of these.\n */\nexport interface Fold<S, M, C> {\n readonly states: readonly S[];\n readonly steps: readonly Step<S, M, C>[];\n readonly finalState: S;\n readonly initCmds: readonly C[];\n}\n\n/**\n * Fold a Msg sequence through a machine's pure reducer, returning the\n * per-step trace, every state in order, the final state, and the Cmds `init`\n * sent. Initial state comes from `replay(machine, { msgs: [], ctx, loaded })`\n * — i.e. `machine.init(loaded ?? null, ctx)` faithfully. Init's emitted cmds\n * are NOT included in any `Step` (they're the boot moment, not a Msg): they\n * come back as `initCmds`, on a fresh start and on a loaded state alike.\n *\n * @param machine The machine under test.\n * @param ctx The Ctx — typically `stubCtxThrowingProxy<Ctx>()` when\n * init is pure. Pass a real ctx if init reads from it.\n * @param loaded Optional pre-init snapshot (the `loaded` arg to\n * `machine.init`). Defaults to `null` (fresh boot).\n * @param msgs The Msg sequence to fold.\n *\n * @example\n * ```ts\n * import type { Machine } from \"@demlik/tea\";\n * import { foldEvents } from \"@demlik/tea/pbt\";\n *\n * type State = { type: \"idle\" } | { type: \"counting\"; n: number } | { type: \"stopped\" };\n * type Msg = { type: \"start\" } | { type: \"tick\" } | { type: \"stop\" };\n * interface Ctx { readonly tabId: number }\n * declare const machine: Machine<State, Msg, never, never, Ctx>;\n * declare const ctx: Ctx;\n *\n * const { states, steps, finalState } = foldEvents(machine, ctx, null, [\n * { type: \"start\" }, { type: \"tick\" }, { type: \"stop\" },\n * ]);\n * // steps[1] = { prev: { type: \"counting\", n: 0 }, msg: { type: \"tick\" }, ... }\n * ```\n */\nexport function foldEvents<\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 ctx: NoInfer<Ctx>,\n loaded: NoInfer<S> | null,\n msgs: readonly NoInfer<M>[],\n): Fold<S, M, C> {\n // Boot through `replay` so `init` runs faithfully and we honor the\n // substrate's loaded-snapshot contract (init may transform the loaded\n // value before the first Msg lands — e.g. the audit machine flips\n // `debuggerAttached: false` on resume). With no msgs, its `cmds` are init's.\n const { state: initialState, cmds: initCmds } = replay(machine, {\n msgs: [],\n ctx,\n loaded: loaded ?? null,\n });\n\n // Per-msg dispatch goes through `applyCell` — the same primitive `run` and\n // `replay` use — so this runner classifies the update form identically to\n // production (`formOf` honors the `__form` tag; #275).\n const states: S[] = [initialState];\n const steps: Step<S, M, C>[] = [];\n let current = initialState;\n\n for (const msg of msgs) {\n const [next, emitted] = applyCell<S, M, C>(machine, current, msg);\n steps.push({ prev: current, msg, next, cmds: [...emitted] });\n states.push(next);\n current = next;\n }\n\n return { states, steps, finalState: current, initCmds };\n}\n","// ---------------------------------------------------------------------------\n// The guided fold: turn blind events into a Msg list in which every answer\n// answers a Cmd that was sent and not yet answered.\n//\n// Any generator can draw the blind events. `arbGuidedSequence` draws them with\n// fast-check, and `@demlik/tea/testing/effect` draws them with Effect's\n// `Arbitrary`, so this file imports neither: one rule, two generators.\n// The route: https://github.com/kamp-us/demlik/issues/745#issuecomment-6552209764\n// ---------------------------------------------------------------------------\n\nimport {\n acceptedTypes,\n applyCell,\n type Cmd,\n type Machine,\n replay,\n type Sub,\n} from \"../../index\";\n\n/**\n * One drawn event. It means nothing until the fold reads it. An answer event\n * may carry an `otherwise` Msg, which stands in for the answer when nothing is\n * waiting, so the event is not dropped.\n */\nexport type BlindEvent<M> =\n | { readonly kind: \"outside\"; readonly msg: M }\n | {\n readonly kind: \"answer\";\n readonly pick: number;\n readonly values: readonly unknown[];\n readonly otherwise?: M;\n };\n\n/**\n * Largest blind pick, read modulo the Cmds waiting. 5040 divides evenly by every\n * count from 1 to 10, so no Cmd is favoured among that many.\n */\nexport const MAX_PICK = 5039;\n\n/**\n * How one Cmd type's answer is made from a drawn value. An answer event holds\n * one value per answerer, in the order of the list the fold is given.\n */\nexport interface Answerer<C extends Cmd, M> {\n readonly cmdType: string;\n readonly make: (cmd: C, value: unknown) => M;\n}\n\n/**\n * Fold blind events through the machine into a Msg list. An answer event's pick\n * is read modulo the Cmds waiting at that point and names one of them; with\n * nothing waiting the answer is dropped, and the event's `otherwise` Msg, when it\n * carries one, goes in its place. An event whose Msg the state has no cell for is\n * dropped too, and a refused answer leaves its Cmd waiting.\n *\n * A boot or step that throws ends the list there, so a runner's own fold meets\n * the same throw and reports it as that list's failure.\n */\nexport function resolveGuided<\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 ctx: NoInfer<Ctx>,\n loaded: NoInfer<S> | null,\n answerers: readonly Answerer<C, M>[],\n events: readonly BlindEvent<M>[],\n): readonly M[] {\n const index = new Map(answerers.map(({ cmdType }, at) => [cmdType, at]));\n\n /**\n * What an event means now: an answer to the waiting Cmd at `answers`, an outside\n * Msg (`answers` is `null`), or `null` when it is dropped.\n */\n const read = (\n event: BlindEvent<M>,\n waiting: readonly C[],\n ): { readonly msg: M; readonly answers: number | null } | null => {\n if (event.kind === \"outside\") return { msg: event.msg, answers: null };\n if (waiting.length === 0) {\n return event.otherwise === undefined\n ? null\n : { msg: event.otherwise, answers: null };\n }\n const at = event.pick % waiting.length;\n const cmd = waiting[at] as C;\n const cell = index.get(cmd.type) as number;\n const answerer = answerers[cell] as Answerer<C, M>;\n return { msg: answerer.make(cmd, event.values[cell]), answers: at };\n };\n const answerable = (cmds: readonly C[]): readonly C[] =>\n cmds.filter((cmd) => index.has(cmd.type));\n\n const msgs: M[] = [];\n const waiting: C[] = [];\n let state: S;\n try {\n const boot = replay(machine, { msgs: [], ctx, loaded });\n state = boot.state;\n waiting.push(...answerable(boot.cmds));\n } catch {\n return msgs; // The runner's fold boots too, and fails on this same throw.\n }\n for (const event of events) {\n const meant = read(event, waiting);\n if (meant === null) continue;\n const { msg, answers } = meant;\n // A refused answer takes nothing off `waiting`: its Cmd still has no answer.\n if (!acceptedTypes(machine, state).includes(msg.type)) continue;\n if (answers !== null) waiting.splice(answers, 1);\n msgs.push(msg);\n try {\n const [next, sent] = applyCell<S, M, C>(machine, state, msg);\n state = next;\n waiting.push(...answerable(sent));\n } catch {\n return msgs; // `msg` is last, so the runner's fold fails on this same throw.\n }\n }\n return msgs;\n}\n"]}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
// src/internal/engine/builtin-runners.ts
|
|
2
|
+
function timer(sub, _ctx, dispatch) {
|
|
3
|
+
const handle = setTimeout(() => dispatch(sub.deps.msg), sub.deps.ms);
|
|
4
|
+
return () => clearTimeout(handle);
|
|
5
|
+
}
|
|
6
|
+
var builtinRunners = { timer };
|
|
7
|
+
|
|
8
|
+
export { builtinRunners };
|
|
9
|
+
//# sourceMappingURL=chunk-GFGOQIEC.js.map
|
|
10
|
+
//# sourceMappingURL=chunk-GFGOQIEC.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/internal/engine/builtin-runners.ts"],"names":[],"mappings":";AAcA,SAAS,KAAA,CACP,GAAA,EACA,IAAA,EACA,QAAA,EACS;AACT,EAAA,MAAM,MAAA,GAAS,UAAA,CAAW,MAAM,QAAA,CAAS,GAAA,CAAI,KAAK,GAAG,CAAA,EAAG,GAAA,CAAI,IAAA,CAAK,EAAE,CAAA;AACnE,EAAA,OAAO,MAAM,aAAa,MAAM,CAAA;AAClC;AAGO,IAAM,cAAA,GAAiB,EAAE,KAAA","file":"chunk-GFGOQIEC.js","sourcesContent":["/**\n * The built-in Sub runners in their plain shape, the Promise engine's (#270\n * R1.1). A machine declares a built-in Sub by type alone — `{ type: \"timer\", deps:\n * (s) => ({ ms, msg }) }` — and `run` starts it with the runner here unless\n * `subscribe` names one of the same type, which replaces it (#270 R2.1). `/react`\n * reads them too, because a hidden component's built-in Sub has to stop as well.\n */\n\nimport type { BuiltinSubType, Dispose, TimerSub } from \"../../pure/core\";\n\n/**\n * `timer`: dispatch `deps.msg` once, `deps.ms` after the Sub starts. The engine\n * restarts it when `ms` or `msg` changes and clears it when the Sub stops.\n */\nfunction timer<M>(\n sub: TimerSub<M>,\n _ctx: unknown,\n dispatch: (msg: M) => void,\n): Dispose {\n const handle = setTimeout(() => dispatch(sub.deps.msg), sub.deps.ms);\n return () => clearTimeout(handle);\n}\n\n/** Every built-in runner, keyed by the Sub type it runs. */\nexport const builtinRunners = { timer } as const satisfies Record<\n BuiltinSubType,\n unknown\n>;\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { undefinedOnly, unchecked } from './chunk-4LPY67E4.js';
|
|
2
|
-
import { Cmd } from './chunk-
|
|
2
|
+
import { Cmd } from './chunk-A3QPMX5M.js';
|
|
3
3
|
|
|
4
4
|
// src/internal/persistence/snapshot/index.ts
|
|
5
5
|
var DEFAULT_SNAPSHOT_KEY = "@@snapshot";
|
|
@@ -60,5 +60,5 @@ function createSnapshot(config) {
|
|
|
60
60
|
}
|
|
61
61
|
|
|
62
62
|
export { createSnapshot, snapshotLoadDef, snapshotWriteDef };
|
|
63
|
-
//# sourceMappingURL=chunk-
|
|
64
|
-
//# sourceMappingURL=chunk-
|
|
63
|
+
//# sourceMappingURL=chunk-IAHEYPYJ.js.map
|
|
64
|
+
//# sourceMappingURL=chunk-IAHEYPYJ.js.map
|