eutaxy 0.18.0 → 0.19.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/README.md +15 -12
  2. package/dist/aws.d.mts +3 -3
  3. package/dist/aws.d.mts.map +1 -1
  4. package/dist/aws.mjs +13 -4
  5. package/dist/aws.mjs.map +1 -1
  6. package/dist/bin.mjs +1 -1
  7. package/dist/check-zkHLdWyf.mjs +1281 -0
  8. package/dist/check-zkHLdWyf.mjs.map +1 -0
  9. package/dist/cli-Bxjvq4p9.mjs +297 -0
  10. package/dist/cli-Bxjvq4p9.mjs.map +1 -0
  11. package/dist/cli.d.mts.map +1 -1
  12. package/dist/cli.mjs +1 -1
  13. package/dist/cloudflare.d.mts +38 -6
  14. package/dist/cloudflare.d.mts.map +1 -1
  15. package/dist/cloudflare.mjs +6466 -3
  16. package/dist/cloudflare.mjs.map +1 -0
  17. package/dist/{delivery-invariants-D-_GPOqE.d.mts → delivery-invariants-C3GXJIbg.d.mts} +2 -2
  18. package/dist/{delivery-invariants-D-_GPOqE.d.mts.map → delivery-invariants-C3GXJIbg.d.mts.map} +1 -1
  19. package/dist/{delivery-invariants-BRwfZJrs.mjs → delivery-invariants-DsBHpT1n.mjs} +2 -2
  20. package/dist/{delivery-invariants-BRwfZJrs.mjs.map → delivery-invariants-DsBHpT1n.mjs.map} +1 -1
  21. package/dist/draft-DEUDffHa.mjs +467 -0
  22. package/dist/draft-DEUDffHa.mjs.map +1 -0
  23. package/dist/{src-H1Q8ytEx.mjs → generate-TBJM3-2P.mjs} +3 -618
  24. package/dist/generate-TBJM3-2P.mjs.map +1 -0
  25. package/dist/index.d.mts +36 -36
  26. package/dist/index.d.mts.map +1 -1
  27. package/dist/index.mjs +6 -3
  28. package/dist/index.mjs.map +1 -1
  29. package/dist/install-DkzpGA5D.mjs +611 -0
  30. package/dist/install-DkzpGA5D.mjs.map +1 -0
  31. package/dist/{explore-D33RP9hF.d.mts → ir-KpC2epGn.d.mts} +70 -70
  32. package/dist/ir-KpC2epGn.d.mts.map +1 -0
  33. package/dist/keys-xtanNmuR.mjs +111 -0
  34. package/dist/keys-xtanNmuR.mjs.map +1 -0
  35. package/dist/mcp-DEn3HnLz.mjs +539 -0
  36. package/dist/mcp-DEn3HnLz.mjs.map +1 -0
  37. package/dist/{platform-CawKCUru.d.mts → platform-Cs9V9t2k.d.mts} +25 -11
  38. package/dist/platform-Cs9V9t2k.d.mts.map +1 -0
  39. package/dist/pool-CXN4CwGY.mjs +61 -0
  40. package/dist/pool-CXN4CwGY.mjs.map +1 -0
  41. package/dist/{provers-DS44OeEm.mjs → provers-D8VaY_OM.mjs} +18 -2
  42. package/dist/provers-D8VaY_OM.mjs.map +1 -0
  43. package/dist/reader-B9FSoEYW.mjs +1 -0
  44. package/dist/reader-Cz6_bLf6.mjs +3774 -0
  45. package/dist/reader-Cz6_bLf6.mjs.map +1 -0
  46. package/dist/report-_Vzavqg0.mjs +310 -0
  47. package/dist/report-_Vzavqg0.mjs.map +1 -0
  48. package/dist/src-B2DpVbMN.mjs +2 -0
  49. package/dist/src-BFGTvuA_.mjs +1235 -0
  50. package/dist/src-BFGTvuA_.mjs.map +1 -0
  51. package/dist/src-BtLZPRyG.mjs +120 -0
  52. package/dist/src-BtLZPRyG.mjs.map +1 -0
  53. package/dist/src-CB8DcvsK.mjs +1 -0
  54. package/dist/src-COuquJvI.mjs +269 -0
  55. package/dist/src-COuquJvI.mjs.map +1 -0
  56. package/dist/src-Chn-m_r1.mjs +1082 -0
  57. package/dist/src-Chn-m_r1.mjs.map +1 -0
  58. package/dist/{src-Whn0RMSh.mjs → src-D-MeEFn3.mjs} +589 -517
  59. package/dist/src-D-MeEFn3.mjs.map +1 -0
  60. package/dist/src-DwYD3QQJ.mjs +346 -0
  61. package/dist/src-DwYD3QQJ.mjs.map +1 -0
  62. package/dist/toolchain-DWfymxAJ.mjs +80 -0
  63. package/dist/toolchain-DWfymxAJ.mjs.map +1 -0
  64. package/dist/verdict-evEM5Gxx.mjs +12 -0
  65. package/dist/verdict-evEM5Gxx.mjs.map +1 -0
  66. package/package.json +4 -1
  67. package/dist/cli-DyA7uTBg.mjs +0 -9447
  68. package/dist/cli-DyA7uTBg.mjs.map +0 -1
  69. package/dist/explore-D33RP9hF.d.mts.map +0 -1
  70. package/dist/platform-CawKCUru.d.mts.map +0 -1
  71. package/dist/provers-DS44OeEm.mjs.map +0 -1
  72. package/dist/src-H1Q8ytEx.mjs.map +0 -1
  73. package/dist/src-Whn0RMSh.mjs.map +0 -1
  74. package/dist/workerd-tI8INa6v.mjs +0 -6334
  75. package/dist/workerd-tI8INa6v.mjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cloudflare.mjs","names":["retryDelayMs","point","retryDelayMs","retryDelayMs","argument","coreAtLeastOncePerMessage","deliverMessage","deliverMessage"],"sources":["../../cloudflare/src/alarm-rules.ts","../../cloudflare/src/background.ts","../../cloudflare/src/proxy-context.ts","../../cloudflare/src/d1.ts","../../cloudflare/src/r2.ts","../../cloudflare/src/services.ts","../../cloudflare/src/entrypoint.ts","../../cloudflare/src/workflows.ts","../../cloudflare/src/object-access.ts","../../cloudflare/src/alarms.ts","../../cloudflare/src/durable-objects.ts","../../cloudflare/src/caller.ts","../../cloudflare/src/cron.ts","../../cloudflare/src/scenario.ts","../../cloudflare/src/rpc.ts","../../cloudflare/src/callees.ts","../../cloudflare/src/check.ts","../../cloudflare/src/scripted-objects.ts","../../cloudflare/src/bindings.ts","../../cloudflare/src/http.ts","../../cloudflare/src/queue-decision.ts","../../cloudflare/src/queues.ts","../../cloudflare/src/scheduled.ts","../../cloudflare/src/websocket.ts","../../cloudflare/src/platform.ts","../../cloudflare/src/differential.ts","../../cli/src/workerd.ts"],"sourcesContent":["/**\n * The rules a Durable Object's alarm is retried and superseded by, as\n * Cloudflare documents them (developers.cloudflare.com/durable-objects/\n * api/base/#alarm): a handler that throws is retried with exponential\n * backoff starting at two seconds, up to six times, and an object has\n * one alarm, which a later `setAlarm` or `deleteAlarm` replaces. Written\n * in the subset the Lean engine translates, so what is proved is this\n * code, and `alarmRetries`, `retryDelayMs`, `nextGeneration` and\n * `superseded` are also the code that runs: alarms.ts retries, waits and\n * drops by them and holds no such decision of its own. Whether a failed\n * alarm is retried is `redelivery`'s decision, core's proved rule, under\n * `alarmRetries`, counting an event's attempts, which are one more than\n * its retries; the claims hold that constant to six through the delays.\n * `retriedAfter` and `generationAfter` state the claims in\n * alarm-rules.props.ts.\n */\n\n/** The retries Cloudflare makes of an alarm whose handler failed. */\nexport const alarmRetries = 6;\n\n/** The delay before the first retry. */\nconst firstRetryMs = 2_000;\n\n/**\n * How long after a run that failed its retry starts, `retryCount` being\n * the retries made before that run: two seconds, doubled for each.\n */\nexport function retryDelayMs(retryCount: number): number {\n return firstRetryMs * doublings(retryCount);\n}\n\n/**\n * Two to the power of `count`, written out for the counts a retry\n * follows, since `**` is outside the subset: no retry follows the sixth,\n * so nothing reads past the last line.\n */\nfunction doublings(count: number): number {\n if (count <= 0) return 1;\n if (count === 1) return 2;\n if (count === 2) return 4;\n if (count === 3) return 8;\n if (count === 4) return 16;\n return 32;\n}\n\n/** The generation a `setAlarm` or `deleteAlarm` starts: one no alarm of the object had before. */\nexport function nextGeneration(generation: number): number {\n return generation + 1;\n}\n\n/** Whether an alarm event or a retry of it is superseded: the object's alarm is of another generation, set again or deleted since. */\nexport function superseded(generation: number, current: number): boolean {\n return generation !== current;\n}\n\n/** Whether Cloudflare's limit leaves a retry to an alarm that has had `retryCount` of them. */\nexport function retriedAfter(retryCount: number): boolean {\n return retryCount < alarmRetries;\n}\n\n/** The object's generation after `changes` to its alarm, each a `setAlarm` (true) or a `deleteAlarm` (false), from `generation`. */\nexport function generationAfter(generation: number, changes: readonly boolean[]): number {\n if (changes.length === 0) return generation;\n return generationAfter(nextGeneration(generation), changes.slice(1));\n}\n","/** What a delivery hands the Worker besides the event: its `ExecutionContext`, and the background work it collects. */\n\nimport type { FaultKind, RunHooks } from \"@eutaxy/core\";\nimport { CrashSignal, note } from \"@eutaxy/engine\";\nimport type { WorkerHandler } from \"./worker.ts\";\n\nconst CUT_OFF: readonly FaultKind[] = [\"cut_off\"];\n\n/** The Worker a delivery runs: its default export and the proxied bindings it sees. */\nexport interface RunningWorker {\n readonly handler: WorkerHandler;\n readonly env: object;\n}\n\n/**\n * The `ExecutionContext` handed to a handler; `waitUntil` work is collected to\n * run after it returns, and `props` is what the caller's binding carries\n * (developers.cloudflare.com/workers/runtime-apis/bindings/service-bindings/rpc/, props). A rejection is kept in `failures` when given: a\n * scheduled invocation's status is that of its first failed `waitUntil`\n * (Cloudflare, Scheduled handler); a queue or HTTP delivery's is not.\n */\nexport function executionContext(\n background: Promise<unknown>[],\n failures?: unknown[],\n /** What `ctx.props` holds: for a callee, the `props` the caller's service binding carries (a copy). */\n props: object = {},\n): ExecutionContext {\n return {\n waitUntil: (promise: Promise<unknown>) => {\n background.push(\n promise.then(\n () => undefined,\n (error: unknown) => {\n failures?.push(error);\n },\n ),\n );\n },\n passThroughOnException: () => {},\n props: structuredClone(props),\n } as unknown as ExecutionContext;\n}\n\n/**\n * Background work extends the invocation but never changes the acknowledgement or the response.\n * A cut-off here is the isolate dying after them: work not yet started is lost.\n */\nexport async function drainBackground(\n hooks: RunHooks,\n inv: { isCrashed(): boolean; readonly crashed: Promise<void> },\n invocation: string,\n target: string,\n background: readonly Promise<unknown>[],\n): Promise<boolean> {\n if (background.length === 0 || inv.isCrashed()) return false;\n try {\n note(hooks, {\n invocation,\n target,\n op: \"background\",\n args: { pending: background.length },\n allowed: CUT_OFF,\n });\n await Promise.race([hooks.settle(Promise.all(background), invocation), inv.crashed]);\n // A fault crashing an effect the work makes hangs that effect rather than throwing, so the\n // race ends on `inv.crashed`: the invocation is crashed all the same.\n return inv.isCrashed();\n } catch (err) {\n if (!(err instanceof CrashSignal)) throw err;\n return true;\n }\n}\n","/**\n * What every binding proxy is given, and the two things each one does with\n * it: name the effect point of a call, and refuse a call the model does not\n * cover while reporting the reason, so the run ends `UNSUPPORTED` rather\n * than guessing.\n */\n\nimport type { EffectPoint, FaultKind, JsonValue, RunHooks } from \"@eutaxy/core\";\n\nexport interface ProxyContext {\n readonly hooks: RunHooks;\n /** The invocation currently running; only one runs at a time, even with several in flight. */\n readonly currentInvocation: () => string;\n /** The Worker's env as the platform proxies it: what an object's own service bindings answer from. */\n readonly env?: () => object;\n /**\n * An object's output gate, for the call it is making right now: set by the\n * object's own env around the synchronous start of a call through a\n * binding, and taken by that binding's stub (`outboundGate`) to wait on\n * inside the effect, before the call is performed.\n */\n readonly gate?: { pending: (() => Promise<void>) | undefined };\n /** Told when a Durable Object stub's fetch answered 101: the object a WebSocket connection reached, the invocation whose call it was, and the client end. */\n readonly onUpgrade?: (info: {\n binding: string;\n id: string;\n object: string;\n invocation: string;\n client: WebSocket;\n }) => void;\n}\n\n/** The effect point of a proxied call: the invocation running now, the binding's target, the call. */\nexport function pointAt(\n ctx: ProxyContext,\n target: string,\n op: string,\n args: JsonValue,\n allowed: readonly FaultKind[],\n): EffectPoint {\n return { invocation: ctx.currentInvocation(), target, op, args, allowed };\n}\n\n/**\n * What performing a call must wait on first, when an object is making it:\n * the object's writes before the call, durable, as the runtime's output gate\n * holds an outgoing message until they are. Taken where the stub's call\n * starts, synchronously; the wait runs inside the effect, as its real I/O,\n * so a fault that keeps the call from leaving does not make the writes\n * durable and one that lands after it finds them kept.\n */\nexport function outboundGate<T>(ctx: ProxyContext, perform: () => Promise<T>): () => Promise<T> {\n // Taken, not read: the slot is empty again before the effect is made. A crash fault on that\n // effect resets the object with `abort()`, which ends its code without running a `finally`, and a\n // gate left in the slot would be the next call's, anywhere, to wait on: another object's storage.\n const gate = ctx.gate?.pending;\n if (ctx.gate) ctx.gate.pending = undefined;\n return gate\n ? async () => {\n await gate();\n return perform();\n }\n : perform;\n}\n\n/** Report why the run cannot be trusted and refuse the call with the same reason. */\nexport function refuse(ctx: ProxyContext, reason: string): never {\n ctx.hooks.unsupported(reason);\n throw new Error(`eutaxy: ${reason}`);\n}\n","/**\n * The D1 binding proxy. Every statement execution is an effect point: the\n * engine decides the fault, the real Miniflare-backed D1 performs the query,\n * and the log records call, result and fault in the documented shape. When\n * a Durable Object is the caller, the query leaves it behind its output\n * gate (`outboundGate`).\n */\n\nimport { canonicalJson, type JsonValue, readFaults, toJson, writeFaults } from \"@eutaxy/core\";\nimport { outboundGate, type ProxyContext, pointAt as point } from \"./proxy-context.ts\";\n\n/** Whether a binding is a D1 database (what the proxies and the differential wrap). */\nexport function isD1(value: unknown): value is D1Database {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as { prepare?: unknown }).prepare === \"function\" &&\n typeof (value as { batch?: unknown }).batch === \"function\"\n );\n}\n\nexport type { ProxyContext } from \"./proxy-context.ts\";\n\nfunction metaOf(result: D1Result<unknown>): JsonValue {\n return { changes: result.meta.changes ?? 0, lastRowId: result.meta.last_row_id ?? null };\n}\n\nclass StatementProxy {\n private readonly real: D1PreparedStatement;\n private readonly target: string;\n private readonly ctx: ProxyContext;\n readonly sql: string;\n readonly params: readonly unknown[];\n\n constructor(\n real: D1PreparedStatement,\n target: string,\n ctx: ProxyContext,\n sql: string,\n params: readonly unknown[],\n ) {\n this.real = real;\n this.target = target;\n this.ctx = ctx;\n this.sql = sql;\n this.params = params;\n }\n\n /** The real statement, for `batch()`. */\n get statement(): D1PreparedStatement {\n return this.real;\n }\n\n private args(): JsonValue {\n return { sql: this.sql, params: toJson(this.params) };\n }\n\n bind(...values: unknown[]): StatementProxy {\n return new StatementProxy(this.real.bind(...values), this.target, this.ctx, this.sql, values);\n }\n\n run<T = Record<string, unknown>>(): Promise<D1Result<T>> {\n return this.ctx.hooks.effect(\n point(this.ctx, this.target, \"run\", this.args(), writeFaults),\n outboundGate(this.ctx, () => this.real.run<T>()),\n (r) => metaOf(r),\n );\n }\n\n all<T = Record<string, unknown>>(): Promise<D1Result<T>> {\n return this.ctx.hooks.effect(\n point(this.ctx, this.target, \"all\", this.args(), readFaults),\n outboundGate(this.ctx, () => this.real.all<T>()),\n (r) => ({ rows: r.results.length, changes: r.meta.changes ?? 0 }),\n );\n }\n\n first<T = unknown>(colName?: string): Promise<T | null> {\n return this.ctx.hooks.effect(\n point(\n this.ctx,\n this.target,\n \"first\",\n { ...(this.args() as object), column: colName ?? null } as JsonValue,\n readFaults,\n ),\n outboundGate(this.ctx, () =>\n colName === undefined ? this.real.first<T>() : this.real.first<T>(colName),\n ),\n (r) => ({ row: toJson(r) }),\n );\n }\n\n raw<T = unknown[]>(options?: { columnNames?: boolean }): Promise<T[]> {\n return this.ctx.hooks.effect(\n point(this.ctx, this.target, \"raw\", this.args(), readFaults),\n outboundGate(\n this.ctx,\n () =>\n (options\n ? this.real.raw<T>(options as { columnNames: true })\n : this.real.raw<T>()) as Promise<T[]>,\n ),\n (r) => ({ rows: r.length }),\n );\n }\n}\n\n/** Wrap a D1 binding. Methods not modelled fall through to the real binding and mark the run unsupported. */\nexport function proxyD1(real: D1Database, binding: string, ctx: ProxyContext): D1Database {\n const target = `D1:${binding}`;\n const modelled = {\n prepare(sql: string): StatementProxy {\n return new StatementProxy(real.prepare(sql), target, ctx, sql, []);\n },\n batch<T = Record<string, unknown>>(\n statements: readonly (StatementProxy | D1PreparedStatement)[],\n ): Promise<D1Result<T>[]> {\n const unwrapped = statements.map((s) => (s instanceof StatementProxy ? s.statement : s));\n const args = {\n statements: statements.map((s) =>\n s instanceof StatementProxy\n ? { sql: s.sql, params: toJson(s.params) }\n : \"<unproxied statement>\",\n ),\n };\n return ctx.hooks.effect(\n point(ctx, target, \"batch\", args, writeFaults),\n outboundGate(ctx, () => real.batch<T>(unwrapped as D1PreparedStatement[])),\n (rs) => ({\n changes: rs.reduce((n, r) => n + (r.meta.changes ?? 0), 0),\n statements: rs.length,\n }),\n );\n },\n exec(sql: string): Promise<D1ExecResult> {\n return ctx.hooks.effect(\n point(ctx, target, \"exec\", { sql }, writeFaults),\n outboundGate(ctx, () => real.exec(sql)),\n (r) => ({ count: r.count, duration: 0 }),\n );\n },\n };\n return new Proxy(real, {\n get(obj, prop, receiver) {\n if (prop in modelled) return modelled[prop as keyof typeof modelled];\n const value = Reflect.get(obj, prop, receiver) as unknown;\n if (typeof value === \"function\") {\n ctx.hooks.unsupported(`D1 ${binding}.${String(prop)} is not modelled`);\n return (value as (...a: unknown[]) => unknown).bind(obj);\n }\n return value;\n },\n }) as D1Database;\n}\n\n/**\n * Statements in a schema file. Splits on semicolons outside string literals,\n * quoted identifiers and comments, and keeps CREATE TRIGGER bodies (and CASE\n * expressions) whole by tracking BEGIN/CASE ... END nesting.\n */\nexport function splitSql(sql: string): readonly string[] {\n const out: string[] = [];\n let cur = \"\";\n let depth = 0;\n let i = 0;\n const isWordChar = (c: string | undefined): boolean => c !== undefined && /[A-Za-z0-9_]/.test(c);\n while (i < sql.length) {\n const c = sql[i] as string;\n const next = sql[i + 1];\n if (c === \"-\" && next === \"-\") {\n while (i < sql.length && sql[i] !== \"\\n\") i++;\n continue;\n }\n if (c === \"/\" && next === \"*\") {\n const end = sql.indexOf(\"*/\", i + 2);\n i = end === -1 ? sql.length : end + 2;\n // A comment separates the tokens around it (`CREATE/* c */TABLE`), as whitespace would.\n cur += \" \";\n continue;\n }\n if (c === \"'\" || c === '\"' || c === \"`\" || c === \"[\") {\n const close = c === \"[\" ? \"]\" : c;\n let j = i + 1;\n for (;;) {\n const k = sql.indexOf(close, j);\n if (k === -1) {\n j = sql.length;\n break;\n }\n if (close !== \"]\" && sql[k + 1] === close) {\n j = k + 2; // a doubled quote inside the literal\n continue;\n }\n j = k + 1;\n break;\n }\n cur += sql.slice(i, j);\n i = j;\n continue;\n }\n if (isWordChar(c) && !isWordChar(sql[i - 1])) {\n let j = i;\n while (isWordChar(sql[j])) j++;\n const word = sql.slice(i, j);\n const upper = word.toUpperCase();\n if (upper === \"BEGIN\" || upper === \"CASE\") depth++;\n else if (upper === \"END\" && depth > 0) depth--;\n cur += word;\n i = j;\n continue;\n }\n if (c === \";\" && depth === 0) {\n const statement = cur.trim();\n if (statement.length > 0) out.push(statement);\n cur = \"\";\n i++;\n continue;\n }\n cur += c;\n i++;\n }\n const last = cur.trim();\n if (last.length > 0) out.push(last);\n return out;\n}\n\n/** Drop every user table and re-apply the schema, using the real binding (not an effect). */\nexport async function resetD1(real: D1Database, schema: string): Promise<void> {\n const tables = await real\n .prepare(\n \"SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' AND name NOT LIKE '\\\\_cf\\\\_%' ESCAPE '\\\\'\",\n )\n .all<{ name: string }>();\n // Children before parents: dropping a table deletes its rows first, which SQLite's foreign key checks\n // refuse while another table's rows still reference them, and a child whose parent is already gone\n // cannot be dropped at all. Each table's parents come from PRAGMA foreign_key_list.\n const quote = (n: string): string => `\"${n.replace(/\"/g, '\"\"')}\"`;\n // Triggers first: a trigger on a table being emptied or dropped can name a table already dropped,\n // which SQLite resolves even when no row fires it.\n const triggers = await real\n .prepare(\"SELECT name FROM sqlite_master WHERE type = 'trigger'\")\n .all<{ name: string }>();\n for (const { name } of triggers.results)\n await real.prepare(`DROP TRIGGER IF EXISTS ${quote(name)}`).run();\n const parents = new Map<string, Set<string>>();\n for (const { name } of tables.results) {\n const keys = await real\n .prepare(`PRAGMA foreign_key_list(${quote(name)})`)\n .all<{ table: string }>();\n parents.set(name, new Set(keys.results.map((k) => k.table).filter((t) => t !== name)));\n }\n const left = new Set(parents.keys());\n for (;;) {\n // A table no remaining table references is a leaf: dropped now.\n const leaves = [...left].filter((t) => ![...left].some((o) => parents.get(o)?.has(t)));\n if (leaves.length === 0) break;\n for (const t of leaves) {\n await real.prepare(`DROP TABLE IF EXISTS ${quote(t)}`).run();\n left.delete(t);\n }\n }\n if (left.size > 0) {\n // Tables that reference each other in a cycle: emptied in one transaction with the checks deferred\n // to its end, when nothing references anything, then dropped.\n const cycle = [...left];\n await real.batch([\n real.prepare(\"PRAGMA defer_foreign_keys = on\"),\n ...cycle.map((t) => real.prepare(`DELETE FROM ${quote(t)}`)),\n ]);\n await real.batch([\n real.prepare(\"PRAGMA defer_foreign_keys = on\"),\n ...cycle.map((t) => real.prepare(`DROP TABLE IF EXISTS ${quote(t)}`)),\n ]);\n }\n for (const statement of splitSql(schema)) {\n await real.prepare(statement).run();\n }\n}\n\n/** Every user table's rows, sorted canonically, read through the real binding (not an effect). */\nexport async function snapshotD1(\n real: D1Database,\n): Promise<{ readonly [table: string]: readonly JsonValue[] }> {\n const tables = await real\n .prepare(\n \"SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' AND name NOT LIKE '\\\\_cf\\\\_%' ESCAPE '\\\\' ORDER BY name\",\n )\n .all<{ name: string }>();\n const out: Record<string, JsonValue[]> = {};\n for (const { name } of tables.results) {\n const rows = await real\n .prepare(`SELECT * FROM \"${name.replace(/\"/g, '\"\"')}\"`)\n .all<Record<string, unknown>>();\n out[name] = rows.results\n .map((r) => toJson(r))\n .map((j) => [canonicalJson(j), j] as const)\n .sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0))\n .map(([, j]) => j);\n }\n return out;\n}\n","/**\n * The R2 binding proxy. Every `put`, `delete`, `get`, `head` and `list` is\n * an effect point against the real Miniflare-backed bucket. A body is read\n * inside its `get`'s effect and handed back in an object with the same\n * fields and body methods: reading it later would be I/O the run cannot\n * see. An object's random `version` and wall-clock `uploaded` are replaced\n * by stand-ins (see `VersionBook`), so traces stay byte-identical. When a\n * Durable Object is the caller, the call leaves it behind its output gate\n * (`outboundGate`).\n */\n\nimport {\n type EffectPoint,\n type FaultKind,\n type JsonValue,\n readFaults,\n toJson,\n writeFaults,\n} from \"@eutaxy/core\";\nimport { outboundGate, type ProxyContext, pointAt, refuse } from \"./proxy-context.ts\";\n\n/** Whether a binding is an R2 bucket (Miniflare's `R2Bucket`). */\nexport function isR2(value: unknown): value is R2Bucket {\n if (typeof value !== \"object\" || value === null) return false;\n const v = value as Record<string, unknown>;\n return [\"head\", \"get\", \"put\", \"delete\", \"list\", \"createMultipartUpload\"].every(\n (m) => typeof v[m] === \"function\",\n );\n}\n\n/**\n * Stand-ins for the version and upload time of each object version the run\n * sees, in the order it first sees them: versions count up, and the time is\n * the virtual time it was first seen.\n */\nexport class VersionBook {\n private readonly seen = new Map<string, { version: string; uploaded: Date }>();\n\n clear(): void {\n this.seen.clear();\n }\n\n standIn(realVersion: string, at: number): { version: string; uploaded: Date } {\n let s = this.seen.get(realVersion);\n if (!s) {\n s = { version: (this.seen.size + 1).toString(16).padStart(32, \"0\"), uploaded: new Date(at) };\n this.seen.set(realVersion, s);\n }\n return { version: s.version, uploaded: new Date(s.uploaded.getTime()) };\n }\n}\n\n/** An object's metadata, with stand-ins for its version and upload time. */\nfunction metadata(real: R2Object, book: VersionBook, at: number): R2Object {\n const { version, uploaded } = book.standIn(real.version, at);\n return {\n key: real.key,\n version,\n size: real.size,\n etag: real.etag,\n httpEtag: real.httpEtag,\n uploaded,\n httpMetadata: real.httpMetadata,\n customMetadata: real.customMetadata,\n range: real.range,\n checksums: real.checksums,\n storageClass: real.storageClass,\n ssecKeyMd5: real.ssecKeyMd5,\n writeHttpMetadata: (headers: Headers) => real.writeHttpMetadata(headers),\n } as R2Object;\n}\n\n/**\n * The bytes behind each body stream the proxy hands out. The stream itself\n * has no known length, which the runtime's put requires, so a put given one\n * (copying an object) is given its bytes instead.\n */\nconst buffered = new WeakMap<ReadableStream, () => Uint8Array>();\n\n/**\n * An object with its body, already read: the stream and the body methods\n * share one consumption, as a real body's do. A method fails once the\n * stream is read, cancelled or locked by a reader; the stream ends empty\n * once a method has read the body.\n */\nfunction withBody(meta: R2Object, bytes: Uint8Array): R2ObjectBody {\n let used = false;\n let stream: ReadableStream | undefined;\n const take = (): Uint8Array => {\n if (used || stream?.locked) throw new TypeError(\"Body has already been used\");\n used = true;\n return bytes.slice();\n };\n // Defined, not assigned: Object.assign would call the getters and use the body up.\n return Object.defineProperties(meta, {\n body: {\n enumerable: true,\n get: () => {\n // Pulled only when read, so looking at the body does not use it.\n stream ??= new ReadableStream(\n {\n pull(controller) {\n if (!used) controller.enqueue(bytes.slice());\n used = true;\n controller.close();\n },\n cancel() {\n used = true;\n },\n },\n { highWaterMark: 0 },\n );\n buffered.set(stream, take);\n return stream;\n },\n },\n bodyUsed: { enumerable: true, get: () => used },\n arrayBuffer: { value: async () => take().buffer as ArrayBuffer },\n bytes: { value: async () => take() },\n text: { value: async () => new TextDecoder().decode(take()) },\n json: { value: async () => JSON.parse(new TextDecoder().decode(take())) as unknown },\n blob: { value: async () => new Blob([take()]) },\n }) as unknown as R2ObjectBody;\n}\n\n/** Conditions as the trace keeps them: a `Headers` object by its entries. */\nfunction conditions(onlyIf: unknown): { onlyIf?: unknown } {\n if (onlyIf === undefined) return {};\n return { onlyIf: onlyIf instanceof Headers ? Object.fromEntries(onlyIf.entries()) : onlyIf };\n}\n\n/** What the trace keeps of a get's options: the conditions and range, never an encryption key. */\nfunction getArgs(key: string, options: R2GetOptions | undefined): JsonValue {\n return toJson({\n key,\n ...conditions(options?.onlyIf),\n ...(options?.range === undefined ? {} : { range: options.range }),\n });\n}\n\n/** What the trace keeps of a put's options: the conditions and metadata, not checksums or keys. */\nfunction putArgs(options: R2PutOptions | undefined): JsonValue {\n if (!options) return {};\n return toJson({\n ...conditions(options.onlyIf),\n ...(options.customMetadata === undefined ? {} : { customMetadata: options.customMetadata }),\n ...(options.httpMetadata === undefined ? {} : { httpMetadata: options.httpMetadata }),\n });\n}\n\nexport function proxyR2(\n real: R2Bucket,\n binding: string,\n ctx: ProxyContext,\n book: VersionBook,\n): R2Bucket {\n const target = `R2:${binding}`;\n const point = (op: string, args: JsonValue, allowed: readonly FaultKind[]): EffectPoint =>\n pointAt(ctx, target, op, args, allowed);\n const notModelled = (what: string): never =>\n refuse(ctx, `R2 ${binding}: ${what} is not modelled`);\n /** Date conditions compare the store's real upload time, not the stand-in the Worker saw. */\n const checkConditions = (onlyIf: unknown): void => {\n const datedHeaders = [\"if-modified-since\", \"if-unmodified-since\"];\n const dated =\n onlyIf instanceof Headers\n ? datedHeaders.some((h) => onlyIf.has(h))\n : typeof onlyIf === \"object\" &&\n onlyIf !== null &&\n (\"uploadedBefore\" in onlyIf || \"uploadedAfter\" in onlyIf);\n if (dated)\n ctx.hooks.unsupported(`R2 ${binding}: conditions on the upload time are not modelled`);\n };\n const described = (o: R2Object | null) =>\n o === null ? { found: false } : { found: true, key: o.key, size: o.size, etag: o.etag };\n return {\n put: (key: string, value: unknown, options?: R2PutOptions) =>\n ctx.hooks.effect(\n point(\"put\", { key, ...(putArgs(options) as object) }, writeFaults),\n outboundGate(ctx, async () => {\n checkConditions(options?.onlyIf);\n const read = value instanceof ReadableStream ? buffered.get(value) : undefined;\n const stored = await real.put(key, (read ? read() : value) as never, options);\n return stored === null ? null : metadata(stored, book, Date.now());\n }),\n (o) => (o === null ? { stored: false } : { stored: true, size: o.size, etag: o.etag }),\n ),\n delete: (keys: string | string[]) =>\n ctx.hooks.effect(\n point(\"delete\", { keys: typeof keys === \"string\" ? [keys] : [...keys] }, writeFaults),\n outboundGate(ctx, () => real.delete(keys)),\n () => null,\n ),\n get: (key: string, options?: R2GetOptions) =>\n ctx.hooks.effect(\n point(\"get\", getArgs(key, options), readFaults),\n outboundGate(ctx, async () => {\n checkConditions(options?.onlyIf);\n const o = await real.get(key, options);\n if (o === null) return null;\n const meta = metadata(o, book, Date.now());\n // A failed precondition answers the metadata without a body.\n if (!(\"body\" in o)) return meta;\n return withBody(meta, new Uint8Array(await (o as R2ObjectBody).arrayBuffer()));\n }),\n (o) => ({ ...described(o), ...(o !== null ? { body: \"body\" in o } : {}) }),\n ),\n head: (key: string) =>\n ctx.hooks.effect(\n point(\"head\", { key }, readFaults),\n outboundGate(ctx, async () => {\n const o = await real.head(key);\n return o === null ? null : metadata(o, book, Date.now());\n }),\n described,\n ),\n list: (options?: R2ListOptions) =>\n ctx.hooks.effect(\n point(\"list\", toJson(options ?? {}), readFaults),\n outboundGate(ctx, async () => {\n const listed = await real.list(options);\n const at = Date.now();\n return { ...listed, objects: listed.objects.map((o) => metadata(o, book, at)) };\n }),\n (l) => ({\n keys: l.objects.map((o) => o.key),\n truncated: l.truncated,\n delimitedPrefixes: l.delimitedPrefixes,\n }),\n ),\n createMultipartUpload: () => notModelled(\"createMultipartUpload()\"),\n resumeMultipartUpload: () => notModelled(\"resumeMultipartUpload()\"),\n } as unknown as R2Bucket;\n}\n\n/** An object a setup seeds: its text, or its text with metadata. */\nexport type R2Seed =\n | string\n | {\n readonly value: string;\n readonly customMetadata?: Readonly<Record<string, string>>;\n readonly httpMetadata?: Readonly<Record<string, string>>;\n };\n\n/** Every object of the bucket, through all pages of a listing. */\nasync function allObjects(real: R2Bucket): Promise<R2Object[]> {\n const out: R2Object[] = [];\n let cursor: string | undefined;\n for (;;) {\n const page: R2Objects = await real.list({\n include: [\"customMetadata\", \"httpMetadata\"],\n ...(cursor === undefined ? {} : { cursor }),\n });\n out.push(...page.objects);\n if (!page.truncated) return out;\n cursor = page.cursor;\n }\n}\n\n/** Empty the bucket and put its seeds, before a run. */\nexport async function resetR2(\n real: R2Bucket,\n seeds: Readonly<Record<string, R2Seed>>,\n): Promise<void> {\n const keys = (await allObjects(real)).map((o) => o.key);\n for (let i = 0; i < keys.length; i += 1000) await real.delete(keys.slice(i, i + 1000));\n for (const [key, seed] of Object.entries(seeds)) {\n if (typeof seed === \"string\") await real.put(key, seed);\n else\n await real.put(key, seed.value, {\n ...(seed.customMetadata ? { customMetadata: { ...seed.customMetadata } } : {}),\n ...(seed.httpMetadata ? { httpMetadata: { ...seed.httpMetadata } } : {}),\n });\n }\n}\n\n/** Largest object whose text the snapshot keeps. */\nconst snapshotTextLimit = 4096;\n\n/**\n * The bucket's objects as rows `{ key, size, etag, customMetadata,\n * httpMetadata, text? }` by key, `text` for an object of up to 4 KiB that is\n * valid UTF-8. Versions and upload times are left out: they are the store's,\n * not the Worker's.\n */\nexport async function snapshotR2(real: R2Bucket): Promise<JsonValue[]> {\n const rows: JsonValue[] = [];\n const objects = (await allObjects(real)).sort((a, b) =>\n a.key < b.key ? -1 : a.key > b.key ? 1 : 0,\n );\n for (const o of objects) {\n let text: string | undefined;\n if (o.size <= snapshotTextLimit) {\n const body = await real.get(o.key);\n if (body && \"body\" in body) {\n try {\n text = new TextDecoder(\"utf-8\", { fatal: true, ignoreBOM: false }).decode(\n await body.arrayBuffer(),\n );\n } catch {\n // not text: the size and etag stand for it\n }\n }\n }\n rows.push(\n toJson({\n key: o.key,\n size: o.size,\n etag: o.etag,\n customMetadata: o.customMetadata ?? {},\n httpMetadata: o.httpMetadata ?? {},\n ...(text === undefined ? {} : { text }),\n }),\n );\n }\n return rows;\n}\n","/**\n * Service bindings with the callee scripted. A Worker reaches a peer through\n * `env.BINDING`, by RPC method or by `fetch()`; Cloudflare routes the call on\n * the same thread and retries nothing (Workers, service bindings). The real\n * binding is never called here: the scenario's `service()` setup scripts the\n * replies, and each call is one effect with the faults of a Durable Object\n * stub call, where `crash_before` and `error` mean the call never reached\n * the callee, `ambiguous` that it acted and the answer was lost, and\n * `crash_after` that the caller died after it. The stub itself (callable\n * methods, awaited properties, `fetch`, the pipelining guards) is shared\n * with the callee that runs for real (`callees.ts`).\n */\n\nimport { type EffectPoint, type JsonValue, toJson, writeFaults } from \"@eutaxy/core\";\nimport { findResponse, isRedirect, parseBody, replyOf, toResponse } from \"@eutaxy/engine\";\nimport { outboundGate, type ProxyContext, pointAt, refuse } from \"./proxy-context.ts\";\nimport type { ScriptedReply, ServiceSetup } from \"./scenario.ts\";\n\n/** Marks of the other kinds of binding, which a service binding's duck type must not carry. */\nconst otherKinds = [\"prepare\", \"idFromName\", \"head\", \"createBatch\"];\n\n/**\n * Whether an env value is a service binding (the runtime's `Fetcher`). In\n * workerd it is an RPC stub whose every property read yields a callable, so\n * duck typing alone would take it for any other kind: the runtime's class is\n * checked first, and the duck type (fetch and connect, none of the other\n * kinds' marks) serves test doubles.\n */\nexport function isServiceBinding(value: unknown): value is object {\n if (typeof value !== \"object\" || value === null) return false;\n const fetcher = (globalThis as { Fetcher?: unknown }).Fetcher;\n if (typeof fetcher === \"function\" && value instanceof fetcher) return true;\n const ctor = Object.getPrototypeOf(value)?.constructor as { name?: string } | undefined;\n if (ctor?.name === \"Fetcher\") return true;\n const v = value as Record<string, unknown>;\n return (\n typeof v[\"fetch\"] === \"function\" &&\n typeof v[\"connect\"] === \"function\" &&\n otherKinds.every((k) => typeof v[k] !== \"function\")\n );\n}\n\n/** The built-in error classes RPC carries across as themselves (workerd keeps the type). */\nconst builtInErrors: { readonly [name: string]: new (message: string) => Error } = {\n Error,\n EvalError,\n RangeError,\n ReferenceError,\n SyntaxError,\n TypeError,\n URIError,\n};\n\n/**\n * The error the caller sees for a `throws` reply, `\"<Name>: <message>\"`: a\n * built-in error class is that class, so `instanceof` holds as it does over\n * RPC; any other name is an `Error` carrying the name.\n */\nexport function scriptedError(spec: string): Error {\n const at = spec.indexOf(\": \");\n if (at < 0) return new Error(spec);\n const name = spec.slice(0, at);\n const message = spec.slice(at + 2);\n const builtIn = builtInErrors[name];\n if (builtIn) return new builtIn(message);\n const error = new Error(message);\n error.name = name;\n return error;\n}\n\n/** A request through the binding as the effect log records it. */\nexport interface RequestRecord {\n readonly url: string;\n readonly method: string;\n readonly headers: Record<string, string>;\n readonly body: JsonValue;\n}\n\n/** Read a request for the log without consuming it: the callee may still read the body. */\nexport async function recordRequest(request: Request): Promise<RequestRecord> {\n const method = request.method.toUpperCase();\n const headers: Record<string, string> = {};\n request.headers.forEach((value, name) => {\n headers[name.toLowerCase()] = value;\n });\n const body = parseBody(await request.clone().text());\n return { url: request.url, method, headers, body };\n}\n\n/** What answers the calls a stub receives; each answer performs its own effect. */\nexport interface ServiceAnswers {\n /** `stub.method(...args)`. */\n call(method: string, args: readonly unknown[]): Promise<unknown>;\n /** `await stub.property` (an RPC getter). */\n property(method: string): Promise<unknown>;\n /** `stub.fetch(...)`. */\n fetch(request: Request): Promise<Response>;\n}\n\n/**\n * The stub a Worker sees under a service binding's name: methods callable\n * and awaitable, `fetch`, and the guards against what is not modelled\n * (promise pipelining, `connect()`), with the answers supplied. A scripted\n * Durable Object's stub is the same thing under its own name (`what`) with\n * members of its own (`own`: its `id` and `name`).\n */\nexport function serviceStub(\n binding: string,\n ctx: ProxyContext,\n answers: ServiceAnswers,\n what = `service binding ${binding}`,\n own: Readonly<Record<string, unknown>> = {},\n): object {\n const unsupported = (reason: string): never => refuse(ctx, `${what}: ${reason}`);\n\n /**\n * The promise a call returns. On the real stub it is an RPC promise that\n * pipelines property reads (`stub.charge().id`); this one is not, so a read\n * on it makes the run UNSUPPORTED instead of yielding undefined.\n */\n const pipelineGuard = <T>(promise: Promise<T>, method: string): Promise<T> =>\n new Proxy(promise, {\n get(target, prop) {\n if (typeof prop === \"symbol\" || prop === \"then\" || prop === \"catch\" || prop === \"finally\") {\n const value = Reflect.get(target, prop, target);\n return typeof value === \"function\" ? value.bind(target) : value;\n }\n ctx.hooks.unsupported(\n `${what}: RPC promise pipelining (reading .${prop} on ${method}()'s promise) is not supported; await the call first`,\n );\n return undefined;\n },\n });\n\n /** One call: `stub.method(...)`, or `await stub.property` (an RPC getter). */\n const call = (method: string) => {\n const invoke = (...args: unknown[]) => pipelineGuard(answers.call(method, args), method);\n const awaitable = (\n onFulfilled?: (v: unknown) => unknown,\n onRejected?: (e: unknown) => unknown,\n ) => answers.property(method).then(onFulfilled, onRejected);\n // Callable and awaitable; any other property read is pipelining, which is not modelled.\n return new Proxy(invoke, {\n get(fn, key) {\n if (key === \"then\") return awaitable;\n if (typeof key === \"symbol\") return Reflect.get(fn, key);\n ctx.hooks.unsupported(\n `${what}: RPC promise pipelining (reading .${method}.${key}) is not supported; await .${method} first`,\n );\n return undefined;\n },\n });\n };\n\n // Async, so a request that cannot be built (an invalid URL) rejects as fetch() does, never throws.\n const fetchThrough = async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> =>\n answers.fetch(new Request(input, init));\n\n return new Proxy(\n {},\n {\n get(_stub, prop) {\n // The stub is not a promise.\n if (prop === \"then\" || typeof prop === \"symbol\") return undefined;\n if (Object.hasOwn(own, prop)) return own[prop];\n if (prop === \"fetch\") return fetchThrough;\n if (prop === \"connect\")\n return () => unsupported(\"connect() (a raw TCP socket) is not modelled\");\n return call(prop);\n },\n },\n );\n}\n\n/** The scripted stub a Worker sees under a service binding's name. */\nexport function proxyService(binding: string, ctx: ProxyContext, script: ServiceSetup): object {\n const target = `Service:${binding}`;\n const point = (op: string, args: JsonValue): EffectPoint =>\n pointAt(ctx, target, op, args, writeFaults);\n const unsupported = (what: string): never => refuse(ctx, `service binding ${binding}: ${what}`);\n /** The scripted reply to a method, by name; a method the script lacks cannot be answered. */\n const replyTo = (method: string): ScriptedReply => {\n if (script.methods === undefined) return { returns: null };\n if (!Object.hasOwn(script.methods, method))\n return unsupported(\n `no scripted reply for method ${method}; add it to the service(${JSON.stringify(binding)}) setup's methods`,\n );\n return script.methods[method] as ScriptedReply;\n };\n const answer = (method: string): unknown => {\n const reply = replyTo(method);\n if (\"throws\" in reply) throw scriptedError(reply.throws);\n // Copied, as RPC copies values: the Worker cannot change the script.\n return structuredClone(reply.returns);\n };\n const summarize = (value: unknown): JsonValue => ({ value: toJson(value) });\n\n return serviceStub(binding, ctx, {\n call: (method, args) =>\n ctx.hooks.effect(\n point(method, { args: args.map((a) => toJson(a)) }),\n outboundGate(ctx, async () => answer(method)),\n summarize,\n ),\n property: (method) =>\n ctx.hooks.effect(\n point(method, { property: true }),\n outboundGate(ctx, async () => answer(method)),\n summarize,\n ),\n async fetch(request) {\n // Taken where the call starts, before anything is awaited: an object's gate, when one is calling.\n const behind = outboundGate(ctx, async () => undefined);\n const url = new URL(request.url);\n const { method, headers, body } = await recordRequest(request);\n const reply = await ctx.hooks.effect(\n point(method, { url: request.url, method, headers, body }),\n async () => {\n await behind();\n // The matcher is the externals'; a service binding takes any host, so none is matched.\n const found = findResponse(\n {\n name: binding,\n host: url.host,\n guarantees: {},\n ...(script.fetch === undefined ? {} : { responses: script.fetch }),\n },\n method,\n url.pathname,\n );\n if (found === undefined)\n return unsupported(\n `no scripted reply for fetch ${method} ${url.pathname}; add it to the service(${JSON.stringify(binding)}) setup's fetch`,\n );\n const reply = replyOf(found);\n // workerd follows a redirect from the callee as fetch does; the script holds only the first reply.\n if (isRedirect(reply.status) && request.redirect !== \"manual\")\n return unsupported(\n `the scripted reply to ${method} ${url.pathname} is a ${reply.status} redirect, which the runtime would follow; script the final reply or fetch with redirect: \"manual\"`,\n );\n return reply;\n },\n (r) => ({ status: r.status }),\n );\n return toResponse(reply);\n },\n });\n}\n","/**\n * Constructing an entrypoint class (`WorkerEntrypoint`, `WorkflowEntrypoint`)\n * outside the runtime, for the one `new` per call or instance run that the\n * models make themselves.\n */\n\n/** Sets `ctx` and `env` as the runtime's base classes do, for the one `new` workerd would refuse. */\nclass StandInEntrypoint {\n readonly ctx: unknown;\n readonly env: unknown;\n constructor(ctx: unknown, env: unknown) {\n this.ctx = ctx;\n this.env = env;\n }\n}\n\n/**\n * Construct a subclass of the entrypoint base class named `base`. workerd's\n * base constructors accept only a native ExecutionContext, so for this one\n * synchronous `new` the class that extends the base directly extends a\n * stand-in instead; its own constructor and field initialisers run as\n * written, and the base is put back before anything else can run.\n */\nexport function constructEntrypoint(\n cls: unknown,\n base: \"WorkerEntrypoint\" | \"WorkflowEntrypoint\",\n ctx: unknown,\n env: unknown,\n): object {\n if (typeof cls !== \"function\") throw new TypeError(\"not a class\");\n let direct = cls as object;\n for (;;) {\n const parent = Object.getPrototypeOf(direct) as unknown;\n if (typeof parent !== \"function\" || parent === Function.prototype)\n throw new TypeError(`${(cls as { name: string }).name} does not extend ${base}`);\n if ((parent as { name: string }).name === base) break;\n direct = parent;\n }\n const original = Object.getPrototypeOf(direct) as object;\n Object.setPrototypeOf(direct, StandInEntrypoint);\n try {\n return Reflect.construct(cls as new (...a: unknown[]) => object, [ctx, env]);\n } finally {\n Object.setPrototypeOf(direct, original);\n }\n}\n\n/**\n * The handler object a `WorkerEntrypoint` class stands for when it is the Worker's default export: each\n * of `fetch`, `queue` and `scheduled` the class defines constructs it anew with the invocation's env and\n * ctx, as workerd does per event, and calls the method with the event alone (its env and ctx are on the\n * instance) (developers.cloudflare.com/workers/runtime-apis/bindings/service-bindings/rpc/).\n */\nexport function entrypointHandler(cls: unknown): {\n readonly [handler in \"fetch\" | \"queue\" | \"scheduled\"]?: (\n event: never,\n env: unknown,\n ctx: unknown,\n ) => unknown;\n} {\n const proto = (typeof cls === \"function\" ? cls.prototype : undefined) as\n | Record<string, unknown>\n | undefined;\n const out: Record<string, (event: never, env: unknown, ctx: unknown) => unknown> = {};\n for (const name of [\"fetch\", \"queue\", \"scheduled\"] as const)\n if (typeof proto?.[name] === \"function\")\n out[name] = (event, env, ctx) => {\n const instance = constructEntrypoint(cls, \"WorkerEntrypoint\", ctx, env) as Record<\n string,\n (event: unknown) => unknown\n >;\n return (instance[name] as (event: unknown) => unknown).call(instance, event);\n };\n return out;\n}\n","/**\n * Workflows, modelled: the binding's `create`/`get`, and each instance run\n * as invocations of its class's `run(event, step)` against a model of the\n * engine (persisted step results, retries in virtual time, restarts that\n * re-run `run` from the start). The real local engine is never called: it\n * runs on its own real-time clock and retry loop, which Eutaxy can neither\n * fault nor schedule. See docs/design.md, \"Workflows\".\n */\n\nimport {\n type DeliveryResult,\n type EventRef,\n type FaultKind,\n invocationOf,\n type JsonValue,\n type RunHooks,\n toJson,\n writeFaults,\n} from \"@eutaxy/core\";\nimport {\n CrashSignal,\n InjectedEffectError,\n note,\n type Outcome as RunOutcome,\n runInvocation,\n} from \"@eutaxy/engine\";\nimport { drainBackground, executionContext } from \"./background.ts\";\nimport { constructEntrypoint } from \"./entrypoint.ts\";\nimport { outboundGate, type ProxyContext, refuse } from \"./proxy-context.ts\";\n\n/** The `EventRef.source` of a Workflow instance's run. */\nexport const workflowSource = \"workflow\";\n\n/**\n * Before a step's callback: the engine restarts before the step runs\n * (`crash_before`), or the attempt outlives its timeout from its start\n * (`ambiguous`): counted as failed and retried while it runs on late.\n */\nconst STEP_START: readonly FaultKind[] = [\"crash_before\", \"ambiguous\"];\n/**\n * After it: the engine restarts after the step ran but before its result\n * was persisted (`crash_after`), or the attempt ran and counted as failed,\n * as a timeout just after its work does (`ambiguous`).\n */\nconst STEP_RESULT: readonly FaultKind[] = [\"crash_after\", \"ambiguous\"];\n\n/**\n * Cloudflare's defaults for a step without a config (Workflows, Sleeping\n * and retrying). A partial config is merged with them field by field, as\n * the engine does. Miniflare's local engine waits 1 s by default; the\n * model keeps the documented 10 s.\n */\nconst defaultRetries = { limit: 5, delay: 10_000, backoff: \"exponential\" } as const;\n\n/**\n * A persisted step result; a failure is kept as the engine keeps it, serialised\n * (built-in types survive; a custom error name does not survive the clone, so\n * it is kept beside and put back on replay).\n */\ntype Outcome =\n | { readonly ok: true; readonly value: unknown }\n | { readonly ok: false; readonly error: unknown; readonly errorName?: string };\n\n/** Keep a thrown value as the engine keeps it, with an Error's name, which the clone would lose. */\nfunction failure(thrown: unknown): Outcome {\n let kept: unknown;\n try {\n kept = structuredClone(thrown);\n } catch {\n kept = new Error(String(thrown));\n }\n return thrown instanceof Error\n ? { ok: false, error: kept, errorName: thrown.name }\n : { ok: false, error: kept };\n}\n\n/** An event sent to an instance, as `waitForEvent` returns it. */\nexport interface InstanceEvent {\n readonly type: string;\n readonly payload: unknown;\n readonly timestamp: Date;\n}\n\nexport interface Instance {\n readonly id: string;\n readonly params: unknown;\n readonly createdAt: number;\n /** The engine's statuses the model reaches; `waiting` while a wait for an event is pending. */\n status: \"queued\" | \"running\" | \"waiting\" | \"complete\" | \"errored\";\n /** Events sent and not yet consumed by a wait, in order, per type (the engine's buffer). */\n readonly events: Map<string, InstanceEvent[]>;\n /**\n * The pending wait, while the instance is `waiting`: its type, its generation, which a wake\n * must match, and whether an event already woke it (a second event is buffered, not a second wake).\n */\n waiting: { readonly type: string; readonly gen: number; woken: boolean } | undefined;\n /** Generations of waits so far, so a stale wake (the timeout of a wait an event ended) is told apart. */\n waitGen: number;\n /** What `run` returned, as the engine keeps it; summarised only where it is recorded. */\n output?: unknown;\n error?: { readonly name: string; readonly message: string };\n /** Persisted step and sleep results, by name and count: what a restart replays. */\n readonly persisted: Map<string, Outcome>;\n /** Attempts started per step, persisted as the engine does, so a restart goes on counting. */\n readonly attempts: Map<string, number>;\n /** Each step's config as its first attempt resolved it; a restart reuses it, as the engine does. */\n readonly configs: Map<\n string,\n { readonly retries: ResolvedRetries; readonly timeout: unknown; readonly sensitive?: string }\n >;\n /** Each pending sleep's or retry's deadline, persisted before it waits, so a restart waits only the rest. */\n readonly deadlines: Map<string, number>;\n}\n\n/** One binding's instances in the current run. */\nexport class WorkflowRegistry {\n readonly instances = new Map<string, Instance>();\n\n clear(): void {\n this.instances.clear();\n }\n\n /** The instances as rows for the end-of-run snapshot, by id. */\n rows(): JsonValue[] {\n return [...this.instances.values()]\n .sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0))\n .map((i) => ({\n id: i.id,\n status: i.status,\n params: toJson(i.params),\n ...(i.output === undefined ? {} : { output: toJson(i.output) }),\n ...(i.error === undefined ? {} : { error: `${i.error.name}: ${i.error.message}` }),\n }));\n }\n}\n\n/** A Workflow binding as the env shows it (Miniflare's `WorkflowImpl`). */\nexport function isWorkflowBinding(value: unknown): value is object {\n if (typeof value !== \"object\" || value === null) return false;\n const v = value as Record<string, unknown>;\n return (\n typeof v[\"create\"] === \"function\" &&\n typeof v[\"createBatch\"] === \"function\" &&\n typeof v[\"get\"] === \"function\"\n );\n}\n\ninterface CreateOptions {\n readonly id?: string;\n readonly params?: unknown;\n}\n\n/**\n * The binding's proxy: instances live in the registry and run as events,\n * never in the real engine. A call an object makes waits behind its output\n * gate (`outboundGate`).\n */\nexport function proxyWorkflow(\n binding: string,\n ctx: ProxyContext,\n registry: WorkflowRegistry,\n): object {\n const target = `Workflow:${binding}`;\n const unsupported = (what: string): never =>\n refuse(ctx, `Workflow ${binding}: ${what} is not modelled`);\n const handle = (id: string): object => ({\n id,\n status: () =>\n ctx.hooks.effect(\n { invocation: ctx.currentInvocation(), target, op: \"status\", args: { id }, allowed: [] },\n outboundGate(ctx, async () => {\n const i = registry.instances.get(id);\n if (!i) throw new Error(\"instance.not_found\");\n return {\n status: i.status,\n // A copy, as the binding's serialised answer is: the caller cannot change the instance.\n // The binding answers null when there is no output yet, or run() returned nothing.\n output: i.output === undefined ? null : structuredClone(i.output),\n ...(i.error === undefined ? {} : { error: { ...i.error } }),\n };\n }),\n (s) => toJson(s),\n ),\n pause: () => unsupported(\"pause()\"),\n resume: () => unsupported(\"resume()\"),\n terminate: () => unsupported(\"terminate()\"),\n restart: () => unsupported(\"restart()\"),\n sendEvent: (args: { readonly type?: unknown; readonly payload?: unknown } = {}) =>\n ctx.hooks.effect(\n {\n invocation: ctx.currentInvocation(),\n target,\n op: \"send_event\",\n args: { id, type: toJson(args.type), payload: toJson(args.payload) },\n // A call to the engine: it may never arrive, or arrive with its answer lost.\n allowed: writeFaults,\n },\n outboundGate(ctx, async () => {\n const type = validEventType(args.type);\n const i = registry.instances.get(id);\n if (!i) throw new Error(\"instance.not_found\");\n if (i.status === \"complete\" || i.status === \"errored\")\n throw new Error(\n `(instance.not_running) Workflow instance with id \"${id}\" is ${i.status} and takes no events`,\n );\n const event: InstanceEvent = {\n type,\n payload: structuredClone(args.payload),\n timestamp: new Date(),\n };\n const queue = i.events.get(type) ?? [];\n queue.push(event);\n i.events.set(type, queue);\n // A wait for this type is pending: wake the instance once; its timeout wake becomes stale.\n if (i.status === \"waiting\" && i.waiting?.type === type && !i.waiting.woken) {\n i.waiting.woken = true;\n ctx.hooks.enqueue({\n id: `workflow:${binding}:${id}:event-${i.waiting.gen}`,\n attempt: 1,\n source: workflowSource,\n data: { binding, id, wake: i.waiting.gen },\n });\n }\n return null;\n }),\n () => null,\n ),\n delete: () => unsupported(\"delete()\"),\n subscribe: () => unsupported(\"subscribe()\"),\n });\n return {\n async create(options: CreateOptions = {}) {\n // Generated with the run's virtual randomness, before the call, as the binding does locally.\n const id = options.id ?? crypto.randomUUID();\n // The binding's own default (Miniflare): no params is an empty object; null stays null.\n const params = structuredClone(options.params === undefined ? {} : options.params);\n return ctx.hooks.effect(\n {\n invocation: ctx.currentInvocation(),\n target,\n op: \"create\",\n args: { id, params: toJson(params) },\n // A call to the engine: it may never arrive, or arrive with its answer lost.\n allowed: writeFaults,\n },\n outboundGate(ctx, async () => {\n if (!validInstanceId(id)) throw new Error(\"Workflow instance has invalid id\");\n if (registry.instances.has(id))\n throw new Error(\n `(instance.already_exists) Workflow instance with id \"${id}\" already exists`,\n );\n registry.instances.set(id, {\n id,\n params,\n createdAt: Date.now(),\n status: \"queued\",\n events: new Map(),\n waiting: undefined,\n waitGen: 0,\n persisted: new Map(),\n attempts: new Map(),\n configs: new Map(),\n deadlines: new Map(),\n });\n ctx.hooks.enqueue({\n id: `workflow:${binding}:${id}`,\n attempt: 1,\n source: workflowSource,\n data: { binding, id },\n });\n return handle(id);\n }),\n () => ({ id }),\n );\n },\n async get(id: string) {\n return ctx.hooks.effect(\n { invocation: ctx.currentInvocation(), target, op: \"get\", args: { id }, allowed: [] },\n outboundGate(ctx, async () => {\n if (!registry.instances.has(id)) throw new Error(\"instance.not_found\");\n return handle(id);\n }),\n () => ({ id }),\n );\n },\n createBatch: () => unsupported(\"createBatch()\"),\n deleteBatch: () => unsupported(\"deleteBatch()\"),\n };\n}\n\n/** The binding's rule for an instance id (Miniflare): up to 100 of these characters. */\nfunction validInstanceId(id: unknown): boolean {\n return typeof id === \"string\" && id.length <= 100 && /^[a-zA-Z0-9_][a-zA-Z0-9-_]*$/.test(id);\n}\n\n/** An event type as Workflows accept it (Events and parameters): up to 100 of these characters, else `workflow.invalid_event_type`. */\nfunction validEventType(type: unknown): string {\n if (typeof type === \"string\" && type.length <= 100 && /^[a-zA-Z0-9_][a-zA-Z0-9-_]*$/.test(type))\n return type;\n throw new Error(\n `(workflow.invalid_event_type) event type must be up to 100 letters, digits, - or _, got ${JSON.stringify(type)}`,\n );\n}\n\n/**\n * A promise that never settles: what a step call gives once its instance hibernated. The engine stops a\n * waiting instance's code where it is, so nothing after the wait runs, caught or not, until a wake re-runs\n * `run()` from the start.\n */\nconst hibernated = <T>(): Promise<T> => new Promise<T>(() => {});\n\n/** A wake event's data: which wait's generation it ends. */\ninterface WakeData {\n readonly binding: string;\n readonly id: string;\n readonly wake?: number;\n}\n\n/**\n * Whether a run event wakes the instance: not a wake at all, the restart of a\n * run a wake began (its first delivery resumed the instance), or the wake of\n * the wait still pending.\n */\nexport function wakes(instance: Instance, event: EventRef): boolean {\n const wake = (event.data as unknown as WakeData).wake;\n if (wake === undefined || event.attempt > 1) return true;\n return instance.status === \"waiting\" && instance.waiting?.gen === wake;\n}\n\n/** Construct a `WorkflowEntrypoint` subclass outside the runtime, for the one `new` per instance run. */\nexport function constructWorkflow(cls: unknown, ctx: unknown, env: unknown): object {\n return constructEntrypoint(cls, \"WorkflowEntrypoint\", ctx, env);\n}\n\n/** The engine's conversion (itty-time): a year is 365.25 days, a month 30; an unknown unit counts 1. */\nconst units: { readonly [unit: string]: number } = {\n year: 31_557_600_000,\n month: 2_592_000_000,\n week: 604_800_000,\n day: 86_400_000,\n hour: 3_600_000,\n minute: 60_000,\n second: 1000,\n m: 1,\n};\n\n/** The engine's reading of a duration, NaN where it reads none. */\nfunction engineDuration(d: unknown): number {\n if (!Number.isNaN(Number(d)) && typeof d !== \"object\") return Number(d);\n if (typeof d !== \"string\") return Number.NaN;\n const m = /^([^ ]+) +(\\w\\w*?)s?$/.exec(d);\n if (!m) return Number.NaN;\n return Number(m[1]) * (units[m[2] as string] ?? 1);\n}\n\n/** A Workflows duration in milliseconds, read as the engine reads it. */\nexport function durationMs(d: unknown): number {\n const ms = engineDuration(d);\n if (Number.isNaN(ms) || ms < 0) throw new TypeError(`not a Workflows duration: ${String(d)}`);\n return ms;\n}\n\n/** Miniflare's `isValidStepConfig`, exactly: its schema is strict, and a timeout `== 0` is refused. */\nexport function validStepConfig(config: unknown): boolean {\n const only = (o: object, keys: readonly string[]) =>\n Object.keys(o).every((k) => keys.includes(k));\n const durationOk = (v: unknown) => !Number.isNaN(engineDuration(v));\n if (\n typeof config !== \"object\" ||\n config === null ||\n !only(config, [\"retries\", \"timeout\", \"sensitive\"])\n )\n return false;\n const c = config as Record<string, unknown>;\n const r = c[\"retries\"] as Record<string, unknown> | undefined;\n if (r !== undefined) {\n if (typeof r !== \"object\" || r === null || !only(r, [\"delay\", \"limit\", \"backoff\"]))\n return false;\n const delay = r[\"delay\"];\n if (\n !(\n typeof delay === \"function\" ||\n typeof delay === \"string\" ||\n (typeof delay === \"number\" && delay >= 0)\n )\n )\n return false;\n if (typeof r[\"limit\"] !== \"number\" || r[\"limit\"] < 0) return false;\n if (\n r[\"backoff\"] !== undefined &&\n ![\"constant\", \"linear\", \"exponential\"].includes(r[\"backoff\"] as string)\n )\n return false;\n if (typeof delay !== \"function\" && !durationOk(delay)) return false;\n }\n const t = c[\"timeout\"];\n if (t !== undefined) {\n if (!(typeof t === \"string\" || (typeof t === \"number\" && t >= 0))) return false;\n // biome-ignore lint/suspicious/noDoubleEquals: the engine's own loose test (\"0\" and \"\" are zero)\n if (t == 0 || !durationOk(t)) return false;\n }\n if (c[\"sensitive\"] !== undefined && c[\"sensitive\"] !== \"output\") return false;\n return true;\n}\n\nconst utf8 = new TextEncoder();\n\n/** About how many bytes a value takes stored, walking it as structured cloning does. */\nfunction approximateBytes(value: unknown, seen = new Set<object>()): number {\n if (value === null || value === undefined) return 1;\n switch (typeof value) {\n case \"string\":\n return utf8.encode(value).length;\n case \"number\":\n case \"bigint\":\n return 8;\n case \"boolean\":\n return 1;\n case \"object\":\n break;\n default:\n return 0;\n }\n const o = value as object;\n if (seen.has(o)) return 0;\n seen.add(o);\n if (o instanceof ArrayBuffer || ArrayBuffer.isView(o)) return o.byteLength;\n if (o instanceof Date) return 8;\n let total = 0;\n if (o instanceof Map)\n for (const [k, v] of o) total += approximateBytes(k, seen) + approximateBytes(v, seen);\n else if (o instanceof Set) for (const v of o) total += approximateBytes(v, seen);\n else\n for (const [k, v] of Object.entries(o))\n total += utf8.encode(k).length + approximateBytes(v, seen);\n return total;\n}\n\nfunction sleep(ms: number): Promise<void> {\n // The virtual setTimeout: the run fires it when the invocation is idle.\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\ninterface ResolvedRetries {\n readonly limit: number;\n readonly delay: unknown;\n readonly backoff?: string;\n}\n\ninterface StepConfig {\n readonly retries?: { readonly limit: number; readonly delay: unknown; readonly backoff?: string };\n readonly timeout?: unknown;\n /** \"output\": the step's output is redacted in the engine's logs, here in the trace. */\n readonly sensitive?: string;\n}\n\ninterface RunDelivery {\n readonly binding: string;\n /** The Workflow's configured name, for `event.workflowName`. */\n readonly name?: string;\n readonly instance: Instance;\n readonly cls: unknown;\n /** The env the instance sees: the proxied bindings. */\n readonly env: object;\n readonly maxFaultsPerRun: number;\n readonly maxRedeliveries: number;\n}\n\n/**\n * One engine attempt of an instance: construct its class and call `run`.\n * Steps whose results were persisted return them without running; a crash\n * restarts the instance (a new attempt, from the start of `run`).\n */\nexport async function deliverWorkflow(\n event: EventRef,\n hooks: RunHooks,\n d: RunDelivery,\n): Promise<DeliveryResult> {\n const invocation = invocationOf(event);\n const inv = hooks.startInvocation(invocation);\n const target = `Workflow:${d.binding}`;\n const instance = d.instance;\n // A wake of a wait that already ended (an event came before the timeout, or the reverse): nothing to do.\n if (!wakes(instance, event)) return { status: \"completed\", followUps: [] };\n instance.status = \"running\";\n instance.waiting = undefined;\n const background: Promise<unknown>[] = [];\n const counts = new Map<string, number>();\n const key = (kind: string, name: string): string => {\n const count = (counts.get(`${kind}:${name}`) ?? 0) + 1;\n counts.set(`${kind}:${name}`, count);\n return `${kind}:${name}#${count}`;\n };\n const replay = (o: Outcome): unknown => {\n if (o.ok) return structuredClone(o.value);\n const error: unknown = structuredClone(o.error);\n if (o.errorName !== undefined && error instanceof Error) error.name = o.errorName;\n throw error;\n };\n\n const step = {\n do: async (name: string, a: unknown, b?: unknown, c?: unknown): Promise<unknown> => {\n const [config, fn, options] = (typeof a === \"function\" ? [{}, a, b] : [a ?? {}, b, c]) as [\n StepConfig,\n (ctx: unknown) => unknown,\n { rollback?: unknown } | undefined,\n ];\n if (suspending !== undefined) return alongsideWait(\"step.do\");\n if (options?.rollback !== undefined) {\n hooks.unsupported(`Workflow ${d.binding}: rollback handlers are not modelled`);\n throw new Error(\"eutaxy: rollback handlers are not modelled\");\n }\n // The engine's checks, before anything runs: fatal errors there, whose catching is not documented.\n const fatal = (message: string): never => {\n hooks.unsupported(`Workflow ${d.binding}: ${message}`);\n const err = new Error(message);\n err.name = \"WorkflowFatalError\";\n throw err;\n };\n if (name.length > 256 || [...name].some((c) => c.charCodeAt(0) < 0x20))\n fatal(`Step name \"${name}\" exceeds max length (256 chars) or invalid characters found`);\n if (!validStepConfig(config))\n fatal(\n `Step config for \"${name}\" is in a invalid format. See https://developers.cloudflare.com/workflows/build/sleeping-and-retrying/`,\n );\n const k = key(\"do\", name);\n const count = counts.get(`do:${name}`) as number;\n const done = instance.persisted.get(k);\n if (done) return replay(done);\n const live = { ...defaultRetries, ...config.retries };\n const first = instance.configs.get(k);\n if (!first)\n instance.configs.set(k, {\n retries: live,\n timeout: config.timeout ?? \"10 minutes\",\n ...(config.sensitive === undefined ? {} : { sensitive: config.sensitive }),\n });\n const sensitive = first ? first.sensitive : config.sensitive;\n const stored = first?.retries;\n // A delay function is not persisted: the engine calls the one the current run passes, or\n // falls back to the default delay; the crashed run's function is never called again.\n const retries =\n stored && typeof stored.delay === \"function\"\n ? {\n ...stored,\n delay: typeof live.delay === \"function\" ? live.delay : defaultRetries.delay,\n }\n : (stored ?? live);\n const limit = Math.min(retries.limit, d.maxRedeliveries);\n // What the callback sees: a delay function is not exposed (Workflows, Step context).\n const { delay, ...shown } = retries;\n const resolved = {\n retries: typeof delay === \"function\" ? shown : retries,\n timeout: first ? first.timeout : (config.timeout ?? \"10 minutes\"),\n ...(sensitive === undefined ? {} : { sensitive }),\n };\n for (let attempt = (instance.attempts.get(k) ?? 0) + 1; ; attempt++) {\n // A retry the engine was waiting for when it restarted: only the rest of its delay.\n const due = instance.deadlines.get(`retry:${k}`);\n if (due !== undefined) {\n await sleep(Math.max(0, due - Date.now()));\n instance.deadlines.delete(`retry:${k}`);\n }\n // A fresh copy per attempt: what the callback does to it does not reach the engine's own.\n const stepContext = {\n step: { name, count },\n attempt,\n config: { ...resolved, retries: { ...resolved.retries } },\n };\n const args = { instance: instance.id, step: name, count, attempt };\n // The callback runs as the instance's own code, between two points: its effects are ordinary\n // effects of the invocation, and its timers are virtual. The points are asynchronous, as the\n // engine's reading and persisting are: other events may run between steps. The ambiguous\n // fault here is an attempt that outlives its timeout from its start.\n let lateAtStart = false;\n try {\n await hooks.effect(\n { invocation, target, op: \"step\", args, allowed: STEP_START },\n async () => null,\n () => null,\n );\n } catch (err) {\n if (!(err instanceof InjectedEffectError)) throw err;\n lateAtStart = true;\n }\n instance.attempts.set(k, attempt);\n // What the attempt threw, kept as thrown (a plain value too), as the engine rethrows it.\n let failed = false;\n let thrown: unknown;\n let value: unknown;\n let returned: { readonly value: unknown } | undefined;\n // The callback is an attempt the engine gives up on at the step's timeout, measured in\n // virtual time (at once, under the fault), as the engine races the callback against its\n // timeout: the attempt is not stopped, since nothing can stop it, and runs on late, its\n // result discarded, while the step is counted as failed and retried (Workflows, Sleeping and\n // retrying: timeout). In a concurrent run what the late attempt still does is a turn the run\n // need not wait for, so it lands before, between or after the retry's work.\n const timeoutMs = durationMs(resolved.timeout);\n const started = hooks.attempt(\n invocation,\n () => {\n try {\n return Promise.resolve(fn(stepContext));\n } catch (err) {\n return Promise.reject(err);\n }\n },\n lateAtStart ? 0 : timeoutMs,\n );\n const settled = started.value.then(\n (v) => ({ ok: true as const, value: v }),\n (error: unknown) => ({ ok: false as const, error }),\n );\n // Under the fault the attempt is late whatever it returns, at once: a callback already done\n // is still an attempt the engine counted out.\n const outcome = lateAtStart\n ? (\"late\" as const)\n : await Promise.race([settled, started.late.then(() => \"late\" as const)]);\n if (outcome === \"late\") {\n if (!lateAtStart)\n note(hooks, {\n invocation,\n target,\n op: \"step_timeout\",\n args: { ...args, timeoutMs },\n allowed: [],\n });\n failed = true;\n thrown = Object.assign(new Error(`Execution timed out after ${timeoutMs}ms`), {\n name: \"WorkflowTimeoutError\",\n });\n // The late attempt is waited for as the instance's background work is; what it returns\n // or throws is noted and dropped, as the engine drops it.\n background.push(\n settled.then((o) => {\n if (inv.isCrashed()) return;\n note(hooks, {\n invocation,\n target,\n op: \"late_result\",\n args: { ...args, outcome: o.ok ? \"returned\" : \"threw\" },\n allowed: [],\n });\n }),\n );\n } else if (outcome.ok) {\n returned = { value: outcome.value };\n } else {\n const err = outcome.error;\n // A crash ends the attempt and the instance; it is not a failure to retry.\n if (err instanceof CrashSignal || inv.isCrashed()) throw err;\n failed = true;\n thrown = err;\n try {\n hooks.effectSync(\n { invocation, target, op: \"step_result\", args, allowed: [] },\n () => {\n throw err;\n },\n () => null,\n );\n } catch {\n // Recorded as the attempt's error; handled below.\n }\n }\n if (returned !== undefined) {\n const notModelled = (reason: string): never => {\n hooks.unsupported(`Workflow ${d.binding}: step \"${name}\" ${reason}`);\n throw new Error(`eutaxy: step \"${name}\" ${reason}`);\n };\n try {\n value = structuredClone(returned.value);\n } catch {\n // A stream, or anything else the engine persists in its own way: not a failure to retry.\n notModelled(\n \"returned a value that is not structured-cloneable (a ReadableStream is not modelled)\",\n );\n }\n if (approximateBytes(value) > 1_048_576)\n notModelled(\n 'returned more than about 1 MiB, which the engine refuses (\"output is too large\"); Eutaxy cannot measure the stored size exactly',\n );\n }\n if (!failed) {\n try {\n await hooks.effect(\n { invocation, target, op: \"step_result\", args, allowed: STEP_RESULT },\n async () => value,\n (v) => ({ output: sensitive === \"output\" ? \"[REDACTED]\" : toJson(v) }),\n );\n instance.persisted.set(k, { ok: true, value });\n return structuredClone(value);\n } catch (err) {\n if (err instanceof CrashSignal || !(err instanceof InjectedEffectError)) throw err;\n // The attempt ran but counted as failed: a timeout just after its work, as the engine reports one.\n thrown = Object.assign(\n new Error(`Execution timed out after ${durationMs(resolved.timeout)}ms`),\n { name: \"WorkflowTimeoutError\" },\n );\n }\n }\n // The engine's predicate (an Error so named, or whose message starts so). It rethrows the\n // value as thrown and does not persist it, so after a restart the callback runs again.\n if (\n thrown instanceof Error &&\n (thrown.name === \"NonRetryableError\" || thrown.message.startsWith(\"NonRetryableError\"))\n )\n throw thrown;\n if (attempt > limit) {\n instance.persisted.set(k, failure(thrown));\n throw thrown;\n }\n let wait: number;\n try {\n // A fresh context from the engine's own values: the callback may have changed its copy.\n const delayContext = {\n step: { name, count },\n attempt,\n config: { ...resolved, retries: { ...resolved.retries } },\n };\n wait = await retryDelayMs(retries, attempt, delayContext, thrown);\n } catch (err) {\n hooks.unsupported(\n `Workflow ${d.binding}: step \"${name}\"'s retry delay function threw (${String(err)})`,\n );\n throw err;\n }\n instance.deadlines.set(`retry:${k}`, Date.now() + wait);\n await sleep(wait);\n instance.deadlines.delete(`retry:${k}`);\n }\n },\n sleep: async (name: string, duration: unknown): Promise<void> => {\n const ms = durationMs(duration);\n // Keyed by name and duration, as the engine keys sleeps: another duration is another sleep.\n await sleepStep(key(\"sleep\", `${name}\\u0000${ms}`), name, ms);\n },\n sleepUntil: async (name: string, timestamp: unknown): Promise<void> => {\n const at = timestamp instanceof Date ? timestamp.getTime() : Number(timestamp);\n const k = key(\"sleepUntil\", `${name}\\u0000${at}`);\n if (instance.persisted.has(k)) {\n // Miniflare's engine checks the time before its cache and throws here; production is undocumented.\n if (at < Date.now())\n hooks.unsupported(\n `Workflow ${d.binding}: step.sleepUntil \"${name}\" replayed after its time, where Miniflare's engine throws`,\n );\n return;\n }\n // Miniflare's engine refuses a time in the past, with this message.\n if (at < Date.now() && !instance.deadlines.has(k))\n throw new Error(\"You can't sleep until a time in the past, time-traveler\");\n await sleepStep(k, name, Math.max(0, at - Date.now()), at);\n },\n waitForEvent: async (\n name: string,\n options: { readonly type?: unknown; readonly timeout?: unknown } = {},\n ): Promise<unknown> => {\n if (suspending !== undefined) return alongsideWait(\"step.waitForEvent\");\n const type = validEventType(options.type);\n const timeoutMs = durationMs(options.timeout ?? \"24 hours\");\n if (!(timeoutMs >= 1000 && timeoutMs <= 365 * 24 * 3_600_000)) {\n hooks.unsupported(\n `Workflow ${d.binding}: waitForEvent \"${name}\" timeout must be between 1 second and 365 days`,\n );\n const err = new Error(`Invalid timeout for waitForEvent \"${name}\"`);\n err.name = \"WorkflowFatalError\";\n throw err;\n }\n // Keyed by name and count, as the engine keys waits.\n const k = key(\"waitForEvent\", name);\n const done = instance.persisted.get(k);\n if (done) return replay(done);\n const args = { instance: instance.id, step: name, type };\n const existing = instance.deadlines.get(k);\n // An event already sent: the first of its type, as the engine's queue gives it, if it came\n // before the wait's deadline; one sent after it finds the wait timed out and stays buffered.\n const queue = instance.events.get(type) ?? [];\n const inTime = queue.findIndex(\n (e) => existing === undefined || e.timestamp.getTime() < existing,\n );\n const received = inTime < 0 ? undefined : queue.splice(inTime, 1)[0];\n if (received) {\n hooks.effectSync(\n {\n invocation,\n target,\n op: \"event\",\n args: { ...args, timestamp: received.timestamp.getTime() },\n allowed: [],\n },\n () => received,\n (e) => ({ payload: toJson(e.payload) }),\n );\n instance.persisted.set(k, { ok: true, value: received });\n return structuredClone(received);\n }\n if (existing !== undefined && Date.now() >= existing) {\n // The wait's time is up: the error is the step's, persisted, and the instance fails unless the code catches it.\n const error = Object.assign(new Error(`Execution timed out after ${timeoutMs}ms`), {\n name: \"WorkflowTimeoutError\",\n });\n note(hooks, { invocation, target, op: \"wait_timeout\", args, allowed: [] });\n instance.persisted.set(k, failure(error));\n throw error;\n }\n const deadline = existing ?? Date.now() + timeoutMs;\n if (existing === undefined) {\n instance.deadlines.set(k, deadline);\n note(hooks, { invocation, target, op: \"wait\", args: { ...args, timeoutMs }, allowed: [] });\n }\n // Nothing to wait on yet: the instance hibernates until the event or the deadline wakes it.\n const gen = ++instance.waitGen;\n instance.waiting = { type, gen, woken: false };\n suspending = { gen, deadline };\n hibernate();\n return hibernated();\n },\n };\n /** Set once a wait hibernated this run; the run then ends with the wait, wherever its code was. */\n let suspending: { readonly gen: number; readonly deadline: number } | undefined;\n /**\n * A step call once a wait hibernated the run. Code after the wait never runs (its promise never\n * settles), so the call comes from code running in parallel with the wait (`Promise.all` of a wait and\n * a step), which the engine would run while the wait is pending: not modelled, so reported, and the\n * call never settles, as the hibernated run's other calls.\n */\n const alongsideWait = <T>(what: string): Promise<T> => {\n hooks.unsupported(\n `Workflow ${d.binding}: ${what} started alongside step.waitForEvent; steps running in parallel with a wait are not modelled`,\n );\n return hibernated();\n };\n async function sleepStep(k: string, name: string, ms: number, until?: number): Promise<void> {\n if (suspending !== undefined) return alongsideWait(\"step.sleep\");\n if (instance.persisted.has(k)) return;\n const pending = instance.deadlines.get(k);\n if (pending !== undefined) {\n await sleep(Math.max(0, pending - Date.now()));\n instance.persisted.set(k, { ok: true, value: null });\n return;\n }\n instance.deadlines.set(k, Date.now() + ms);\n note(hooks, {\n invocation,\n target,\n op: \"sleep\",\n args: { instance: instance.id, step: name, ms, ...(until === undefined ? {} : { until }) },\n allowed: [],\n });\n await sleep(ms);\n instance.persisted.set(k, { ok: true, value: null });\n }\n\n // Resolved when a wait hibernates the instance: the run ends there, while run() itself never settles.\n let hibernate = (): void => {};\n const hibernation = new Promise<undefined>((resolve) => {\n hibernate = () => resolve(undefined);\n });\n const ran = await runInvocation(hooks, inv, () => {\n const flow = constructWorkflow(d.cls, executionContext(background), d.env) as {\n run(event: unknown, step: unknown): unknown;\n };\n const workflowEvent: Record<string, unknown> = {\n payload: structuredClone(instance.params),\n timestamp: new Date(instance.createdAt),\n instanceId: instance.id,\n };\n if (d.name !== undefined) workflowEvent[\"workflowName\"] = d.name;\n else\n Object.defineProperty(workflowEvent, \"workflowName\", {\n enumerable: true,\n get: () => {\n hooks.unsupported(\n `Workflow ${d.binding}: event.workflowName needs the Workflow's name, workflow(binding, className, { name })`,\n );\n return undefined;\n },\n });\n return Promise.race([flow.run(workflowEvent, step), hibernation]);\n });\n // The engine keeps the result serialised: one it cannot keep fails the instance.\n const serialised = (value: unknown): RunOutcome<unknown> => {\n try {\n return { status: \"completed\", value: structuredClone(value) };\n } catch {\n hooks.unsupported(\n `Workflow ${d.binding}: run() returned a value that is not structured-cloneable`,\n );\n return {\n status: \"errored\",\n error: new Error(\"run() returned a value that is not structured-cloneable\"),\n };\n }\n };\n let result: RunOutcome<unknown> = ran.status === \"completed\" ? serialised(ran.value) : ran;\n // The run ended by hibernating: its outcome is the wait.\n if (suspending !== undefined && ran.status !== \"crashed\")\n result = { status: \"completed\", value: undefined };\n let status = result.status;\n // The engine restarts a crashed instance from the start of `run`; crashes come from faults, so few.\n const restart = (): EventRef[] =>\n status === \"crashed\" && instance.status === \"running\" && event.attempt <= d.maxFaultsPerRun\n ? [{ ...event, attempt: event.attempt + 1 }]\n : [];\n if (suspending !== undefined && result.status === \"completed\") {\n instance.status = \"waiting\";\n const suspended = suspending;\n if (await drainBackground(hooks, inv, invocation, target, background)) status = \"crashed\";\n if (status === \"crashed\") {\n // The crash ends the run; the restart below suspends again with a new generation.\n instance.status = \"running\";\n instance.waiting = undefined;\n }\n const followUps: EventRef[] =\n status === \"crashed\"\n ? restart()\n : [\n // The timeout wake, due at the deadline; an event sent earlier wakes the instance first.\n {\n id: `workflow:${d.binding}:${instance.id}:timeout-${suspended.gen}`,\n attempt: 1,\n source: workflowSource,\n data: { binding: d.binding, id: instance.id, wake: suspended.gen },\n at: suspended.deadline,\n },\n ];\n return { status, followUps };\n }\n if (result.status === \"completed\") {\n instance.status = \"complete\";\n instance.output = result.value;\n note(hooks, {\n invocation,\n target,\n op: \"complete\",\n args: { instance: instance.id, output: toJson(instance.output) },\n allowed: [],\n });\n } else if (result.status === \"errored\") {\n instance.status = \"errored\";\n const e = result.error;\n instance.error =\n e instanceof Error\n ? { name: e.name, message: e.message }\n : { name: \"Error\", message: String(e) };\n note(hooks, {\n invocation,\n target,\n op: \"errored\",\n args: { instance: instance.id, error: `${instance.error.name}: ${instance.error.message}` },\n allowed: [],\n });\n }\n if (await drainBackground(hooks, inv, invocation, target, background)) status = \"crashed\";\n return { status, followUps: restart() };\n}\n\n/** The delay before the next attempt (Workflows, Sleeping and retrying; a delay function is called). */\nasync function retryDelayMs(\n retries: NonNullable<StepConfig[\"retries\"]>,\n attempt: number,\n ctx: unknown,\n error: unknown,\n): Promise<number> {\n const delay =\n typeof retries.delay === \"function\"\n ? await (retries.delay as (i: unknown) => unknown)({ ctx, error })\n : retries.delay;\n // The backoff applies to a delay function's value too, as in Miniflare's engine.\n const base = durationMs(delay);\n switch (retries.backoff) {\n case \"linear\":\n return base * attempt;\n case \"exponential\":\n return base * 2 ** (attempt - 1);\n default:\n return base;\n }\n}\n","/**\n * Code run inside a Durable Object as one of its own events does (an alarm,\n * a WebSocket message), and the crash semantics that go with it: the effect\n * hosts the object's effects, work the object goes on with after it is the\n * object's own turns, an abandoned effect resets the object, an effect\n * inside blockConcurrencyWhile may not wait for a turn, and a crash drops\n * the instance, whose in-memory state goes with it.\n */\n\nimport {\n type DeliveryResult,\n type EffectPoint,\n type EventRef,\n type Invocation,\n invocationOf,\n type JsonValue,\n type RunHooks,\n} from \"@eutaxy/core\";\nimport { type Outcome, runInvocation } from \"@eutaxy/engine\";\nimport { isD1 } from \"./d1.ts\";\nimport { isR2 } from \"./r2.ts\";\nimport type { ScriptedObjectSetup, ServiceSetup } from \"./scenario.ts\";\nimport { isServiceBinding, scriptedError } from \"./services.ts\";\nimport { isWorkflowBinding } from \"./workflows.ts\";\n\n/** A Durable Object namespace as the env shows it. */\nexport function isDurableObjectNamespace(value: unknown): value is DurableObjectNamespace {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as { idFromName?: unknown }).idFromName === \"function\" &&\n typeof (value as { get?: unknown }).get === \"function\"\n );\n}\n\n/** The host an object's code runs as (`EffectOptions.host`): its namespace's target and its name. */\nexport function hostOf(target: string, object: string): string {\n return `${target}/${object}`;\n}\n\n/** Where a class's `method` is defined along `instance`'s prototype chain. */\nfunction owner(instance: object, method: string): object | undefined {\n for (let o: object | null = instance; o !== null; o = Object.getPrototypeOf(o))\n if (Object.hasOwn(o, method)) return o;\n return undefined;\n}\n\n/** The host each instance's code runs as, set each time a call enters it. */\nconst hostOfInstance = new WeakMap<object, { hooks: RunHooks; host: string }>();\nconst hostingWrappers = new WeakSet<object>();\n\n/**\n * Have the object's `method` run as the host's code (`RunHooks.hostedCode`)\n * when the runtime calls it next: the runtime carries no async context into\n * an object's code, so the method is wrapped where its class defines it, and\n * the wrapper looks the instance's host up; code the method spawns and does\n * not await carries the object's identity too.\n */\nexport function hostMethod(hooks: RunHooks, host: string, instance: unknown, method: string): void {\n if (instance === null || typeof instance !== \"object\") return;\n hostOfInstance.set(instance, { hooks, host });\n const where = owner(instance, method);\n if (!where) return;\n const descriptor = Object.getOwnPropertyDescriptor(where, method);\n if (!descriptor?.configurable) return;\n const hosted = (original: (...a: unknown[]) => unknown) =>\n function (this: unknown, ...args: unknown[]): unknown {\n const of = this !== null && typeof this === \"object\" ? hostOfInstance.get(this) : undefined;\n const call = () => original.apply(this, args);\n return of ? of.hooks.hostedCode(of.host, call, method) : call();\n };\n // A method, or an RPC property's getter: either runs the object's code when the call arrives.\n if (typeof descriptor.value === \"function\" && descriptor.writable) {\n if (hostingWrappers.has(descriptor.value)) return;\n const wrapper = hosted(descriptor.value as (...a: unknown[]) => unknown);\n hostingWrappers.add(wrapper);\n Object.defineProperty(where, method, { ...descriptor, value: wrapper });\n } else if (typeof descriptor.get === \"function\") {\n if (hostingWrappers.has(descriptor.get)) return;\n const wrapper = hosted(descriptor.get as (...a: unknown[]) => unknown);\n hostingWrappers.add(wrapper);\n Object.defineProperty(where, method, { ...descriptor, get: wrapper });\n }\n}\n\n/**\n * Under this key a callee's view of env (`calleeEnv`) gives the callee's\n * name, so an object constructed with that view has its bindings read back\n * to the names the scenario knows them by (`PEER` to `orders/PEER`).\n */\nexport const calleeOfEnv: unique symbol = Symbol.for(\"eutaxy.calleeOfEnv\");\n\n/**\n * Make an object's calls through its own bindings the scenario's. The\n * runtime hands an object the Worker's real `env`, where a service binding\n * is not the scenario's script or callee (a call through it would reach\n * whatever the isolate holds under that name and fail or answer unseen),\n * a database or bucket is the real one, whose calls nothing records or\n * faults, and a Workflow binding is the local engine, which would run the\n * class on the real clock. So the instance's `env` is put behind a view\n * under which every binding is the one the\n * Worker itself sees (`worker()`, the platform's env, under the binding's\n * qualified name): the call is an effect of whichever invocation the\n * object's code is running as, with that binding's faults: a service's\n * answered from the `service()` script or by the `callee()` hosted inside\n * it, a statement or a bucket operation performed on the real store, a\n * Workflow instance created in the model, a call into another object the\n * stub call it is from the Worker; and a call on a binding of a\n * kind the model does not cover is refused as it is from the Worker, never\n * passed on. The binding is resolved when first used, so reading it off\n * `env` does nothing. Without the platform's env, or when it holds nothing\n * under the name, a service call ends the run `UNSUPPORTED`, and any other\n * binding is the object's own, unrecorded. A\n * class given the platform's base (`simulateConstruction`) is constructed\n * with the view (`envView`) and this only tells it whose it is; for any\n * other the view is in place once the constructor has returned, and the\n * `env` parameter a constructor keeps for itself is out of reach either\n * way.\n *\n * A call leaves the object only once what the object wrote before it is\n * durable, as the runtime's output gate holds an outgoing message until the\n * writes before it are confirmed: around the start of each call the\n * object's gate (`gate.durable`, the storage's `sync()`) is left in\n * `gate.slot` for the binding's stub to wait on inside its effect. A fault\n * that resets the object after the call then finds those writes kept,\n * where a reset straight after an unflushed write would lose them and a\n * claim recorded before the call would look as if never made.\n */\nexport function ownEnv(\n hooks: RunHooks,\n binding: string,\n object: string,\n instance: unknown,\n worker?: () => object,\n gate?: EnvGate,\n): void {\n if (instance === null || typeof instance !== \"object\") return;\n const descriptor = Object.getOwnPropertyDescriptor(instance, \"env\");\n const env: unknown = descriptor?.value;\n if (env === null || typeof env !== \"object\") return;\n // Constructed with the view already (`envView`, through the class's base): whose it is, for this run.\n const known = ownerOfView.get(env);\n if (known) {\n Object.assign(known, { hooks, binding, object });\n return;\n }\n if (!descriptor?.writable) return;\n (instance as { env: unknown }).env = envView(env, { hooks, binding, object }, worker, gate);\n}\n\n/**\n * The env an object is constructed with outside a run (the reset constructs\n * each seeded object to clear and seed it). No run is there to record a\n * call, and the isolate's own binding must not be reached either: a method\n * of a service binding the scenario scripts (`scripted`, by the binding's\n * name there) is answered from the script as it will be in the run, so a\n * constructor that loads from one comes up; anything else through a\n * service binding (a `fetch()`, a binding with a callee or with no script)\n * is refused, and so are a call on a Workflow binding, which would start\n * an instance in the local engine, and a call into another object, which\n * would run that object for real and leave it up, unless the scenario\n * scripts that object's namespace: then its methods answer from the\n * script, as a service's do. A database or a bucket is the real one\n * there, as it is the reset's own: what a constructor writes to one while\n * its object is reset stays unless that store's setup step comes after the\n * object's. The\n * instance is evicted before the run, whose first call constructs the\n * object again, inside the run.\n */\nexport function outsideRunEnv(\n env: object,\n scripted: (binding: string) => ServiceSetup | ScriptedObjectSetup | undefined = () => undefined,\n): object {\n const callee = (env as { readonly [calleeOfEnv]?: unknown })[calleeOfEnv];\n const qualified = (name: string): string =>\n typeof callee === \"string\" ? `${callee}/${name}` : name;\n const stubs = new Map<string, object>();\n const stubFor = (name: string): object => {\n let stub = stubs.get(name);\n if (!stub) {\n const member = (method: string): object => {\n const answer = async (): Promise<unknown> => {\n const script = scripted(qualified(name));\n const reply =\n script?.kind !== \"service\" || method === \"fetch\" || method === \"connect\"\n ? undefined\n : script.methods === undefined\n ? { returns: null }\n : Object.hasOwn(script.methods, method)\n ? script.methods[method]\n : undefined;\n if (reply === undefined)\n throw new Error(\n `eutaxy: a Durable Object's constructor called ${method} on the service binding ${name} while the scenario's objects were being reset, outside a run, and no service() script answers it there`,\n );\n if (\"throws\" in reply) throw scriptedError(reply.throws);\n return structuredClone(reply.returns);\n };\n return Object.assign(answer, {\n // biome-ignore lint/suspicious/noThenProperty: an RPC property is awaitable as well as callable\n then: (onFulfilled?: (v: unknown) => unknown, onRejected?: (e: unknown) => unknown) =>\n answer().then(onFulfilled, onRejected),\n });\n };\n stub = new Proxy(\n {},\n {\n get: (_t, prop) =>\n prop === \"then\" || typeof prop === \"symbol\" ? undefined : member(prop),\n },\n );\n stubs.set(name, stub);\n }\n return stub;\n };\n /** A Workflow binding whose every call is refused: no run is there to hold the instance. */\n const flows = new Map<string, object>();\n const flowFor = (name: string, own: object): object => {\n let flow = flows.get(name);\n if (!flow) {\n flow = new Proxy(own, {\n get(target, prop) {\n const value = Reflect.get(target, prop, target) as unknown;\n if (typeof value !== \"function\" || typeof prop !== \"string\") return value;\n return async (): Promise<never> => {\n throw new Error(\n `eutaxy: a Durable Object's constructor called ${prop} on the Workflow binding ${name} while the scenario's objects were being reset, outside a run, where no instance can be created or read`,\n );\n };\n },\n });\n flows.set(name, flow);\n }\n return flow;\n };\n /**\n * A namespace whose stubs refuse every call: the object called would run\n * for real, on the real clock, and stay up into the run with what the\n * call left in it. Ids are the namespace's own.\n */\n const namespaces = new Map<string, object>();\n const namespaceFor = (name: string, own: object): object => {\n let namespace = namespaces.get(name);\n if (!namespace) {\n const refused = (method: string): object => {\n const call = async (): Promise<unknown> => {\n const script = scripted(qualified(name));\n // A scripted namespace's method answers as it will in the run; nothing of it would run.\n const reply =\n script?.kind !== \"scripted_object\" || method === \"fetch\" || method === \"connect\"\n ? undefined\n : script.methods === undefined\n ? { returns: null }\n : Object.hasOwn(script.methods, method)\n ? script.methods[method]\n : undefined;\n if (reply === undefined)\n throw new Error(\n `eutaxy: a Durable Object's constructor called ${method} on an object of ${name} while the scenario's objects were being reset, outside a run, where a call into another object is not made${script?.kind === \"scripted_object\" ? \" and the scriptedObject() script does not answer it\" : \"\"}`,\n );\n if (\"throws\" in reply) throw scriptedError(reply.throws);\n return structuredClone(reply.returns);\n };\n return Object.assign(call, {\n // biome-ignore lint/suspicious/noThenProperty: an RPC property is awaitable as well as callable\n then: (onFulfilled?: (v: unknown) => unknown, onRejected?: (e: unknown) => unknown) =>\n call().then(onFulfilled, onRejected),\n });\n };\n namespace = new Proxy(own, {\n get(target, prop) {\n const value = Reflect.get(target, prop, target) as unknown;\n if (typeof value !== \"function\") return value;\n if (prop !== \"get\" && prop !== \"getByName\") return value.bind(target);\n return (...args: unknown[]) =>\n new Proxy(Reflect.apply(value, target, args) as object, {\n get(stub, key) {\n // The stub is not a promise; its id and name are its own.\n if (typeof key !== \"string\" || key === \"then\" || key === \"id\" || key === \"name\")\n return key === \"then\" ? undefined : (Reflect.get(stub, key, stub) as unknown);\n return refused(key);\n },\n });\n },\n });\n namespaces.set(name, namespace);\n }\n return namespace;\n };\n return new Proxy(env, {\n get(target, prop) {\n const value = Reflect.get(target, prop, target) as unknown;\n if (typeof prop !== \"string\") return value;\n // A service binding first: in workerd it answers every duck type.\n if (isServiceBinding(value)) return stubFor(prop);\n if (isDurableObjectNamespace(value)) return namespaceFor(prop, value);\n return isWorkflowBinding(value) ? flowFor(prop, value) : value;\n },\n });\n}\n\n/** What an object's output gate needs: the slot a call leaves it in, and the wait itself. */\nexport interface EnvGate {\n readonly slot: { pending: (() => Promise<void>) | undefined };\n readonly durable: () => Promise<void>;\n}\n\n/** Whose each view over an env is: the object and the run a refusal is reported to. */\nconst ownerOfView = new WeakMap<object, { hooks: RunHooks; binding: string; object: string }>();\n\n/**\n * The view `ownEnv` puts over an object's `env`, made on its own so that a\n * class given a base of the platform's (`simulatedBase`) is constructed\n * with it and its constructor's first line already reads the scenario's\n * bindings. `owner` is told again at each entry into the object.\n */\nexport function envView(\n env: object,\n owner: { hooks: RunHooks; binding: string; object: string },\n worker?: () => object,\n gate?: EnvGate,\n): object {\n const callee = (env as { readonly [calleeOfEnv]?: unknown })[calleeOfEnv];\n /** The name the scenario knows the object's binding by. */\n const qualified = (name: string): string =>\n typeof callee === \"string\" ? `${callee}/${name}` : name;\n const refuse = (name: string): never => {\n const reason = `Durable Object ${owner.binding} ${owner.object} called the service binding ${name} through its own env, and the scenario's env holds no service binding ${qualified(name)} to answer it`;\n owner.hooks.unsupported(reason);\n throw new Error(`eutaxy: ${reason}`);\n };\n const stubs = new Map<string, object>();\n const stubFor = (name: string): object => {\n let stub = stubs.get(name);\n if (!stub) {\n // What stands in when the scenario's env cannot answer: a method called, or awaited uncalled (an\n // RPC getter), is the refused call, rejecting as an RPC call does.\n const refused = Object.assign(async (): Promise<never> => refuse(name), {\n // biome-ignore lint/suspicious/noThenProperty: an RPC property is awaitable as well as callable\n then: (onFulfilled?: (v: unknown) => unknown, onRejected?: (e: unknown) => unknown) =>\n refused().then(onFulfilled, onRejected),\n });\n stub = new Proxy(\n {},\n {\n get(_t, prop) {\n // The binding itself is not a promise.\n if (prop === \"then\" || typeof prop === \"symbol\") return undefined;\n // The Worker's own stub for the binding, looked up now: the run's script or callee.\n const through = worker\n ? (Reflect.get(worker(), qualified(name)) as unknown)\n : undefined;\n if (through === null || typeof through !== \"object\") return refused;\n const member = Reflect.get(through, prop, through) as unknown;\n return typeof member === \"function\" ? calling(member, owner, gate) : member;\n },\n },\n );\n stubs.set(name, stub);\n }\n return stub;\n };\n /**\n * The scenario's database, bucket or Workflow under the object's binding\n * `name`, or the object's own. `flow` tells a Workflow, whose `create()`\n * and `get()` answer with an instance to call later.\n */\n const modelled = new Map<string, object>();\n const modelledFor = (name: string, own: object, flow: boolean): object => {\n let through = modelled.get(name);\n if (!through) {\n through = new Proxy(own, {\n get(target, prop) {\n // The Worker's own proxy for the binding, looked up now: its effects carry the run.\n const model = worker ? (Reflect.get(worker(), qualified(name)) as unknown) : undefined;\n if (model === null || typeof model !== \"object\" || model === target) {\n const value = Reflect.get(target, prop, target) as unknown;\n return typeof value === \"function\" ? value.bind(target) : value;\n }\n const member = Reflect.get(model, prop, model) as unknown;\n if (typeof member !== \"function\") return member;\n // A statement is executed later: that, not preparing it, is the object's call.\n if (prop === \"prepare\")\n return (...args: unknown[]) =>\n handedView(Reflect.apply(member, model, args) as object, owner, gate, \"bind\");\n const call = calling(member.bind(model), owner, gate);\n if (!flow || (prop !== \"create\" && prop !== \"get\")) return call;\n // Creating or finding an instance is the object's call, and so is each call on it after.\n return async (...args: unknown[]) =>\n handedView(\n (await Reflect.apply(\n call as (...a: unknown[]) => unknown,\n undefined,\n args,\n )) as object,\n owner,\n gate,\n );\n },\n });\n modelled.set(name, through);\n }\n return through;\n };\n /**\n * The scenario's namespace under the object's binding `name`, or the\n * object's own: a call on a stub it gives is the object's call into\n * another object (or into itself, as the runtime allows).\n */\n const namespaces = new Map<string, object>();\n const namespaceFor = (name: string, own: object): object => {\n let namespace = namespaces.get(name);\n if (!namespace) {\n namespace = new Proxy(own, {\n get(target, prop) {\n const model = worker ? (Reflect.get(worker(), qualified(name)) as unknown) : undefined;\n const through = model === null || typeof model !== \"object\" ? target : model;\n const member = Reflect.get(through, prop, through) as unknown;\n if (typeof member !== \"function\") return member;\n if (through === target || (prop !== \"get\" && prop !== \"getByName\"))\n return member.bind(through);\n return (...args: unknown[]) => {\n const stub = Reflect.apply(member, through, args) as object;\n return new Proxy(stub, {\n get(to, key) {\n const value = Reflect.get(to, key, to) as unknown;\n // Unbound: the stub's members are callable and awaitable as they are.\n return typeof value === \"function\" ? calling(value, owner, gate) : value;\n },\n });\n };\n },\n });\n namespaces.set(name, namespace);\n }\n return namespace;\n };\n const view = new Proxy(env, {\n get(target, prop) {\n const value = Reflect.get(target, prop, target) as unknown;\n if (typeof prop !== \"string\") return value;\n // A service binding first: in workerd it answers every duck type.\n if (isServiceBinding(value)) return stubFor(prop);\n if (isD1(value) || isR2(value)) return modelledFor(prop, value, false);\n if (isWorkflowBinding(value)) return modelledFor(prop, value, true);\n if (isDurableObjectNamespace(value)) return namespaceFor(prop, value);\n if (!worker) return value;\n // Anything else is what the Worker sees under the name: a binding of a kind the model does not\n // cover with every call refused, a var as it is.\n const seen = Reflect.get(worker(), qualified(prop)) as unknown;\n return seen === undefined ? value : seen;\n },\n });\n ownerOfView.set(view, owner);\n return view;\n}\n\n/**\n * What a binding handed an object to call later (a D1 statement, a Workflow\n * instance): each method called is the object's call (a statement's `run`,\n * `all`, `first`, `raw`; an instance's `status`, `sendEvent`), and the\n * method named `again` (a statement's `bind`) gives another such thing.\n * What else is read of it (`batch()` reads a statement's text) is its own.\n */\nfunction handedView(\n handed: object,\n owner: { hooks: RunHooks; binding: string; object: string },\n gate: EnvGate | undefined,\n again?: string,\n): object {\n return new Proxy(handed, {\n get(target, key) {\n const value = Reflect.get(target, key, target) as unknown;\n if (typeof value !== \"function\") return value;\n if (key === again)\n return (...values: unknown[]) =>\n handedView(Reflect.apply(value, target, values) as object, owner, gate, again);\n return calling(value.bind(target), owner, gate);\n },\n });\n}\n\n/**\n * A method of a binding as an object calls it. The call (or the await of\n * an RPC getter) starts as the object's code, which it is: in a\n * method it already runs as such, but the runtime carries no context into\n * a constructor, whose call would otherwise be a turn of nobody's inside\n * the call that is entering the object (`RunHooks.hostEntering`). And\n * while it starts, the object's output gate is in the slot for the stub to\n * take. The start is synchronous, so no other call sees the slot. Anything\n * else read on the method is its own (the stub's guards).\n */\nfunction calling(\n member: object,\n owner: { hooks: RunHooks; binding: string; object: string },\n gate: EnvGate | undefined,\n): object {\n const starting = <T>(start: () => T): T => {\n const behind = (): T => {\n if (!gate) return start();\n gate.slot.pending = gate.durable;\n try {\n return start();\n } finally {\n gate.slot.pending = undefined;\n }\n };\n // Test doubles for the hooks may lack it; the run's has it. Only the start is the entering\n // code: a constructor that starts a call and returns is not waiting on it, so the promise is\n // handed out around the hook, not through it.\n if (typeof owner.hooks.hostEntering !== \"function\") return behind();\n let started: { readonly value: T } | undefined;\n owner.hooks.hostEntering(hostOf(`DO:${owner.binding}`, owner.object), () => {\n started = { value: behind() };\n });\n return (started as unknown as { readonly value: T }).value;\n };\n type Then = (ok?: (v: unknown) => unknown, fail?: (e: unknown) => unknown) => unknown;\n return new Proxy(member, {\n apply: (target, self, args) =>\n starting(() => Reflect.apply(target as (...a: unknown[]) => unknown, self, args)),\n get(target, key) {\n const value = Reflect.get(target, key, target) as unknown;\n if (key !== \"then\" || typeof value !== \"function\") return value;\n const then: Then = (ok, fail) => starting(() => (value as Then)(ok, fail));\n return then;\n },\n });\n}\n\n/** `EventRef.source` of an object's wake at the end of a run. */\nexport const wakeSource = \"durable_object_wake\";\n\n/**\n * The event that wakes the object `id` of `binding`, the `n`-th of the run:\n * its instance was dropped by a crash and nothing has entered it since.\n */\nexport function wakeEvent(binding: string, id: string, object: string, n: number): EventRef {\n return {\n id: `wake:${binding}:${object}:${n}`,\n attempt: 1,\n source: wakeSource,\n data: { binding, id, object },\n };\n}\n\n/**\n * Wake an object the run's crashes left dropped, as its next event would:\n * the runtime constructs a new instance over the storage the old one left.\n * Without it only the end-of-run snapshot would construct the object, after\n * the run, where its constructor's requests, timers and clock are the real\n * ones. Here the constructor runs as the object's code inside one effect of\n * an invocation of its own, which hosts whatever effects it makes; the wake\n * itself takes no fault (it is the model's reading of the object, not an\n * event of the platform's), a fault on an effect the constructor makes\n * resets the object as anywhere else, and it is then woken again. A timer\n * the constructor leaves running is not followed (its code runs with no\n * context of the wake's), so the run is `UNSUPPORTED` rather than\n * snapshotted without what that work would have done.\n */\nexport async function deliverWake(\n event: EventRef,\n hooks: RunHooks,\n objects: ObjectAccess,\n): Promise<DeliveryResult> {\n const { binding, id, object } = event.data as { binding: string; id: string; object: string };\n const invocation = invocationOf(event);\n const inv = hooks.startInvocation(invocation);\n let leftTimer = false;\n const status = await hostedInObject(\n hooks,\n inv,\n objects,\n binding,\n id,\n object,\n { invocation, target: `DO:${binding}`, op: \"wake\", args: { object }, allowed: [] },\n async () => {\n // Entered as the object's code, so that where the runtime carries the context a timer the\n // constructor sets is the object's own work, waited for like any work after an answer.\n await hooks.hostedCode(hostOf(`DO:${binding}`, object), () =>\n objects.run(binding, id, object, async () => undefined),\n );\n // Where it does not (workerd), such a timer is this invocation's, whose end drops it:\n // looked for while the invocation is alive.\n leftTimer = hooks.timersPending(invocation);\n return null;\n },\n () => null,\n );\n // The runtime carries no context of the wake into the constructor, so a timer it set is this\n // invocation's, which is over: nothing would fire it, and the snapshot would miss what it does.\n if (status === \"completed\" && leftTimer)\n hooks.unsupported(\n `Durable Object ${binding} ${object} was woken at the end of the run and its constructor left a timer running; work a constructor starts and does not await is not followed there`,\n );\n return { status, followUps: [] };\n}\n\n/** What a delivery into an object needs of its namespace: to run code inside one, and the crash semantics. */\nexport interface ObjectAccess {\n run<T>(\n binding: string,\n id: string,\n object: string,\n fn: (instance: unknown, live: DurableObjectState) => Promise<T>,\n ): Promise<T | undefined>;\n abort(binding: string, id: string): void;\n mayPark(binding: string, id: string): boolean;\n evict(binding: string, id: string): Promise<void>;\n}\n\n/**\n * One effect of `inv` performed inside the object `id` of `binding`: `perform`\n * runs as the effect, which hosts what the object does; a fault that\n * abandons it resets the object, and a crash evicts the instance. The\n * invocation's outcome.\n */\nexport async function hostedInObject<T>(\n hooks: RunHooks,\n inv: Invocation,\n objects: ObjectAccess,\n binding: string,\n id: string,\n object: string,\n point: EffectPoint,\n perform: () => Promise<T>,\n summarize: (value: T) => JsonValue,\n): Promise<Outcome<T>[\"status\"]> {\n const { status } = await runInvocation(hooks, inv, () =>\n hooks.effect({ ...point, hostsEffects: true }, perform, summarize, {\n host: hostOf(`DO:${binding}`, object),\n onAbandon: () => objects.abort(binding, id),\n mayPark: () => objects.mayPark(binding, id),\n }),\n );\n if (status === \"crashed\") {\n await objects.evict(binding, id);\n hooks.hostReset(hostOf(`DO:${binding}`, object));\n }\n return status;\n}\n","/**\n * Durable Object alarms in virtual time. Eutaxy takes over each object's\n * alarm methods (on its storage and inside transactions), so the runtime\n * never schedules an alarm on the real clock, whose time is far ahead of\n * the virtual one. A set alarm is kept per object, so it survives eviction\n * as a real one does, and becomes an event due at its virtual time; when\n * the run reaches it, the object's `alarm()` handler runs as one effect.\n *\n * Semantics, as Cloudflare documents them (developers.cloudflare.com/\n * durable-objects/api/base/#alarm): an object has one alarm, a later\n * `setAlarm` replaces it, execution is at least once, and a handler that\n * throws is retried with exponential backoff starting at two seconds, up to\n * six retries, with `{ retryCount, isRetry }`. `setAlarm` inside a\n * transaction takes effect only if the transaction commits. How many\n * retries, how long before each and which alarm is superseded are the\n * rules of alarm-rules.ts, whose claims are proved; this file decides\n * none of the three itself, and counts an alarm's retries as its event's\n * attempts less one, by which `redelivery` applies the limit.\n */\n\nimport {\n type DeliveryResult,\n type EventRef,\n invocationOf,\n type JsonValue,\n type RunHooks,\n readFaults,\n redelivery,\n} from \"@eutaxy/core\";\nimport { alarmRetries, nextGeneration, retryDelayMs, superseded } from \"./alarm-rules.ts\";\nimport { hostedInObject, hostOf, type ObjectAccess } from \"./object-access.ts\";\n\n/** `EventRef.source` of an alarm event. */\nexport const alarmSource = \"durable_object_alarm\";\n\n/** One object's alarm, kept across its instances for the run. */\ninterface AlarmEntry {\n time: number | null;\n /**\n * The current alarm's generation: every setAlarm or deleteAlarm starts a\n * new one (`nextGeneration`), and an event or retry of an older\n * generation is superseded (`superseded`). It also numbers the alarm's\n * events, whose ids are unique by it.\n */\n gen: number;\n /** Times the alarm fired this run (retries not counted). */\n firings: number;\n}\n\n/** What an alarm event carries. */\ninterface AlarmData {\n readonly binding: string;\n readonly gen: number;\n readonly id: string;\n readonly object: string;\n readonly retryCount: number;\n}\n\n/** The alarms of one namespace's objects; the platform clears it before each run. */\nexport class AlarmBook {\n private readonly entries = new Map<string, AlarmEntry>();\n\n clear(): void {\n this.entries.clear();\n }\n\n entry(id: string): AlarmEntry {\n let e = this.entries.get(id);\n if (!e) {\n e = { time: null, gen: 0, firings: 0 };\n this.entries.set(id, e);\n }\n return e;\n }\n}\n\n/** The alarm of one object, as its taken-over methods see it. */\nexport interface AlarmControl {\n get(): number | null;\n set(time: number): void;\n delete(): void;\n /** Report something about the object's alarms that Eutaxy cannot model faithfully. */\n unsupported(reason: string): void;\n}\n\n/** One alarm control per object: setting schedules an event at the alarm's virtual time. */\nexport function alarmControl(\n book: AlarmBook,\n binding: string,\n id: string,\n object: string,\n hooks: () => RunHooks,\n): AlarmControl {\n const entry = book.entry(id);\n return {\n get: () => entry.time,\n set: (time) => {\n entry.time = time;\n entry.gen = nextGeneration(entry.gen);\n const data: AlarmData = { binding, gen: entry.gen, id, object, retryCount: 0 };\n const now = Date.now();\n hooks().enqueue({\n id: `alarm:${binding}:${object}:${entry.gen}`,\n attempt: 1,\n source: alarmSource,\n data: data as unknown as JsonValue,\n ...(time > now ? { at: time } : {}),\n });\n },\n delete: () => {\n entry.time = null;\n // Supersedes the pending event and any retry of it.\n entry.gen = nextGeneration(entry.gen);\n },\n unsupported: (reason) => hooks().unsupported(`Durable Object ${binding} ${object}: ${reason}`),\n };\n}\n\n/** Storage objects whose alarm methods Eutaxy has taken over (one per live instance). */\nexport const takenOver = new WeakSet<object>();\n\nconst timeOf = (time: number | Date) => (typeof time === \"number\" ? time : time.getTime());\n\n/** Storage objects whose alarm was read before Eutaxy took them over (in a constructor). */\nconst readBeforeTakeover = new WeakSet<object>();\n/** Storage prototypes whose getAlarm records such reads. */\nconst watched = new WeakSet<object>();\n\n/**\n * Record reads of the native alarm on storage not yet taken over: a rebuilt\n * object's constructor reads native storage, where Eutaxy's pending alarm is\n * not. The wrapper only records; it returns what the native method returns.\n */\nfunction watchReads(storage: DurableObjectStorage): void {\n const proto = Object.getPrototypeOf(storage) as { getAlarm?: (...a: unknown[]) => unknown };\n if (!proto || watched.has(proto) || typeof proto.getAlarm !== \"function\") return;\n watched.add(proto);\n const native = proto.getAlarm;\n proto.getAlarm = function (this: object, ...args: unknown[]) {\n if (!takenOver.has(this)) readBeforeTakeover.add(this);\n return native.apply(this, args);\n };\n}\n\n/**\n * Replace an object's alarm methods so no real alarm is ever scheduled. An\n * alarm the object set before the takeover (in its constructor) is moved\n * over: deleted from the runtime and set on the control, unless an alarm is\n * still pending, which the constructor could not see in native storage\n * (Eutaxy keeps it): then the pending one stays and the run is UNSUPPORTED.\n */\nexport async function takeOverAlarms(\n storage: DurableObjectStorage,\n alarm: AlarmControl,\n): Promise<void> {\n if (takenOver.has(storage)) return;\n // From the first takeover on, later instances' constructor reads are recorded.\n watchReads(storage);\n takenOver.add(storage);\n if (readBeforeTakeover.has(storage) && alarm.get() !== null) {\n alarm.unsupported(\n \"its constructor read the alarm while one was pending; natively it would have seen that alarm, so constructors that read the alarm are not modelled\",\n );\n }\n const existing = await storage.getAlarm();\n if (existing !== null) {\n await storage.deleteAlarm();\n if (alarm.get() === null) alarm.set(existing);\n else\n alarm.unsupported(\n \"its constructor set an alarm while one was pending; natively it would have seen that alarm, so constructors that read the alarm are not modelled\",\n );\n }\n const s = storage as unknown as Record<string, unknown>;\n // Inside transactionSync an alarm change would have to roll back with it: not modelled.\n let inSync = false;\n const outsideSync = (op: string) => {\n if (inSync) alarm.unsupported(`${op} inside transactionSync() is not modelled`);\n };\n Object.assign(s, {\n setAlarm: async (time: number | Date) => {\n outsideSync(\"setAlarm\");\n alarm.set(timeOf(time));\n },\n getAlarm: async () => alarm.get(),\n deleteAlarm: async () => {\n outsideSync(\"deleteAlarm\");\n alarm.delete();\n },\n });\n if (typeof s[\"transactionSync\"] === \"function\") {\n const transactionSync = (s[\"transactionSync\"] as (cb: () => unknown) => unknown).bind(storage);\n s[\"transactionSync\"] = (callback: () => unknown) => {\n inSync = true;\n try {\n return transactionSync(callback);\n } finally {\n inSync = false;\n }\n };\n }\n const transaction = (\n s[\"transaction\"] as (cb: (txn: unknown) => unknown) => Promise<unknown>\n ).bind(storage);\n // Inside a transaction an alarm change is held until the transaction commits.\n s[\"transaction\"] = async (callback: (txn: unknown) => unknown) => {\n // Per attempt: the runtime may run the callback again after a conflict, discarding the first.\n let pending: { time: number | null } | undefined;\n let rolledBack = false;\n const held = {\n setAlarm: async (time: number | Date) => {\n pending = { time: timeOf(time) };\n },\n getAlarm: async () => (pending ? pending.time : alarm.get()),\n deleteAlarm: async () => {\n pending = { time: null };\n },\n };\n const result = await transaction((txn) => {\n pending = undefined;\n rolledBack = false;\n return callback(\n new Proxy(txn as Record<string, unknown>, {\n get(target, prop) {\n if (typeof prop === \"string\" && prop in held) return held[prop as keyof typeof held];\n const value = target[prop as string];\n if (prop === \"rollback\" && typeof value === \"function\") {\n return (...args: unknown[]) => {\n rolledBack = true;\n return (value as (...a: unknown[]) => unknown).apply(target, args);\n };\n }\n // Native methods check their receiver: call them on the real transaction.\n return typeof value === \"function\" ? value.bind(target) : value;\n },\n }),\n );\n });\n if (pending && !rolledBack) {\n if (pending.time === null) alarm.delete();\n else alarm.set(pending.time);\n }\n return result;\n };\n}\n\nexport interface AlarmDelivery {\n readonly binding: string;\n readonly book: AlarmBook;\n /** Alarm firings allowed per object per run; later ones are recorded and not fired. */\n readonly limit: number;\n /** The namespace's objects: the handler runs inside one, with an alarm's crash semantics. */\n readonly objects: ObjectAccess;\n /** Record a platform action (an alarm not fired, a handler given up on). */\n readonly bookkeep: (op: string, args: JsonValue) => void;\n}\n\n/**\n * Run an object's `alarm()` handler inside it, after taking over its alarms\n * (the instance may be new since the alarm was set).\n */\nexport async function runAlarm(\n hooks: RunHooks,\n d: Pick<AlarmDelivery, \"binding\" | \"book\" | \"objects\">,\n id: string,\n object: string,\n info: { readonly retryCount: number; readonly isRetry: boolean },\n gen: number,\n): Promise<void> {\n await d.objects.run(d.binding, id, object, async (instance) => {\n // Superseded while the effect waited for its turn: the handler of a cancelled alarm never runs.\n const entry = d.book.entry(id);\n if (superseded(gen, entry.gen)) return;\n // The alarm is consumed as its handler starts: from here getAlarm() returns null.\n entry.time = null;\n const handler = (instance as { alarm?: (info: unknown) => unknown }).alarm;\n if (typeof handler !== \"function\") {\n hooks.unsupported(\n `Durable Object ${d.binding} ${object} set an alarm but has no alarm() handler`,\n );\n return;\n }\n await hooks.hostedCode(hostOf(`DO:${d.binding}`, object), () => handler.call(instance, info));\n });\n}\n\n/**\n * Fire an alarm event: skip it when the object's alarm has since been set\n * again or deleted, run `alarm()` as one effect otherwise, and schedule a\n * retry with backoff when the handler fails, crashes, or a fault says it\n * did.\n */\nexport async function deliverAlarm(\n event: EventRef,\n hooks: RunHooks,\n maxRedeliveries: number,\n d: AlarmDelivery,\n): Promise<DeliveryResult> {\n const a = event.data as unknown as AlarmData;\n const entry = d.book.entry(a.id);\n // Superseded by a later setAlarm or deleteAlarm: dropped before anything, faults included.\n if (superseded(a.gen, entry.gen)) return { status: \"completed\", followUps: [] };\n if (a.retryCount === 0) {\n // It stays set until the handler starts (runAlarm clears it after the takeover), as natively.\n if (entry.firings >= d.limit) {\n entry.time = null;\n d.bookkeep(\"alarm_not_fired\", { object: a.object, firings: entry.firings });\n return { status: \"completed\", followUps: [] };\n }\n entry.firings++;\n }\n const invocation = invocationOf(event);\n const inv = hooks.startInvocation(invocation);\n const info = { retryCount: a.retryCount, isRetry: a.retryCount > 0 };\n // A crash is the object's: its in-memory state goes with the instance, whatever the handler did.\n const status = await hostedInObject(\n hooks,\n inv,\n d.objects,\n d.binding,\n a.id,\n a.object,\n {\n invocation,\n target: `DO:${d.binding}`,\n op: \"alarm\",\n args: { object: a.object, retryCount: a.retryCount },\n // Crash before: the handler never ran. Crash after: it ran and committed, but counts as failed.\n allowed: readFaults,\n },\n async () => {\n await runAlarm(hooks, d, a.id, a.object, info, a.gen);\n return null;\n },\n () => null,\n );\n if (status !== \"completed\") {\n // The retries so far are the attempt less one: retryCount counts them too.\n const next = redelivery(event, alarmRetries, { maxRedeliveries });\n if (next) {\n const retryAt = Date.now() + retryDelayMs(a.retryCount);\n const data: AlarmData = { ...a, retryCount: a.retryCount + 1 };\n // The alarm stays set, for its retry, until a later change supersedes it.\n if (!superseded(a.gen, entry.gen)) entry.time = retryAt;\n hooks.enqueue({ ...next, data: data as unknown as JsonValue, at: retryAt });\n } else {\n // Given up on: no longer pending, unless a newer alarm replaced it meanwhile.\n if (!superseded(a.gen, entry.gen)) entry.time = null;\n d.bookkeep(\"alarm_gave_up\", { object: a.object, retries: a.retryCount });\n }\n }\n return { status, followUps: [] };\n}\n","/**\n * The Durable Object namespace proxy. The objects are the real ones workerd\n * runs: storage, transactions and the input and output gates are the\n * runtime's own. Eutaxy proxies the boundary a Worker crosses to reach them:\n * every call on a stub is an effect point, so a call can fail before it\n * reaches the object (`crash_before`, `error`), or reach it, commit, and\n * lose its answer (`ambiguous`) or its caller (`crash_after`).\n *\n * Between runs every object is cleared, seeded from the scenario's setup\n * and evicted, so it starts from storage alone; after a run its storage is\n * snapshotted for state invariants. Both go through the Cloudflare Vitest\n * plugin's test helpers. Alarms are taken over on each object's storage and\n * fire in virtual time (see alarms.ts).\n */\n\nimport { canonicalJson, type JsonValue, type RunHooks, toJson, writeFaults } from \"@eutaxy/core\";\nimport { withoutNetwork } from \"@eutaxy/engine\";\nimport { AlarmBook, alarmControl, takenOver, takeOverAlarms } from \"./alarms.ts\";\nimport { envView, hostMethod, hostOf, outsideRunEnv, ownEnv } from \"./object-access.ts\";\nimport { outboundGate, type ProxyContext } from \"./proxy-context.ts\";\nimport type { DurableObjectSqlSeed, ScriptedObjectSetup, ServiceSetup } from \"./scenario.ts\";\n\n/** Seeds by object name: key-value entries, and SQL for SQLite-backed objects. */\ntype Seeds = { readonly [name: string]: { readonly [key: string]: JsonValue } };\ntype SqlSeeds = { readonly [name: string]: DurableObjectSqlSeed };\n\n/** The SQL surface the seed and the snapshot use, as workerd's `ctx.storage.sql` offers it. */\ninterface SqlSurface {\n exec(query: string, ...bindings: unknown[]): { toArray(): Record<string, unknown>[] };\n}\n\n/** A storage's SQL surface, when the object is SQLite-backed; a key-value object has none that works. */\nfunction sqlOf(storage: unknown): SqlSurface | undefined {\n const sql = (storage as { sql?: unknown }).sql;\n if (typeof sql !== \"object\" || sql === null || typeof (sql as SqlSurface).exec !== \"function\")\n return undefined;\n try {\n (sql as SqlSurface).exec(\"SELECT 1\");\n return sql as SqlSurface;\n } catch {\n return undefined;\n }\n}\n\n/** A JSON value as SQLite stores it: booleans as 0 and 1, objects and arrays as their JSON text. */\nfunction sqlValue(v: JsonValue): unknown {\n if (typeof v === \"boolean\") return v ? 1 : 0;\n if (typeof v === \"object\" && v !== null) return JSON.stringify(v);\n return v;\n}\n\nconst quoted = (name: string): string => `\"${name.replaceAll('\"', '\"\"')}\"`;\n\n/** Run a seed: the schema, then one insert per row. */\nfunction seedSql(sql: SqlSurface, seed: DurableObjectSqlSeed): void {\n sql.exec(seed.schema);\n for (const [table, rows] of Object.entries(seed.rows ?? {}))\n for (const row of rows) {\n const columns = Object.keys(row);\n if (columns.length === 0) {\n // Every column defaulted or generated: still one row.\n sql.exec(`INSERT INTO ${quoted(table)} DEFAULT VALUES`);\n continue;\n }\n sql.exec(\n `INSERT INTO ${quoted(table)} (${columns.map(quoted).join(\", \")}) VALUES (${columns.map(() => \"?\").join(\", \")})`,\n ...columns.map((c) => sqlValue(row[c] as JsonValue)),\n );\n }\n}\n\n/** The user tables of a SQLite-backed object: not SQLite's own, not the runtime's (`_cf_*`, the key-value API's among them). */\nfunction userTables(sql: SqlSurface): string[] {\n return sql\n .exec(\n \"SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite\\\\_%' ESCAPE '\\\\' AND name NOT LIKE '\\\\_cf\\\\_%' ESCAPE '\\\\' ORDER BY name\",\n )\n .toArray()\n .map((r) => String(r[\"name\"]));\n}\n\n/** Each user table of a SQLite-backed object with its rows, as the storage holds them. */\nfunction readSqlTables(sql: SqlSurface): [string, JsonValue[]][] {\n return userTables(sql).map((t) => [\n t,\n sortedRows(sql.exec(`SELECT * FROM ${quoted(t)}`).toArray()),\n ]);\n}\n\n/** The SQL tables each seeded object held right after its seed, as the snapshot of an object the run never reached. */\nexport type SeededSql = Map<string, [string, JsonValue[]][]>;\n\n/** A table's rows in a fixed order: a table has none of its own, so the canonical JSON of each row decides. */\nfunction sortedRows(rows: readonly Record<string, unknown>[]): JsonValue[] {\n return rows\n .map((r) => toJson(r))\n .sort((a, b) => {\n const x = canonicalJson(a);\n const y = canonicalJson(b);\n return x < y ? -1 : x > y ? 1 : 0;\n });\n}\n\n/**\n * The Cloudflare Vitest plugin's test helpers, as exported by\n * `cloudflare:test` (pass the module namespace). Typed loosely on purpose:\n * the plugin's generic overloads are too deep to check against an interface.\n */\nexport interface DurableObjectTestHelpers {\n readonly runInDurableObject: unknown;\n readonly evictDurableObject: unknown;\n readonly listDurableObjectIds: unknown;\n}\n\n/** The helpers with the signatures this module calls them with. */\ninterface Helpers {\n runInDurableObject<R>(\n stub: DurableObjectStub,\n callback: (instance: unknown, state: DurableObjectState) => R | Promise<R>,\n ): Promise<R>;\n evictDurableObject(stub: DurableObjectStub): Promise<void>;\n listDurableObjectIds(namespace: DurableObjectNamespace): Promise<DurableObjectId[]>;\n}\n\nconst typed = (helpers: DurableObjectTestHelpers): Helpers => helpers as unknown as Helpers;\n\n/** Object names by id, so snapshots and the log name objects as the Worker does. */\nexport type ObjectNames = Map<string, string>;\n\n/** How deep each object state is inside blockConcurrencyWhile, while it is. */\nconst gateDepth = new WeakMap<object, number>();\n/** Object-state prototypes whose blockConcurrencyWhile records that depth. */\nconst gateWatched = new WeakSet<object>();\n/**\n * By object id, the host an object's code runs as and the run it runs in,\n * noted before each entry into the object: what its constructor does on the\n * way in has no other way to know whose code it is.\n */\nconst hostOfId = new Map<\n string,\n {\n readonly hooks: () => RunHooks;\n readonly host: string;\n readonly binding: string;\n readonly object: string;\n /** The platform's proxy context: its env answers the object's bindings, its slot carries the gate. */\n readonly ctx: ProxyContext;\n /** Told the instance's state as soon as it is constructed: the gate it may hold is watched from then. */\n readonly constructed: (state: DurableObjectState) => void;\n /** Told when a callback behind the instance's input gate failed: the runtime resets the object. */\n readonly broken: (state: DurableObjectState) => void;\n /** Told when the object's own code calls `ctx.abort()`: a reset the simulation did not make. */\n readonly selfReset: () => void;\n }\n>();\n\n/**\n * Whether the platform is running a scenario (from its reset to its\n * cleanup). Only then is a construction the scenario's: the base a class\n * was given stays on it, and outside the platform's runs (the differential\n * runner's raw side, which compares against the real bindings) it hands\n * the runtime's env on untouched.\n */\nlet simulating = false;\n\n/** Tell that the platform's run of a scenario begins or is over. */\nexport function simulatingConstruction(on: boolean): void {\n simulating = on;\n if (!on) hostOfId.clear();\n}\n\n/** Forget every object's host: a new run notes them again as it enters each. */\nexport function forgetHosts(): void {\n hostOfId.clear();\n}\n\n/** The scenario's scripts by binding (a service's, a namespace's), for what a constructor calls while its object is reset. */\nlet scriptedOutsideRuns: (binding: string) => ServiceSetup | ScriptedObjectSetup | undefined = () =>\n undefined;\n\n/** Tell which service bindings and namespaces the scenario being reset scripts (see `outsideRunEnv`). */\nexport function scriptsOutsideRuns(\n scripted: (binding: string) => ServiceSetup | ScriptedObjectSetup | undefined,\n): void {\n scriptedOutsideRuns = scripted;\n}\n\n/** The bases the platform gave to Durable Object classes (`simulateConstruction`). */\nconst simulatedBases = new WeakSet<object>();\n\n/**\n * Give each Durable Object class among a module's exports a base that hands\n * its constructor the scenario's view of env (`envView`), so that\n * `this.env` is the scenario's from the constructor's first line: a call\n * the constructor makes through a service binding is answered as any of the\n * object's is. The class that extends the runtime's `DurableObject` (found\n * by name, as the entrypoint bases are) is made to extend a class of the\n * platform's that extends it in turn; the runtime constructs the same\n * class as before. Outside a run (the reset) the constructor is given an\n * env whose service bindings refuse. A class the platform is not given, or\n * the `env` parameter a constructor keeps for itself, is out of reach.\n */\nexport function simulateConstruction(exports: Readonly<Record<string, unknown>> | undefined): void {\n for (const value of Object.values(exports ?? {})) {\n if (typeof value !== \"function\") continue;\n // The class that extends the runtime's base directly, unless it was given a base already.\n let direct: object | undefined = value;\n while (direct !== undefined) {\n const parent = Object.getPrototypeOf(direct) as unknown;\n if (\n typeof parent !== \"function\" ||\n parent === Function.prototype ||\n simulatedBases.has(parent)\n )\n direct = undefined;\n else if ((parent as { name: string }).name === \"DurableObject\") break;\n else direct = parent;\n }\n if (direct === undefined) continue;\n const real = Object.getPrototypeOf(direct) as new (state: unknown, env: unknown) => object;\n const base = class extends real {\n constructor(state: unknown, env: unknown) {\n super(state, constructionEnv(state, env));\n }\n };\n // Still the runtime's base to anything that looks for it by name.\n Object.defineProperty(base, \"name\", { value: \"DurableObject\" });\n simulatedBases.add(base);\n Object.setPrototypeOf(direct, base);\n Object.setPrototypeOf((direct as { prototype: object }).prototype, base.prototype);\n }\n}\n\n/** The env a class given a simulated base is constructed with: the entering run's view, or the refusing one outside a run. */\nfunction constructionEnv(state: unknown, env: unknown): unknown {\n if (!simulating || env === null || typeof env !== \"object\") return env;\n const id = (state as { id?: { toString(): string } } | null)?.id;\n const of = id === undefined ? undefined : hostOfId.get(id.toString());\n if (!of) return outsideRunEnv(env, scriptedOutsideRuns);\n // Before the constructor's own code runs: a gate it takes is seen, and its effects wait behind it.\n // The gate is watched from here too: for an object nobody seeded, no reset has installed that yet.\n watchGate(state as DurableObjectState);\n watchAbort(state as DurableObjectState);\n of.constructed(state as DurableObjectState);\n const sync = (state as { storage?: { sync?: () => Promise<void> } }).storage?.sync;\n const storage = (state as { storage?: object }).storage;\n return envView(\n env,\n { hooks: of.hooks(), binding: of.binding, object: of.object },\n of.ctx.env,\n of.ctx.gate && typeof sync === \"function\"\n ? { slot: of.ctx.gate, durable: () => sync.call(storage) }\n : undefined,\n );\n}\n\n/** State prototypes whose `abort` tells the run of a reset an object makes itself. */\nconst abortWatched = new WeakSet<object>();\n/** Set while the simulation itself aborts an object, for a crash it injected (`BindingState.abort`). */\nlet simulationAborts = false;\n\n/**\n * Tell the run when an object resets itself. `ctx.abort()` called by the\n * object's own code ends the requests inside it and drops the instance,\n * with what the object held in memory\n * (developers.cloudflare.com/durable-objects/api/state/#abort). The\n * simulation resets an object itself where it injects a crash, and then\n * accounts for what the object had in flight; a reset it did not make is\n * not accounted for, so the run is UNSUPPORTED (`selfReset`), wherever in\n * the object's code the abort is: a call, an alarm, work after its answer.\n * The wrapper only tells: the abort happens as the runtime makes it. It is\n * on the prototype the states share, installed where the first state is\n * seen: before the constructor for a class given a simulated base, and at\n * the scenario's reset or the first entry otherwise. Not seen: an `abort`\n * a constructor saved by reference (`ctx.abort.bind(ctx)`) before any\n * state was seen, in a class without a simulated base, on the isolate's\n * first run.\n */\nfunction watchAbort(state: DurableObjectState): void {\n const proto = Object.getPrototypeOf(state) as { abort?: (reason?: string) => void };\n if (!proto || abortWatched.has(proto) || typeof proto.abort !== \"function\") return;\n abortWatched.add(proto);\n const native = proto.abort;\n proto.abort = function (this: object, reason?: string) {\n if (simulating && !simulationAborts) {\n const id = (this as { id?: { toString(): string } }).id;\n (id === undefined ? undefined : hostOfId.get(id.toString()))?.selfReset();\n }\n return native.call(this, reason);\n };\n}\n\n/**\n * Record when an object holds its input gate with blockConcurrencyWhile,\n * on the state prototype so constructors are covered too, and run what it\n * holds the gate for as the object's code (`RunHooks.hostEntering`): a\n * constructor's work behind the gate has no context of the call entering\n * the object, and a timer it awaited would be nobody's to fire. Inside a\n * method the code is the object's already and runs as it is. A callback\n * that fails breaks the gate, and the runtime resets the object\n * (developers.cloudflare.com/durable-objects/api/state/#blockconcurrencywhile):\n * the run is told (`broken`), so nothing waits on the instance that is\n * gone.\n */\nfunction watchGate(state: DurableObjectState): void {\n const proto = Object.getPrototypeOf(state) as {\n blockConcurrencyWhile?: (cb: () => Promise<unknown>) => Promise<unknown>;\n };\n if (!proto || gateWatched.has(proto) || typeof proto.blockConcurrencyWhile !== \"function\") return;\n gateWatched.add(proto);\n const native = proto.blockConcurrencyWhile;\n proto.blockConcurrencyWhile = function (this: object, callback: () => Promise<unknown>) {\n const id = (this as { id?: { toString(): string } }).id;\n const of = !simulating || id === undefined ? undefined : hostOfId.get(id.toString());\n // The state holding a gate is its object's live one, whether or not its class was given a base.\n of?.constructed(this as DurableObjectState);\n const held = async (): Promise<unknown> => {\n gateDepth.set(this, (gateDepth.get(this) ?? 0) + 1);\n try {\n return await callback();\n } catch (err) {\n of?.broken(this as DurableObjectState);\n throw err;\n } finally {\n gateDepth.set(this, (gateDepth.get(this) ?? 1) - 1);\n }\n };\n return native.call(this, of ? () => of.hooks().hostEntering(of.host, held) : held);\n };\n}\n\n/** Whether the object is inside blockConcurrencyWhile now. */\nfunction gateHeld(state: DurableObjectState | undefined): boolean {\n return state !== undefined && (gateDepth.get(state) ?? 0) > 0;\n}\n\n/** What Eutaxy keeps about one namespace during a run; the platform clears it before each run. */\nexport class BindingState {\n /** Names learned this run (seeded ones come back with the setup), so traces never depend on earlier runs. */\n readonly names: ObjectNames = new Map();\n /** Ids of the objects a call or an alarm reached this run. */\n readonly touched = new Set<string>();\n /** The objects' alarms in virtual time. */\n readonly alarms = new AlarmBook();\n /** Each reached object's live state, so an invocation that crashes inside it can reset it. */\n readonly states = new Map<string, DurableObjectState>();\n /**\n * Ids of the objects whose instance a crash dropped (a reset inside the\n * object, or its eviction after one) and nothing has entered since. One\n * still here when the run would end is woken inside the run (`wakeEvents`).\n */\n readonly dropped = new Set<string>();\n /** Ids of the objects that reset themselves this run (their own `ctx.abort()`), each told once. */\n private readonly resetThemselves = new Set<string>();\n /** The SQL tables the seed left in each seeded object, materialized, for the snapshot of one never reached. */\n seededSql: SeededSql = new Map();\n\n /** Whether the object's own effects may wait for a turn: not while it holds its input gate. */\n mayPark(id: string): boolean {\n return !gateHeld(this.states.get(id));\n }\n\n clear(): void {\n this.names.clear();\n this.touched.clear();\n this.alarms.clear();\n this.states.clear();\n this.dropped.clear();\n this.resetThemselves.clear();\n this.seededSql = new Map();\n }\n\n /** The object reset itself: true the first time this run, so the run is told once for it. */\n selfReset(id: string): boolean {\n if (this.resetThemselves.has(id)) return false;\n this.resetThemselves.add(id);\n return true;\n }\n\n /**\n * The object's instance is gone because a callback behind its input gate\n * failed, which makes the runtime reset it. Nothing to abort: the runtime\n * did. Not for an instance a crash already reset (its failing callback\n * is that crash unwinding), nor for one a newer instance has replaced.\n */\n broke(id: string, live: DurableObjectState, reset: () => void): void {\n if (this.states.get(id) !== live) return;\n this.states.delete(id);\n this.dropped.add(id);\n reset();\n }\n\n /**\n * Reset an object the way a crash does, with `ctx.abort()`, which\n * application code cannot catch: the runtime ends the requests inside it.\n * Called where an injected crash happens inside the object's own work,\n * which is the one place abort() works (from outside, workerd refuses).\n */\n abort(id: string): void {\n const state = this.states.get(id);\n this.states.delete(id);\n this.dropped.add(id);\n // The simulation's own reset: not one the object made (`watchAbort`).\n simulationAborts = true;\n try {\n state?.abort(\"Eutaxy: the invocation crashed inside this object\");\n } catch {\n // abort() throws to unwind the object's code; the reset has happened.\n } finally {\n simulationAborts = false;\n }\n }\n}\n\n/** The storage's own alarm deletion, even after Eutaxy replaced the method on it. */\nasync function deleteRealAlarm(storage: DurableObjectStorage): Promise<void> {\n const proto = Object.getPrototypeOf(storage) as { deleteAlarm?: () => Promise<void> };\n const own = Object.hasOwn(storage, \"deleteAlarm\");\n const deleteAlarm = own ? proto.deleteAlarm : storage.deleteAlarm;\n await deleteAlarm?.call(storage);\n}\n\n/** An RPC argument as effect-log data; a Request becomes its method and URL. */\nfunction argument(value: unknown): JsonValue {\n if (value instanceof Request) return { method: value.method, url: value.url };\n return toJson(value);\n}\n\n/**\n * Whether a result is data the caller holds by value. Anything else (an RPC\n * capability, an object with methods) would let later calls bypass the\n * proxy, so it makes the run UNSUPPORTED.\n */\nexport function isPlainData(value: unknown, depth = 0): boolean {\n if (value === null || value === undefined) return true;\n if (typeof value === \"function\") return false;\n if (typeof value !== \"object\") return true;\n // Too deep to inspect: not certified as data.\n if (depth > 8) return false;\n if (value instanceof Response || value instanceof Date) return true;\n if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer) return true;\n const proto = Object.getPrototypeOf(value);\n if (Array.isArray(value)) return value.every((v) => isPlainData(v, depth + 1));\n if (proto !== Object.prototype && proto !== null) return false;\n return Object.values(value).every((v) => isPlainData(v, depth + 1));\n}\n\n/**\n * A call's plain result as the caller gets it: a copy, with the runtime's\n * own result disposed. The runtime's result keeps the call's session open\n * until it is disposed or collected, and an object that hands it on as its\n * own answer (`return stub.method()`) would keep the object it called\n * referenced past the run, where the next run's reset cannot evict it. A\n * `Response` is the caller's as it is.\n */\nfunction released<T>(result: T): T {\n if (result === null || typeof result !== \"object\" || result instanceof Response) return result;\n let copy: T;\n try {\n copy = structuredClone(result);\n } catch {\n // Something inside does not clone (a Response): the caller keeps the runtime's own.\n return result;\n }\n const dispose =\n disposer === undefined ? undefined : (result as Record<symbol, unknown>)[disposer];\n if (disposer !== undefined && typeof dispose === \"function\") {\n // Code that disposes its results (`using`) still can.\n Object.defineProperty(copy, disposer, { value: () => {}, enumerable: false });\n dispose.call(result);\n }\n return copy;\n}\n\n/** `Symbol.dispose`, where the host has it (the compile target's library does not name it). */\nconst disposer = (Symbol as unknown as { readonly dispose?: symbol }).dispose;\n\n/** An RPC result as effect-log data; a Response becomes its status. */\nfunction summarize(result: unknown): JsonValue {\n if (result instanceof Response) return { status: result.status, ok: result.ok };\n return toJson(result);\n}\n\nexport function proxyNamespace(\n real: DurableObjectNamespace,\n binding: string,\n ctx: ProxyContext,\n state: BindingState,\n helpers: DurableObjectTestHelpers | undefined,\n /** Whether the running scenario resets this namespace (has a `durableObject` setup for it). */\n isReset: () => boolean,\n): DurableObjectNamespace {\n const target = `DO:${binding}`;\n const { names } = state;\n const nameOf = (id: DurableObjectId) => names.get(id.toString()) ?? id.toString();\n\n function stubFor(stub: DurableObjectStub, id: string, object: string): DurableObjectStub {\n /** Make sure the call may reach the object, take over its alarms first, and host the method about to run. */\n async function reach(real: DurableObjectStub, method?: string): Promise<void> {\n if (!helpers) {\n ctx.hooks.unsupported(\n `Durable Object binding ${binding} needs the Cloudflare test helpers (pass durableObjects to createCloudflarePlatform)`,\n );\n } else if (!isReset()) {\n ctx.hooks.unsupported(\n `Durable Object binding ${binding} has no durableObject setup, so its objects are not reset between runs; add durableObject(${JSON.stringify(binding)}) to the scenario's setup`,\n );\n } else {\n await enterObject(real, binding, ctx, helpers, state, id, object, async (instance) => {\n if (method !== undefined) hostMethod(ctx.hooks, hostOf(target, object), instance, method);\n });\n }\n }\n\n /** A result passed back to the caller; one that is not plain data cannot be followed. */\n function plain<T>(result: T): T {\n if (!isPlainData(result)) {\n ctx.hooks.unsupported(\n `Durable Object ${binding} ${object} returned something that is not plain data (an RPC capability or an object with methods); calls on it would bypass Eutaxy`,\n );\n return result;\n }\n return released(result);\n }\n\n /**\n * The promise a call returns. On a real stub it is an RPC promise that\n * pipelines property reads (`stub.getData().value`); this one is not, so\n * a read on it makes the run UNSUPPORTED instead of yielding undefined.\n */\n function pipelineGuard<T>(promise: Promise<T>): Promise<T> {\n return new Proxy(promise, {\n get(target, prop) {\n if (\n typeof prop === \"symbol\" ||\n prop === \"then\" ||\n prop === \"catch\" ||\n prop === \"finally\"\n ) {\n const value = Reflect.get(target, prop, target);\n return typeof value === \"function\" ? value.bind(target) : value;\n }\n ctx.hooks.unsupported(\n `Durable Object ${binding} ${object}: RPC promise pipelining (reading .${prop} on a call's promise) is not supported; await the call first`,\n );\n return undefined;\n },\n });\n }\n\n /** One effect on the object: a method call, or awaiting an RPC property. */\n function onObject(op: string, args: JsonValue, perform: () => Promise<unknown>) {\n return ctx.hooks.effect(\n // The object's own effects during the call (its fetch) belong to this call's turn.\n {\n invocation: ctx.currentInvocation(),\n target,\n op,\n args,\n allowed: writeFaults,\n hostsEffects: true,\n },\n // From another object the call leaves once that object's earlier writes are durable.\n outboundGate(ctx, perform),\n summarize,\n {\n // The object's code is the host's: inside the call its effects are the call's; after the\n // answer, work it goes on with is the object's own turns.\n host: hostOf(target, object),\n // A crash inside the object's own work leaves its request pending: reset the object.\n onAbandon: () => state.abort(id),\n // Inside blockConcurrencyWhile nothing else enters the object: its effects run at once.\n mayPark: () => state.mayPark(id),\n },\n );\n }\n\n return new Proxy(stub, {\n get(real, prop, receiver) {\n // A stub is not a promise; `id` and `name` are not calls.\n if (prop === \"then\") return undefined;\n if (typeof prop !== \"string\" || prop === \"id\" || prop === \"name\")\n return Reflect.get(real, prop, receiver);\n // `stub.method(...)` calls it; `await stub.property` reads an RPC getter. Both are one effect.\n const call = (...args: unknown[]) =>\n pipelineGuard(\n onObject(prop, { object, args: args.map(argument) }, async () => {\n await reach(real, prop);\n // Reflect.apply, not method.apply: an RPC stub's methods are proxies, `.apply` would be a call.\n const method = (real as unknown as Record<string, (...a: unknown[]) => unknown>)[\n prop\n ];\n if (typeof method !== \"function\")\n throw new TypeError(`${binding} stub has no ${prop}`);\n const result = await Reflect.apply(method, real, args);\n // A 101 from the object's fetch: a WebSocket connection now reaches this object.\n if (\n prop === \"fetch\" &&\n result instanceof Response &&\n result.status === 101 &&\n result.webSocket\n )\n ctx.onUpgrade?.({\n binding,\n id,\n object,\n invocation: ctx.currentInvocation(),\n client: result.webSocket,\n });\n return plain(result);\n }),\n );\n const read = () =>\n onObject(prop, { object, property: true }, async () => {\n await reach(real, prop);\n return plain(await (real as unknown as Record<string, unknown>)[prop]);\n });\n const awaitable = (\n onFulfilled?: (v: unknown) => unknown,\n onRejected?: (e: unknown) => unknown,\n ) => read().then(onFulfilled, onRejected);\n // Callable and awaitable; any other property read is pipelining, which is not modelled.\n return new Proxy(call, {\n get(target, key) {\n if (key === \"then\") return awaitable;\n if (typeof key === \"symbol\") return Reflect.get(target, key);\n ctx.hooks.unsupported(\n `Durable Object ${binding} ${object}: RPC promise pipelining (reading .${prop}.${key}) is not supported; await .${prop} first`,\n );\n return undefined;\n },\n });\n },\n });\n }\n\n function idFromName(name: string): DurableObjectId {\n const id = real.idFromName(name);\n names.set(id.toString(), name);\n return id;\n }\n\n return new Proxy(real, {\n get(target, prop, receiver) {\n switch (prop) {\n case \"idFromName\":\n return idFromName;\n case \"idFromString\":\n return (hex: string) => target.idFromString(hex);\n case \"newUniqueId\":\n return (options?: DurableObjectNamespaceNewUniqueIdOptions) => {\n if (options?.jurisdiction !== undefined) {\n ctx.hooks.unsupported(\n `${binding}.newUniqueId({ jurisdiction }) ids are not proxied or reset; use newUniqueId() without one`,\n );\n return target.newUniqueId(options);\n }\n // Natively the id is random. Drawn from the run's random stream it repeats on replay, and the\n // draw counts as a read of randomness, as it must: which id an invocation gets depends on\n // the order of turns. The id is a named one (its name is the draw), so the real namespace\n // accepts it and the reset finds its object; a Worker reading `id.name` sees that name.\n return idFromName(`eutaxy:unique:${crypto.randomUUID()}`);\n };\n case \"get\":\n return (id: DurableObjectId, options?: DurableObjectNamespaceGetDurableObjectOptions) =>\n stubFor(target.get(id, options), id.toString(), nameOf(id));\n case \"getByName\":\n return (name: string) => {\n const id = idFromName(name);\n return stubFor(target.get(id), id.toString(), name);\n };\n case \"jurisdiction\":\n return (jurisdiction: DurableObjectJurisdiction) => {\n ctx.hooks.unsupported(\n `${binding}.jurisdiction() namespaces are not proxied or reset; use the namespace itself`,\n );\n return target.jurisdiction(jurisdiction);\n };\n default: {\n // Native methods check their receiver: call them on the real namespace.\n const value = Reflect.get(target, prop, receiver);\n return typeof value === \"function\" ? value.bind(target) : value;\n }\n }\n },\n });\n}\n\n/**\n * The objects of a namespace that are running now, each evicted: eviction\n * only succeeds on a running object. For a namespace none of whose objects\n * should have run.\n */\nexport async function evictRunning(\n real: DurableObjectNamespace,\n helpers: DurableObjectTestHelpers,\n): Promise<DurableObjectId[]> {\n const running: DurableObjectId[] = [];\n const ids = await typed(helpers).listDurableObjectIds(real);\n for (const id of [...ids].sort((a, b) => (a.toString() < b.toString() ? -1 : 1))) {\n const evicted = await typed(helpers)\n .evictDurableObject(real.get(id))\n .then(\n () => true,\n () => false,\n );\n if (evicted) running.push(id);\n }\n return running;\n}\n\n/** Drop an object's instance from outside it; one that is not running has nothing to drop. */\nexport async function evictObject(\n real: DurableObjectNamespace,\n helpers: DurableObjectTestHelpers | undefined,\n id: string,\n): Promise<void> {\n if (!helpers) return;\n await typed(helpers)\n .evictDurableObject(real.get(real.idFromString(id)))\n .catch(() => {});\n}\n\n/**\n * Run code inside an object as one of its own events does (an alarm, a\n * WebSocket message): the object is marked reached, its gate watched, its\n * alarms taken over, then `fn` runs with the instance and its state.\n */\nexport async function runInObject<T>(\n real: DurableObjectNamespace,\n binding: string,\n ctx: ProxyContext,\n helpers: DurableObjectTestHelpers | undefined,\n state: BindingState,\n id: string,\n object: string,\n fn: (instance: unknown, live: DurableObjectState) => Promise<T>,\n): Promise<T | undefined> {\n if (!helpers) {\n ctx.hooks.unsupported(`Durable Object binding ${binding} needs the Cloudflare test helpers`);\n return undefined;\n }\n return enterObject(real.get(real.idFromString(id)), binding, ctx, helpers, state, id, object, fn);\n}\n\n/**\n * Enter an object through a stub for a call or an event of its own: the\n * object is marked reached, its gate watched, its state kept for the run,\n * its alarms taken over, then `fn` runs with the instance and its state.\n */\nfunction enterObject<T>(\n stub: DurableObjectStub,\n binding: string,\n ctx: ProxyContext,\n helpers: DurableObjectTestHelpers,\n state: BindingState,\n id: string,\n object: string,\n fn: (instance: unknown, live: DurableObjectState) => Promise<T>,\n): Promise<T> {\n state.touched.add(id);\n // Whoever enters the object constructs it, inside the run: no need to wake it at the end.\n state.dropped.delete(id);\n // Known before the runtime constructs the instance: its constructor's work is this object's.\n hostOfId.set(id, {\n hooks: () => ctx.hooks,\n host: hostOf(`DO:${binding}`, object),\n binding,\n object,\n ctx,\n constructed: (live) => void state.states.set(id, live),\n broken: (live) =>\n state.broke(id, live, () => ctx.hooks.hostReset(hostOf(`DO:${binding}`, object))),\n selfReset: () => {\n if (state.selfReset(id))\n ctx.hooks.unsupported(\n `Durable Object ${object} reset itself with ctx.abort() during the run; the simulation resets an object only where it injects a crash, so what this one held in memory and had in flight is not modelled`,\n );\n },\n });\n return typed(helpers).runInDurableObject(stub, async (instance, live) => {\n watchGate(live);\n watchAbort(live);\n state.states.set(id, live);\n await takeOverAlarms(\n live.storage,\n alarmControl(state.alarms, binding, id, object, () => ctx.hooks),\n );\n // What the object wrote is durable before a call of its own leaves it, as behind the output gate.\n const sync = (live.storage as { sync?: () => Promise<void> }).sync;\n ownEnv(\n ctx.hooks,\n binding,\n object,\n instance,\n ctx.env,\n ctx.gate && typeof sync === \"function\"\n ? { slot: ctx.gate, durable: () => sync.call(live.storage) }\n : undefined,\n );\n return fn(instance, live);\n });\n}\n\n/** The objects to reset: every id the namespace has created, plus the setup's named ones. */\nasync function objectIds(\n real: DurableObjectNamespace,\n helpers: DurableObjectTestHelpers,\n names: ObjectNames,\n seeded: readonly string[],\n): Promise<DurableObjectId[]> {\n const ids = new Map<string, DurableObjectId>();\n for (const id of await typed(helpers).listDurableObjectIds(real)) ids.set(id.toString(), id);\n for (const name of seeded) {\n const id = real.idFromName(name);\n names.set(id.toString(), name);\n ids.set(id.toString(), id);\n }\n return [...ids.values()].sort((a, b) => (a.toString() < b.toString() ? -1 : 1));\n}\n\n/**\n * Clear every object of the namespace, write the seeded entries, and evict\n * them all, so each run's first call constructs the object from storage.\n */\nexport async function resetNamespace(\n real: DurableObjectNamespace,\n helpers: DurableObjectTestHelpers,\n names: ObjectNames,\n objects: Seeds,\n sql: SqlSeeds = {},\n): Promise<SeededSql> {\n // Clearing an object constructs it, outside the simulation: its constructor must not reach the network.\n const { value, requested } = await withoutNetwork(() =>\n clearAndSeed(real, helpers, names, objects, sql),\n );\n if (requested) {\n throw new Error(\n \"a Durable Object constructor made a request during reset; constructors run outside the simulation there, so objects whose constructor does I/O are not supported\",\n );\n }\n return value;\n}\n\n/** The names a setup seeds: those with key-value entries and those with SQL. */\nconst seededNames = (objects: Seeds, sql: SqlSeeds): string[] => [\n ...new Set([...Object.keys(objects), ...Object.keys(sql)]),\n];\n\nasync function clearAndSeed(\n real: DurableObjectNamespace,\n helpers: DurableObjectTestHelpers,\n names: ObjectNames,\n objects: Seeds,\n sql: SqlSeeds,\n): Promise<SeededSql> {\n const seededSql: SeededSql = new Map();\n const ids = await objectIds(real, helpers, names, seededNames(objects, sql));\n for (const id of ids) {\n const stub = real.get(id);\n const name = names.get(id.toString());\n // Own entries only, and only for a known name: an object may be named \"\" or \"__proto__\".\n const entries = name !== undefined && Object.hasOwn(objects, name) ? objects[name] : undefined;\n const seed = name !== undefined && Object.hasOwn(sql, name) ? sql[name] : undefined;\n await typed(helpers).runInDurableObject(stub, async (_instance, state) => {\n // Before any constructor of this run: so its blockConcurrencyWhile is seen too.\n watchGate(state);\n watchAbort(state);\n // deleteAll drops SQL and key-value data alike (Cloudflare, Storage API).\n await state.storage.deleteAll();\n await deleteRealAlarm(state.storage);\n if (entries && Object.keys(entries).length > 0) await state.storage.put(entries);\n if (seed) {\n const surface = sqlOf(state.storage);\n if (!surface)\n throw new Error(\n `Durable Object ${name} has a sql seed but is not SQLite-backed (no working ctx.storage.sql); add its class to new_sqlite_classes in the wrangler migrations`,\n );\n seedSql(surface, seed);\n // What the seed left, as SQLite holds it (defaults, generated ids, affinities), for the snapshot\n // of this object when no call reaches it.\n seededSql.set(name as string, readSqlTables(surface));\n }\n });\n // The object just ran, so eviction can only fail for a real reason: let it fail the reset.\n await typed(helpers).evictDurableObject(stub);\n }\n return seededSql;\n}\n\n/**\n * Each object's storage as rows `{ key, value }`, sorted by key, one table\n * per object name. An object no call reached this run still holds exactly\n * its seed (reset left it evicted), so its rows come from the seed and it is\n * not constructed: its constructor would run outside the simulation. Such an\n * object that is running anyway was reached some other way (through another\n * object's own binding): `onIndirect` is told, and the seed is not its state.\n * The tables are the seeded objects and those a call reached, never objects\n * only earlier runs created, so a snapshot depends on this run alone.\n */\nexport async function snapshotNamespace(\n real: DurableObjectNamespace,\n helpers: DurableObjectTestHelpers,\n names: ObjectNames,\n touched: ReadonlySet<string>,\n objects: Seeds,\n sql: SqlSeeds,\n seededSql: SeededSql,\n onIndirect: (object: string) => void,\n onUnsupported: (reason: string) => void,\n /** Read every seeded object's storage, touched or not, as the raw side of a differential does: no proxy saw its calls. */\n all = false,\n): Promise<{ readonly [object: string]: readonly JsonValue[] }> {\n // Reading an object that is no longer running reconstructs it, outside the simulation.\n const { value, requested } = await withoutNetwork(() =>\n readTables(\n real,\n helpers,\n names,\n touched,\n objects,\n sql,\n seededSql,\n onIndirect,\n onUnsupported,\n all,\n ),\n );\n if (requested)\n onUnsupported(\"a Durable Object made a request while its storage was being snapshotted\");\n return value;\n}\n\nasync function readTables(\n real: DurableObjectNamespace,\n helpers: DurableObjectTestHelpers,\n names: ObjectNames,\n touched: ReadonlySet<string>,\n objects: Seeds,\n sql: SqlSeeds,\n seededSql: SeededSql,\n onIndirect: (object: string) => void,\n onUnsupported: (reason: string) => void,\n all: boolean,\n): Promise<{ readonly [object: string]: readonly JsonValue[] }> {\n const out: Record<string, JsonValue[]> = {};\n // Defined, not assigned: an object may be named \"__proto__\". Names may not hold \"/\", so a table's\n // key never collides with an object's; a collision anyway is a bug, never a silent overwrite.\n const define = (table: string, rows: JsonValue[]) => {\n if (Object.hasOwn(out, table)) throw new Error(`snapshot key ${table} named twice`);\n Object.defineProperty(out, table, {\n value: rows,\n enumerable: true,\n writable: true,\n configurable: true,\n });\n };\n const seeded = seededNames(objects, sql);\n for (const id of await objectIds(real, helpers, names, seeded)) {\n const name = names.get(id.toString()) ?? id.toString();\n // The raw side of a differential reads every object, a call's own unseeded one included; the\n // stale empties earlier runs left read the same on both sides.\n const read = all || touched.has(id.toString());\n if (!read) {\n // Eviction only succeeds on a running object, and reset left every object evicted.\n const running = await typed(helpers)\n .evictDurableObject(real.get(id))\n .then(\n () => true,\n () => false,\n );\n if (running) onIndirect(name);\n // Objects earlier runs created stay in the namespace's list: only the seed and this run count.\n if (!seeded.includes(name)) continue;\n }\n let entries: [string, unknown][];\n const tables: [string, JsonValue[]][] = [];\n if (read) {\n let failed: { readonly reason: string } | undefined;\n const read = await typed(helpers)\n .runInDurableObject(real.get(id), (_instance, state) => {\n // Storage Eutaxy never took over belongs to an instance built after the run's calls.\n if (!all && !takenOver.has(state.storage))\n onUnsupported(\n `Durable Object ${name} was reset during the run and reconstructed for the snapshot; its constructor ran outside the simulation`,\n );\n const surface = sqlOf(state.storage);\n const sqlTables: [string, JsonValue[]][] = surface ? readSqlTables(surface) : [];\n return Promise.resolve(state.storage.list()).then((kv) => ({ kv: [...kv], sqlTables }));\n })\n .catch((err: unknown) => {\n failed = { reason: err instanceof Error ? err.message : String(err) };\n return undefined;\n });\n // An object that cannot be constructed cannot be read: said, and left out of the snapshot.\n if (!read) {\n onUnsupported(\n `Durable Object ${name} could not be entered to read its storage for the snapshot (${failed?.reason ?? \"no reason given\"})`,\n );\n continue;\n }\n entries = read.kv;\n tables.push(...read.sqlTables);\n } else {\n // Untouched: exactly the seed, the key-value entries as given and the SQL tables as the reset\n // read them back after seeding.\n entries = Object.entries(Object.hasOwn(objects, name) ? (objects[name] ?? {}) : {});\n tables.push(...(seededSql.get(name) ?? []));\n }\n define(\n name,\n entries\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n .map(([key, value]) => ({ key, value: toJson(value) })),\n );\n for (const [table, rows] of tables) define(`${name}/${table}`, rows);\n }\n return out;\n}\n","/**\n * The caller of an inbound request or RPC call. Cloudflare retries neither,\n * so resends follow the policy the drive declares for the caller: how many\n * times it resends, the virtual delay before each resend, and how long it\n * waits for an answer. The decision is the caller's and is made once per\n * attempt: at the response point, or at its deadline if the handler has\n * not answered by then.\n */\n\nimport {\n type EventRef,\n type FaultKind,\n type JsonValue,\n type RunHooks,\n redelivery,\n type ScenarioSpec,\n} from \"@eutaxy/core\";\nimport { CrashSignal, InjectedEffectError, note } from \"@eutaxy/engine\";\n\n/** The response point: a crash before it is a response the caller never saw. */\nconst RESPOND: readonly FaultKind[] = [\"crash_before\"];\n/**\n * With a caller deadline the answer can also arrive too late: `ambiguous`\n * here means it was sent, the caller counted it as failed, and the handler\n * carried on.\n */\nconst RESPOND_WITH_DEADLINE: readonly FaultKind[] = [\"crash_before\", \"ambiguous\"];\n\n/** What a drive declares about its caller. */\nexport interface CallerPolicy {\n /** Resends after the first attempt. */\n readonly retries: number;\n /** Virtual time the caller waits before resend number i + 1; the last entry repeats, none means at once. */\n readonly delaysMs?: readonly number[];\n /** How long the caller waits for an answer; one that comes later counts as failed. */\n readonly deadlineMs?: number;\n}\n\n/** The virtual delay before resend number `resend` (1 for the first), per the policy. */\nexport function retryDelayMs(policy: Pick<CallerPolicy, \"delaysMs\">, resend: number): number {\n const delays = policy.delaysMs ?? [];\n return delays[Math.min(resend, delays.length) - 1] ?? 0;\n}\n\n/** How an attempt ended for its caller: an answer the handler sent, the answer an uncaught error gets, or none. */\nexport type Answer =\n | { readonly kind: \"answered\"; readonly value: JsonValue; readonly accepted: boolean }\n | { readonly kind: \"errored\"; readonly value: JsonValue }\n | { readonly kind: \"none\" };\n\n/** One attempt's caller, waiting for its answer. */\nexport interface Caller {\n /**\n * The response point: the answer is recorded as the `response` effect under\n * the caller's faults (an injected crash is the handler's, before the send;\n * an injected error is an answer sent after the deadline, which the caller\n * counts as failed while the handler carries on), a synthetic answer for an\n * uncaught error under none, and the caller settles. Whether the invocation\n * crashed at the point.\n */\n respond(invocation: string, args: JsonValue, answer: Answer): boolean;\n}\n\n/**\n * Start waiting for the attempt's answer. With a deadline, a virtual timer\n * makes the caller give up at it whatever the handler is doing, so a resend\n * can start while the first attempt still runs. `gaveUp` is what the\n * `gave_up` effect records when the retries are spent.\n */\nexport function startCaller(\n event: EventRef,\n hooks: RunHooks,\n spec: ScenarioSpec,\n policy: CallerPolicy,\n target: string,\n gaveUp: JsonValue,\n): Caller {\n // Virtual time: when the caller sent this attempt, for its deadline.\n const started = Date.now();\n const deadline = policy.deadlineMs;\n // The caller gives up at its deadline even when the answer comes later still.\n const lateAt = deadline === undefined ? undefined : started + deadline;\n\n /** The caller decides once: it accepts the answer, or gives up at `at` and resends or stops. */\n let decided = false;\n const giveUp = (at: number): void => {\n if (decided) return;\n decided = true;\n const next = redelivery(event, policy.retries, spec.bounds);\n if (next) {\n const resendAt = Math.max(at + retryDelayMs(policy, event.attempt), Date.now());\n hooks.enqueue({ ...next, ...(resendAt > Date.now() ? { at: resendAt } : {}) });\n } else {\n note(hooks, {\n invocation: hooks.bookkeeping(),\n target,\n op: \"gave_up\",\n args: gaveUp,\n allowed: [],\n });\n }\n };\n // A virtual timer: at the deadline the caller gives up, whatever the handler is doing.\n const deadlineTimer =\n lateAt === undefined ? undefined : setTimeout(() => giveUp(lateAt), deadline);\n\n const responseFaults = deadline === undefined ? RESPOND : RESPOND_WITH_DEADLINE;\n const isLate = (): boolean => lateAt !== undefined && Date.now() > lateAt;\n /** The caller decides as soon as it has an answer or gives up, before background work ends. */\n const settle = (accepted: boolean, late: boolean): void => {\n if (deadlineTimer !== undefined) clearTimeout(deadlineTimer);\n if (accepted) decided = true;\n else giveUp(late && lateAt !== undefined ? lateAt : Date.now());\n };\n\n return {\n respond(invocation, args, answer) {\n let late = isLate();\n let accepted = false;\n let crashed = false;\n const record = (allowed: readonly FaultKind[], value: JsonValue): void => {\n hooks.effectSync(\n { invocation, target, op: \"response\", args, allowed },\n () => value,\n (v) => v,\n );\n };\n if (answer.kind === \"answered\") {\n try {\n record(responseFaults, answer.value);\n accepted = answer.accepted;\n } catch (err) {\n if (err instanceof CrashSignal) crashed = true;\n else if (err instanceof InjectedEffectError) late = true;\n else throw err;\n }\n } else if (answer.kind === \"errored\") {\n record([], answer.value);\n }\n settle(accepted && !late, late);\n return crashed;\n },\n };\n}\n","/**\n * Cloudflare's cron expressions (Workers, Cron Triggers): five fields,\n * minute, hour, day of month, month and weekday, in UTC, with `*`, lists,\n * ranges, steps and names; weekdays run 1 = Sunday to 7 = Saturday. The\n * tick times a scenario drives are the expression's matches from the\n * virtual epoch on, so `scheduledTime` is what the trigger would have set.\n * `L`, `W` and `#` are not modelled: a scenario using them is refused.\n */\n\nconst monthNames = [\n \"jan\",\n \"feb\",\n \"mar\",\n \"apr\",\n \"may\",\n \"jun\",\n \"jul\",\n \"aug\",\n \"sep\",\n \"oct\",\n \"nov\",\n \"dec\",\n];\nconst dayNames = [\"sun\", \"mon\", \"tue\", \"wed\", \"thu\", \"fri\", \"sat\"];\n\ninterface Field {\n readonly name: string;\n readonly min: number;\n readonly max: number;\n readonly names?: readonly string[];\n /** The number the first name stands for (months start at 1, Cloudflare's weekdays at 1 = Sunday). */\n readonly firstName?: number;\n}\n\nconst fields: readonly Field[] = [\n { name: \"minute\", min: 0, max: 59 },\n { name: \"hour\", min: 0, max: 23 },\n { name: \"day of month\", min: 1, max: 31 },\n { name: \"month\", min: 1, max: 12, names: monthNames, firstName: 1 },\n { name: \"weekday\", min: 1, max: 7, names: dayNames, firstName: 1 },\n];\n\n/** A parsed expression: the values each field admits. */\nexport interface CronSchedule {\n readonly minutes: ReadonlySet<number>;\n readonly hours: ReadonlySet<number>;\n readonly daysOfMonth: ReadonlySet<number>;\n readonly months: ReadonlySet<number>;\n /** 1 = Sunday to 7 = Saturday, as Cloudflare numbers them. */\n readonly weekdays: ReadonlySet<number>;\n /** Whether the day fields were both given: then a day matches either, as cron has it. */\n readonly anyDayOfMonth: boolean;\n readonly anyWeekday: boolean;\n}\n\nfunction value(token: string, field: Field): number {\n const lower = token.toLowerCase();\n if (field.names) {\n const i = field.names.indexOf(lower);\n if (i >= 0) return (field.firstName ?? 0) + i;\n }\n if (!/^\\d+$/.test(token))\n throw new Error(`${field.name}: ${JSON.stringify(token)} is not a value`);\n const n = Number(token);\n if (n < field.min || n > field.max)\n throw new Error(`${field.name}: ${n} is outside ${field.min}-${field.max}`);\n return n;\n}\n\nfunction parseField(text: string, field: Field): Set<number> {\n if (/[LW#]/i.test(text) && !field.names?.some((n) => text.toLowerCase().includes(n)))\n throw new Error(`${field.name}: L, W and # are not modelled`);\n const out = new Set<number>();\n for (const part of text.split(\",\")) {\n const pieces = part.split(\"/\");\n if (pieces.length > 2 || part === \"\")\n throw new Error(`${field.name}: ${JSON.stringify(part)} is not a value, range or step`);\n const [rangeText, stepText] = pieces as [string, string?];\n let step = 1;\n if (stepText !== undefined) {\n if (!/^\\d+$/.test(stepText) || Number(stepText) < 1)\n throw new Error(`${field.name}: step ${JSON.stringify(stepText)} is not a positive number`);\n step = Number(stepText);\n }\n let from: number;\n let to: number;\n if (rangeText === \"*\") {\n from = field.min;\n to = field.max;\n } else if (rangeText.includes(\"-\")) {\n const ends = rangeText.split(\"-\");\n if (ends.length !== 2)\n throw new Error(`${field.name}: ${JSON.stringify(rangeText)} is not a range`);\n const [a, b] = ends as [string, string];\n from = value(a, field);\n to = value(b, field);\n if (from > to) throw new Error(`${field.name}: range ${rangeText} runs backwards`);\n } else {\n from = value(rangeText, field);\n to = stepText === undefined ? from : field.max;\n }\n for (let v = from; v <= to; v += step) out.add(v);\n }\n return out;\n}\n\n/** Parse an expression; throws with the field and the problem when it is not one Cloudflare accepts. */\nexport function parseCron(expression: string): CronSchedule {\n const parts = expression.trim().split(/\\s+/);\n if (parts.length !== 5)\n throw new Error(\n `a cron expression has five fields, got ${parts.length}: ${JSON.stringify(expression)}`,\n );\n const [minute, hour, dom, month, weekday] = parts as [string, string, string, string, string];\n return {\n minutes: parseField(minute, fields[0] as Field),\n hours: parseField(hour, fields[1] as Field),\n daysOfMonth: parseField(dom, fields[2] as Field),\n months: parseField(month, fields[3] as Field),\n weekdays: parseField(weekday, fields[4] as Field),\n anyDayOfMonth: dom === \"*\",\n anyWeekday: weekday === \"*\",\n };\n}\n\n/** Whether the minute starting at `time` (ms since the epoch, UTC) matches. */\nexport function cronMatches(schedule: CronSchedule, time: number): boolean {\n const d = new Date(time);\n if (!schedule.minutes.has(d.getUTCMinutes()) || !schedule.hours.has(d.getUTCHours()))\n return false;\n if (!schedule.months.has(d.getUTCMonth() + 1)) return false;\n const dayOk = schedule.daysOfMonth.has(d.getUTCDate());\n const weekdayOk = schedule.weekdays.has(d.getUTCDay() + 1);\n // Both day fields restricted: either may match (standard cron); one restricted: it must.\n if (!schedule.anyDayOfMonth && !schedule.anyWeekday) return dayOk || weekdayOk;\n return dayOk && weekdayOk;\n}\n\nconst minuteMs = 60_000;\n/**\n * Between two matches of any expression Cloudflare accepts lie at most eight\n * years (the 29th of February across a century's missing leap year); an\n * expression with no match in that span never fires.\n */\nconst longestGapMs = 9 * 366 * 24 * 60 * minuteMs;\n\n/** The first `count` tick times at or after `from`, each the start of a matching minute. */\nexport function cronTicks(expression: string, from: number, count: number): number[] {\n const schedule = parseCron(expression);\n const out: number[] = [];\n let t = Math.ceil(from / minuteMs) * minuteMs;\n let horizon = t + longestGapMs;\n while (out.length < count) {\n if (t > horizon) throw new Error(`${JSON.stringify(expression)} never fires`);\n if (cronMatches(schedule, t)) {\n out.push(t);\n horizon = t + longestGapMs;\n }\n t += minuteMs;\n }\n return out;\n}\n","/**\n * Typed construction of scenario specs for Cloudflare Workers. Everything here\n * produces the plain-data `ScenarioSpec` from core; this module only knows the\n * Cloudflare shapes (queues, D1 bindings) and the effect conventions the\n * proxies follow.\n */\n\nimport {\n type AtLeastOnce,\n type Bounds,\n atLeastOncePerMessage as coreAtLeastOncePerMessage,\n defaultBounds,\n type EffectSelector,\n type EventRef,\n type EveryRow,\n type ExternalDecl,\n type FaultKind,\n type FaultSite,\n type Implies,\n type Invariant,\n type JsonValue,\n type PinnedSchedule,\n type PlatformData,\n type References,\n type Refines,\n type RowCondition,\n type ScenarioSpec,\n type ScriptedResponse,\n type StateQuery,\n type Unique,\n validateScenario,\n type WorkerRef,\n} from \"@eutaxy/core\";\nimport { virtualEpoch } from \"@eutaxy/engine\";\nimport { cronTicks, parseCron } from \"./cron.ts\";\nimport type { R2Seed } from \"./r2.ts\";\n\n/** One queue message to deliver; `id` defaults to its position. */\nexport interface QueueMessage {\n readonly id?: string;\n readonly body: JsonValue;\n}\n\n/** Drive the Worker's `queue()` handler with these messages. */\nexport interface QueueDrive extends PlatformData {\n readonly kind: \"queue\";\n readonly queue: string;\n readonly messages: readonly { readonly id: string; readonly body: JsonValue }[];\n}\n\n/** One inbound request; `id` defaults to its position, `method` to POST with a body and GET without. */\nexport interface HttpRequestInput {\n readonly id?: string;\n readonly method?: string;\n readonly path: string;\n readonly headers?: { readonly [name: string]: string };\n /** JSON body (sent as application/json) or a string body. */\n readonly body?: JsonValue;\n}\n\n/** A type alias, not an interface, so it is assignable to the JSON shape of `PlatformData`. */\nexport type HttpRequestSpec = {\n readonly id: string;\n readonly method: string;\n readonly path: string;\n readonly headers: { readonly [name: string]: string };\n /** Absent: no body at all. `null` is a JSON body, sent as `null`. */\n readonly body?: JsonValue;\n};\n\n/**\n * Drive the Worker's `fetch()` handler with these requests. The caller's\n * retry policy decides redelivery: a webhook provider resends a request it\n * got no 2xx for (`retryOn: \"non-2xx\"`, the default) or only on 5xx and\n * failures (`\"5xx\"`), up to `retries` times; a browser-like caller has\n * `retries: 0`. `delaysMs[i]` is the virtual time the caller waits before\n * its resend number i + 1 (the last entry repeats; none means at once).\n * `deadlineMs` is how long the caller waits for an answer: one that comes\n * later counts as failed and is resent while the handler may still run.\n */\nexport interface HttpDrive extends PlatformData {\n readonly kind: \"http\";\n readonly requests: readonly HttpRequestSpec[];\n readonly retries: number;\n readonly retryOn: \"non-2xx\" | \"5xx\";\n readonly delaysMs?: readonly number[];\n readonly deadlineMs?: number;\n}\n\n/**\n * How the HTTP drive's caller resends a request it got no acceptable answer for: up to `retries` times\n * (default 3), on a status `retryOn` rejects (default any non-2xx), after `delaysMs` of virtual time, and\n * not waiting past `deadlineMs`.\n */\nexport interface HttpCallerOptions {\n readonly retries?: number;\n readonly retryOn?: \"non-2xx\" | \"5xx\";\n readonly delaysMs?: readonly number[];\n readonly deadlineMs?: number;\n}\n\n/**\n * Drive the Worker's `fetch()` handler with these requests, each resent as `options` say. A request's\n * method defaults to POST with a body and GET without; its id to `req-<n>`, by position.\n */\nexport function http(\n requests: readonly HttpRequestInput[],\n options: HttpCallerOptions = {},\n): HttpDrive {\n return {\n kind: \"http\",\n requests: requests.map((r, i) => ({\n id: r.id ?? `req-${i + 1}`,\n method: (r.method ?? (r.body === undefined ? \"GET\" : \"POST\")).toUpperCase(),\n path: r.path,\n headers: r.headers ?? {},\n ...(r.body === undefined ? {} : { body: r.body }),\n })),\n retries: options.retries ?? 3,\n retryOn: options.retryOn ?? \"non-2xx\",\n ...(options.delaysMs === undefined ? {} : { delaysMs: [...options.delaysMs] }),\n ...(options.deadlineMs === undefined ? {} : { deadlineMs: options.deadlineMs }),\n };\n}\n\n/** One message the scenario sends on a connection: text, or a JSON value sent as its text (plain data, as drives are). */\nexport type WebSocketMessageSpec = {\n readonly id: string;\n readonly data: JsonValue;\n};\n\n/** One WebSocket connection the scenario opens to the Worker, and the messages it sends on it, in order. */\nexport type WebSocketConnectionSpec = {\n readonly id: string;\n readonly path: string;\n readonly headers: Readonly<Record<string, string>>;\n readonly messages: readonly WebSocketMessageSpec[];\n};\n\n/**\n * Drive the Worker over WebSocket connections: each connection is opened\n * with an upgrade request to its path (one event) and its messages are sent\n * in order (one event each, after its connection opened and its previous\n * message was handled); every connection closes at the end of the run.\n * Events of different connections interleave as concurrency allows.\n */\nexport interface WebSocketDrive extends PlatformData {\n readonly kind: \"websocket\";\n readonly connections: readonly WebSocketConnectionSpec[];\n}\n\n/** One message to send on a connection: its data (a JSON value is sent as its text) and an optional id. */\nexport interface WebSocketMessageInput {\n readonly id?: string;\n readonly data: JsonValue;\n}\n\n/** One connection to open: the path of its upgrade request, its headers and the messages to send on it. */\nexport interface WebSocketConnectionInput {\n /** Defaults to its position: `conn-1`, `conn-2`, … */\n readonly id?: string;\n readonly path: string;\n readonly headers?: Readonly<Record<string, string>>;\n /** Message ids default to `<connection>:1`, `<connection>:2`, … */\n readonly messages?: readonly WebSocketMessageInput[];\n}\n\n/**\n * Drive the Worker over these WebSocket connections: each opened through its `fetch()` and handed to a\n * Durable Object, its messages delivered in order to the object's `webSocketMessage` handler.\n */\nexport function websocket(connections: readonly WebSocketConnectionInput[]): WebSocketDrive {\n return {\n kind: \"websocket\",\n connections: connections.map((c, i) => {\n const id = c.id ?? `conn-${i + 1}`;\n return {\n id,\n path: c.path,\n headers: c.headers ?? {},\n messages: (c.messages ?? []).map((m, j) => ({\n id: m.id ?? `${id}:${j + 1}`,\n data: m.data,\n })),\n };\n }),\n };\n}\n\n/** One RPC call; `id` defaults to its position, `args` to none. */\nexport interface RpcCallInput {\n readonly id?: string;\n readonly method: string;\n readonly args?: readonly JsonValue[];\n}\n\n/** A type alias, not an interface, so it is assignable to the JSON shape of `PlatformData`. */\nexport type RpcCallSpec = {\n readonly id: string;\n readonly method: string;\n readonly args: readonly JsonValue[];\n};\n\n/**\n * Drive a `WorkerEntrypoint` of the Worker with these method calls, one\n * invocation per attempt, the entrypoint constructed anew for each. The\n * entrypoint is the Worker's default export, or the named export\n * `entrypoint`. Cloudflare does not retry an RPC call; the caller resends\n * a call that threw or got no answer up to `retries` times (default 0: a\n * calling Worker resends only when written to), after `delaysMs` of\n * virtual time, and gives up waiting at `deadlineMs`, as the HTTP drive's\n * caller does.\n */\nexport interface RpcDrive extends PlatformData {\n readonly kind: \"rpc\";\n readonly entrypoint?: string;\n readonly calls: readonly RpcCallSpec[];\n readonly retries: number;\n readonly delaysMs?: readonly number[];\n readonly deadlineMs?: number;\n}\n\n/**\n * The RPC drive's entrypoint (a named export; default the default export) and how its caller resends a call\n * that threw or got no answer: `retries` (default 0), `delaysMs` and `deadlineMs`, as for `http`.\n */\nexport interface RpcCallerOptions {\n readonly entrypoint?: string;\n readonly retries?: number;\n readonly delaysMs?: readonly number[];\n readonly deadlineMs?: number;\n}\n\n/** Drive a `WorkerEntrypoint` of the Worker with these method calls; a call's id defaults to `call-<n>`. */\nexport function rpc(calls: readonly RpcCallInput[], options: RpcCallerOptions = {}): RpcDrive {\n return {\n kind: \"rpc\",\n ...(options.entrypoint === undefined ? {} : { entrypoint: options.entrypoint }),\n calls: calls.map((c, i) => ({\n id: c.id ?? `call-${i + 1}`,\n method: c.method,\n args: [...(c.args ?? [])],\n })),\n retries: options.retries ?? 0,\n ...(options.delaysMs === undefined ? {} : { delaysMs: [...options.delaysMs] }),\n ...(options.deadlineMs === undefined ? {} : { deadlineMs: options.deadlineMs }),\n };\n}\n\n/** The target of a call's effects: the method, under the entrypoint's name when the drive names one. */\nexport function rpcTarget(drive: Pick<RpcDrive, \"entrypoint\">, method: string): string {\n return `Rpc:${drive.entrypoint === undefined ? method : `${drive.entrypoint}.${method}`}`;\n}\n\n/** One tick of a Cron Trigger: its id and the virtual time it fires, which the handler sees as `scheduledTime`. */\nexport type CronTickSpec = { readonly id: string; readonly at: number };\n\n/**\n * Drive the Worker's `scheduled()` handler with the ticks of a Cron Trigger:\n * the expression's first `ticks` matches from the virtual epoch on, in UTC,\n * each an event delivered at its virtual time. Cloudflare documents\n * `noRetry()` but no retry count, so the drive declares how many times a\n * tick whose handler failed is re-run (`retries`, default 0); a handler that\n * called `noRetry()` is not re-run.\n */\nexport interface CronDrive extends PlatformData {\n readonly kind: \"cron\";\n readonly cron: string;\n readonly ticks: readonly CronTickSpec[];\n readonly retries: number;\n}\n\n/** How many ticks of the expression to drive, and how many times a tick whose handler failed is re-run. */\nexport interface CronOptions {\n /** How many ticks to drive, from the first match on (default 1). */\n readonly ticks?: number;\n readonly retries?: number;\n}\n\n/**\n * Drive the Worker's `scheduled()` handler with the ticks of a Cron Trigger expression, in Cloudflare's\n * dialect: one tick by default, re-run 0 times by default.\n */\nexport function cron(expression: string, options: CronOptions = {}): CronDrive {\n const count = options.ticks ?? 1;\n const times =\n Number.isInteger(count) && count >= 1 ? cronTicks(expression, virtualEpoch, count) : [];\n return {\n kind: \"cron\",\n cron: expression,\n ticks: times.map((at, i) => ({ id: `tick-${i + 1}`, at })),\n retries: options.retries ?? 0,\n };\n}\n\n/** The drives a Cloudflare scenario can have. */\nexport type Drive = QueueDrive | HttpDrive | RpcDrive | CronDrive | WebSocketDrive;\n\n/** What a WebSocket drive's events carry: an open, or a message with its position on its connection. */\nexport type WebSocketEventData =\n | {\n readonly kind: \"open\";\n readonly connection: string;\n readonly path: string;\n readonly headers: Readonly<Record<string, string>>;\n }\n | {\n readonly kind: \"message\";\n readonly connection: string;\n readonly message: string;\n readonly index: number;\n readonly data: JsonValue;\n };\n\n/** The drive's events as they are first delivered: one per message, request or call, attempt 1. */\nexport function driveEvents(drive: Drive): readonly EventRef[] {\n switch (drive.kind) {\n case \"queue\":\n return drive.messages.map((m) => ({ id: m.id, attempt: 1, data: m.body }));\n case \"http\":\n return drive.requests.map((r) => ({ id: r.id, attempt: 1, data: r as unknown as JsonValue }));\n case \"rpc\":\n return drive.calls.map((c) => ({ id: c.id, attempt: 1, data: c as unknown as JsonValue }));\n case \"cron\":\n // Delivered at its virtual time: the clock moves there once nothing else can.\n return drive.ticks.map((t) => ({\n id: t.id,\n attempt: 1,\n data: { cron: drive.cron, scheduledTime: t.at },\n at: t.at,\n }));\n case \"websocket\": {\n // The opens first, then the messages a round at a time (every connection's first, then every\n // second, …), so the scheduler can interleave connections; each message waits for its connection\n // to be open and for the message before it on that connection.\n const opens: EventRef[] = drive.connections.map((c) => ({\n id: c.id,\n attempt: 1,\n data: {\n kind: \"open\",\n connection: c.id,\n path: c.path,\n headers: c.headers,\n } satisfies WebSocketEventData as unknown as JsonValue,\n }));\n const rounds = Math.max(0, ...drive.connections.map((c) => c.messages.length));\n const messages: EventRef[] = [];\n for (let i = 0; i < rounds; i++)\n for (const c of drive.connections) {\n const m = c.messages[i];\n if (m)\n messages.push({\n id: m.id,\n attempt: 1,\n data: {\n kind: \"message\",\n connection: c.id,\n message: m.id,\n index: i,\n data: m.data,\n } satisfies WebSocketEventData as unknown as JsonValue,\n });\n }\n return [...opens, ...messages];\n }\n }\n}\n\n/** The drive with only the named events kept, for shrinking. */\nexport function restrictDrive(drive: Drive, keepIds: readonly string[]): Drive {\n const keep = (id: string): boolean => keepIds.includes(id);\n switch (drive.kind) {\n case \"queue\":\n return { ...drive, messages: drive.messages.filter((m) => keep(m.id)) };\n case \"http\":\n return { ...drive, requests: drive.requests.filter((r) => keep(r.id)) };\n case \"rpc\":\n return { ...drive, calls: drive.calls.filter((c) => keep(c.id)) };\n case \"cron\":\n return { ...drive, ticks: drive.ticks.filter((t) => keep(t.id)) };\n case \"websocket\":\n // A connection whose open is dropped goes with its messages; a dropped message leaves its\n // connection's others in order.\n return {\n ...drive,\n connections: drive.connections\n .filter((c) => keep(c.id))\n .map((c) => ({ ...c, messages: c.messages.filter((m) => keep(m.id)) })),\n };\n }\n}\n\n/** Apply a SQL file to a D1 binding before each run. */\nexport interface D1Setup extends PlatformData {\n readonly kind: \"d1\";\n readonly binding: string;\n readonly schemaFile: string;\n}\n\n/**\n * Clear a Durable Object namespace before each run and seed the named\n * objects' storage with these entries; its storage is snapshotted after the\n * run for state invariants (see `durableObjectRows`).\n */\nexport interface DurableObjectSetup extends PlatformData {\n readonly kind: \"durable_object\";\n readonly binding: string;\n readonly objects: { readonly [name: string]: { readonly [key: string]: JsonValue } };\n /**\n * How many times each object's alarm may fire in one run (retries not\n * counted); an object that keeps re-arming stops there. Default 3.\n */\n readonly alarmsPerObject?: number;\n /** For SQLite-backed objects, by name: the tables to create and the rows to insert after the clear. */\n readonly sql?: { readonly [name: string]: DurableObjectSqlSeed };\n}\n\n/** A SQLite-backed object's starting storage: its `CREATE TABLE` statements, and rows per table (plain data, as setup steps are). */\nexport type DurableObjectSqlSeed = {\n /** SQL run after the clear: the schema, `CREATE TABLE` statements and the like. */\n readonly schema: string;\n readonly rows?: { readonly [table: string]: readonly SqlRow[] };\n};\n\n/** One row to insert, or one row snapshotted: column name to value (booleans and objects as SQLite stores them). */\nexport type SqlRow = { readonly [column: string]: JsonValue };\n\n/**\n * A Durable Object namespace the scenario uses: cleared before each run, the named objects seeded with\n * key-value entries (and with `sql`, a SQLite-backed object's tables and rows), and its storage snapshotted\n * after the run. `alarmsPerObject` caps an object's alarm firings per run (default 3).\n */\nexport function durableObject(\n binding: string,\n objects: { readonly [name: string]: { readonly [key: string]: JsonValue } } = {},\n options: {\n readonly alarmsPerObject?: number;\n readonly sql?: { readonly [name: string]: DurableObjectSqlSeed };\n } = {},\n): DurableObjectSetup {\n return {\n kind: \"durable_object\",\n binding,\n objects,\n ...(options.alarmsPerObject === undefined ? {} : { alarmsPerObject: options.alarmsPerObject }),\n ...(options.sql === undefined ? {} : { sql: options.sql }),\n };\n}\n\n/** An R2 bucket the scenario uses: emptied, then seeded with these objects, before each run. */\nexport interface R2Setup extends PlatformData {\n readonly kind: \"r2\";\n readonly binding: string;\n readonly objects: Readonly<Record<string, R2Seed>>;\n}\n\n/** An R2 bucket the scenario uses: emptied before each run, then seeded with these objects by key. */\nexport function r2Bucket(binding: string, objects: Readonly<Record<string, R2Seed>> = {}): R2Setup {\n return { kind: \"r2\", binding, objects };\n}\n\n/**\n * Selects an R2 bucket's operations that completed, a `put` by default; a\n * put whose `onlyIf` failed stored nothing and is not selected, as a D1\n * write that changed no row is not.\n */\nexport function r2Op(\n binding: string,\n op: \"put\" | \"delete\" | \"get\" | \"head\" | \"list\" = \"put\",\n): EffectSelector {\n const target = `R2:${binding}`;\n return op === \"put\"\n ? { target, op, kind: \"result\", where: { \"result.stored\": true } }\n : { target, op, kind: \"result\" };\n}\n\n/** A bucket's objects at the end of the run as rows `{ key, size, etag, customMetadata, httpMetadata, text? }`. */\nexport function r2Rows(binding: string, where?: readonly RowCondition[]): StateQuery {\n const target = `R2:${binding}`;\n return where ? { target, table: \"objects\", where } : { target, table: \"objects\" };\n}\n\n/**\n * Every row the query returns is named by some row of `in` (its `column`\n * equals the row's value at `path`), as with a foreign key.\n */\nexport function references(\n name: string,\n query: StateQuery,\n path: string,\n inQuery: StateQuery,\n column: string,\n): References {\n return { kind: \"references\", name, query, path, in: inQuery, column };\n}\n\n/** A Workflow binding, and the class (an export of the Worker module) its instances run. */\nexport interface WorkflowSetup extends PlatformData {\n readonly kind: \"workflow\";\n readonly binding: string;\n readonly className: string;\n /** The Workflow's `name` in the wrangler config, which instances see as `event.workflowName`. */\n readonly name?: string;\n}\n\n/**\n * A Workflow binding and the class its instances run, an export of the Worker module; `name` is the\n * Workflow's name in the wrangler config, which instances read as `event.workflowName`.\n */\nexport function workflow(\n binding: string,\n className: string,\n options: { readonly name?: string } = {},\n): WorkflowSetup {\n return {\n kind: \"workflow\",\n binding,\n className,\n ...(options.name === undefined ? {} : { name: options.name }),\n };\n}\n\n/** A scripted method's reply: a value returned to the caller, or an error (`\"<Name>: <message>\"`) thrown to it. */\nexport type ScriptedReply = { readonly returns: JsonValue } | { readonly throws: string };\n\n/** A reply to `fetch()` through a service binding; a type alias of core's `ScriptedResponse`, for the JSON shape. */\nexport type ServiceResponse = {\n readonly method?: string;\n readonly path?: string;\n readonly status: number;\n readonly headers?: { readonly [name: string]: string };\n readonly body?: JsonValue;\n};\n\n/**\n * Script the Worker another Worker reaches through a service binding: its\n * RPC methods answer from `methods` (every method returns `null` when\n * omitted; a method missing from a present `methods` makes the run\n * UNSUPPORTED) and its `fetch()` from `fetch`, matched by method and path\n * as an external's responses are (200 with an empty body when omitted).\n * The real binding is never called. Each call is one effect,\n * `Service:<binding>`, with the faults of a Durable Object stub call.\n */\nexport interface ServiceSetup extends PlatformData {\n readonly kind: \"service\";\n readonly binding: string;\n readonly methods?: { readonly [method: string]: ScriptedReply };\n readonly fetch?: readonly ServiceResponse[];\n}\n\n/**\n * Script the Worker behind a service binding: its RPC methods answer from `methods` and its `fetch()` from\n * `fetch`, and the real binding is never called. See `ServiceSetup`.\n */\nexport function service(\n binding: string,\n options: {\n readonly methods?: { readonly [method: string]: ScriptedReply };\n readonly fetch?: readonly ServiceResponse[];\n } = {},\n): ServiceSetup {\n return {\n kind: \"service\",\n binding,\n ...(options.methods === undefined ? {} : { methods: options.methods }),\n ...(options.fetch === undefined ? {} : { fetch: [...options.fetch] }),\n };\n}\n\n/**\n * Script the objects of a Durable Object namespace: every object of the\n * namespace answers its RPC methods from `methods` and its `fetch()` from\n * `fetch`, as a scripted service does (see `ServiceSetup`), and no object\n * of the namespace is constructed or run. For a class the test's isolate\n * cannot run (one backed by a container) or one the scenario does not\n * explore. Each call is one effect, `DO:<binding>`, with the object's name\n * in its arguments and the faults of a Durable Object stub call.\n */\nexport interface ScriptedObjectSetup extends PlatformData {\n readonly kind: \"scripted_object\";\n readonly binding: string;\n readonly methods?: { readonly [method: string]: ScriptedReply };\n readonly fetch?: readonly ServiceResponse[];\n}\n\n/**\n * Script a Durable Object namespace: its objects' RPC methods answer from `methods` and their `fetch()`\n * from `fetch`, and no object of it runs. See `ScriptedObjectSetup`.\n */\nexport function scriptedObject(\n binding: string,\n options: {\n readonly methods?: { readonly [method: string]: ScriptedReply };\n readonly fetch?: readonly ServiceResponse[];\n } = {},\n): ScriptedObjectSetup {\n return {\n kind: \"scripted_object\",\n binding,\n ...(options.methods === undefined ? {} : { methods: options.methods }),\n ...(options.fetch === undefined ? {} : { fetch: [...options.fetch] }),\n };\n}\n\n/** The snapshot targets an invariant reads state from. */\nfunction stateTargets(invariant: Invariant): readonly string[] {\n switch (invariant.kind) {\n case \"everyRow\":\n case \"unique\":\n return [invariant.query.target];\n case \"implies\":\n return [invariant.state.target];\n case \"references\":\n return [invariant.query.target, invariant.in.target];\n default:\n return [];\n }\n}\n\n/**\n * A namespace is the real objects or a script, not both; one script per\n * namespace; and a script has no storage for an invariant to read.\n */\nfunction validateScriptedObjectSetups(\n setup: ScenarioSpec[\"setup\"],\n invariants: readonly Invariant[],\n): string[] {\n const errors: string[] = [];\n const real = new Set(\n setup.filter((s) => s.kind === \"durable_object\").map((s) => String(s[\"binding\"])),\n );\n const seen = new Set<string>();\n for (const step of setup) {\n if (step.kind !== \"scripted_object\") continue;\n const binding = String(step[\"binding\"]);\n if (!step[\"binding\"]) errors.push(\"scriptedObject() needs a binding name\");\n if (real.has(binding))\n errors.push(\n `Durable Object binding ${JSON.stringify(binding)} has both a durableObject() setup and a scriptedObject() script; keep one`,\n );\n if (seen.has(binding))\n errors.push(\n `Durable Object binding ${JSON.stringify(binding)} has two scriptedObject() steps`,\n );\n seen.add(binding);\n }\n for (const invariant of invariants)\n for (const target of stateTargets(invariant))\n if (target.startsWith(\"DO:\") && seen.has(target.slice(3)))\n errors.push(\n `invariant ${JSON.stringify(invariant.name)} reads the storage of ${target.slice(3)}, a namespace the scenario scripts: a script has no storage; select its calls with objectCall()`,\n );\n return errors;\n}\n\n/**\n * Selects the calls into a Durable Object namespace that completed (real objects' or scripted ones'), one\n * method's or all; `object` keeps those into the object of that name.\n */\nexport function objectCall(binding: string, method?: string, object?: string): EffectSelector {\n return {\n target: `DO:${binding}`,\n ...(method === undefined ? {} : { op: method }),\n kind: \"result\",\n ...(object === undefined ? {} : { where: { \"args.object\": object } }),\n };\n}\n\n/**\n * The Worker behind a service binding, run for real: its module and wrangler\n * config, relative to the scenario, in place of a script. The `name` in that\n * config qualifies the callee's bindings (`orders/DB`) in effect targets,\n * setup steps, state queries and snapshots. Each call is one effect,\n * `Service:<binding>`, hosting the callee's invocation\n * (`<caller invocation>/<binding>.<method>`), with the faults of a call in\n * the network: `crash_before`, `ambiguous` and `crash_after`; what the\n * callee throws is real.\n */\nexport interface CalleeSetup extends PlatformData {\n readonly kind: \"callee\";\n readonly binding: string;\n /** The callee's module, relative to the scenario. */\n readonly entry: string;\n /** Its wrangler config, relative to the scenario; its `name` qualifies the callee's bindings. */\n readonly config: string;\n /** The named export the binding reaches; the default export otherwise. */\n readonly entrypoint?: string;\n}\n\n/**\n * Run the Worker behind a service binding for real, named by its module and its wrangler config, relative\n * to the scenario; `entrypoint` names the export the binding reaches. See `CalleeSetup`.\n */\nexport function callee(\n binding: string,\n worker: { readonly entry: string; readonly config: string; readonly entrypoint?: string },\n): CalleeSetup {\n return {\n kind: \"callee\",\n binding,\n entry: worker.entry,\n config: worker.config,\n ...(worker.entrypoint === undefined ? {} : { entrypoint: worker.entrypoint }),\n };\n}\n\n/**\n * A var or a secret given its value by the scenario: the Worker's by its\n * binding name, a callee's by its qualified one (`<worker name>/<binding>`).\n * A Worker reads both the same way, off `env`; `secret` says the value is\n * one, so the platform's own messages do not print it. `eutaxy check` puts\n * the value in the isolate's env (over a var of that name the wrangler\n * config gives); under Vitest the Cloudflare plugin's `miniflare.bindings`\n * does, and the platform checks at the start of every run that the env\n * holds it, since a Worker that reads `undefined` for a secret it requires\n * fails in ways that say nothing of why. A name that is a binding of\n * another kind, or qualified by a Worker that is no callee, is refused.\n * The values are a test's, never one that works anywhere real: a trace\n * records what the Worker does, so a secret it sends in a request's header\n * is in the trace and the JSON report, and the scenario file and the files\n * `--keep` leaves hold it as written.\n */\nexport interface EnvSetup extends PlatformData {\n readonly kind: \"env\";\n readonly binding: string;\n readonly value: JsonValue;\n readonly secret: boolean;\n}\n\n/** Give a var its value: the Worker's (`\"REGION\"`), or a callee's (`\"orders/REGION\"`). See `EnvSetup`. */\nexport function envVar(binding: string, value: JsonValue): EnvSetup {\n return { kind: \"env\", binding, value, secret: false };\n}\n\n/** Give a secret its value: the Worker's (`\"API_KEY\"`), or a callee's (`\"orders/API_KEY\"`). See `EnvSetup`. */\nexport function secret(binding: string, value: string): EnvSetup {\n return { kind: \"env\", binding, value, secret: true };\n}\n\n/** A var or a secret has a name, one value, and a secret's is a string, as the runtime gives it. */\nfunction validateEnvSetups(setup: ScenarioSpec[\"setup\"]): string[] {\n const errors: string[] = [];\n const seen = new Set<string>();\n for (const step of setup) {\n if (step.kind !== \"env\") continue;\n const what = step[\"secret\"] === true ? \"secret\" : \"envVar\";\n const binding = String(step[\"binding\"] ?? \"\");\n if (binding === \"\") {\n errors.push(`${what}() needs a binding name`);\n continue;\n }\n if (step[\"secret\"] === true && typeof step[\"value\"] !== \"string\")\n errors.push(`secret(${JSON.stringify(binding)}) needs a string: a secret is text`);\n if (step[\"value\"] === undefined)\n errors.push(`${what}(${JSON.stringify(binding)}) needs a value`);\n if (seen.has(binding))\n errors.push(`${JSON.stringify(binding)} is given a value twice (envVar() or secret())`);\n seen.add(binding);\n }\n return errors;\n}\n\n/** A callee and a script for one binding would contradict each other; a callee needs both files named. */\nfunction validateCalleeSetups(setup: ScenarioSpec[\"setup\"]): string[] {\n const errors: string[] = [];\n const scripted = new Set(\n setup.filter((s) => s.kind === \"service\").map((s) => String(s[\"binding\"])),\n );\n const seen = new Set<string>();\n for (const step of setup) {\n if (step.kind !== \"callee\") continue;\n const binding = String(step[\"binding\"]);\n if (!step[\"binding\"]) errors.push(\"callee() needs a binding name\");\n if (!step[\"entry\"]) errors.push(`callee(${JSON.stringify(binding)}) needs the callee's entry`);\n if (!step[\"config\"])\n errors.push(`callee(${JSON.stringify(binding)}) needs the callee's wrangler config`);\n if (scripted.has(binding))\n errors.push(\n `service binding ${JSON.stringify(binding)} has both a service() script and a callee(); keep one`,\n );\n if (seen.has(binding))\n errors.push(`service binding ${JSON.stringify(binding)} has two callee() steps`);\n seen.add(binding);\n }\n return errors;\n}\n\n/** Selects the calls through a service binding that completed (scripted or a callee's), one method's or all. */\nexport function serviceCall(binding: string, method?: string): EffectSelector {\n return {\n target: `Service:${binding}`,\n ...(method === undefined ? {} : { op: method }),\n kind: \"result\",\n };\n}\n\n/** Selects a Workflow's step attempts, optionally of one step; a failed attempt's result carries its error. */\nexport function workflowStep(binding: string, step?: string): EffectSelector {\n return {\n target: `Workflow:${binding}`,\n op: \"step_result\",\n kind: \"result\",\n ...(step === undefined ? {} : { where: { \"args.step\": step } }),\n };\n}\n\n/**\n * A fault site (for `bounds.faultsAt`) on a Workflow step's attempts: the\n * point where an attempt starts (`crash_before`, `ambiguous`) and the one\n * where its result is persisted (`crash_after`, `ambiguous`), of every\n * attempt or only `attempt` (from 1), of the kinds `faults` lists or every\n * kind those points allow. It matches every step of that name in every\n * instance of the binding's Workflow.\n */\nexport function stepFaults(\n binding: string,\n step: string,\n options: { readonly attempt?: number; readonly faults?: readonly FaultKind[] } = {},\n): FaultSite {\n const { attempt } = options;\n if (attempt !== undefined && !(Number.isInteger(attempt) && attempt >= 1))\n throw new RangeError(`stepFaults: attempt counts from 1, got ${attempt}`);\n return {\n target: `Workflow:${binding}`,\n where: {\n \"args.step\": step,\n ...(options.attempt === undefined ? {} : { \"args.attempt\": options.attempt }),\n },\n ...(options.faults === undefined ? {} : { faults: options.faults }),\n };\n}\n\n/** A Workflow's instances at the end of the run as rows `{ id, status, params, output?, error? }`. */\nexport function workflowRows(binding: string, where?: readonly RowCondition[]): StateQuery {\n const target = `Workflow:${binding}`;\n return where ? { target, table: \"instances\", where } : { target, table: \"instances\" };\n}\n\n/** Alarm firings per object per run when the setup does not say. */\nexport const defaultAlarmsPerObject = 3;\n\n/**\n * The storage of one object (by the name its id was made from) as rows\n * `{ key, value }`, for state invariants.\n */\nexport function durableObjectRows(\n binding: string,\n object: string,\n where?: readonly RowCondition[],\n): StateQuery {\n const target = `DO:${binding}`;\n return where ? { target, table: object, where } : { target, table: object };\n}\n\n/**\n * One SQL table of a SQLite-backed object (by the name its id was made\n * from) at the end of the run, its rows as the table holds them, for state\n * invariants. The snapshot names it `<object>/<table>`.\n */\nexport function durableObjectTable(\n binding: string,\n object: string,\n table: string,\n where?: readonly RowCondition[],\n): StateQuery {\n const target = `DO:${binding}`;\n const name = `${object}/${table}`;\n return where ? { target, table: name, where } : { target, table: name };\n}\n\n/**\n * The input to `defineScenario`: the Worker, the drive, the setup steps, the externals it fetches, the\n * invariants, the bounds (merged with the defaults) and the core modules whose specs run.\n */\nexport interface CloudflareScenarioInput {\n readonly name: string;\n readonly worker: WorkerRef;\n readonly drive:\n | QueueDrive\n | HttpDrive\n | RpcDrive\n | CronDrive\n | WebSocketDrive\n | {\n readonly kind: \"queue\";\n readonly queue: string;\n readonly messages: readonly QueueMessage[];\n };\n readonly setup?: readonly (\n | CalleeSetup\n | EnvSetup\n | D1Setup\n | DurableObjectSetup\n | R2Setup\n | WorkflowSetup\n | ServiceSetup\n | ScriptedObjectSetup\n )[];\n readonly externals?: readonly ExternalDecl[];\n readonly invariants: readonly Invariant[];\n readonly bounds?: Partial<Bounds>;\n /** Modules of pure core functions with spec files beside them, relative to the scenario (see ScenarioSpec.specs). */\n readonly specs?: readonly string[];\n /** Schedules the check runs before it explores, each fault at the call it names (see ScenarioSpec.pinned). */\n readonly pinned?: readonly PinnedSchedule[];\n}\n\n/** Drive the Worker's `queue()` handler with these messages from the named queue; an id defaults to `msg-<n>`. */\nexport function queue(name: string, messages: readonly QueueMessage[]): QueueDrive {\n return {\n kind: \"queue\",\n queue: name,\n messages: messages.map((m, i) => ({ id: m.id ?? `msg-${i + 1}`, body: m.body })),\n };\n}\n\n/**\n * A D1 binding the scenario uses: its tables dropped before each run and the schema file applied, relative\n * to the scenario. Several steps on one binding apply their files in order, a migration per file.\n */\nexport function d1Schema(binding: string, schemaFile: string): D1Setup {\n return { kind: \"d1\", binding, schemaFile };\n}\n\n/**\n * Effect conventions for D1 (what the proxies record):\n * call payload { args: { sql, params } }\n * result payload { args: { sql, params }, result: { changes, lastRowId } }\n * A committed write is a `result` whose `result.changes` is at least 1.\n */\nexport function d1Write(binding: string, op: \"run\" | \"batch\" = \"run\"): EffectSelector {\n return { target: `D1:${binding}`, op, kind: \"result\", atLeast: { \"result.changes\": 1 } };\n}\n\n/** Reads of a D1 binding: `first` (result payload `{ row }`), `all` or `raw`. */\nexport function d1Read(binding: string, op: \"first\" | \"all\" | \"raw\" = \"first\"): EffectSelector {\n return { target: `D1:${binding}`, op, kind: \"result\" };\n}\n\n/** Dot path to the Nth bound parameter of a D1 statement, in an effect payload. */\nexport function d1Param(index: number): string {\n return `args.params.${index}`;\n}\n\n/**\n * The shell follows the core function `decision` (see the `refines`\n * invariant): every selected effect carries out the latest decision of its\n * invocation, agrees with it on `follows`, and, with `state`, was not made\n * stale by another invocation's write between the read it rests on and the\n * effect. The core function's module must be listed in the scenario's\n * `specs`, which is what records its calls.\n */\nexport function refines(\n name: string,\n decision: string,\n effect: EffectSelector,\n options: Pick<Refines, \"follows\" | \"state\"> = {},\n): Refines {\n return { kind: \"refines\", name, decision, effect, ...options };\n}\n\n/**\n * Every message's (or request's, or call's) `bodyKey` value must appear at\n * least once as `key` in a selected effect: nothing the drive delivered may\n * be lost. For an RPC drive `bodyKey` is a path into the call's arguments\n * (`\"0.orderId\"`).\n */\nexport function atLeastOncePerMessage(\n name: string,\n drive: Drive,\n effect: EffectSelector,\n key: string,\n bodyKey: string,\n): AtLeastOnce {\n if (drive.kind === \"queue\")\n return coreAtLeastOncePerMessage(name, drive.messages, effect, key, bodyKey);\n if (drive.kind === \"cron\") {\n const ticks = drive.ticks.map((t) => ({\n id: t.id,\n body: { cron: drive.cron, scheduledTime: t.at },\n }));\n return coreAtLeastOncePerMessage(name, ticks, effect, key, bodyKey);\n }\n if (drive.kind === \"rpc\") {\n const calls = drive.calls.map((c) => ({ id: c.id, body: c.args }));\n const inv = coreAtLeastOncePerMessage(name, calls, effect, key, bodyKey);\n // An RPC event's data is the whole call, so the path to re-derive from starts at its arguments.\n return { ...inv, perMessage: { bodyKey: bodyKey === \"\" ? \"args\" : `args.${bodyKey}` } };\n }\n if (drive.kind === \"websocket\") {\n // Per connection, keyed by its path: the one thing its open event carries that a key can come from\n // (a message event has no path, so re-deriving from the remaining events counts opens alone).\n if (bodyKey !== \"\")\n throw new Error(\n `atLeastOncePerMessage ${JSON.stringify(name)}: a websocket drive keys each connection by its path; bodyKey must be \"\"`,\n );\n const conns = drive.connections.map((c) => ({ id: c.id, body: c.path }));\n const inv = coreAtLeastOncePerMessage(name, conns, effect, key, \"\");\n return { ...inv, perMessage: { bodyKey: \"path\" } };\n }\n const requests = drive.requests.map((r) => ({ id: r.id, body: r.body ?? null }));\n const inv = coreAtLeastOncePerMessage(name, requests, effect, key, bodyKey);\n // An HTTP event's data is the whole request, so the path to re-derive from starts at its body.\n return { ...inv, perMessage: { bodyKey: bodyKey === \"\" ? \"body\" : `body.${bodyKey}` } };\n}\n\n/**\n * Selects the frames the Worker sent on a connection (`WebSocket:<connection>`,\n * op `message`), each recorded at the end of the run, in arrival order, with\n * its data (JSON where it parses, text otherwise).\n */\nexport function webSocketReceived(connection: string): EffectSelector {\n return { target: `WebSocket:${connection}`, op: \"message\", kind: \"result\" };\n}\n\n/**\n * Selects the responses the Worker returned for a path (`ok` narrows to 2xx\n * or to everything else). One `result` per attempt: a crash before the\n * response leaves none, a thrown error records status 500.\n */\nexport function httpResponse(\n path: string,\n options: { readonly ok?: boolean } = {},\n): EffectSelector {\n return {\n target: `Http:${path}`,\n op: \"response\",\n kind: \"result\",\n ...(options.ok === undefined ? {} : { where: { \"result.ok\": options.ok } }),\n };\n}\n\n/**\n * Selects the answers an RPC method gave (`ok` narrows to values returned\n * or to errors thrown). One `result` per attempt: a crash before the\n * response leaves none.\n */\nexport function rpcResponse(\n method: string,\n options: { readonly ok?: boolean; readonly entrypoint?: string } = {},\n): EffectSelector {\n return {\n target: rpcTarget(options, method),\n op: \"response\",\n kind: \"result\",\n ...(options.ok === undefined ? {} : { where: { \"result.ok\": options.ok } }),\n };\n}\n\n/** Rows of a D1 table in the end-of-run snapshot, optionally filtered. */\nexport function d1Rows(\n binding: string,\n table: string,\n where?: readonly RowCondition[],\n): StateQuery {\n return where ? { target: `D1:${binding}`, table, where } : { target: `D1:${binding}`, table };\n}\n\n/** Every row the query selects satisfies all conditions. */\nexport function everyRow(\n name: string,\n query: StateQuery,\n holds: readonly RowCondition[],\n): EveryRow {\n return { kind: \"everyRow\", name, query, holds };\n}\n\n/** No two rows the query selects share the value at `path` (a column, or a dot path into the row). */\nexport function unique(name: string, query: StateQuery, path: string): Unique {\n return { kind: \"unique\", name, query, path };\n}\n\n/** Every selected effect has a row whose column equals the effect's key. */\nexport function implies(\n name: string,\n when: EffectSelector,\n key: string,\n state: StateQuery,\n column: string,\n): Implies {\n return { kind: \"implies\", name, when, key, state, column };\n}\n\n/** Selects the acknowledgement that took effect for each message (explicit or implicit; not one ignored after a retry). */\nexport function queueAck(queueName: string): EffectSelector {\n return {\n target: `Queue:${queueName}`,\n op: \"ack\",\n kind: \"result\",\n where: { \"result.effective\": true },\n };\n}\n\n/**\n * Declare an external service: requests to `host` are answered from\n * `responses` (every request gets 200 and an empty body when omitted), and\n * `dedupeBy` names the header whose value makes repeated requests\n * idempotent at that service.\n */\nexport function external(\n name: string,\n host: string,\n options: { readonly dedupeBy?: string; readonly responses?: readonly ScriptedResponse[] } = {},\n): ExternalDecl {\n return {\n name,\n host,\n guarantees: options.dedupeBy ? { dedupeBy: options.dedupeBy } : {},\n ...(options.responses ? { responses: options.responses } : {}),\n };\n}\n\n/**\n * Selects the requests to an external that took effect: a request replayed\n * under a dedupe key the external had already seen is not counted.\n */\nexport function fetchCall(externalName: string, method?: string): EffectSelector {\n return {\n target: `Fetch:${externalName}`,\n ...(method ? { op: method.toUpperCase() } : {}),\n kind: \"result\",\n where: { \"result.effective\": true },\n };\n}\n\nfunction validateWebSocketDrive(drive: WebSocketDrive): readonly string[] {\n const errors: string[] = [];\n if (drive.connections.length === 0) errors.push(\"websocket drive needs at least one connection\");\n const ids = new Set<string>();\n drive.connections.forEach((c, i) => {\n if (!c.path.startsWith(\"/\")) errors.push(`connections[${i}].path must start with \"/\"`);\n if (ids.has(c.id)) errors.push(`duplicate connection id ${JSON.stringify(c.id)}`);\n ids.add(c.id);\n for (const m of c.messages) {\n if (ids.has(m.id)) errors.push(`duplicate message id ${JSON.stringify(m.id)}`);\n ids.add(m.id);\n }\n });\n return errors;\n}\n\nfunction validateHttpDrive(drive: HttpDrive): readonly string[] {\n const errors: string[] = [];\n if (drive.requests.length === 0) errors.push(\"http drive needs at least one request\");\n const ids = new Set<string>();\n drive.requests.forEach((r, i) => {\n if (!r.path.startsWith(\"/\")) errors.push(`requests[${i}].path must start with \"/\"`);\n if (!r.method) errors.push(`requests[${i}].method must not be empty`);\n if (ids.has(r.id)) errors.push(`duplicate request id ${JSON.stringify(r.id)}`);\n ids.add(r.id);\n if ((r.method === \"GET\" || r.method === \"HEAD\") && r.body !== undefined)\n errors.push(`requests[${i}] is a ${r.method} and cannot carry a body`);\n });\n errors.push(...validateCaller(\"http\", drive));\n return errors;\n}\n\n/** The caller's policy, as both drives a caller resends declare it. */\nfunction validateCaller(\n kind: string,\n drive: {\n readonly retries: number;\n readonly delaysMs?: readonly number[];\n readonly deadlineMs?: number;\n },\n): readonly string[] {\n const errors: string[] = [];\n if (!(Number.isInteger(drive.retries) && drive.retries >= 0))\n errors.push(`${kind} drive retries must be a non-negative integer`);\n (drive.delaysMs ?? []).forEach((d, i) => {\n if (!(Number.isInteger(d) && d >= 0))\n errors.push(`${kind} drive delaysMs[${i}] must be a non-negative integer`);\n });\n if (\n drive.deadlineMs !== undefined &&\n !(Number.isInteger(drive.deadlineMs) && drive.deadlineMs > 0)\n )\n errors.push(`${kind} drive deadlineMs must be a positive integer`);\n return errors;\n}\n\nfunction validateCronDrive(drive: CronDrive): readonly string[] {\n const errors: string[] = [];\n try {\n parseCron(drive.cron);\n } catch (err) {\n errors.push(`cron drive: ${(err as Error).message}`);\n }\n if (drive.ticks.length === 0) errors.push(\"cron drive ticks must be a positive integer\");\n const ids = new Set<string>();\n drive.ticks.forEach((t, i) => {\n if (ids.has(t.id)) errors.push(`duplicate tick id ${JSON.stringify(t.id)}`);\n ids.add(t.id);\n const previous = drive.ticks[i - 1];\n if (previous && !(t.at > previous.at))\n errors.push(`ticks[${i}] does not come after ticks[${i - 1}]`);\n });\n if (!(Number.isInteger(drive.retries) && drive.retries >= 0))\n errors.push(\"cron drive retries must be a non-negative integer\");\n return errors;\n}\n\n/** A method name the entrypoint can have: an identifier that is not the constructor. */\nconst methodName = /^[A-Za-z_$][\\w$]*$/;\n\nfunction validateRpcDrive(drive: RpcDrive): readonly string[] {\n const errors: string[] = [];\n if (drive.entrypoint !== undefined && !methodName.test(drive.entrypoint))\n errors.push(\"rpc drive entrypoint must be an exported class name\");\n const ids = new Set<string>();\n drive.calls.forEach((c, i) => {\n if (!methodName.test(c.method) || c.method === \"constructor\")\n errors.push(`calls[${i}].method must be a method name`);\n if (!Array.isArray(c.args)) errors.push(`calls[${i}].args must be an array`);\n if (ids.has(c.id)) errors.push(`duplicate call id ${JSON.stringify(c.id)}`);\n ids.add(c.id);\n });\n errors.push(...validateCaller(\"rpc\", drive));\n return errors;\n}\n\n/**\n * Durable Object setups: an object's or a SQL table's name may not hold\n * \"/\", since the snapshot names a table `<object>/<table>` and a selector\n * must read back to one place.\n */\nfunction validateDurableObjectSetups(setup: readonly PlatformData[]): readonly string[] {\n const errors: string[] = [];\n for (const step of setup) {\n if (step[\"kind\"] !== \"durable_object\") continue;\n const s = step as unknown as DurableObjectSetup;\n for (const name of [...Object.keys(s.objects), ...Object.keys(s.sql ?? {})])\n if (name.includes(\"/\"))\n errors.push(\n `durableObject ${s.binding}: object name ${JSON.stringify(name)} holds \"/\", which the snapshot uses between an object and its table`,\n );\n for (const [name, seed] of Object.entries(s.sql ?? {})) {\n if (typeof seed.schema !== \"string\" || seed.schema.trim() === \"\")\n errors.push(\n `durableObject ${s.binding}: object ${JSON.stringify(name)} has a sql seed without a schema`,\n );\n for (const [table, rows] of Object.entries(seed.rows ?? {})) {\n if (table.includes(\"/\"))\n errors.push(\n `durableObject ${s.binding}: table name ${JSON.stringify(table)} of ${JSON.stringify(name)} holds \"/\"`,\n );\n if (\n !Array.isArray(rows) ||\n rows.some((r) => typeof r !== \"object\" || r === null || Array.isArray(r))\n )\n errors.push(\n `durableObject ${s.binding}: rows of ${JSON.stringify(name)}.${table} must be an array of objects`,\n );\n }\n }\n }\n return errors;\n}\n\n/** Build and validate a scenario spec; throws with every problem listed. */\nexport function defineScenario(input: CloudflareScenarioInput): ScenarioSpec {\n // queue() keeps the ids a QueueDrive already has, so it serves both forms.\n const drive: Drive =\n input.drive.kind === \"queue\" ? queue(input.drive.queue, input.drive.messages) : input.drive;\n const spec: ScenarioSpec = {\n version: 1,\n name: input.name,\n platform: \"cloudflare\",\n worker: input.worker,\n drive,\n setup: input.setup ?? [],\n externals: input.externals ?? [],\n invariants: input.invariants,\n bounds: { ...defaultBounds, ...input.bounds },\n ...(input.specs ? { specs: input.specs } : {}),\n ...(input.pinned ? { pinned: input.pinned } : {}),\n };\n const errors = [\n ...validateScenario(spec),\n ...validateDurableObjectSetups(spec.setup),\n ...validateCalleeSetups(spec.setup),\n ...validateEnvSetups(spec.setup),\n ...validateScriptedObjectSetups(spec.setup, spec.invariants),\n ...(drive.kind === \"http\" ? validateHttpDrive(drive) : []),\n ...(drive.kind === \"rpc\" ? validateRpcDrive(drive) : []),\n ...(drive.kind === \"cron\" ? validateCronDrive(drive) : []),\n ...(drive.kind === \"websocket\" ? validateWebSocketDrive(drive) : []),\n ];\n if (errors.length > 0) {\n throw new Error(`invalid scenario ${JSON.stringify(input.name)}:\\n- ${errors.join(\"\\n- \")}`);\n }\n return spec;\n}\n","/**\n * Inbound RPC delivery: one invocation per attempt of a `WorkerEntrypoint`\n * method call the drive's caller makes. The entrypoint is constructed anew\n * for each call, as the runtime does (Cloudflare, Workers RPC: a new\n * instance of the class for every call), and its return value or the error\n * it threw is the response the caller sees.\n */\n\nimport {\n type DeliveryResult,\n type EventRef,\n type JsonValue,\n type RunHooks,\n type ScenarioSpec,\n toJson,\n} from \"@eutaxy/core\";\nimport { runInvocation } from \"@eutaxy/engine\";\nimport { drainBackground, executionContext } from \"./background.ts\";\nimport { type Answer, startCaller } from \"./caller.ts\";\nimport { isPlainData } from \"./durable-objects.ts\";\nimport { constructEntrypoint } from \"./entrypoint.ts\";\nimport { type RpcCallSpec, type RpcDrive, rpcTarget } from \"./scenario.ts\";\n\n/**\n * An error as the caller sees it over RPC: a new error object with the\n * name and message (Cloudflare, RPC error handling), nothing of its class.\n */\nexport function describeError(error: unknown): string {\n if (error instanceof Error) return `${error.name}: ${error.message}`;\n return typeof error === \"string\" ? error : JSON.stringify(toJson(error));\n}\n\n/** One attempt of a call, under the caller's retry policy and deadline. */\nexport async function deliverCall(\n event: EventRef,\n hooks: RunHooks,\n spec: ScenarioSpec,\n drive: RpcDrive,\n invocation: string,\n cls: unknown,\n env: object,\n): Promise<DeliveryResult> {\n const call = event.data as unknown as RpcCallSpec;\n const target = rpcTarget(drive, call.method);\n const inv = hooks.startInvocation(invocation);\n const background: Promise<unknown>[] = [];\n const args: JsonValue = { callId: event.id, method: call.method, args: call.args };\n const caller = startCaller(event, hooks, spec, drive, target, {\n callId: event.id,\n attempts: event.attempt,\n });\n\n const ran = await runInvocation(hooks, inv, () =>\n callMethod(cls, call, executionContext(background), env),\n );\n let status: DeliveryResult[\"status\"] = ran.status;\n let answer: Answer = { kind: \"none\" };\n if (ran.status === \"completed\") {\n // Data travels by copy; a stub, a function or a stream would let later calls bypass the run.\n if (!isPlainData(ran.value))\n hooks.unsupported(\n `Rpc ${call.method}: the result is not plain data (a stub, a function or a stream); RPC capabilities are not modelled`,\n );\n answer = { kind: \"answered\", value: { ok: true, value: toJson(ran.value) }, accepted: true };\n } else if (ran.status === \"errored\") {\n // The exception reaches the caller as a new error with its name and message; the caller saw an answer.\n answer = { kind: \"errored\", value: { ok: false, error: describeError(ran.error) } };\n }\n if (caller.respond(invocation, args, answer)) status = \"crashed\";\n if (await drainBackground(hooks, inv, invocation, target, background)) status = \"crashed\";\n return { status, followUps: [] };\n}\n\n/**\n * The class an RPC drive calls: the named export, or the Worker's default\n * export (the class passed as the handler, or `exports.default`). Not\n * necessarily a class: the platform reports what it found instead.\n */\nexport function entrypointClass(\n handler: unknown,\n exports: Readonly<Record<string, unknown>> | undefined,\n entrypoint: string | undefined,\n): unknown {\n if (entrypoint !== undefined) return exports?.[entrypoint];\n return typeof handler === \"function\" ? handler : exports?.[\"default\"];\n}\n\n/**\n * The method RPC exposes under a name: one the class or a superclass defines\n * on its prototype. An instance property, even a function, and Object's own\n * methods are not callable (workerd: \"The RPC receiver does not implement the\n * method\").\n */\nexport function rpcMethod(\n instance: object,\n name: string,\n): ((...a: unknown[]) => unknown) | undefined {\n for (\n let proto = Object.getPrototypeOf(instance) as object | null;\n proto !== null && proto !== Object.prototype;\n proto = Object.getPrototypeOf(proto) as object | null\n ) {\n const own = Object.getOwnPropertyDescriptor(proto, name);\n if (!own) continue;\n return typeof own.value === \"function\" && name !== \"constructor\"\n ? (own.value as (...a: unknown[]) => unknown)\n : undefined;\n }\n return undefined;\n}\n\n/**\n * Construct the entrypoint for one call and invoke the method, as the\n * runtime does per call. The arguments are copied, as RPC copies them: a\n * method that mutates one changes neither the scenario nor a later attempt.\n */\nexport function callMethod(cls: unknown, call: RpcCallSpec, ctx: unknown, env: object): unknown {\n const instance = constructEntrypoint(cls, \"WorkerEntrypoint\", ctx, env);\n const method = rpcMethod(instance, call.method);\n if (!method)\n throw new TypeError(`The RPC receiver does not implement the method \"${call.method}\".`);\n return method.apply(instance, structuredClone(call.args) as unknown[]);\n}\n","/**\n * Service bindings with the callee real. A scenario names the Worker behind a\n * binding (`callee(binding, { entry, config })`), and the test gives the\n * platform its module and the name from its wrangler config; the callee's\n * code then runs in the same simulation as the caller's, in the same\n * isolate, as Cloudflare runs both Workers on one thread (Workers, service\n * bindings). Each RPC method call or `fetch()` through the binding is one\n * effect, `Service:<binding>`, with the faults of a call in the network\n * (`crash_before`: it never reached the callee; `ambiguous`: the callee\n * acted and the answer was lost; `crash_after`: the caller died after it);\n * `error` is not among them, since what the callee throws is real. The\n * effect hosts the callee's invocation (`<caller invocation>/<binding>.<method>`,\n * `#<n>` for the n-th call of that method from the same caller invocation):\n * the entrypoint is constructed anew with a fresh `ExecutionContext` and the\n * callee's `env`, a view of the scenario's env under the callee's own names\n * (`DB` for `orders/DB`), so its code runs unchanged while its effects are\n * recorded under its own invocation, interleave as turns and take faults by\n * their position within it. What the callee throws reaches the caller as a\n * new error with its name, message and serializable own properties, a\n * built-in class as itself (Workers RPC, error handling); a fault that\n * crashes the callee ends its invocation and the caller sees an `Error`\n * thrown from the call. The callee's `waitUntil` work finishes before its\n * answer crosses: one of the orders the runtime allows.\n */\n\nimport { type FaultKind, type JsonValue, toJson } from \"@eutaxy/core\";\nimport { hostInvocation, isRedirect, type Outcome, runInvocation } from \"@eutaxy/engine\";\nimport { drainBackground, executionContext } from \"./background.ts\";\nimport { isPlainData } from \"./durable-objects.ts\";\nimport { constructEntrypoint } from \"./entrypoint.ts\";\nimport { calleeOfEnv } from \"./object-access.ts\";\nimport { outboundGate, type ProxyContext, pointAt, refuse } from \"./proxy-context.ts\";\nimport { describeError, entrypointClass, rpcMethod } from \"./rpc.ts\";\nimport type { CalleeSetup } from \"./scenario.ts\";\nimport { recordRequest, scriptedError, serviceStub } from \"./services.ts\";\n\n/**\n * The callee's module as the test gives it: the Worker's name from its\n * wrangler config, which qualifies its bindings, its exports, and what the\n * caller's service binding carries in its own config: the `entrypoint` the\n * binding reaches (the scenario's `callee()` may name one too, and wins)\n * and the `props` the callee reads from `ctx.props`.\n */\nexport interface CalleeModule {\n readonly name: string;\n readonly exports: Readonly<Record<string, unknown>>;\n readonly entrypoint?: string;\n readonly props?: Readonly<Record<string, JsonValue>>;\n /**\n * The module is the scenario's own Worker, reached back through a\n * callee's binding (the Worker it called calls it in turn): it runs with\n * the scenario's env as it is, under its own names, not with a view\n * qualified by `name`, so what it reads and writes there is what the\n * scenario's events read and write.\n */\n readonly self?: boolean;\n}\n\n/** The faults a call to a real callee admits; `error` is the callee's own to throw. */\nexport const callFaults: readonly FaultKind[] = [\"crash_before\", \"ambiguous\", \"crash_after\"];\n\n/** What the platform keeps per run about its callees; cleared before each run. */\nexport class CalleeState {\n /** Calls so far per caller invocation, binding and method, to name each hosted invocation. */\n readonly counts = new Map<string, number>();\n clear(): void {\n this.counts.clear();\n }\n}\n\n/**\n * The callee's `env`: the scenario's env seen under the callee's own names,\n * each mapped onto `<name>/<key>`. Over the platform's proxied env the\n * entries are the proxies, so the callee's effects are recorded under their\n * qualified targets, and an alias (`<name>/STOCK` for the caller's `STOCK`)\n * is already resolved; over workerd's raw env (a callee's Durable Object,\n * which the runtime constructs with the main Worker's env) the aliases are\n * given here, so the shared binding is there under the callee's name too.\n */\nexport function calleeEnv(\n name: string,\n env: object,\n aliases: Readonly<Record<string, string>> = {},\n): object {\n const prefix = `${name}/`;\n const source = env as Record<string, unknown>;\n /** The key of `env` a property of the view reads: the qualified name, or the binding it is an alias of. */\n const keyOf = (prop: string | symbol): string | undefined => {\n if (typeof prop !== \"string\") return undefined;\n const qualified = `${prefix}${prop}`;\n return qualified in source ? qualified : (aliases[qualified] ?? qualified);\n };\n const aliasKeys = Object.keys(aliases).filter(\n (a) => a.startsWith(prefix) && (aliases[a] ?? \"\") in source,\n );\n return new Proxy(Object.create(null) as Record<string, unknown>, {\n get(_t, prop) {\n // Whose view this is, for an object constructed with it (see `ownEnv`).\n if (prop === calleeOfEnv) return name;\n const key = keyOf(prop);\n return key === undefined ? undefined : source[key];\n },\n has(_t, prop) {\n const key = keyOf(prop);\n return key !== undefined && key in source;\n },\n ownKeys: () => [\n ...new Set(\n [...Reflect.ownKeys(source).filter((k): k is string => typeof k === \"string\"), ...aliasKeys]\n .filter((k) => k.startsWith(prefix))\n .map((k) => k.slice(prefix.length)),\n ),\n ],\n getOwnPropertyDescriptor(_t, prop) {\n const key = keyOf(prop);\n if (key === undefined || !(key in source)) return undefined;\n return { value: source[key], enumerable: true, configurable: true, writable: false };\n },\n });\n}\n\n/**\n * The error the caller sees for what the callee threw: a new error with the\n * name and message, a built-in class as itself, and the serializable own\n * properties the thrown error carried (Workers RPC, error handling, enhanced\n * error serialization). Nothing of the original's identity or stack.\n */\nexport function crossingError(error: unknown): Error {\n const crossed = scriptedError(describeError(error));\n if (error instanceof Error) {\n for (const key of Object.keys(error)) {\n if (key === \"name\" || key === \"message\" || key === \"stack\") continue;\n try {\n Object.defineProperty(crossed, key, {\n value: structuredClone((error as unknown as Record<string, unknown>)[key]),\n enumerable: true,\n configurable: true,\n writable: true,\n });\n } catch {\n // Not serializable: it does not cross.\n }\n }\n }\n return crossed;\n}\n\n/**\n * The fetch handler the binding reaches: the named entrypoint's method when\n * the setup names one, else the default export's (a handler object's `fetch`,\n * or an entrypoint class's method).\n */\nfunction fetchHandlerOf(\n exports: Readonly<Record<string, unknown>>,\n entrypoint: string | undefined,\n ctx: ExecutionContext,\n env: object,\n): ((request: Request) => unknown) | undefined {\n const def = entrypoint === undefined ? exports[\"default\"] : exports[entrypoint];\n if (typeof def === \"function\") {\n const instance = constructEntrypoint(def, \"WorkerEntrypoint\", ctx, env) as {\n fetch?: (request: Request) => unknown;\n };\n return typeof instance.fetch === \"function\" ? instance.fetch.bind(instance) : undefined;\n }\n if (typeof def === \"object\" && def !== null) {\n const handler = def as {\n fetch?: (request: Request, env: object, ctx: ExecutionContext) => unknown;\n };\n return typeof handler.fetch === \"function\"\n ? (request) => handler.fetch?.call(handler, request, env, ctx)\n : undefined;\n }\n return undefined;\n}\n\n/**\n * The getter RPC exposes under a name: one the class or a superclass defines\n * on its prototype. An instance field is not reachable over RPC (workerd:\n * \"The RPC receiver does not implement the method\").\n */\nfunction rpcGetter(instance: object, name: string): (() => unknown) | undefined {\n for (\n let proto = Object.getPrototypeOf(instance) as object | null;\n proto !== null && proto !== Object.prototype;\n proto = Object.getPrototypeOf(proto) as object | null\n ) {\n const own = Object.getOwnPropertyDescriptor(proto, name);\n if (!own) continue;\n return typeof own.get === \"function\" ? own.get : undefined;\n }\n return undefined;\n}\n\n/** The stub a Worker sees under a service binding whose callee runs for real. */\nexport function proxyCallee(\n binding: string,\n ctx: ProxyContext,\n setup: CalleeSetup,\n module: CalleeModule,\n env: object,\n state: CalleeState,\n): object {\n const target = `Service:${binding}`;\n const view = module.self ? env : calleeEnv(module.name, env);\n const entrypointName = setup.entrypoint ?? module.entrypoint;\n const props = module.props ?? {};\n const unsupported = (what: string): never => refuse(ctx, `callee ${binding}: ${what}`);\n const point = (op: string, args: JsonValue) => pointAt(ctx, target, op, args, callFaults);\n /** The hosted invocation's id: the n-th call of a method from one caller invocation is `#n`. */\n const invocationId = (method: string): string => {\n const key = `${ctx.currentInvocation()}/${binding}.${method}`;\n const n = (state.counts.get(key) ?? 0) + 1;\n state.counts.set(key, n);\n return n === 1 ? key : `${key}#${n}`;\n };\n\n /** The callee's code as an invocation of its own inside the call: the handler, then its background work. */\n const invoke = <T>(\n method: string,\n work: (executionContext: ExecutionContext) => T | Promise<T>,\n ): Promise<Outcome<T>> => {\n const hooks = ctx.hooks;\n const id = invocationId(method);\n return hostInvocation(hooks, id, async (inv) => {\n const background: Promise<unknown>[] = [];\n const ran = await runInvocation(hooks, inv, () =>\n work(executionContext(background, undefined, props)),\n );\n // A cut-off here crashes the callee after it answered: the answer stands, work not started is lost.\n if (ran.status !== \"crashed\") await drainBackground(hooks, inv, id, target, background);\n return ran;\n });\n };\n\n /** What the caller gets out of the callee's outcome: the value, the error as RPC carries it, or an error for a crash. */\n const answer = <T>(outcome: Outcome<T>, method: string): T => {\n if (outcome.status === \"completed\") return outcome.value;\n if (outcome.status === \"errored\") throw crossingError(outcome.error);\n throw new Error(\n `the Worker behind service binding ${binding} crashed while handling ${method}`,\n );\n };\n\n /**\n * Arguments travel by copy, as plain data: a function, a stub or a stream is\n * a capability the model lacks, and a class instance is what RPC refuses\n * (structuredClone would silently make a plain object of it).\n */\n const copied = (method: string, args: readonly unknown[]): unknown[] => {\n if (!args.every((a) => isPlainData(a)))\n return unsupported(\n `the arguments of ${method} are not plain data (a stub, a function, a stream or a class instance); RPC carries plain data only`,\n );\n try {\n return structuredClone([...args]);\n } catch {\n return unsupported(`the arguments of ${method} cannot be copied as RPC copies them`);\n }\n };\n\n /** A result passed back to the caller, by copy; one that is not plain data cannot be followed. */\n const plain = (method: string, value: unknown): unknown => {\n if (!isPlainData(value))\n unsupported(\n `${method} returned something that is not plain data (a stub, a function or a stream); RPC capabilities are not modelled`,\n );\n try {\n return structuredClone(value);\n } catch {\n return value;\n }\n };\n\n const entrypoint = (): unknown => {\n const cls = entrypointClass(undefined, module.exports, entrypointName);\n if (typeof cls !== \"function\")\n unsupported(\n `${entrypointName === undefined ? \"the default export\" : `export ${entrypointName}`} of ${module.name} is not a WorkerEntrypoint class`,\n );\n return cls;\n };\n\n const summarize = (value: unknown): JsonValue => ({ value: toJson(value) });\n\n return serviceStub(binding, ctx, {\n call: (method, args) => {\n // Copied now, as RPC copies at the call: what the caller does to its arguments after calling\n // (while the call waits for its turn) does not reach the callee. A refused argument rejects the\n // call's promise, as the real stub's does.\n let copy: unknown[];\n try {\n copy = copied(method, args);\n } catch (err) {\n return Promise.reject(err);\n }\n return ctx.hooks.effect(\n point(method, { args: args.map((a) => toJson(a)) }),\n outboundGate(ctx, async () => {\n const cls = entrypoint();\n const outcome = await invoke(method, (executionContext) => {\n const instance = constructEntrypoint(cls, \"WorkerEntrypoint\", executionContext, view);\n const fn = rpcMethod(instance, method);\n if (!fn)\n throw new TypeError(`The RPC receiver does not implement the method \"${method}\".`);\n return fn.apply(instance, copy);\n });\n return plain(method, answer(outcome, method));\n }),\n summarize,\n );\n },\n property: (name) =>\n ctx.hooks.effect(\n point(name, { property: true }),\n outboundGate(ctx, async () => {\n const cls = entrypoint();\n const outcome = await invoke(name, (executionContext) => {\n const instance = constructEntrypoint(cls, \"WorkerEntrypoint\", executionContext, view);\n const getter = rpcGetter(instance, name);\n if (!getter)\n throw new TypeError(`The RPC receiver does not implement the method \"${name}\".`);\n return getter.call(instance);\n });\n return plain(name, answer(outcome, name));\n }),\n summarize,\n ),\n async fetch(request) {\n // Taken where the call starts, before anything is awaited: an object's gate, when one is calling.\n const behind = outboundGate(ctx, async () => undefined);\n const { method, headers, body } = await recordRequest(request);\n return ctx.hooks.effect(\n point(method, { url: request.url, method, headers, body }),\n async () => {\n await behind();\n const outcome = await invoke(\"fetch\", (executionContext) => {\n const handler = fetchHandlerOf(module.exports, entrypointName, executionContext, view);\n if (!handler)\n return unsupported(\n `${entrypointName === undefined ? module.name : `export ${entrypointName} of ${module.name}`} has no fetch handler`,\n );\n return handler(request);\n });\n const response = answer(outcome, \"fetch\");\n if (!(response instanceof Response))\n return unsupported(\n `${module.name}'s fetch handler returned something that is not a Response`,\n );\n // workerd follows a redirect from the callee as fetch does; only the first answer ran here.\n if (isRedirect(response.status) && request.redirect !== \"manual\")\n return unsupported(\n `${module.name} answered ${method} ${new URL(request.url).pathname} with a ${response.status} redirect, which the runtime would follow; fetch with redirect: \"manual\"`,\n );\n return response;\n },\n (r) => ({ status: r.status }),\n );\n },\n });\n}\n","import {\n describeVerdict,\n type Platform,\n type ScenarioSpec,\n type ScenarioVerdict,\n} from \"@eutaxy/core\";\nimport { type ExploreOptions, explore } from \"@eutaxy/engine\";\n\n/** Explore a scenario on a platform and return its verdict. */\nexport function check(\n spec: ScenarioSpec,\n platform: Platform,\n options: ExploreOptions = { seed: spec.name },\n): Promise<ScenarioVerdict> {\n return explore(spec, platform, options);\n}\n\n/** For use from a test: passes only when the scenario is BOUNDED. */\nexport async function expectHolds(\n spec: ScenarioSpec,\n platform: Platform,\n options?: ExploreOptions,\n): Promise<void> {\n const verdict = await check(spec, platform, options);\n if (verdict.kind !== \"BOUNDED\") throw new Error(describeVerdict(verdict));\n}\n","/**\n * A Durable Object namespace with its objects scripted. A caller reaches an\n * object through a stub of its namespace (`env.BINDING.get(id)`,\n * `getByName(name)`), by RPC method or by `fetch()` (Durable Objects, create\n * Durable Object stubs and send requests). Here no object of the namespace\n * is constructed or run: the scenario's `scriptedObject()` setup scripts\n * the replies, as `service()` scripts a Worker, and each call is one effect\n * on `DO:<binding>` with the object's name in its arguments and the faults\n * of a stub call, where `crash_before` and `error` mean the call never\n * reached the object, `ambiguous` that it acted and the answer was lost,\n * and `crash_after` that the caller died after it. Ids are the namespace's\n * own, so an id made here equals the one the runtime would make. The stub\n * is the one a scripted service has (`serviceStub`).\n */\n\nimport { type EffectPoint, type JsonValue, toJson, writeFaults } from \"@eutaxy/core\";\nimport { findResponse, isRedirect, replyOf, toResponse } from \"@eutaxy/engine\";\nimport { outboundGate, type ProxyContext, pointAt, refuse } from \"./proxy-context.ts\";\nimport type { ScriptedObjectSetup, ScriptedReply } from \"./scenario.ts\";\nimport { recordRequest, scriptedError, serviceStub } from \"./services.ts\";\n\n/** An RPC argument as effect-log data; a Request becomes its method and URL. */\nfunction argument(value: unknown): JsonValue {\n if (value instanceof Request) return { method: value.method, url: value.url };\n return toJson(value);\n}\n\n/** The namespace a caller sees under a scripted Durable Object binding's name. */\nexport function proxyScriptedNamespace(\n real: DurableObjectNamespace,\n binding: string,\n ctx: ProxyContext,\n script: ScriptedObjectSetup,\n): DurableObjectNamespace {\n const target = `DO:${binding}`;\n const setup = `scriptedObject(${JSON.stringify(binding)})`;\n /** Object names by id, so the log names an object as its caller does. */\n const names = new Map<string, string>();\n const nameOf = (id: DurableObjectId): string =>\n names.get(id.toString()) ?? id.name ?? id.toString();\n const point = (op: string, args: JsonValue): EffectPoint =>\n pointAt(ctx, target, op, args, writeFaults);\n\n function stubFor(id: DurableObjectId): DurableObjectStub {\n const object = nameOf(id);\n const what = `scripted Durable Object ${binding} ${object}`;\n const unsupported = (reason: string): never => refuse(ctx, `${what}: ${reason}`);\n /** The scripted reply to a method, by name; a method the script lacks cannot be answered. */\n const replyTo = (method: string): ScriptedReply => {\n if (script.methods === undefined) return { returns: null };\n if (!Object.hasOwn(script.methods, method))\n return unsupported(\n `no scripted reply for method ${method}; add it to the ${setup} setup's methods`,\n );\n return script.methods[method] as ScriptedReply;\n };\n const answer = (method: string): unknown => {\n const reply = replyTo(method);\n if (\"throws\" in reply) throw scriptedError(reply.throws);\n // Copied, as RPC copies values: the caller cannot change the script.\n return structuredClone(reply.returns);\n };\n const stub = serviceStub(\n binding,\n ctx,\n {\n call: (method, args) =>\n ctx.hooks.effect(\n point(method, { object, args: args.map(argument) }),\n // From another object the call leaves once that object's earlier writes are durable.\n outboundGate(ctx, async () => answer(method)),\n toJson,\n ),\n property: (method) =>\n ctx.hooks.effect(\n point(method, { object, property: true }),\n outboundGate(ctx, async () => answer(method)),\n toJson,\n ),\n async fetch(request) {\n // Taken where the call starts, before anything is awaited: an object's gate, when one is calling.\n const behind = outboundGate(ctx, async () => undefined);\n const url = new URL(request.url);\n const { method, headers, body } = await recordRequest(request);\n const reply = await ctx.hooks.effect(\n point(\"fetch\", { object, url: request.url, method, headers, body }),\n async () => {\n await behind();\n // The matcher is the externals'; an object takes any host, so none is matched.\n const found = findResponse(\n {\n name: binding,\n host: url.host,\n guarantees: {},\n ...(script.fetch === undefined ? {} : { responses: script.fetch }),\n },\n method,\n url.pathname,\n );\n if (found === undefined)\n return unsupported(\n `no scripted reply for fetch ${method} ${url.pathname}; add it to the ${setup} setup's fetch`,\n );\n const reply = replyOf(found);\n // A 101 carries a WebSocket the object accepted; a script has no object to hold its end.\n if (reply.status === 101)\n return unsupported(\n `the scripted reply to ${method} ${url.pathname} is a 101, and a scripted object accepts no WebSocket`,\n );\n // The runtime follows a redirect an object answers with as fetch does; the script holds only the first reply.\n if (isRedirect(reply.status) && request.redirect !== \"manual\")\n return unsupported(\n `the scripted reply to ${method} ${url.pathname} is a ${reply.status} redirect, which the runtime would follow; script the final reply or fetch with redirect: \"manual\"`,\n );\n return reply;\n },\n (r) => ({ status: r.status, ok: r.status >= 200 && r.status < 300 }),\n );\n return toResponse(reply);\n },\n },\n what,\n { id, name: id.name },\n );\n return stub as DurableObjectStub;\n }\n\n function idFromName(name: string): DurableObjectId {\n const id = real.idFromName(name);\n names.set(id.toString(), name);\n return id;\n }\n\n return new Proxy(real, {\n get(namespace, prop, receiver) {\n switch (prop) {\n case \"idFromName\":\n return idFromName;\n case \"idFromString\":\n return (hex: string) => namespace.idFromString(hex);\n case \"newUniqueId\":\n return (options?: DurableObjectNamespaceNewUniqueIdOptions) => {\n if (options?.jurisdiction !== undefined)\n return refuse(\n ctx,\n `${binding}.newUniqueId({ jurisdiction }) is not modelled for a scripted namespace; use newUniqueId() without one`,\n );\n // Natively the id is random. Drawn from the run's random stream it repeats on replay, as a\n // real namespace's does here; the name is the draw.\n return idFromName(`eutaxy:unique:${crypto.randomUUID()}`);\n };\n case \"get\":\n return (id: DurableObjectId) => stubFor(id);\n case \"getByName\":\n return (name: string) => stubFor(idFromName(name));\n case \"jurisdiction\":\n return () =>\n refuse(\n ctx,\n `${binding}.jurisdiction() is not modelled for a scripted namespace; use the namespace itself`,\n );\n default: {\n // Native members check their receiver: read them on the real namespace.\n const value = Reflect.get(namespace, prop, receiver);\n return typeof value === \"function\" ? value.bind(namespace) : value;\n }\n }\n },\n });\n}\n","/**\n * Each kind of binding the platform models, as one record: how an env value\n * is recognised, what the Worker sees in its place, what is forgotten before\n * a run, the reset its setup step asks for, the snapshot the run ends with,\n * and, for the kinds with events of their own (alarms, Workflow runs), their\n * delivery. The platform and the differential runner iterate these records;\n * neither knows a kind by name.\n */\n\nimport type {\n DeliveryResult,\n EventRef,\n JsonValue,\n PlatformData,\n RunHooks,\n ScenarioSpec,\n} from \"@eutaxy/core\";\nimport { note } from \"@eutaxy/engine\";\nimport { alarmSource, deliverAlarm } from \"./alarms.ts\";\nimport { type CalleeModule, CalleeState, calleeEnv, proxyCallee } from \"./callees.ts\";\nimport { isD1, proxyD1, resetD1, snapshotD1 } from \"./d1.ts\";\nimport {\n BindingState,\n type DurableObjectTestHelpers,\n evictObject,\n evictRunning,\n forgetHosts,\n proxyNamespace,\n resetNamespace,\n runInObject,\n snapshotNamespace,\n} from \"./durable-objects.ts\";\nimport {\n deliverWake,\n isDurableObjectNamespace,\n type ObjectAccess,\n wakeEvent,\n wakeSource,\n} from \"./object-access.ts\";\nimport type { ProxyContext } from \"./proxy-context.ts\";\nimport { isR2, proxyR2, resetR2, snapshotR2, VersionBook } from \"./r2.ts\";\nimport {\n type CalleeSetup,\n type D1Setup,\n type DurableObjectSetup,\n defaultAlarmsPerObject,\n type R2Setup,\n type ScriptedObjectSetup,\n type ServiceSetup,\n type WorkflowSetup,\n} from \"./scenario.ts\";\nimport { proxyScriptedNamespace } from \"./scripted-objects.ts\";\nimport { isServiceBinding, proxyService } from \"./services.ts\";\nimport {\n deliverWorkflow,\n isWorkflowBinding,\n proxyWorkflow,\n WorkflowRegistry,\n workflowSource,\n} from \"./workflows.ts\";\n\n/** A setup step that names a binding; every kind modelled here has one. */\nexport interface BindingSetup extends PlatformData {\n readonly binding: string;\n}\n\n/** The tables of one binding's end-of-run snapshot. */\nexport type Tables = { readonly [table: string]: readonly JsonValue[] };\n\n/**\n * One kind of binding. `Real` is the env value's type once `is` accepted it;\n * `Setup` the setup step that names a binding of this kind.\n */\nexport interface Binding<Real = unknown, Setup extends BindingSetup = BindingSetup> {\n /** The `kind` of the setup step naming a binding of this type. */\n readonly kind: Setup[\"kind\"];\n /** The prefix of its snapshot targets: `D1`, `DO`, `R2`, `Workflow`. */\n readonly target: string;\n /** Whether an env value is a binding of this kind. */\n is(value: unknown): value is Real;\n /**\n * What the Worker sees in place of the real binding, asked on every access\n * of `env.<name>`: the record keeps one proxy per name where it may, and\n * reports a binding the scenario did not set up each time it is touched.\n * `undefined` means the name is not this record's (two records share one\n * kind of env value: a service binding is a callee's or scripted), so the\n * next record is asked.\n */\n proxy(name: string, real: Real, ctx: ProxyContext): unknown;\n /** Forget what the last run learned, before the next run's setup. */\n clear(): void;\n /** Bring the real binding, or the model, to the state the setup step asks for. */\n reset(step: Setup, real: unknown): Promise<void>;\n /**\n * The snapshot the run ends with, read through the real binding, or null\n * when the env value is not this binding. `unsupported` reports what the\n * snapshot found that the run could not control.\n */\n snapshot(\n step: Setup,\n real: unknown,\n unsupported: (reason: string) => void,\n ): Promise<Tables | null>;\n /** `EventRef.source` of the events this binding emits, when it has any. */\n readonly source?: string;\n /** A second source of events it delivers, when it has one. */\n readonly closingSource?: string;\n /** Deliver one of its events. */\n deliver?(event: EventRef, hooks: RunHooks, spec: ScenarioSpec): Promise<DeliveryResult>;\n /** Its events the end of the run calls for (see `Platform.closingEvents`), each handed out once. */\n closing?(): readonly EventRef[];\n}\n\n/** A D1 database: Miniflare's SQLite, reset to the scenario's schema and read back whole. */\nexport function d1Binding(schemas: Readonly<Record<string, string>>): Binding<D1Database, D1Setup> {\n const proxies = new Map<string, D1Database>();\n return {\n kind: \"d1\",\n target: \"D1\",\n is: isD1,\n proxy(name, real, ctx) {\n let p = proxies.get(name);\n if (!p) {\n p = proxyD1(real, name, ctx);\n proxies.set(name, p);\n }\n return p;\n },\n clear() {},\n async reset(step, real) {\n const schema = schemas[step.binding];\n if (schema === undefined)\n throw new Error(`no schema provided for D1 binding ${step.binding}`);\n if (!isD1(real)) throw new Error(`env.${step.binding} is not a D1 binding`);\n await resetD1(real, schema);\n },\n async snapshot(_step, real) {\n return isD1(real) ? snapshotD1(real) : null;\n },\n };\n}\n\n/** An R2 bucket: Miniflare's real one, emptied and seeded before each run. */\nexport function r2Binding(): Binding<R2Bucket, R2Setup> {\n /** The buckets the current scenario sets up. */\n let setUp = new Set<string>();\n const proxies = new Map<string, R2Bucket>();\n /** One book for every bucket: the stand-ins count up across them. */\n const versions = new VersionBook();\n return {\n kind: \"r2\",\n target: \"R2\",\n is: isR2,\n proxy(name, real, ctx) {\n if (!setUp.has(name))\n ctx.hooks.unsupported(\n `R2 binding ${name} needs an r2Bucket() setup step, which empties it before each run`,\n );\n let p = proxies.get(name);\n if (!p) {\n p = proxyR2(real, name, ctx, versions);\n proxies.set(name, p);\n }\n return p;\n },\n clear() {\n setUp = new Set();\n versions.clear();\n },\n async reset(step, real) {\n if (!isR2(real)) throw new Error(`env.${step.binding} is not an R2 bucket`);\n setUp.add(step.binding);\n await resetR2(real, step.objects);\n },\n async snapshot(_step, real) {\n return isR2(real) ? { objects: await snapshotR2(real) } : null;\n },\n };\n}\n\nexport interface DurableObjectDeps {\n readonly ctx: ProxyContext;\n /** The Cloudflare test helpers, without which objects cannot be reset, seeded or snapshotted. */\n readonly helpers: DurableObjectTestHelpers | undefined;\n /** The env value under a binding name: alarm events name their binding, not an object. */\n readonly real: (name: string) => unknown;\n /** Snapshot every seeded object from its storage: the raw side of a differential, where no proxy saw the calls. */\n readonly snapshotAll?: boolean;\n}\n\n/**\n * A Durable Object namespace: the real objects workerd runs, cleared, seeded\n * and evicted before each run, their storage snapshotted after it, and their\n * alarms taken over and fired as events of the run.\n */\nexport function durableObjectBinding(\n deps: DurableObjectDeps,\n): Binding<DurableObjectNamespace, DurableObjectSetup> & { readonly objects: ObjectAccess } {\n const { ctx, helpers } = deps;\n const proxies = new Map<string, DurableObjectNamespace>();\n /** The bindings the current scenario's setup resets before each run. */\n let setUp = new Set<string>();\n /** Per binding, alarm firings allowed per object in the current run. */\n let alarmLimits = new Map<string, number>();\n /** Per binding, what the current run knows about its objects. */\n const states = new Map<string, BindingState>();\n const stateFor = (binding: string): BindingState => {\n let state = states.get(binding);\n if (!state) {\n state = new BindingState();\n states.set(binding, state);\n }\n return state;\n };\n const namespace = (name: string, real: unknown = deps.real(name)): DurableObjectNamespace => {\n if (!isDurableObjectNamespace(real))\n throw new Error(`env.${name} is not a Durable Object namespace`);\n return real;\n };\n const required = (): DurableObjectTestHelpers => {\n if (!helpers)\n throw new Error(\n 'Durable Object setup needs the Cloudflare test helpers: createCloudflarePlatform({ ..., durableObjects: await import(\"cloudflare:test\") })',\n );\n return helpers;\n };\n const objects: ObjectAccess = {\n run: (binding, id, object, fn) =>\n runInObject(namespace(binding), binding, ctx, helpers, stateFor(binding), id, object, fn),\n abort: (binding, id) => stateFor(binding).abort(id),\n mayPark: (binding, id) => stateFor(binding).mayPark(id),\n evict: (binding, id) => {\n // The instance a crash left is dropped: woken at the end of the run unless something enters it.\n stateFor(binding).dropped.add(id);\n return evictObject(namespace(binding), helpers, id);\n },\n };\n /** Wakes handed out this run, to name each one. */\n let wakes = 0;\n /** Wakes delivered to each object this run, by binding and id. */\n const woken = new Map<string, number>();\n return {\n objects,\n kind: \"durable_object\",\n target: \"DO\",\n is: isDurableObjectNamespace,\n proxy(name, real, ctx) {\n let p = proxies.get(name);\n if (!p) {\n p = proxyNamespace(real, name, ctx, stateFor(name), helpers, () => setUp.has(name));\n proxies.set(name, p);\n }\n return p;\n },\n clear() {\n setUp = new Set();\n alarmLimits = new Map();\n wakes = 0;\n woken.clear();\n forgetHosts();\n for (const state of states.values()) state.clear();\n },\n async reset(step, real) {\n setUp.add(step.binding);\n alarmLimits.set(step.binding, step.alarmsPerObject ?? defaultAlarmsPerObject);\n stateFor(step.binding).seededSql = await resetNamespace(\n namespace(step.binding, real),\n required(),\n stateFor(step.binding).names,\n step.objects,\n step.sql ?? {},\n );\n },\n async snapshot(step, real, unsupported) {\n const binding = step.binding;\n return snapshotNamespace(\n namespace(binding, real),\n required(),\n stateFor(binding).names,\n stateFor(binding).touched,\n step.objects,\n step.sql ?? {},\n stateFor(binding).seededSql,\n (object) =>\n unsupported(\n `Durable Object ${binding} ${object} was reached without a call Eutaxy saw: another object called it through an env the simulation does not stand behind (the env parameter its constructor kept, or a class the platform was not given)`,\n ),\n unsupported,\n deps.snapshotAll === true,\n );\n },\n source: alarmSource,\n closingSource: wakeSource,\n closing() {\n const events: EventRef[] = [];\n for (const [binding, state] of states) {\n for (const id of [...state.dropped].sort()) {\n state.dropped.delete(id);\n events.push(wakeEvent(binding, id, state.names.get(id) ?? id, ++wakes));\n }\n }\n return events;\n },\n async deliver(event, hooks, spec) {\n if (event.source === wakeSource) {\n const { binding, id, object } = event.data as {\n binding: string;\n id: string;\n object: string;\n };\n const key = `${binding}\\n${id}`;\n const times = (woken.get(key) ?? 0) + 1;\n woken.set(key, times);\n const result = await deliverWake(event, hooks, objects);\n // A wake that left the object dropped again failed: a fault landed in its constructor, or\n // the constructor fails by itself. Each fault explains one failure, so more failures than\n // the run has faults are the object's own, and waking it again would fail the same way.\n const state = stateFor(binding);\n if (state.dropped.has(id) && times > spec.bounds.maxFaultsPerRun) {\n state.dropped.delete(id);\n hooks.unsupported(\n `Durable Object ${binding} ${object} could not be woken at the end of the run: a callback behind its input gate failed each of the ${times} times it was constructed for that, more often than the run's faults explain, so what its storage holds was not read as its next event would find it`,\n );\n }\n return result;\n }\n const binding = String((event.data as { binding?: unknown }).binding ?? \"\");\n return deliverAlarm(event, hooks, spec.bounds.maxRedeliveries, {\n binding,\n book: stateFor(binding).alarms,\n limit: alarmLimits.get(binding) ?? defaultAlarmsPerObject,\n objects,\n bookkeep: (op, args) =>\n note(hooks, {\n invocation: hooks.bookkeeping(),\n target: `DO:${binding}`,\n op,\n args,\n allowed: [],\n }),\n });\n },\n };\n}\n\nexport interface WorkflowDeps {\n /** The Worker module's exports, where the classes `workflow` setup steps name are found. */\n readonly exports: Readonly<Record<string, unknown>> | undefined;\n /** The env the instances run with: the Worker's proxied one. */\n readonly env: () => object;\n /** The callee a qualified binding (`inventory/FLOW`) belongs to, if the platform was given it: its classes and env are the callee's. */\n readonly calleeOf?: (binding: string) => CalleeModule | undefined;\n}\n\n/**\n * A Workflow binding: a model of the engine running the scenario's own\n * class, never the real binding; instances live in a registry and run as\n * events of the run.\n */\nexport function workflowBinding(deps: WorkflowDeps): Binding<object, WorkflowSetup> {\n /** The bindings the current scenario sets up, with the class each runs. */\n let classes = new Map<string, WorkflowSetup>();\n const registries = new Map<string, WorkflowRegistry>();\n const registryFor = (binding: string): WorkflowRegistry => {\n let r = registries.get(binding);\n if (!r) {\n r = new WorkflowRegistry();\n registries.set(binding, r);\n }\n return r;\n };\n const proxies = new Map<string, object>();\n return {\n kind: \"workflow\",\n target: \"Workflow\",\n is: isWorkflowBinding,\n proxy(name, _real, ctx) {\n if (!classes.has(name)) {\n ctx.hooks.unsupported(\n `Workflow binding ${name} needs a workflow() setup step naming its class`,\n );\n // Never the real binding: its engine would run the class on the real clock.\n return proxyWorkflow(name, ctx, new WorkflowRegistry());\n }\n let p = proxies.get(name);\n if (!p) {\n p = proxyWorkflow(name, ctx, registryFor(name));\n proxies.set(name, p);\n }\n return p;\n },\n clear() {\n classes = new Map();\n for (const registry of registries.values()) registry.clear();\n },\n async reset(step) {\n classes.set(step.binding, step);\n },\n async snapshot(step) {\n return { instances: registryFor(step.binding).rows() };\n },\n source: workflowSource,\n async deliver(event, hooks, spec) {\n const { binding, id } = event.data as { binding: string; id: string };\n const setup = classes.get(binding);\n // A binding with no setup step was already reported when the Worker touched it.\n if (!setup) return { status: \"errored\", followUps: [] };\n const className = setup.className;\n // A callee's Workflow runs the callee's class with the callee's env, as the callee's code does.\n const callee = deps.calleeOf?.(binding);\n const cls = (callee?.exports ?? deps.exports)?.[className];\n const instance = registryFor(binding).instances.get(id);\n if (typeof cls !== \"function\" || !instance) {\n hooks.unsupported(\n callee\n ? `Workflow ${binding}: class ${className} is not among the exports of the callee ${callee.name}`\n : `Workflow ${binding}: class ${className} is not among the Worker module's exports; pass them as createCloudflarePlatform({ ..., exports })`,\n );\n return { status: \"errored\", followUps: [] };\n }\n return deliverWorkflow(event, hooks, {\n binding,\n ...(setup.name === undefined ? {} : { name: setup.name }),\n instance,\n cls,\n env: callee ? calleeEnv(callee.name, deps.env()) : deps.env(),\n maxFaultsPerRun: spec.bounds.maxFaultsPerRun,\n maxRedeliveries: spec.bounds.maxRedeliveries,\n });\n },\n };\n}\n\nexport interface CalleeDeps {\n /** The callees' modules by binding, as the test gives them. */\n readonly callees: Readonly<Record<string, CalleeModule>> | undefined;\n /** The scenario's env as the Worker sees it: the callee's env is a view of it under qualified names. */\n readonly env: () => object;\n}\n\n/**\n * A service binding whose callee runs for real (a `callee` setup step): a\n * stub running the callee's module inside each call. Never the real binding.\n * Nothing to reset or snapshot of its own: the callee's bindings have their\n * own steps under their qualified names. A binding without a `callee` step\n * is not this record's.\n */\nexport function calleeBinding(deps: CalleeDeps): Binding<object, CalleeSetup> {\n /** The bindings the current scenario names a callee for. */\n let setups = new Map<string, CalleeSetup>();\n const proxies = new Map<string, object>();\n const state = new CalleeState();\n return {\n kind: \"callee\",\n target: \"Service\",\n is: isServiceBinding,\n proxy(name, _real, ctx) {\n const setup = setups.get(name);\n if (!setup) return undefined;\n let p = proxies.get(name);\n if (!p) {\n const module = deps.callees?.[name];\n if (!module) {\n ctx.hooks.unsupported(\n `callee ${name}: the platform was not given its module; pass createCloudflarePlatform({ ..., callees: { ${name}: { name, exports } } }), as eutaxy check does from the callee() step`,\n );\n // Never the real binding: a stub whose every call is reported.\n return proxyService(name, ctx, { kind: \"service\", binding: name, methods: {} });\n }\n p = proxyCallee(name, ctx, setup, module, deps.env(), state);\n proxies.set(name, p);\n }\n return p;\n },\n clear() {\n setups = new Map();\n proxies.clear();\n state.clear();\n },\n async reset(step) {\n setups.set(step.binding, step);\n },\n async snapshot() {\n return null;\n },\n };\n}\n\n/**\n * A service binding: never the real binding, a stub answering from the\n * scenario's `service` setup; each call one effect. Nothing to reset or\n * snapshot, the callee is scripted.\n */\nexport function serviceBinding(): Binding<object, ServiceSetup> {\n /** The bindings the current scenario scripts. */\n let scripts = new Map<string, ServiceSetup>();\n /** Per binding, the stub for the current run's script. */\n const proxies = new Map<string, object>();\n return {\n kind: \"service\",\n target: \"Service\",\n is: isServiceBinding,\n proxy(name, _real, ctx) {\n const script = scripts.get(name);\n if (!script) {\n ctx.hooks.unsupported(\n `service binding ${name} needs a service() setup step scripting the Worker it reaches`,\n );\n // Never the real binding: it would call the real peer.\n return proxyService(name, ctx, { kind: \"service\", binding: name, methods: {} });\n }\n let p = proxies.get(name);\n if (!p) {\n p = proxyService(name, ctx, script);\n proxies.set(name, p);\n }\n return p;\n },\n clear() {\n scripts = new Map();\n proxies.clear();\n },\n async reset(step) {\n scripts.set(step.binding, step);\n },\n async snapshot() {\n return null;\n },\n };\n}\n\n/**\n * A Durable Object namespace the scenario scripts: never its objects, a\n * namespace whose stubs answer from the `scriptedObject` setup, each call\n * one effect. Nothing to reset, and no storage to snapshot: the end of the\n * run only looks for an object of the namespace that is running, which a\n * call the simulation did not stand behind reached (the real namespace's\n * snapshot looks for the same). A namespace without that step is not this\n * record's: it is the real objects'.\n */\nexport function scriptedObjectBinding(\n helpers: DurableObjectTestHelpers | undefined,\n): Binding<DurableObjectNamespace, ScriptedObjectSetup> {\n /** The namespaces the current scenario scripts. */\n let scripts = new Map<string, ScriptedObjectSetup>();\n /** Per binding, the namespace for the current run's script. */\n const proxies = new Map<string, DurableObjectNamespace>();\n return {\n kind: \"scripted_object\",\n target: \"DO\",\n is: isDurableObjectNamespace,\n proxy(name, real, ctx) {\n const script = scripts.get(name);\n if (!script) return undefined;\n let p = proxies.get(name);\n if (!p) {\n p = proxyScriptedNamespace(real, name, ctx, script);\n proxies.set(name, p);\n }\n return p;\n },\n clear() {\n scripts = new Map();\n proxies.clear();\n },\n async reset(step, real) {\n // Without them nothing could tell that a real object of the namespace ran after all, whichever\n // way it was reached: no run is made, as with the real objects' setup.\n if (!helpers)\n throw new Error(\n 'scriptedObject setup needs the Cloudflare test helpers, to see that none of the namespace\\'s objects ran: createCloudflarePlatform({ ..., durableObjects: await import(\"cloudflare:test\") })',\n );\n scripts.set(step.binding, step);\n // What runs before the run is not the run's: an object another scenario left up, where that\n // one ran the namespace's real objects.\n if (isDurableObjectNamespace(real)) await evictRunning(real, helpers);\n },\n async snapshot(step, real, unsupported) {\n if (!helpers || !isDurableObjectNamespace(real)) return null;\n for (const id of await evictRunning(real, helpers))\n unsupported(\n `Durable Object ${step.binding} ${id.name ?? id.toString()}, of a namespace the scenario scripts, ran for real: something called it through an env the simulation does not stand behind (the env parameter a constructor kept, or a class the platform was not given)`,\n );\n return null;\n },\n };\n}\n\n/**\n * The setup steps these records own, each with its record, in setup order:\n * what the platform resets and snapshots, and the differential runner\n * compares. A step no record owns is left to the scenario's validation.\n */\nexport function ownedSetups(\n setup: ScenarioSpec[\"setup\"],\n bindings: readonly Binding[],\n): readonly (readonly [Binding, BindingSetup])[] {\n const out: (readonly [Binding, BindingSetup])[] = [];\n // Several d1Schema steps on one binding are migrations of one database, whose schema is their files\n // joined: it is reset and snapshotted once, at its first step.\n const databases = new Set<string>();\n for (const step of setup) {\n const binding = bindings.find((b) => b.kind === step.kind);\n if (!binding) continue;\n if (step.kind === \"d1\") {\n const name = String(step[\"binding\"]);\n if (databases.has(name)) continue;\n databases.add(name);\n }\n out.push([binding, step as BindingSetup]);\n }\n return out;\n}\n","/** Inbound HTTP delivery: one invocation per attempt of a request the drive's caller sends. */\n\nimport type { DeliveryResult, EventRef, JsonValue, RunHooks, ScenarioSpec } from \"@eutaxy/core\";\nimport { runInvocation } from \"@eutaxy/engine\";\nimport { drainBackground, executionContext, type RunningWorker } from \"./background.ts\";\nimport { type Answer, startCaller } from \"./caller.ts\";\nimport type { HttpDrive, HttpRequestSpec } from \"./scenario.ts\";\n\n/** The URL inbound requests are addressed to; handlers read only the path. */\nexport const requestOrigin = \"https://worker.test\";\n\n/** Build the `Request` a drive entry describes. */\nexport function requestFor(r: HttpRequestSpec): Request {\n const headers = new Headers(r.headers);\n let body: string | null = null;\n if (r.body !== undefined) {\n if (typeof r.body === \"string\") body = r.body;\n else {\n // Any JSON value, `null` included, travels as application/json.\n body = JSON.stringify(r.body);\n if (!headers.has(\"content-type\")) headers.set(\"content-type\", \"application/json\");\n }\n }\n return new Request(`${requestOrigin}${r.path}`, { method: r.method, headers, body });\n}\n\n/** A compact record of a response for the effect log: status, ok, and a bounded body. */\nexport async function summarizeResponse(response: Response): Promise<JsonValue> {\n const text = await response.clone().text();\n let body: JsonValue = text.length > 1000 ? `${text.slice(0, 1000)}…` : text;\n if (text && (response.headers.get(\"content-type\") ?? \"\").includes(\"json\")) {\n try {\n body = JSON.parse(text) as JsonValue;\n } catch {\n // keep the text\n }\n }\n return { status: response.status, ok: response.ok, body };\n}\n\n/** One attempt of an inbound request, under the caller's retry policy and deadline. */\nexport async function deliverRequest(\n event: EventRef,\n hooks: RunHooks,\n spec: ScenarioSpec,\n drive: HttpDrive,\n invocation: string,\n worker: RunningWorker,\n): Promise<DeliveryResult> {\n const req = event.data as unknown as HttpRequestSpec;\n const target = `Http:${req.path}`;\n const inv = hooks.startInvocation(invocation);\n const background: Promise<unknown>[] = [];\n const handler = worker.handler.fetch;\n if (!handler) throw new Error(\"the Worker has no fetch() handler\");\n const args: JsonValue = { requestId: event.id, method: req.method, path: req.path };\n const caller = startCaller(event, hooks, spec, drive, target, {\n requestId: event.id,\n attempts: event.attempt,\n });\n\n const handled = await runInvocation(hooks, inv, async () => {\n const value: unknown = await handler.call(\n worker.handler,\n requestFor(req),\n worker.env,\n executionContext(background),\n );\n // The Workers runtime fails a request whose handler resolves to anything but a Response, as it\n // fails one whose handler throws: the same uncaught error, answered with a 500 below.\n if (!(value instanceof Response))\n throw new TypeError(\"the fetch handler returned something that is not a Response\");\n return value;\n });\n let status: DeliveryResult[\"status\"] = handled.status;\n let answer: Answer = { kind: \"none\" };\n if (handled.status === \"completed\") {\n // The body is read before the point so the record is complete; the point itself is the send.\n // Streaming bodies run handler code: a crash inside it abandons the read, an error fails the delivery.\n const body = await runInvocation(hooks, inv, () => summarizeResponse(handled.value));\n if (body.status === \"completed\") {\n const sent = body.value as { status: number; ok: boolean; body: JsonValue };\n answer = {\n kind: \"answered\",\n value: sent,\n accepted: drive.retryOn === \"5xx\" ? sent.status < 500 : sent.ok,\n };\n } else status = body.status;\n }\n // Cloudflare answers an uncaught exception with a 500 (workers runtime behaviour); the caller sees that.\n if (status === \"errored\")\n answer = { kind: \"errored\", value: { status: 500, ok: false, body: \"\" } };\n if (caller.respond(invocation, args, answer)) status = \"crashed\";\n\n if (await drainBackground(hooks, inv, invocation, target, background)) status = \"crashed\";\n return { status, followUps: [] };\n}\n","/**\n * The rule a queue message's delivery is decided by, as Cloudflare\n * documents it. Of a handler's calls to `ack()` and `retry()` on one\n * message the first wins and every later one is ignored\n * (developers.cloudflare.com/queues/configuration/batching-retries/,\n * \"Explicit acknowledgement and retries\"); a message whose handler\n * completed without deciding is acknowledged by the platform, and one\n * acknowledged is not delivered again, whatever the handler does after\n * (developers.cloudflare.com/queues/configuration/javascript-apis/,\n * \"Consumer\"). Written in the subset the Lean engine translates, so what\n * is proved is this code, and the four rule functions are also the code\n * that runs: `deliverMessage` in queues.ts decides by them and holds no\n * decision of its own. The three below them state the claims in\n * queue-decision.props.ts, two of them as a model of a whole delivery;\n * queue-decision.test.ts holds `deliverMessage` to that model.\n */\n\n/** What a handler decides of a message. */\nexport type Decision = \"ack\" | \"retry\";\n\n/** What a delivery holds of its message: the decision that stands, or none yet. */\nexport type Standing = Decision | \"none\";\n\n/** The decision that stands after a call: the first made, which no later call replaces. */\nexport function standsAfter(standing: Standing, call: Decision): Standing {\n return standing === \"none\" ? call : standing;\n}\n\n/** Whether a call takes effect: only one made while no decision stands. */\nexport function takesEffect(standing: Standing): boolean {\n return standing === \"none\";\n}\n\n/** Whether the platform acknowledges the message itself: its handler completed without deciding. */\nexport function acknowledgedImplicitly(completed: boolean, standing: Standing): boolean {\n return completed && standing === \"none\";\n}\n\n/** Whether the delivery was handled, so that the message is not delivered again: its decision is an acknowledgement. */\nexport function handled(standing: Standing): boolean {\n return standing === \"ack\";\n}\n\n/** The decision that stands after a handler's calls on one message, in order, from the one standing before them. */\nexport function standingAfter(standing: Standing, calls: readonly Decision[]): Standing {\n if (calls.length === 0) return standing;\n return standingAfter(standsAfter(standing, calls[0] ?? \"ack\"), calls.slice(1));\n}\n\n/**\n * The decision a delivery ends with: the handler's calls on the message\n * in order, then the platform's own acknowledgement where the rule gives\n * one. `completed` says whether the handler completed and that\n * acknowledgement was made; a handler that threw, or a crash that ended\n * it or lost the acknowledgement, is one that did not.\n */\nexport function settled(calls: readonly Decision[], completed: boolean): Standing {\n const standing = standingAfter(\"none\", calls);\n return acknowledgedImplicitly(completed, standing) ? standsAfter(standing, \"ack\") : standing;\n}\n\n/** Whether every call is one a handler can make, as the types say; the claims repeat it for the Lean engine, which reads a union of string literals as any string. */\nexport function decisions(calls: readonly Decision[]): boolean {\n return calls.every((call) => call === \"ack\" || call === \"retry\");\n}\n","/**\n * Queue delivery: one invocation per delivery of a message, redelivered\n * until acked or dead-lettered. Which call takes effect, when the\n * platform acknowledges for the handler and whether the delivery was\n * handled are the rule of queue-decision.ts, whose claims are proved;\n * this file decides none of them itself.\n */\n\nimport {\n type DeliveryResult,\n decisionFaults,\n type EffectPoint,\n type EventRef,\n type JsonValue,\n type RunHooks,\n redelivery,\n type ScenarioSpec,\n} from \"@eutaxy/core\";\nimport { decide, note, runInvocation } from \"@eutaxy/engine\";\nimport { drainBackground, executionContext, type RunningWorker } from \"./background.ts\";\nimport {\n acknowledgedImplicitly,\n type Decision,\n handled,\n type Standing,\n standsAfter,\n takesEffect,\n} from \"./queue-decision.ts\";\nimport type { QueueDrive } from \"./scenario.ts\";\n\n/** Deep-copy JSON data so a handler that mutates its message cannot leak into other runs. */\nexport function cloneJson(value: JsonValue): JsonValue {\n return JSON.parse(JSON.stringify(value)) as JsonValue;\n}\n\n/** One delivery of a queue message, with Queues' at-least-once semantics. */\nexport async function deliverMessage(\n event: EventRef,\n hooks: RunHooks,\n spec: ScenarioSpec,\n drive: QueueDrive,\n invocation: string,\n worker: RunningWorker,\n maxRetries: number,\n): Promise<DeliveryResult> {\n const queueTarget = `Queue:${drive.queue}`;\n const inv = hooks.startInvocation(invocation);\n /** The decision that stands for the message: Cloudflare honours the first, and later ones are ignored. */\n const state: { standing: Standing } = { standing: \"none\" };\n const background: Promise<unknown>[] = [];\n\n const decisionPoint = (op: Decision, args: JsonValue): EffectPoint => ({\n invocation,\n target: queueTarget,\n op,\n args,\n allowed: decisionFaults,\n });\n /** The first decision wins; a later one is recorded as not effective. */\n const take = (op: Decision) => (): boolean => {\n const effective = takesEffect(state.standing);\n state.standing = standsAfter(state.standing, op);\n return effective;\n };\n const effective = (e: boolean): JsonValue => ({ effective: e });\n /** Records the handler's call; the result says whether it took effect. */\n const record = (op: Decision, args: JsonValue): void => {\n hooks.effectSync(decisionPoint(op, args), take(op), effective);\n };\n const message: Message<unknown> = {\n id: event.id,\n timestamp: new Date(),\n body: cloneJson(event.data),\n attempts: event.attempt,\n ack: () => record(\"ack\", { messageId: event.id, implicit: false, body: event.data }),\n retry: () => record(\"retry\", { messageId: event.id, body: event.data }),\n };\n const batch: MessageBatch<unknown> = {\n queue: drive.queue,\n messages: [message],\n metadata: { metrics: { backlogCount: 0, backlogBytes: 0 } },\n ackAll: () => message.ack(),\n retryAll: () => message.retry(),\n };\n const execution = executionContext(background);\n\n const handler = worker.handler.queue;\n if (!handler) throw new Error(\"the Worker has no queue() handler\");\n let status: DeliveryResult[\"status\"] = (\n await runInvocation(hooks, inv, () =>\n handler.call(worker.handler, batch, worker.env, execution),\n )\n ).status;\n\n if (acknowledgedImplicitly(status === \"completed\", state.standing)) {\n const implicit = decisionPoint(\"ack\", {\n messageId: event.id,\n implicit: true,\n body: event.data,\n });\n if (decide(hooks, implicit, take(\"ack\"), effective) === \"crashed\") status = \"crashed\";\n }\n\n if (await drainBackground(hooks, inv, invocation, queueTarget, background)) status = \"crashed\";\n\n const followUps: EventRef[] = [];\n if (!handled(state.standing)) {\n const next = redelivery(event, maxRetries, spec.bounds);\n if (next) {\n followUps.push(next);\n } else {\n note(hooks, {\n invocation: hooks.bookkeeping(),\n target: queueTarget,\n op: \"dead_letter\",\n args: { messageId: event.id, attempts: event.attempt },\n allowed: [],\n });\n }\n }\n return { status, followUps };\n}\n","/**\n * Cron Trigger delivery: one invocation of the Worker's `scheduled()` handler\n * per tick attempt, with `scheduledTime` the tick's virtual time and `cron`\n * the expression (Workers, Scheduled handler). Cloudflare documents\n * `noRetry()` but no retry count, so the drive declares how many times a\n * tick whose handler failed is re-run; `noRetry()` stops them.\n */\n\nimport {\n type DeliveryResult,\n decisionFaults,\n type EventRef,\n type RunHooks,\n redelivery,\n type ScenarioSpec,\n} from \"@eutaxy/core\";\nimport { note, runInvocation } from \"@eutaxy/engine\";\nimport { drainBackground, executionContext, type RunningWorker } from \"./background.ts\";\nimport type { CronDrive } from \"./scenario.ts\";\n\n/** What a tick event carries: what the controller shows the handler. */\nexport interface TickData {\n readonly cron: string;\n readonly scheduledTime: number;\n}\n\n/** One attempt of a tick: the handler runs, and a failure is re-run as the drive declares unless it said noRetry(). */\nexport async function deliverTick(\n event: EventRef,\n hooks: RunHooks,\n spec: ScenarioSpec,\n drive: CronDrive,\n invocation: string,\n worker: RunningWorker,\n): Promise<DeliveryResult> {\n const tick = event.data as unknown as TickData;\n const target = `Cron:${drive.cron}`;\n const inv = hooks.startInvocation(invocation);\n const background: Promise<unknown>[] = [];\n /** Rejections of waitUntil work: the first one is the invocation's status (Cloudflare, Scheduled handler). */\n const failures: unknown[] = [];\n const handler = worker.handler.scheduled;\n if (!handler) throw new Error(\"the Worker has no scheduled() handler\");\n let noRetry = false;\n const controller: ScheduledController = {\n scheduledTime: tick.scheduledTime,\n cron: tick.cron,\n // A decision the runtime honours, like a queue ack: a crash around it may lose or keep it.\n noRetry: () => {\n hooks.effectSync(\n { invocation, target, op: \"no_retry\", args: { tick: event.id }, allowed: decisionFaults },\n () => {\n noRetry = true;\n return null;\n },\n () => null,\n );\n },\n };\n let status: DeliveryResult[\"status\"] = (\n await runInvocation(hooks, inv, () =>\n handler.call(worker.handler, controller, worker.env, executionContext(background, failures)),\n )\n ).status;\n if (await drainBackground(hooks, inv, invocation, target, background)) status = \"crashed\";\n if (status === \"completed\" && failures.length > 0) status = \"errored\";\n\n const followUps: EventRef[] = [];\n if (status !== \"completed\" && !noRetry) {\n // The re-run is the same tick: same scheduledTime, next attempt.\n const next = redelivery(event, drive.retries, spec.bounds);\n if (next) followUps.push(next);\n else\n note(hooks, {\n invocation: hooks.bookkeeping(),\n target,\n op: \"gave_up\",\n args: { tick: event.id, attempts: event.attempt },\n allowed: [],\n });\n }\n return { status, followUps };\n}\n","/**\n * WebSocket connections as events. The scenario opens a connection with an\n * upgrade request through the Worker's fetch handler, as a client would;\n * the Worker hands it to a Durable Object (the Agents SDK's router does),\n * whose fetch answers 101, and Eutaxy keeps the client end. Each message is\n * then one event delivered inside the object, by calling its\n * `webSocketMessage` handler (the Hibernation API; the Agents SDK uses it)\n * on the server end of that connection, as an alarm is delivered by calling\n * `alarm()`, with the faults an alarm has: `crash_before` (the object\n * crashed before handling it), `crash_after` (handled, then crashed) and\n * `error` (the handler threw). A crash drops the instance, rebuilt within\n * the same delivery since no retry follows a message; the runtime keeps\n * a hibernatable connection, as it does across hibernation, and the next\n * instance sees it under a new `WebSocket` identity with its attachment and\n * tags, so before each message the connection's server end is found again\n * in the live object: by identity, else by attachment and tags (the object\n * must give them to tell its connections apart; otherwise the run is\n * `UNSUPPORTED`). A message is an event of its own, so the scheduler\n * interleaves connections; it waits for its connection to be open and for\n * the message before it on that connection. One the object closed is\n * recorded as not delivered. What the object sends back arrives on the\n * client end; the frames are kept per connection in arrival order and\n * recorded at the end of the run as effects (`WebSocket:<connection>`, op\n * `message`, under the platform's own invocation), since when a frame\n * crosses the pair depends on the event loop, not on the schedule, and a\n * trace must repeat. A close the object makes during the run is recorded\n * too (op `close`). After the run's snapshot the connections still open are\n * torn down outside the run: what the objects' `webSocketClose` handlers\n * do then is not modelled (a request made then makes the run UNSUPPORTED),\n * and the teardown waits until each has returned.\n */\n\nimport {\n canonicalJson,\n type DeliveryResult,\n type EventRef,\n invocationOf,\n type JsonValue,\n type RunHooks,\n readFaults,\n type ScenarioSpec,\n toJson,\n} from \"@eutaxy/core\";\nimport { note, realTick, runInvocation } from \"@eutaxy/engine\";\nimport { drainBackground, executionContext, type RunningWorker } from \"./background.ts\";\nimport { requestOrigin } from \"./http.ts\";\nimport { hostedInObject, hostOf, type ObjectAccess } from \"./object-access.ts\";\nimport type { WebSocketConnectionSpec, WebSocketDrive, WebSocketEventData } from \"./scenario.ts\";\n\n/** The object a connection reached, as the stub proxy saw its 101: the invocation whose stub call it was, and the client end. */\nexport interface UpgradeInfo {\n readonly binding: string;\n readonly id: string;\n readonly object: string;\n readonly invocation: string;\n readonly client: WebSocket;\n}\n\n/**\n * Drop a client end nobody will use, so the object sees the connection close\n * (as it does when a Worker dies holding one). An end must be accepted before\n * it can be closed; one left unaccepted stays in the object for ever and\n * keeps its instance from being evicted.\n */\nfunction dropEnd(ws: WebSocket, reason: string): void {\n try {\n ws.accept();\n } catch {\n // accepted already\n }\n try {\n ws.close(1011, reason);\n } catch {\n // closed already\n }\n}\n\n/** How the object closed a connection (its handler called `close`), as the client end saw it. */\nexport interface Closed {\n readonly code: number;\n readonly reason: string;\n}\n\ninterface Connection {\n readonly spec: WebSocketConnectionSpec;\n readonly client: WebSocket;\n /** The server end as the object last saw it; a dropped instance leaves a new identity behind. None when the object closed the connection before answering the upgrade. */\n server: WebSocket | undefined;\n /** The tags and the attachment the object gave the server end, as last seen; both survive the instance. */\n identity: Identity;\n readonly upgrade: UpgradeInfo;\n closed: Closed | undefined;\n}\n\n/** A promise settled from outside, for one connection's open and for each message's turn. */\nclass Gate {\n readonly promise: Promise<void>;\n resolve: () => void = () => {};\n constructor() {\n this.promise = new Promise((r) => {\n this.resolve = r;\n });\n }\n}\n\n/** What identifies a server end across instances: its tags (fixed at accept) and its attachment (the object may change it). */\ninterface Identity {\n readonly tags: string;\n readonly attachment: string;\n}\n\nfunction identityOf(ws: WebSocket, live: DurableObjectState): Identity {\n let attachment: JsonValue;\n try {\n attachment = toJson(ws.deserializeAttachment());\n } catch {\n attachment = \"<unreadable>\";\n }\n let tags: string[] = [];\n try {\n tags = live.getTags(ws);\n } catch {\n // not accepted with the Hibernation API: no tags\n }\n return { tags: canonicalJson(tags), attachment: canonicalJson(attachment) };\n}\n\n/** Turns of the event loop the teardown waits for the objects to let their connections go. */\nconst closeTurns = 20;\n\n/**\n * Turns of the event loop the teardown waits for an object's `webSocketClose` to have returned\n * from the close of each socket the object held. A close is on its way once sent, and when the\n * handler runs is the event loop's doing: on a loaded machine it runs after the next run began,\n * and writes into that run's storage. So the wait is for the handler, by its return, and this is\n * only its bound.\n */\nexport const closeHandlerTurns = 500;\n\n/** What a watched instance's `webSocketClose` has done: the sockets it returned from, and the calls still running. */\nexport interface CloseWatch {\n readonly handled: WeakSet<object>;\n running: number;\n}\n\nconst closeWatches = new WeakMap<object, CloseWatch>();\n\n/**\n * Have this instance's `webSocketClose` tell which socket's close it has returned from. On the\n * instance, not its class: a framework gives each instance a handler of its own (the Agents SDK\n * does), and the instance entered just before the closes are sent is the one they reach. The\n * wrapper only keeps track. `\"none\"` when the object has no such handler: the runtime then ends\n * the connection itself, and there is nothing of the object's to wait for. `\"unwatchable\"` when\n * it has one and the instance does not take the wrapper (it is frozen, or the handler is its own\n * and fixed): when that handler has finished cannot be known.\n */\nexport function watchCloses(instance: unknown): CloseWatch | \"none\" | \"unwatchable\" {\n if (instance === null || typeof instance !== \"object\") return \"none\";\n const known = closeWatches.get(instance);\n if (known) return known;\n const original = (instance as { webSocketClose?: unknown }).webSocketClose;\n if (typeof original !== \"function\") return \"none\";\n const watch: CloseWatch = { handled: new WeakSet(), running: 0 };\n try {\n Object.defineProperty(instance, \"webSocketClose\", {\n configurable: true,\n writable: true,\n value: async function (this: unknown, ...args: unknown[]): Promise<unknown> {\n watch.running++;\n try {\n return await (original as (...a: unknown[]) => unknown).apply(this, args);\n } finally {\n watch.running--;\n const ws = args[0];\n if (typeof ws === \"object\" && ws !== null) watch.handled.add(ws);\n }\n },\n });\n } catch {\n return \"unwatchable\";\n }\n closeWatches.set(instance, watch);\n return watch;\n}\n\n/**\n * Wait for something known to be on its way, a turn of the event loop at a time, until it has\n * arrived or `turns` turns have passed. Whether it arrived. Not a fixed number of turns: how long\n * a frame or a close takes to cross is the machine's load, not the schedule.\n */\nexport async function untilArrived(\n arrived: () => boolean,\n turns: number,\n tick: () => Promise<void> = realTick,\n): Promise<boolean> {\n for (let turn = 0; !arrived(); turn++) {\n if (turn >= turns) return false;\n await tick();\n }\n return true;\n}\n\n/** The run's connections; the platform clears it before each run, closing what is still open. */\nexport class Connections {\n readonly open = new Map<string, Connection>();\n /** Per connection: settled once its open was delivered, whatever came of it. */\n readonly opened = new Map<string, Gate>();\n /** Per connection and message index: settled once that message was delivered. */\n readonly delivered = new Map<string, Gate>();\n /** The frames each connection received this run, in arrival order, until the end of the run records them. */\n readonly frames = new Map<string, JsonValue[]>();\n /** Every 101 a stub fetch answered this run, as the proxy saw it; an open claims its own, the rest are dropped. */\n readonly upgrades: { readonly info: UpgradeInfo; claimed: boolean }[] = [];\n\n gate(map: Map<string, Gate>, key: string): Gate {\n let g = map.get(key);\n if (!g) {\n g = new Gate();\n map.set(key, g);\n }\n return g;\n }\n\n /** Resolves once the connection's open was delivered (it may have failed: `open` then lacks it). */\n openedOf(connection: string): Promise<void> {\n return this.gate(this.opened, connection).promise;\n }\n\n /** Resolves once message `index` of the connection was delivered; index -1 is at once. */\n deliveredOf(connection: string, index: number): Promise<void> {\n return index < 0\n ? Promise.resolve()\n : this.gate(this.delivered, `${connection}:${index}`).promise;\n }\n\n /** Closes that reached a client end before its connection was registered: the object closed it while answering the upgrade. */\n readonly earlyClosed = new Map<string, Closed>();\n /** Counts the runs, so what a client end of an earlier run reports after its teardown is ignored. */\n generation = 0;\n\n received(generation: number, connection: string, data: JsonValue): void {\n if (generation !== this.generation) return;\n const list = this.frames.get(connection);\n if (list) list.push(data);\n else this.frames.set(connection, [data]);\n }\n\n /** The client end saw a close during the run: the object closed the connection. */\n closedBy(generation: number, connection: string, code: number, reason: string): void {\n if (generation !== this.generation) return;\n const c = this.open.get(connection);\n if (c) {\n if (!c.closed) c.closed = { code, reason };\n } else if (!this.earlyClosed.has(connection))\n this.earlyClosed.set(connection, { code, reason });\n }\n\n upgradedTo(info: UpgradeInfo): void {\n this.upgrades.push({ info, claimed: false });\n }\n\n /** The object this open reached: a stub fetch of its own invocation answered 101 during it. Claimed once. */\n upgraded(invocation: string): UpgradeInfo | undefined {\n const u = this.upgrades.find((x) => !x.claimed && x.info.invocation === invocation);\n if (u) u.claimed = true;\n return u?.info;\n }\n\n /** Drop the client ends no open claimed: an open that crashed after the object accepted, or an upgrade made elsewhere. */\n dropUnclaimed(reason: string): boolean {\n let dropped = false;\n for (const u of this.upgrades) {\n if (u.claimed) continue;\n u.claimed = true;\n dropEnd(u.info.client, reason);\n dropped = true;\n }\n return dropped;\n }\n\n /**\n * Inside an object: bind its open connections to the sockets it holds now.\n * A connection whose server end is still there keeps it; one whose instance\n * was dropped since finds it again by its tags, or by tags and attachment\n * when the tags alone do not single it out. What comes back:\n * the sockets no connection holds (a new one during an open), and the\n * connections that could not be told apart.\n */\n rebind(\n upgrade: Pick<UpgradeInfo, \"binding\" | \"id\">,\n live: DurableObjectState,\n ): { readonly unbound: readonly WebSocket[]; readonly lost: readonly Connection[] } {\n const free = new Set(live.getWebSockets());\n const stale: Connection[] = [];\n for (const c of this.open.values()) {\n if (c.upgrade.binding !== upgrade.binding || c.upgrade.id !== upgrade.id || c.closed)\n continue;\n if (c.server && free.has(c.server)) {\n free.delete(c.server);\n // The object may have rewritten the attachment since: what identifies the end is what it holds now.\n c.identity = identityOf(c.server, live);\n } else stale.push(c);\n }\n const lost: Connection[] = [];\n const identities = new Map([...free].map((ws) => [ws, identityOf(ws, live)] as const));\n const single = (ok: (i: Identity) => boolean): WebSocket | undefined => {\n const matches = [...free].filter((ws) => ok(identities.get(ws) as Identity));\n return matches.length === 1 ? matches[0] : undefined;\n };\n for (const c of stale) {\n const ws =\n single((i) => i.tags === c.identity.tags) ??\n single((i) => i.tags === c.identity.tags && i.attachment === c.identity.attachment);\n if (ws) {\n c.server = ws;\n free.delete(ws);\n } else lost.push(c);\n }\n return { unbound: [...free], lost };\n }\n\n /**\n * After the run's snapshot: close what is still open and wait until each\n * object has let its connections go, so nothing survives into the next run\n * (a hibernatable socket outlives eviction and `deleteAll`). The objects'\n * `webSocketClose` handlers run meanwhile, outside the run: nothing they\n * do is observed, and each is waited for until it has returned. Returns\n * why, when a handler has not returned or an object still holds a socket.\n */\n async teardown(objects: ObjectAccess): Promise<string | undefined> {\n // Every object a connection of this run reached: one the object closed itself is among them,\n // since the close that answers it is handled by the object too.\n const reached = new Map<string, UpgradeInfo>();\n for (const u of this.upgrades)\n if (!u.claimed) reached.set(`${u.info.binding}/${u.info.id}`, u.info);\n for (const c of this.open.values())\n reached.set(`${c.upgrade.binding}/${c.upgrade.id}`, c.upgrade);\n // Before any close is sent, the handler of each is watched, and the sockets it holds are\n // noted: each of them is closed by the end of this, and its close handled by that handler.\n // Entered in every run: the instance is another one after an eviction. A call of the handler\n // that began before this is not seen: only one that begins from here on counts as running.\n const waits: { upgrade: UpgradeInfo; watch: CloseWatch; held: readonly object[] }[] = [];\n let unwatchable: string | undefined;\n for (const u of reached.values()) {\n const found = await objects.run(u.binding, u.id, u.object, async (instance, live) => ({\n watch: watchCloses(instance),\n held: live.getWebSockets() as readonly object[],\n }));\n if (found === undefined || found.watch === \"none\") continue;\n if (found.watch === \"unwatchable\")\n unwatchable ??= `the webSocketClose handler of ${u.object} cannot be watched (the object is frozen, or the handler is a fixed property of it); when it has finished after the run closed its connections is not known`;\n else waits.push({ upgrade: u, watch: found.watch, held: found.held });\n }\n this.dropUnclaimed(\"the Worker died holding this connection\");\n for (const c of this.open.values()) {\n if (c.closed) continue;\n try {\n c.client.close(1000, \"run over\");\n } catch {\n // the other side closed first; its close reaches the client end on its way\n }\n }\n // Told once the connections are closed: nothing of this run stays open either way.\n if (unwatchable !== undefined) return unwatchable;\n for (const { upgrade: u, watch, held } of waits) {\n const returned = (): boolean =>\n watch.running === 0 && held.every((ws) => watch.handled.has(ws));\n if (!(await untilArrived(returned, closeHandlerTurns)))\n return `the webSocketClose handler of ${u.object} had not finished ${closeHandlerTurns} turns of the event loop after the run closed its connections; what it does later would land in another run`;\n }\n for (const u of reached.values()) {\n let left = 0;\n for (let turn = 0; turn < closeTurns; turn++) {\n left =\n (await objects.run(\n u.binding,\n u.id,\n u.object,\n async (_i, live) => live.getWebSockets().length,\n )) ?? 0;\n if (left === 0) break;\n await realTick();\n }\n if (left !== 0)\n return `WebSocket connections of ${u.object} were still open ${closeTurns} turns of the event loop after the run closed them`;\n }\n return undefined;\n }\n\n /** Record every connection's frames (connection order, then arrival order) and the close the object made, if any; forget the frames. */\n record(hooks: RunHooks): void {\n const bookkeeping = () => hooks.bookkeeping();\n for (const [connection, c] of this.open) {\n for (const data of this.frames.get(connection) ?? [])\n note(hooks, {\n invocation: bookkeeping(),\n target: `WebSocket:${connection}`,\n op: \"message\",\n args: { connection, data },\n allowed: [],\n });\n if (c.closed)\n note(hooks, {\n invocation: bookkeeping(),\n target: `WebSocket:${connection}`,\n op: \"close\",\n args: { connection, code: c.closed.code, reason: c.closed.reason },\n allowed: [],\n });\n }\n this.frames.clear();\n }\n\n /** Before a run: close what the last run left open (it ended early), and let the closes cross before the objects are evicted. */\n async clear(): Promise<void> {\n this.generation++;\n let closing = this.dropUnclaimed(\"run over\");\n for (const c of this.open.values()) {\n if (c.closed) continue;\n closing = true;\n try {\n c.client.close(1000, \"run over\");\n } catch {\n // already closed by the other side\n }\n }\n this.open.clear();\n this.frames.clear();\n this.earlyClosed.clear();\n this.opened.clear();\n this.delivered.clear();\n this.upgrades.length = 0;\n if (closing) await settleFrames();\n }\n}\n\n/** The upgrade request a connection opens with. */\nexport function upgradeRequest(c: WebSocketConnectionSpec): Request {\n const headers = new Headers(c.headers);\n headers.set(\"Upgrade\", \"websocket\");\n headers.set(\"Connection\", \"Upgrade\");\n return new Request(`${requestOrigin}${c.path}`, { headers });\n}\n\n/** A frame's data as recorded: JSON where it parses, the text otherwise. */\nexport function frameData(data: unknown): JsonValue {\n const text = typeof data === \"string\" ? data : \"<binary>\";\n try {\n return JSON.parse(text) as JsonValue;\n } catch {\n return text;\n }\n}\n\n/** The text a message is sent as: a string as is, any other JSON value as its JSON. */\nexport function frameText(data: JsonValue): string {\n return typeof data === \"string\" ? data : JSON.stringify(data);\n}\n\n/** Two turns of the real event loop: what a frame, or a close, needs to cross from one end of the pair to the other. */\nasync function settleFrames(): Promise<void> {\n await realTick();\n await realTick();\n}\n\nexport interface WebSocketDeps {\n readonly worker: RunningWorker;\n readonly connections: Connections;\n readonly objects: ObjectAccess;\n}\n\nexport async function deliverWebSocket(\n event: EventRef,\n hooks: RunHooks,\n _spec: ScenarioSpec,\n drive: WebSocketDrive,\n deps: WebSocketDeps,\n): Promise<DeliveryResult> {\n const data = event.data as unknown as WebSocketEventData;\n const c = drive.connections.find((x) => x.id === data.connection);\n if (!c) throw new Error(`websocket drive has no connection ${data.connection}`);\n switch (data.kind) {\n case \"open\":\n try {\n return await openConnection(event, hooks, drive, c, deps);\n } finally {\n deps.connections.gate(deps.connections.opened, c.id).resolve();\n }\n case \"message\":\n try {\n return await deliverMessage(event, hooks, c, data, deps);\n } finally {\n deps.connections.gate(deps.connections.delivered, `${c.id}:${data.index}`).resolve();\n }\n }\n}\n\n/** What an open finds in the object: this connection's server end, or why there is none. */\ntype Found =\n | { readonly server: WebSocket; readonly identity: Identity }\n | { readonly unbound: readonly WebSocket[]; readonly lost: readonly Connection[] };\n\nasync function openConnection(\n event: EventRef,\n hooks: RunHooks,\n drive: WebSocketDrive,\n c: WebSocketConnectionSpec,\n deps: WebSocketDeps,\n): Promise<DeliveryResult> {\n const invocation = invocationOf(event);\n const inv = hooks.startInvocation(invocation);\n const target = `WebSocket:${c.id}`;\n const background: Promise<unknown>[] = [];\n const handler = deps.worker.handler.fetch;\n if (!handler) throw new Error(\"the Worker has no fetch() handler\");\n const position = drive.connections.findIndex((x) => x.id === c.id);\n const previous = drive.connections[position - 1];\n // Opens run one at a time, in order, so the socket an object accepts during this one is this\n // connection's; the wait is this invocation's, which the scheduler can see and abandon. Messages are\n // not held back this way.\n const handled = await runInvocation(hooks, inv, async () => {\n if (previous) await deps.connections.openedOf(previous.id);\n return handler.call(\n deps.worker.handler,\n upgradeRequest(c),\n deps.worker.env,\n executionContext(background),\n );\n });\n let status: DeliveryResult[\"status\"] = handled.status;\n const response = handled.status === \"completed\" ? handled.value : undefined;\n const args: JsonValue = { connection: c.id, path: c.path };\n if (status === \"completed\" && response) {\n const r = response;\n // The open as one effect: the answer, and, on a 101, the client end accepted and the server end\n // found in the object. The waits inside are I/O of this invocation, which the scheduler sees.\n const opened = await runInvocation(hooks, inv, () =>\n hooks.effect(\n { invocation, target, op: \"open\", args, allowed: [], hostsEffects: true },\n async () => {\n const summary = { status: r.status, ok: r.status === 101 };\n if (r.status !== 101 || !r.webSocket) return summary;\n const client = r.webSocket;\n const upgrade = deps.connections.upgraded(invocation);\n if (!upgrade) {\n hooks.unsupported(\n `WebSocket ${c.id}: the Worker answered the upgrade itself; only connections a Durable Object accepts are modelled`,\n );\n dropEnd(client, \"not modelled\");\n return summary;\n }\n // Kept, not recorded: when a frame crosses the pair is the event loop's doing, so the end of\n // the run records them in arrival order. A close the object makes is kept the same way.\n const generation = deps.connections.generation;\n client.addEventListener(\"message\", (ev: MessageEvent) => {\n deps.connections.received(generation, c.id, frameData(ev.data));\n });\n client.addEventListener(\"close\", (ev: CloseEvent) => {\n deps.connections.closedBy(generation, c.id, ev.code, ev.reason);\n });\n client.accept();\n await settleFrames();\n // Closed by the object while it answered the upgrade: open and closed at once, nothing to send on.\n const early = deps.connections.earlyClosed.get(c.id);\n if (early) {\n deps.connections.open.set(c.id, {\n spec: c,\n client,\n server: undefined,\n identity: { tags: \"[]\", attachment: \"null\" },\n upgrade,\n closed: early,\n });\n return summary;\n }\n // The server end: the one socket the object holds that no connection does.\n const found = await deps.objects.run(\n upgrade.binding,\n upgrade.id,\n upgrade.object,\n async (_i, live): Promise<Found> => {\n const { unbound, lost } = deps.connections.rebind(upgrade, live);\n const server = unbound[0];\n if (lost.length > 0 || unbound.length !== 1 || !server) return { unbound, lost };\n return { server, identity: identityOf(server, live) };\n },\n );\n if (!found || !(\"server\" in found)) {\n // Accepted above: closing it from here reaches the object.\n client.close(1011, \"not modelled\");\n const lost = found?.lost ?? [];\n const n = found?.unbound.length ?? 0;\n hooks.unsupported(\n lost.length > 0\n ? `WebSocket ${c.id}: the connections ${lost.map((l) => l.spec.id).join(\", \")} of ${upgrade.object} cannot be told apart after its instance was dropped; give each socket an attachment or a tag`\n : `WebSocket ${c.id}: ${n === 0 ? \"the object accepted no WebSocket with the Hibernation API (ctx.acceptWebSocket); the standard API is not modelled\" : `${n} sockets were accepted by ${upgrade.object} during this open, so this connection's cannot be told apart`}`,\n );\n return summary;\n }\n deps.connections.open.set(c.id, {\n spec: c,\n client,\n server: found.server,\n identity: found.identity,\n upgrade,\n closed: undefined,\n });\n return summary;\n },\n (v) => v,\n ),\n );\n if (opened.status !== \"completed\") status = opened.status;\n } else {\n // The Worker did not answer: an object it reached meanwhile sees its connection close, as when a\n // Worker dies holding one. An uncaught exception is answered with a 500; so is the connection's open.\n const upgrade = deps.connections.upgraded(invocation);\n // The runtime hands the object the close before any later call reaches it (events enter an\n // object in arrival order), so the snapshot sees what webSocketClose wrote.\n if (upgrade) dropEnd(upgrade.client, \"the Worker died during the upgrade\");\n if (status === \"errored\")\n hooks.effectSync(\n { invocation, target, op: \"open\", args, allowed: [] },\n () => ({ status: 500, ok: false }),\n (v) => v,\n );\n }\n if (await drainBackground(hooks, inv, invocation, target, background)) status = \"crashed\";\n return { status, followUps: [] };\n}\n\nasync function deliverMessage(\n event: EventRef,\n hooks: RunHooks,\n c: WebSocketConnectionSpec,\n data: Extract<WebSocketEventData, { kind: \"message\" }>,\n deps: WebSocketDeps,\n): Promise<DeliveryResult> {\n const invocation = invocationOf(event);\n const inv = hooks.startInvocation(invocation);\n const target = `WebSocket:${c.id}`;\n // Its connection must be open and the message before it handled. Waited for as a run of this\n // invocation, which the scheduler can see and abandon; the effect then starts in a run of its own,\n // so this invocation is the one running when the object's handler makes its effects.\n const waited = await runInvocation(hooks, inv, async () => {\n await Promise.all([\n deps.connections.openedOf(c.id),\n deps.connections.deliveredOf(c.id, data.index - 1),\n ]);\n return null;\n });\n if (waited.status !== \"completed\") return { status: waited.status, followUps: [] };\n const conn = deps.connections.open.get(c.id);\n const args: JsonValue = {\n connection: c.id,\n object: conn?.upgrade.object ?? null,\n message: data.message,\n data: data.data,\n };\n // Nothing to send on: the open failed or was refused, or the object closed the connection since.\n const server = conn?.server;\n if (!conn || conn.closed || !server) {\n hooks.effectSync(\n { invocation, target, op: \"send\", args, allowed: [] },\n () => ({ delivered: false }),\n (v) => v,\n );\n return { status: \"completed\", followUps: [] };\n }\n const { binding, id, object } = conn.upgrade;\n // A crash is the object's: its in-memory state goes with the instance; the connection stays.\n const status = await hostedInObject(\n hooks,\n inv,\n deps.objects,\n binding,\n id,\n object,\n { invocation, target, op: \"send\", args, allowed: readFaults },\n async () => {\n await deps.objects.run(binding, id, object, async (instance, live) => {\n // A dropped instance left the connection's server end under a new identity: find it again.\n const { lost } = deps.connections.rebind(conn.upgrade, live);\n if (lost.includes(conn)) {\n hooks.unsupported(\n `WebSocket ${c.id}: the connections ${lost.map((l) => l.spec.id).join(\", \")} of ${object} cannot be told apart after its instance was dropped; give each socket an attachment or a tag`,\n );\n return;\n }\n // The runtime would answer these without waking the object; delivering to the handler would not.\n if (live.getWebSocketAutoResponse()) {\n hooks.unsupported(\n `Durable Object ${binding} ${object} uses setWebSocketAutoResponse, which is not modelled`,\n );\n return;\n }\n const handler = (instance as { webSocketMessage?: unknown }).webSocketMessage;\n if (typeof handler !== \"function\") {\n hooks.unsupported(\n `Durable Object ${binding} ${object} has no webSocketMessage handler; only the Hibernation API is modelled`,\n );\n return;\n }\n const end = conn.server ?? server;\n await hooks.hostedCode(hostOf(`DO:${binding}`, object), () =>\n (handler as (ws: WebSocket, m: string) => Promise<unknown>).call(\n instance,\n end,\n frameText(data.data),\n ),\n );\n // The handler may have rewritten the attachment: keep what identifies the end current.\n conn.identity = identityOf(end, live);\n });\n // The frames the object sent back, or its close, cross to the client end now.\n await settleFrames();\n return { delivered: true };\n },\n (v) => v,\n );\n // No retry follows a message, so the instance is rebuilt here, within the run, where its\n // constructor is observed (an alarm's retry does that for an alarm); an object rebuilt only for\n // the snapshot would make the run UNSUPPORTED.\n if (status === \"crashed\") {\n // An effect of a run of its own (the crashed invocation is over), so the scheduler sees the\n // wait and the constructor's effects have an invocation.\n const rebuild = hooks.startInvocation(`${invocation}/rebuild`);\n await runInvocation(hooks, rebuild, () =>\n hooks.effect(\n {\n invocation: rebuild.id,\n target,\n op: \"rebuild\",\n args: { connection: c.id, object },\n allowed: [],\n hostsEffects: true,\n },\n async () => {\n await deps.objects.run(binding, id, object, async () => undefined);\n return null;\n },\n () => null,\n ),\n );\n }\n return { status, followUps: [] };\n}\n","/**\n * The Cloudflare platform: delivers queue messages to the Worker's `queue()`\n * handler and inbound requests to its `fetch()` handler, with proxied\n * bindings, and applies Queues' at-least-once semantics (explicit and\n * implicit ack, retry, redelivery up to max_retries, dead-lettering) as\n * documented by Cloudflare, and for requests the caller's retry policy\n * declared in the drive.\n */\n\nimport {\n type DeliveryResult,\n type EventRef,\n invocationOf,\n type JsonValue,\n jsonEqual,\n type Platform,\n type RunHooks,\n type ScenarioSpec,\n} from \"@eutaxy/core\";\nimport { withoutNetwork } from \"@eutaxy/engine\";\nimport type { RunningWorker } from \"./background.ts\";\nimport {\n type Binding,\n calleeBinding,\n d1Binding,\n durableObjectBinding,\n ownedSetups,\n r2Binding,\n scriptedObjectBinding,\n serviceBinding,\n workflowBinding,\n} from \"./bindings.ts\";\nimport type { CalleeModule } from \"./callees.ts\";\nimport {\n type DurableObjectTestHelpers,\n isPlainData,\n scriptsOutsideRuns,\n simulateConstruction,\n simulatingConstruction,\n} from \"./durable-objects.ts\";\nimport { entrypointHandler } from \"./entrypoint.ts\";\nimport { deliverRequest } from \"./http.ts\";\nimport { type ProxyContext, refuse } from \"./proxy-context.ts\";\nimport { deliverMessage } from \"./queues.ts\";\nimport { deliverCall, entrypointClass } from \"./rpc.ts\";\nimport {\n type Drive,\n driveEvents,\n restrictDrive,\n type ScriptedObjectSetup,\n type ServiceSetup,\n} from \"./scenario.ts\";\nimport { deliverTick } from \"./scheduled.ts\";\nimport { Connections, deliverWebSocket } from \"./websocket.ts\";\nimport type { WorkerHandler } from \"./worker.ts\";\n\n/** A `WorkerEntrypoint` subclass: the Worker's default export when it exposes RPC methods. Its env is its own. */\nexport type WorkerEntrypointClass = abstract new (ctx: ExecutionContext, env: never) => object;\n\n/**\n * What `createCloudflarePlatform` needs: the env and the Worker's default export, the schema per D1\n * binding, and for the bindings that need them the test helpers, the module's exports, the callees and\n * the aliases.\n */\nexport interface CloudflarePlatformOptions {\n /** The bindings from `cloudflare:workers`. */\n readonly env: object;\n /**\n * The Worker's default export: the handler object, or a\n * `WorkerEntrypoint` class, whose `fetch()`, `queue()` and `scheduled()`\n * are its handlers and whose other methods the `rpc` drive calls.\n */\n readonly handler: WorkerHandler | WorkerEntrypointClass;\n /** Schema SQL per D1 binding named in the scenario's setup. */\n readonly schemas: Readonly<Record<string, string>>;\n /** The consumer's max_retries, a whole number that is not negative; Cloudflare's default, 3, when it sets none. */\n readonly maxRetries?: number;\n /**\n * The Cloudflare Vitest plugin's test helpers (`import * as helpers from\n * \"cloudflare:test\"`), needed for Durable Object bindings: Eutaxy resets,\n * seeds and snapshots the real objects through them.\n */\n readonly durableObjects?: DurableObjectTestHelpers;\n /**\n * The Worker module's exports (`import * as worker from \"./worker.ts\"`),\n * where the classes `workflow` setup steps name are found.\n */\n readonly exports?: Readonly<Record<string, unknown>>;\n /**\n * The Workers behind service bindings that `callee` setup steps name, by\n * binding: each one's name from its wrangler config, which qualifies its\n * bindings in `env` (`orders/DB`), and its module's exports.\n */\n readonly callees?: Readonly<Record<string, CalleeModule>>;\n /**\n * Bindings that name a resource another binding already names (the same\n * database, the same Durable Object namespace), by their qualified name\n * (`inventory/DB`) to the name the resource is set up and snapshotted\n * under (`DB`): one resource, one snapshot, the alias a second name for it\n * in `env`. A setup step on an alias is refused.\n */\n readonly aliases?: Readonly<Record<string, string>>;\n}\n\n/**\n * Whether an env value is a binding and not a var: something with methods.\n * A JSON var is plain data, whose only methods are `Object.prototype`'s or\n * an array's, so those do not count; a test double written as an object\n * literal counts by the functions it holds itself.\n */\nfunction isBindingLike(value: unknown): boolean {\n if (typeof value === \"function\") return true;\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return false;\n const proto = Object.getPrototypeOf(value) as object | null;\n const inherited = proto === null || proto === Object.prototype ? {} : proto;\n const names = [...Object.getOwnPropertyNames(value), ...Object.getOwnPropertyNames(inherited)];\n return names.some(\n (k) => k !== \"constructor\" && typeof (value as Record<string, unknown>)[k] === \"function\",\n );\n}\n\nconst assumptions: readonly string[] = [\n \"platform model: Cloudflare Queues at-least-once delivery; the first ack or retry decision per message wins; unacked messages are redelivered up to max_retries then dead-lettered\",\n \"D1 statements run against Miniflare's SQLite; each run/first/all/raw/batch/exec is one effect; SQL that reads the time or draws randomness itself (CURRENT_TIMESTAMP, strftime('now'), random()) reads SQLite's own clock and generator, not the virtual ones, so a value it stores differs from run to run\",\n \"message.timestamp is the virtual clock's time at delivery\",\n \"only D1, Durable Object, R2, Workflow and scripted service bindings are proxied; a call on any other binding, from the Worker or from a Durable Object through this.env, makes the run UNSUPPORTED (reading one off env does not)\",\n \"service bindings are scripted callees unless the scenario names a callee for them: the Worker behind a scripted binding is never called; each RPC method call or fetch() through it is one effect answered from the scenario's service() setup, where crash_before and error mean the call never reached the callee, ambiguous that it acted and the answer was lost, and crash_after that the caller died after it (developers.cloudflare.com/workers/runtime-apis/bindings/service-bindings/); Cloudflare does not retry such a call\",\n \"a Durable Object namespace with a scriptedObject() setup is scripted: none of its objects is run (one found running at the end of a run makes it UNSUPPORTED); each RPC method call or fetch() on a stub of it, from the Worker or from another object, is one effect on DO:<binding> answered from the script, the same reply whatever was called before, with the faults of a stub call (crash_before and error: it never reached the object; ambiguous: the object acted and the answer was lost; crash_after: the caller died after it) (developers.cloudflare.com/durable-objects/best-practices/create-durable-object-stubs-and-send-requests/)\",\n \"a callee that is the scenario's own Worker, called back by a Worker it called, runs with the scenario's env under its own names; a binding named as an alias of another (the same database, the same Durable Object namespace, in two Workers' configs) is that binding: its effects and snapshot carry the other's name, and a callee's Workflow runs the callee's class with the callee's env\",\n \"a service binding with a callee() setup runs that Worker's real code in the caller's simulation, in the same isolate, as Cloudflare runs both Workers on one thread (developers.cloudflare.com/workers/runtime-apis/bindings/service-bindings/): each RPC method call or fetch() through it is one effect hosting the callee's invocation (<caller invocation>/<binding>.<method>), which constructs the entrypoint anew with a fresh ExecutionContext and the callee's env (its bindings under <worker name>/<binding>) and answers with the return value, plain data by copy, or the Response as it is; what the callee throws reaches the caller as a new error with its name, message and serializable own properties, a built-in class as itself (developers.cloudflare.com/workers/runtime-apis/rpc/error-handling/); the callee's waitUntil work finishes before its answer crosses; crash_before means the call never reached the callee, ambiguous that it acted and the answer was lost, crash_after that the caller died after it, and a fault that crashes the callee ends its invocation and throws an Error to the caller; Cloudflare retries nothing\",\n \"R2 buckets are Miniflare's real ones, emptied and seeded before each run and snapshotted after it; R2 is strongly consistent and the last writer wins (developers.cloudflare.com/r2/reference/consistency/); each put, delete, get, head and list is one effect, a body is read inside its get, and an object's version and upload time are stand-ins so traces repeat; multipart uploads and conditions on the upload time are not modelled\",\n \"Durable Objects are the real objects workerd runs (storage, transactions, input and output gates are the runtime's own); each stub call is one effect: crash_before or error means it never reached the object, ambiguous means the object committed and the caller lost the answer, crash_after means the caller died after it; in a concurrent run an object's own outbound I/O during a call is a turn, so another event may enter the object meanwhile (its input gate is open then), except while it holds the gate with blockConcurrencyWhile, when its effects run at once; work an object starts and does not await (a promise left running, a timer, ctx.waitUntil) goes on after its answer as the object's own invocation, DO:<binding>/<object>/after, whose effects are turns of their own and take faults by their position in it, until nothing of it can move or a crash resets the object, which ends it with the instance (work that keeps setting timers is waited for up to 100 firings without settling, then the run is UNSUPPORTED); an object that awaits a timer of its own before answering is woken by it; an effect it issued before its answer and did not await, a timer it set and real work it started (Web Crypto) are its own once the call has answered: the caller's crash does not end them and a fault in them resets the object, not the caller; in a sequential run that work runs to rest before the next event (developers.cloudflare.com/durable-objects/concepts/durable-object-lifecycle/); storage operations are not turns (the input gate holds other events during them); a call the object makes through a service binding on this.env is the scenario's: an effect of the invocation its code runs as (the call it serves, or its own work after the answer), answered from the service() script or by the callee() hosted inside it, and leaving the object once its earlier writes are durable, as behind the output gate (developers.cloudflare.com/durable-objects/api/state/, /durable-objects/concepts/durable-object-lifecycle/); a statement it runs on a D1 database or an operation on an R2 bucket through this.env is an effect of that invocation too, performed on the real store behind the same gate, and so is a call on a Workflow binding or on an instance it gave, answered by the model of the engine; a call into another object (or itself) through this.env is the stub call it is from the Worker, hosting what the called object does: a crash inside the called object ends the invocation and resets every object the call went through, and an object reset while a call it made is in flight takes what awaited the call with it, the called object going on by itself if its code had started; a call's plain result reaches its caller as a copy; a callback behind blockConcurrencyWhile that fails resets the object, as the runtime does (developers.cloudflare.com/durable-objects/api/state/#blockconcurrencywhile); objects are cleared, seeded and evicted before each run and their storage is snapshotted after it, an object a crash reset and nothing entered since being woken once inside the run first (a wake effect, its constructor's effects hosted), as its next event would wake it (developers.cloudflare.com/durable-objects/api/storage-api/)\",\n \"Durable Object alarms are taken over so none is scheduled on the real clock and fire in virtual time: one alarm per object, a later setAlarm replaces it, setAlarm in a transaction applies on commit, the alarm survives eviction, alarm() is one effect (crash_before: it never ran; crash_after: it ran and counts as failed; error: it threw), and a failed alarm is retried after 2 s, 4 s, 8 s ... up to six retries and maxRedeliveries, with retryCount and isRetry (developers.cloudflare.com/durable-objects/api/base/#alarm); each object's alarm fires at most alarmsPerObject times per run (default 3)\",\n \"Workflows are a model of the engine, never the local one, running the scenario's own class: create is one effect that queues the instance; each step.do attempt is two effect points around its callback, which runs as the instance's own code (step, crash_before: the engine restarts before it; step_result, crash_after: it ran and committed but its result was not persisted, so it runs again; ambiguous at step: the attempt outlives its timeout from its start; ambiguous at step_result: it ran but counted as failed just after its work, as a timeout does); a failed attempt is retried after its delay in virtual time (defaults 5 retries, 10 s, exponential, merged field by field with a step's config), up to its limit and maxRedeliveries, except a NonRetryableError; a restart re-runs run() from the start with the persisted step and sleep results, so code outside steps repeats; a step's timeout is measured in virtual time (default 10 minutes), and an attempt that passes it is not stopped, as the engine cannot stop it either: it runs on as the late attempt while the step is retried or fails for good, its result dropped, and in a concurrent run its remaining effects land before, between or after the retry's or the recovery's (a sequential run lets it run first) (developers.cloudflare.com/workflows/build/rules-of-workflows/, /workflows/build/sleeping-and-retrying/)\",\n \"state invariants read a snapshot of every D1 binding named in setup, taken after the last event\",\n \"work passed to ctx.waitUntil runs after the handler returns and never affects acknowledgement or the response; a cut_off fault at that point loses work not yet started, and an effect in flight commits without its continuation\",\n \"concurrent invocations (maxConcurrentInvocations above 1) share one isolate's module state and bindings, and another may run while one awaits I/O (developers.cloudflare.com/workers/reference/how-workers-works/); queue consumers run concurrently up to max_concurrency (developers.cloudflare.com/queues/configuration/consumer-concurrency/)\",\n \"inbound requests: one invocation per attempt; an uncaught exception is a 500 response; the drive's caller resends a request it got no acceptable response for (crash before the response, an answer after its deadlineMs, or a status its retryOn policy rejects) up to its retries, each resend after its delaysMs entry of virtual time; the handler's own time is virtual, so a late answer is the ambiguous fault at the response point or an answer later than deadlineMs in virtual time\",\n \"cron triggers: each tick of the drive's expression is one invocation of scheduled(), with scheduledTime the tick's virtual time (UTC, the expression's matches from the virtual epoch on, in Cloudflare's dialect where weekdays run 1 = Sunday to 7 = Saturday; L, W and # are not modelled) and cron the expression (developers.cloudflare.com/workers/runtime-apis/handlers/scheduled/, /workers/configuration/cron-triggers/); Cloudflare documents noRetry() but no retry count, so the drive declares how many times a tick whose handler failed is re-run, and none after noRetry()\",\n \"inbound RPC: one invocation per call attempt, the entrypoint constructed anew for each with a fresh ExecutionContext (developers.cloudflare.com/workers/runtime-apis/bindings/service-bindings/rpc/); the return value is the response effect, and an exception reaches the caller as a new error with its name and message (developers.cloudflare.com/workers/runtime-apis/rpc/error-handling/); Cloudflare does not retry a call, so the drive's caller resends a call that threw or got no answer as the http drive's caller does; a result that is not plain data (a stub, a function, a stream) makes the run UNSUPPORTED\",\n];\n\n/**\n * The Cloudflare platform for `check`, run inside workerd under the Cloudflare Vitest plugin: the scenario's\n * drive delivered to the Worker's handlers, its bindings proxied so every call is an effect that faults can\n * hit, and the setup's resources reset before each run and snapshotted after it.\n */\nexport function createCloudflarePlatform(options: CloudflarePlatformOptions): Platform {\n const env = options.env as Record<string, unknown>;\n const aliases = options.aliases ?? {};\n /** The name a binding is known by: itself, or the name it is an alias of. */\n const canonical = (name: string): string => aliases[name] ?? name;\n const maxRetries = options.maxRetries ?? 3;\n // The redelivery rule takes no limit that is not whole or is negative; this says so by the option's name.\n if (!(Number.isInteger(maxRetries) && maxRetries >= 0))\n throw new Error(\"maxRetries must be a non-negative integer\");\n let hooksRef: RunHooks | null = null;\n\n const connections = new Connections();\n const ctx: ProxyContext = {\n get hooks() {\n if (!hooksRef) throw new Error(\"no run in progress\");\n return hooksRef;\n },\n // Bindings are shared by every invocation in flight; the engine knows which one is running.\n currentInvocation: () => ctx.hooks.running(),\n env: () => proxiedEnv,\n gate: { pending: undefined },\n onUpgrade: (info) => connections.upgradedTo(info),\n };\n\n /**\n * The kinds of binding modelled, in the order an env value is tried against\n * them: service bindings first (a callee's, then scripted), since in workerd\n * they answer every duck type (their property reads are RPC stubs).\n */\n // The Worker's and the callees' Durable Object classes are constructed with the scenario's env.\n simulateConstruction(options.exports);\n for (const callee of Object.values(options.callees ?? {})) simulateConstruction(callee.exports);\n const durable = durableObjectBinding({\n ctx,\n helpers: options.durableObjects,\n real: (name) => env[name],\n });\n const bindings: readonly Binding[] = [\n calleeBinding({ callees: options.callees, env: () => proxiedEnv }),\n serviceBinding(),\n d1Binding(options.schemas),\n // A namespace the scenario scripts, before the real objects' record.\n scriptedObjectBinding(options.durableObjects),\n durable,\n r2Binding(),\n workflowBinding({\n exports: options.exports,\n env: () => proxiedEnv,\n // A qualified binding's callee: the Worker whose name qualifies it.\n calleeOf: (binding) => {\n const at = binding.indexOf(\"/\");\n if (at < 0) return undefined;\n const name = binding.slice(0, at);\n return Object.values(options.callees ?? {}).find((c) => c.name === name);\n },\n }),\n ];\n // The Cloudflare Vitest plugin adds bindings of its own to env (its loopback and self services, its\n // runner object); a Worker that walks env (the Agents SDK's router does, to name each namespace) must\n // not meet them: they are the test environment's, not the Worker's.\n const own = (prop: string | symbol): boolean =>\n typeof prop !== \"string\" || !prop.startsWith(\"__VITEST_POOL_WORKERS_\");\n // An alias is read as the binding it names, so effects and snapshots carry that binding's name.\n const aliasKeys = Object.keys(aliases).filter((a) => canonical(a) in env);\n /**\n * What the Worker sees under a binding of a kind the simulation does not\n * model: the binding with every method refused. Reading it does nothing,\n * as code that builds its dependencies from `env` on every call does;\n * the first call on it ends the run `UNSUPPORTED` and is never passed to\n * the real binding.\n */\n const standIns = new Map<string, object>();\n const unproxied = (name: string, real: object): object => {\n let p = standIns.get(name);\n if (!p) {\n const refuseCall = (): never => refuse(ctx, `binding ${name} is not proxied`);\n p = new Proxy(typeof real === \"function\" ? refuseCall : {}, {\n get(_t, prop) {\n const value = Reflect.get(real, prop, real) as unknown;\n return typeof value === \"function\" ? refuseCall : value;\n },\n has: (_t, prop) => Reflect.has(real, prop),\n // Its keys and data are the binding's own, for code that walks or copies what it was given.\n ownKeys: () => Reflect.ownKeys(real),\n getOwnPropertyDescriptor(_t, prop) {\n const d = Reflect.getOwnPropertyDescriptor(real, prop);\n if (!d) return undefined;\n const value = Reflect.get(real, prop, real) as unknown;\n return {\n value: typeof value === \"function\" ? refuseCall : value,\n enumerable: d.enumerable ?? false,\n configurable: true,\n writable: false,\n };\n },\n apply: refuseCall,\n });\n standIns.set(name, p);\n }\n return p;\n };\n const proxiedEnv = new Proxy(env, {\n get(target, prop, receiver) {\n if (!own(prop)) return undefined;\n if (typeof prop !== \"string\") return Reflect.get(target, prop, receiver) as unknown;\n const name = canonical(prop);\n const value = Reflect.get(target, name, receiver) as unknown;\n for (const binding of bindings) {\n if (!binding.is(value)) continue;\n const proxied = binding.proxy(name, value, ctx);\n if (proxied !== undefined) return proxied;\n }\n return isBindingLike(value) ? unproxied(name, value as object) : value;\n },\n has: (target, prop) =>\n own(prop) &&\n (Reflect.has(target, prop) || (typeof prop === \"string\" && aliasKeys.includes(prop))),\n // An alias may also be a key of env (the test declared it for the callee's sake): listed once.\n ownKeys: (target) => [...new Set([...Reflect.ownKeys(target).filter(own), ...aliasKeys])],\n getOwnPropertyDescriptor: (target, prop) => {\n if (!own(prop)) return undefined;\n if (typeof prop === \"string\" && aliasKeys.includes(prop))\n return {\n value: env[canonical(prop)],\n enumerable: true,\n configurable: true,\n writable: false,\n };\n return Reflect.getOwnPropertyDescriptor(target, prop);\n },\n });\n // An entrypoint class exposes RPC methods, and its fetch(), queue() and scheduled() are the Worker's\n // handlers, called on an instance constructed for each invocation.\n const handler: WorkerHandler =\n typeof options.handler === \"function\"\n ? (entrypointHandler(options.handler) as WorkerHandler)\n : options.handler;\n const worker: RunningWorker = { handler, env: proxiedEnv };\n\n return {\n name: \"cloudflare\",\n assumptions,\n concurrent: true,\n\n async reset(spec: ScenarioSpec): Promise<void> {\n await connections.clear();\n for (const binding of bindings) binding.clear();\n // From here to the cleanup, a Durable Object is constructed with the scenario's env.\n simulatingConstruction(true);\n // What a constructor calls while its object is reset is answered from the scenario's scripts,\n // found under the name the binding is set up by, as inside a run.\n scriptsOutsideRuns((name) =>\n spec.setup.find(\n (s): s is ServiceSetup | ScriptedObjectSetup =>\n (s.kind === \"service\" || s.kind === \"scripted_object\") &&\n s[\"binding\"] === canonical(name),\n ),\n );\n // A var or a secret the scenario gives a value is in the isolate's env with that value, or the\n // run does not start: a Worker reading undefined for it fails in ways that say nothing of why.\n for (const step of spec.setup) {\n if (step.kind !== \"env\") continue;\n const name = String(step[\"binding\"]);\n const isSecret = step[\"secret\"] === true;\n const what = `the scenario's ${isSecret ? \"secret\" : \"envVar\"}(${JSON.stringify(name)})`;\n // A qualified name is a callee's: one that names no callee would reach no Worker at all.\n const worker = name.includes(\"/\") ? name.slice(0, name.indexOf(\"/\")) : undefined;\n const known = Object.values(options.callees ?? {}).map((c) => c.name);\n if (worker !== undefined && !known.includes(worker))\n throw new Error(\n `${what} names a Worker ${JSON.stringify(worker)} that is not a callee of the scenario${known.length > 0 ? ` (its callees: ${known.join(\", \")})` : \", which has none\"}`,\n );\n // Another name of a binding, or a binding of another kind: what a Worker reads there is\n // that binding, whatever value the step gives.\n if (name in aliases)\n throw new Error(\n `${what} takes the name of a binding: ${name} is another name of ${canonical(name)}`,\n );\n if (env[name] !== undefined && !isPlainData(env[name]))\n throw new Error(\n `${what} takes the name of a binding: the Worker's env holds one of another kind under ${name}`,\n );\n if (jsonEqual(env[name] as JsonValue | undefined, step[\"value\"] as JsonValue)) continue;\n throw new Error(\n `${what} is not in the Worker's env${name in env ? \" with that value\" : \"\"}: eutaxy check puts it there when it can import the scenario in Node; under Vitest give the Cloudflare plugin miniflare: { bindings: { ${JSON.stringify(name)}: ${isSecret ? \"<the secret>\" : JSON.stringify(step[\"value\"])} } }`,\n );\n }\n for (const [binding, setup] of ownedSetups(spec.setup, bindings)) {\n // One resource is set up once, under the name it is known by.\n if (setup.binding in aliases)\n throw new Error(\n `binding ${setup.binding} is an alias of ${canonical(setup.binding)}: set it up and read it as ${canonical(setup.binding)}`,\n );\n await binding.reset(setup, env[setup.binding]);\n }\n },\n\n async cleanup(): Promise<void> {\n // Outside the platform's runs a class is constructed with the runtime's env again.\n simulatingConstruction(false);\n },\n\n restrictEvents(spec: ScenarioSpec, keepIds: readonly string[]): ScenarioSpec {\n return { ...spec, drive: restrictDrive(spec.drive as Drive, keepIds) };\n },\n\n async finish(spec: ScenarioSpec, hooks: RunHooks): Promise<void> {\n // What each WebSocket connection received, and a close its object made, before the stores are read.\n connections.record(hooks);\n for (const [binding, setup] of ownedSetups(spec.setup, bindings)) {\n const tables = await binding.snapshot(setup, env[setup.binding], (reason) =>\n hooks.unsupported(reason),\n );\n if (tables)\n hooks.snapshot(hooks.bookkeeping(), `${binding.target}:${setup.binding}`, { tables });\n }\n // Then the connections are torn down, outside the run: what an object does on close is not\n // modelled, and a request it makes then is caught.\n const torn = await withoutNetwork(() => connections.teardown(durable.objects));\n if (torn.value) hooks.unsupported(torn.value);\n if (torn.requested)\n hooks.unsupported(\n \"a Durable Object made a request while its WebSocket connections were torn down after the run; what webSocketClose does is not modelled\",\n );\n },\n\n closingEvents(): readonly EventRef[] {\n return bindings.flatMap((b) => b.closing?.() ?? []);\n },\n\n initialEvents(spec: ScenarioSpec): readonly EventRef[] {\n return driveEvents(spec.drive as Drive);\n },\n\n async deliver(event: EventRef, hooks: RunHooks, spec: ScenarioSpec): Promise<DeliveryResult> {\n const drive = spec.drive as Drive;\n const invocation = invocationOf(event);\n hooksRef = hooks;\n // An event of a binding's own (an alarm, a Workflow run) is the binding's to deliver.\n const owner =\n event.source === undefined\n ? undefined\n : bindings.find((b) => b.source === event.source || b.closingSource === event.source);\n if (owner?.deliver) return owner.deliver(event, hooks, spec);\n switch (drive.kind) {\n case \"http\":\n return deliverRequest(event, hooks, spec, drive, invocation, worker);\n case \"cron\":\n return deliverTick(event, hooks, spec, drive, invocation, worker);\n case \"websocket\":\n return deliverWebSocket(event, hooks, spec, drive, {\n worker,\n connections,\n objects: durable.objects,\n });\n case \"rpc\": {\n const cls = entrypointClass(options.handler, options.exports, drive.entrypoint);\n if (typeof cls !== \"function\") {\n hooks.unsupported(\n `Rpc: ${drive.entrypoint === undefined ? \"the Worker's default export\" : `export ${drive.entrypoint}`} is not a WorkerEntrypoint class; pass the Worker module's exports as createCloudflarePlatform({ ..., exports })`,\n );\n return { status: \"errored\", followUps: [] };\n }\n return deliverCall(event, hooks, spec, drive, invocation, cls, proxiedEnv);\n }\n default:\n return deliverMessage(event, hooks, spec, drive, invocation, worker, maxRetries);\n }\n },\n };\n}\n","/**\n * Differential check: the same fault-free scenario run once through Eutaxy's\n * proxies and once against the raw bindings, with the queue model (or the\n * HTTP caller's retry policy) applied on the raw side itself. Any difference in the per-attempt decisions or in\n * the final D1, R2 and Durable Object state is a bug in the proxies or the platform model, not in\n * the Worker. The raw side shares Eutaxy's *reading* of Cloudflare's queue\n * semantics (core's redelivery rule among it) and the engine's raw loop; what\n * it does not share is any proxy code.\n */\n\nimport {\n type EventRef,\n getPath,\n invocationOf,\n type JsonValue,\n type RunHooks,\n type ScenarioSpec,\n toJson,\n} from \"@eutaxy/core\";\nimport {\n compareSides,\n effectLatencyMs,\n proxiedSide,\n type RawAttempt,\n type RawContext,\n rawRun,\n type VirtualClock,\n} from \"@eutaxy/engine\";\nimport { executionContext } from \"./background.ts\";\nimport {\n type Binding,\n d1Binding,\n durableObjectBinding,\n ownedSetups,\n r2Binding,\n} from \"./bindings.ts\";\nimport { isD1 } from \"./d1.ts\";\nimport type { DurableObjectTestHelpers } from \"./durable-objects.ts\";\nimport { requestFor } from \"./http.ts\";\nimport { isDurableObjectNamespace } from \"./object-access.ts\";\nimport { type CloudflarePlatformOptions, createCloudflarePlatform } from \"./platform.ts\";\nimport { cloneJson } from \"./queues.ts\";\nimport { isR2 } from \"./r2.ts\";\nimport { callMethod, describeError, entrypointClass } from \"./rpc.ts\";\nimport {\n type CronDrive,\n type Drive,\n driveEvents,\n type HttpDrive,\n type HttpRequestSpec,\n type QueueDrive,\n type RpcCallSpec,\n type RpcDrive,\n} from \"./scenario.ts\";\nimport type { TickData } from \"./scheduled.ts\";\nimport type { WorkerHandler } from \"./worker.ts\";\n\n/** A type, not an interface, so it is JSON data the comparison takes as it is. */\nexport type AttemptRecord = {\n readonly event: string;\n readonly attempt: number;\n readonly status: \"completed\" | \"errored\";\n /** Queue drive: the acknowledgement that took effect. Cron drive: `no_retry` when the handler asked for none. */\n readonly decision: \"ack\" | \"retry\" | \"no_retry\" | null;\n /** HTTP drive: the response status the caller saw (500 for an uncaught exception). */\n readonly response?: number;\n /** RPC drive: the answer the caller saw, `{ ok: true, value }` or `{ ok: false, error }`. */\n readonly result?: JsonValue;\n};\n\nexport interface Side {\n readonly attempts: readonly AttemptRecord[];\n readonly state: {\n readonly [binding: string]: { readonly [table: string]: readonly JsonValue[] };\n };\n}\n\n/** What `runDifferential` found: each side's attempts and end state, and where they differ. */\nexport interface DifferentialResult {\n /** True only when both sides agree and the proxied run touched nothing unmodelled. */\n readonly equal: boolean;\n readonly eutaxy: Side;\n readonly raw: Side;\n readonly differences: readonly string[];\n /** What the proxied run could not control; non-empty means the comparison proves nothing. */\n readonly unsupported: readonly string[];\n}\n\n/**\n * The raw side's only wrapper: counts D1 calls in flight (so the settle loop\n * knows real I/O is pending) and advances the clock as the proxies do. It\n * records nothing and injects nothing.\n */\nfunction countingD1(real: D1Database, io: { n: number }, clock: VirtualClock): D1Database {\n const realOf = new WeakMap<object, D1PreparedStatement>();\n const track = async <T>(p: Promise<T>): Promise<T> => {\n io.n++;\n try {\n return await p;\n } finally {\n io.n--;\n clock.advance(effectLatencyMs);\n }\n };\n const wrapStatement = (s: D1PreparedStatement): D1PreparedStatement => {\n const proxy = new Proxy(s, {\n get(t, prop, r) {\n const v = Reflect.get(t, prop, r) as unknown;\n if (prop === \"bind\") return (...a: unknown[]) => wrapStatement(t.bind(...a));\n if (prop === \"run\" || prop === \"all\" || prop === \"first\" || prop === \"raw\") {\n return (...a: unknown[]) =>\n track((v as (...x: unknown[]) => Promise<unknown>).apply(t, a));\n }\n return typeof v === \"function\" ? (v as (...x: unknown[]) => unknown).bind(t) : v;\n },\n });\n realOf.set(proxy, s);\n return proxy;\n };\n return new Proxy(real, {\n get(t, prop, r) {\n const v = Reflect.get(t, prop, r) as unknown;\n if (prop === \"prepare\") return (sql: string) => wrapStatement(t.prepare(sql));\n if (prop === \"batch\") {\n return (stmts: D1PreparedStatement[]) =>\n track(t.batch(stmts.map((s) => realOf.get(s) ?? s)));\n }\n if (prop === \"exec\") return (sql: string) => track(t.exec(sql));\n return typeof v === \"function\" ? (v as (...x: unknown[]) => unknown).bind(t) : v;\n },\n });\n}\n\n/**\n * The same for an R2 bucket: each call advances the clock as its proxied\n * effect does, and reading a body it gave counts as I/O in flight but does\n * not advance the clock (the proxy reads it inside the get). Reads through\n * the body's own stream are not counted: wrapping it would lose the known\n * length a copy's put needs, and Miniflare answers them within the settle\n * loop's real tick (checked with an 8 MB body).\n */\nfunction countingR2(real: R2Bucket, io: { n: number }, clock: VirtualClock): R2Bucket {\n const track = async <T>(p: Promise<T>, advance: boolean): Promise<T> => {\n io.n++;\n try {\n return await p;\n } finally {\n io.n--;\n if (advance) clock.advance(effectLatencyMs);\n }\n };\n const reads = [\"arrayBuffer\", \"bytes\", \"text\", \"json\", \"blob\"];\n const counted = (o: unknown): unknown => {\n if (o === null || typeof o !== \"object\" || !(\"body\" in o)) return o;\n return new Proxy(o, {\n get(t, prop) {\n // The object's own getters (body, etag) need the object itself as receiver.\n const v = Reflect.get(t, prop) as unknown;\n if (typeof prop === \"string\" && reads.includes(prop) && typeof v === \"function\")\n return (...a: unknown[]) =>\n track((v as (...x: unknown[]) => Promise<unknown>).apply(t, a), false);\n return typeof v === \"function\" ? (v as (...x: unknown[]) => unknown).bind(t) : v;\n },\n });\n };\n return new Proxy(real, {\n get(t, prop, r) {\n const v = Reflect.get(t, prop, r) as unknown;\n if (\n prop === \"put\" ||\n prop === \"delete\" ||\n prop === \"get\" ||\n prop === \"head\" ||\n prop === \"list\"\n )\n return async (...a: unknown[]) =>\n counted(await track((v as (...x: unknown[]) => Promise<unknown>).apply(t, a), true));\n return typeof v === \"function\" ? (v as (...x: unknown[]) => unknown).bind(t) : v;\n },\n });\n}\n\n/**\n * The bindings whose state the two sides compare: those a store holds and\n * the real binding resets and reads back (D1, R2, and Durable Objects when\n * the test helpers are given: the raw side reads every seeded object's\n * storage, since no proxy saw which were reached). Workflows have no raw\n * side.\n */\nfunction storedBindings(options: CloudflarePlatformOptions): readonly Binding[] {\n const helpers = options.durableObjects;\n const env = options.env as Record<string, unknown>;\n return [\n d1Binding(options.schemas),\n r2Binding(),\n ...(helpers\n ? [\n durableObjectBinding({\n // Reset and snapshot never reach the proxy context; the raw side has no run to give it.\n ctx: { hooks: undefined as unknown as RunHooks, currentInvocation: () => \"raw\" },\n helpers: helpers as DurableObjectTestHelpers,\n real: (name) => env[name],\n snapshotAll: true,\n }),\n ]\n : []),\n ];\n}\n\n/**\n * A Durable Object namespace whose stub calls count as I/O in flight: the\n * call crosses workerd, which the settle loop cannot otherwise see, and\n * advances the clock as the proxied call does. It records nothing.\n */\nfunction countingNamespace(\n real: DurableObjectNamespace,\n io: { n: number },\n clock: VirtualClock,\n): DurableObjectNamespace {\n const track = async <T>(p: Promise<T>): Promise<T> => {\n io.n++;\n try {\n return await p;\n } finally {\n io.n--;\n clock.advance(effectLatencyMs);\n }\n };\n const countingStub = (stub: DurableObjectStub): DurableObjectStub =>\n new Proxy(stub, {\n get(t, prop, r) {\n const v = Reflect.get(t, prop, r) as unknown;\n if (prop === \"then\" || prop === \"id\" || prop === \"name\" || typeof prop !== \"string\")\n return v;\n if (typeof v !== \"function\") return v;\n // An RPC member is callable (a method) and awaitable (a property): both cross workerd, so both\n // count. Reflect.apply, not method.apply: the member is a proxy, `.apply` would be a call.\n return new Proxy(v as (...x: unknown[]) => unknown, {\n apply: (member, _self, a: unknown[]) =>\n track(Promise.resolve(Reflect.apply(member, t, a))),\n get(member, key, receiver) {\n if (key === \"then\") {\n const read = track(Promise.resolve(member as unknown as Promise<unknown>));\n return read.then.bind(read);\n }\n return Reflect.get(member, key, receiver);\n },\n });\n },\n });\n return new Proxy(real, {\n get(t, prop, r) {\n const v = Reflect.get(t, prop, r) as unknown;\n if (prop === \"get\")\n return (...a: Parameters<DurableObjectNamespace[\"get\"]>) => countingStub(t.get(...a));\n if (prop === \"getByName\") return (name: string) => countingStub(t.getByName(name));\n return typeof v === \"function\" ? (v as (...x: unknown[]) => unknown).bind(t) : v;\n },\n });\n}\n\nasync function snapshotAll(\n spec: ScenarioSpec,\n options: CloudflarePlatformOptions,\n stored: readonly Binding[],\n): Promise<Side[\"state\"]> {\n const env = options.env as Record<string, unknown>;\n const out: Record<string, { readonly [table: string]: readonly JsonValue[] }> = {};\n for (const [binding, setup] of ownedSetups(spec.setup, stored)) {\n // A D1 or R2 snapshot reports nothing; if one ever did, the comparison could not stand.\n const tables = await binding.snapshot(setup, env[setup.binding], (reason) => {\n throw new Error(`snapshot of ${setup.binding}: ${reason}`);\n });\n if (tables) out[setup.binding] = tables;\n }\n return out;\n}\n\n/** The Eutaxy side, keeping each delivery's status and the decision it made. */\nasync function eutaxySide(\n spec: ScenarioSpec,\n options: CloudflarePlatformOptions,\n stored: readonly Binding[],\n): Promise<Side & { readonly unsupported: readonly string[] }> {\n const { attempts, unsupported } = await proxiedSide(\n spec,\n createCloudflarePlatform(options),\n (event, result, entries): AttemptRecord => {\n const invocation = invocationOf(event);\n const mine = entries.filter((e) => e.invocation === invocation);\n const decision = mine.some((e) => e.kind === \"result\" && e.op === \"no_retry\")\n ? \"no_retry\"\n : (mine.find(\n (e) =>\n e.kind === \"result\" &&\n (e.op === \"ack\" || e.op === \"retry\") &&\n getPath(e.payload, \"result.effective\") === true,\n )?.op as \"ack\" | \"retry\" | undefined);\n const response = mine.find((e) => e.kind === \"result\" && e.op === \"response\");\n const answer = (): Partial<AttemptRecord> => {\n if (!response) return {};\n if (spec.drive.kind === \"rpc\")\n return { result: getPath(response.payload, \"result\") ?? null };\n return { response: getPath(response.payload, \"result.status\") as number };\n };\n return {\n event: event.id,\n attempt: event.attempt,\n status: result.status === \"completed\" ? \"completed\" : \"errored\",\n decision: decision ?? null,\n ...answer(),\n };\n },\n );\n return { attempts, state: await snapshotAll(spec, options, stored), unsupported };\n}\n\n/** Each binding's tables under `<binding>.<table>`, as the comparison names them. */\nfunction flatten(state: Side[\"state\"]): { readonly [name: string]: readonly JsonValue[] } {\n const out: Record<string, readonly JsonValue[]> = {};\n for (const [binding, tables] of Object.entries(state))\n for (const [table, rows] of Object.entries(tables)) out[`${binding}.${table}`] = rows;\n return out;\n}\n\n/** The real bindings with each call counted as I/O in flight and the clock advanced as the proxies do. */\nfunction countingEnv(env: Record<string, unknown>, ctx: RawContext): Record<string, unknown> {\n const counting = new Map<string, D1Database | R2Bucket | DurableObjectNamespace>();\n return new Proxy(env, {\n get(target, prop, receiver) {\n const value = Reflect.get(target, prop, receiver) as unknown;\n if (\n typeof prop !== \"string\" ||\n !(isD1(value) || isR2(value) || isDurableObjectNamespace(value))\n )\n return value;\n let c = counting.get(prop);\n if (!c) {\n c = isD1(value)\n ? countingD1(value, ctx.io, ctx.clock)\n : isR2(value)\n ? countingR2(value, ctx.io, ctx.clock)\n : countingNamespace(value, ctx.io, ctx.clock);\n counting.set(prop, c);\n }\n return c;\n },\n });\n}\n\n/** One raw attempt of a drive's event: the handler called directly with the real bindings and a plain message or Request object. */\ntype RawAttemptOf = (event: EventRef) => Promise<RawAttempt<AttemptRecord>>;\n\nfunction rawCall(\n ctx: RawContext,\n drive: RpcDrive,\n options: CloudflarePlatformOptions,\n env: object,\n): RawAttemptOf {\n const cls = entrypointClass(options.handler, options.exports, drive.entrypoint);\n if (typeof cls !== \"function\") throw new Error(\"the Worker has no WorkerEntrypoint class\");\n return async (event) => {\n const call = event.data as unknown as RpcCallSpec;\n const background: Promise<unknown>[] = [];\n const ran = await ctx.call(async () =>\n toJson(await callMethod(cls, call, executionContext(background), env)),\n );\n await ctx.settle(Promise.all(background));\n const result: JsonValue =\n ran.status === \"completed\"\n ? { ok: true, value: ran.value }\n : { ok: false, error: describeError(ran.error) };\n return {\n record: {\n event: event.id,\n attempt: event.attempt,\n status: ran.status,\n decision: null,\n result,\n },\n handled: ran.status === \"completed\",\n };\n };\n}\n\nfunction rawTick(\n ctx: RawContext,\n _drive: CronDrive,\n handlers: WorkerHandler,\n env: object,\n): RawAttemptOf {\n const handler = handlers.scheduled;\n if (!handler) throw new Error(\"the Worker has no scheduled() handler\");\n return async (event) => {\n const tick = event.data as unknown as TickData;\n const background: Promise<unknown>[] = [];\n const failures: unknown[] = [];\n let noRetry = false;\n const controller: ScheduledController = {\n scheduledTime: tick.scheduledTime,\n cron: tick.cron,\n noRetry: () => {\n noRetry = true;\n },\n };\n const ran = await ctx.call(() =>\n handler.call(handlers, controller, env, executionContext(background, failures)),\n );\n await ctx.settle(Promise.all(background));\n // A failed waitUntil is the invocation's status, as for the proxied side.\n const status = ran.status === \"completed\" && failures.length === 0 ? \"completed\" : \"errored\";\n return {\n record: {\n event: event.id,\n attempt: event.attempt,\n status,\n decision: noRetry ? \"no_retry\" : null,\n },\n handled: status === \"completed\" || noRetry,\n };\n };\n}\n\nfunction rawRequest(\n ctx: RawContext,\n drive: HttpDrive,\n handlers: WorkerHandler,\n env: object,\n): RawAttemptOf {\n const handler = handlers.fetch;\n if (!handler) throw new Error(\"the Worker has no fetch() handler\");\n return async (event) => {\n const req = event.data as unknown as HttpRequestSpec;\n const background: Promise<unknown>[] = [];\n const ran = await ctx.call(async () => {\n const r = await handler.call(handlers, requestFor(req), env, executionContext(background));\n await r.clone().text();\n return r.status;\n });\n await ctx.settle(Promise.all(background));\n const response = ran.status === \"completed\" ? ran.value : 500;\n const accepted = drive.retryOn === \"5xx\" ? response < 500 : response >= 200 && response < 300;\n return {\n record: {\n event: event.id,\n attempt: event.attempt,\n status: ran.status,\n decision: null,\n response,\n },\n handled: accepted,\n };\n };\n}\n\nfunction rawMessage(\n ctx: RawContext,\n drive: QueueDrive,\n handlers: WorkerHandler,\n env: object,\n): RawAttemptOf {\n const handler = handlers.queue;\n if (!handler) throw new Error(\"the Worker has no queue() handler\");\n return async (event) => {\n let decision: \"ack\" | \"retry\" | null = null;\n const background: Promise<unknown>[] = [];\n const message: Message<unknown> = {\n id: event.id,\n timestamp: new Date(),\n body: cloneJson(event.data),\n attempts: event.attempt,\n ack: () => {\n decision ??= \"ack\";\n },\n retry: () => {\n decision ??= \"retry\";\n },\n };\n const batch: MessageBatch<unknown> = {\n queue: drive.queue,\n messages: [message],\n metadata: { metrics: { backlogCount: 0, backlogBytes: 0 } },\n ackAll: () => message.ack(),\n retryAll: () => message.retry(),\n };\n const ran = await ctx.call(() =>\n handler.call(handlers, batch, env, executionContext(background)),\n );\n if (ran.status === \"completed\") decision ??= \"ack\";\n await ctx.settle(Promise.all(background));\n return {\n record: { event: event.id, attempt: event.attempt, status: ran.status, decision },\n handled: decision === \"ack\",\n };\n };\n}\n\n/** The raw side: the engine's raw loop, each attempt calling the handler directly with the real bindings. */\nasync function rawSide(\n spec: ScenarioSpec,\n options: CloudflarePlatformOptions,\n stored: readonly Binding[],\n): Promise<Side> {\n const env = options.env as Record<string, unknown>;\n const drive = spec.drive as Drive;\n if (drive.kind === \"websocket\")\n throw new Error(\n \"runDifferential has no raw side for a websocket drive: its messages are delivered inside the object\",\n );\n // The same resets as the proxied side's, which ran first on the same env and so already holds.\n for (const [binding, setup] of ownedSetups(spec.setup, stored))\n await binding.reset(setup, env[setup.binding]);\n // The queue, http and cron drives need the handler object; an entrypoint class has none of the handlers.\n const handlers: WorkerHandler = typeof options.handler === \"function\" ? {} : options.handler;\n const attempts = await rawRun<AttemptRecord>(spec, {\n events: driveEvents(drive),\n limit: drive.kind === \"queue\" ? (options.maxRetries ?? 3) : drive.retries,\n install: (ctx) => {\n const counted = countingEnv(env, ctx);\n switch (drive.kind) {\n case \"rpc\":\n return { attempt: rawCall(ctx, drive, options, counted) };\n case \"cron\":\n return { attempt: rawTick(ctx, drive, handlers, counted) };\n case \"http\":\n return { attempt: rawRequest(ctx, drive, handlers, counted) };\n case \"queue\":\n return { attempt: rawMessage(ctx, drive, handlers, counted) };\n }\n },\n });\n return { attempts, state: await snapshotAll(spec, options, stored) };\n}\n\n/** Run both sides and compare. The Eutaxy side runs first; both start from the schema. */\nexport async function runDifferential(\n spec: ScenarioSpec,\n options: CloudflarePlatformOptions,\n): Promise<DifferentialResult> {\n if (\n (spec.drive.kind === \"http\" || spec.drive.kind === \"rpc\") &&\n (\"delaysMs\" in spec.drive || \"deadlineMs\" in spec.drive)\n ) {\n throw new Error(\"runDifferential does not model the caller's delaysMs or deadlineMs yet\");\n }\n // The raw side calls the real bindings; a callee's real code is Eutaxy's model, with no runtime side.\n if (spec.setup.some((s) => s.kind === \"callee\"))\n throw new Error(\n \"runDifferential keeps to the binding proxies: a scenario with a callee() has no raw side; script the service for the differential entry\",\n );\n // A scripted namespace's objects are never run; the raw side would run the real ones.\n if (spec.setup.some((s) => s.kind === \"scripted_object\"))\n throw new Error(\n \"runDifferential keeps to the binding proxies: a scenario with a scriptedObject() has no raw side\",\n );\n const stored = storedBindings(options);\n const { unsupported, ...eutaxy } = await eutaxySide(spec, options, stored);\n const raw = await rawSide(spec, options, stored);\n const differences = compareSides(\n { attempts: eutaxy.attempts, state: flatten(eutaxy.state) },\n { attempts: raw.attempts, state: flatten(raw.state) },\n unsupported,\n );\n return { equal: differences.length === 0, eutaxy, raw, differences, unsupported };\n}\n","/**\n * The half of `eutaxy check` that runs inside workerd: the generated test\n * passes its module globs here and stores what this returns in its task\n * meta, which the CLI reads back. It imports nothing that needs Node, so\n * the Cloudflare Vitest plugin can load it.\n */\n\nimport {\n type CalleeModule,\n check,\n createCloudflarePlatform,\n type DurableObjectTestHelpers,\n type WorkerHandler,\n} from \"@eutaxy/cloudflare\";\nimport type { ScenarioSpec, SpecVerdict } from \"@eutaxy/core\";\nimport { observeCore } from \"@eutaxy/engine\";\nimport { checkSpecModule } from \"@eutaxy/prover\";\nimport { renderJson } from \"@eutaxy/report\";\nimport type { ModuleSpecs } from \"@eutaxy/spec\";\nimport { globKey, specKey } from \"./keys.ts\";\n\n/** What the generated test stores in its task meta. */\nexport interface CheckTransport {\n readonly report: unknown;\n /** Set instead of a report when a module the scenario's `specs` names has no usable spec file. */\n readonly specErrors?: readonly SpecError[];\n readonly worker: { readonly entry: string; readonly config: string };\n readonly setup: readonly { readonly kind: string; readonly [key: string]: unknown }[];\n /** The scenario's drive, for what the regression test must pass the platform (a named entrypoint). */\n readonly drive?: { readonly kind: string; readonly [key: string]: unknown };\n /** The core modules observed (as the scenario's specs name them) and the functions on each. */\n /** The callees the platform ran, by binding: each one's Worker name, and what the binding carried, for the regression test. */\n readonly callees?: Readonly<\n Record<\n string,\n {\n readonly name: string;\n readonly entrypoint?: string;\n readonly props?: Readonly<Record<string, unknown>>;\n readonly self?: boolean;\n }\n >\n >;\n /** The aliases the platform ran with, for the regression test. */\n readonly aliases?: Readonly<Record<string, string>>;\n readonly observed?: readonly { readonly module: string; readonly functions: readonly string[] }[];\n}\n\nexport interface SpecError {\n readonly module: string;\n readonly line: number;\n readonly message: string;\n}\n\n/** A generated spec entry: the module's specs, read on the Node side, and a loader of its spec file. */\nexport interface SpecEntry {\n readonly specs: ModuleSpecs;\n readonly load: () => Promise<object>;\n}\n\n/** Vite globs, keyed as `import.meta.glob` keys them from `.eutaxy/` (see `globKey`). */\nexport type ModuleGlob = Readonly<Record<string, () => Promise<unknown>>>;\n\n/**\n * Each D1 binding's schema, read from the `.sql` files next to the scenario. Several `d1Schema` steps\n * on one binding (a migration per file) are joined in setup order, each file its own statements.\n */\nexport function schemasFor(\n scenario: ScenarioSpec,\n sqlFiles: Readonly<Record<string, string>>,\n): Record<string, string> {\n const schemas: Record<string, string> = {};\n for (const step of scenario.setup) {\n if (step.kind !== \"d1\") continue;\n const file = String(step[\"schemaFile\"]);\n const sql = sqlFiles[globKey(file)];\n if (sql === undefined) throw new Error(`schema file ${file} not found next to the scenario`);\n const binding = String(step[\"binding\"]);\n const earlier = schemas[binding];\n schemas[binding] = earlier === undefined ? sql : `${earlier}\\n;\\n${sql}`;\n }\n return schemas;\n}\n\nexport interface SelectedModule {\n /** As the scenario names it. */\n readonly path: string;\n readonly key: string;\n readonly namespace: object;\n readonly specs: ModuleSpecs;\n /** The spec file's namespace: its exports are the specs. */\n readonly props: Readonly<Record<string, unknown>>;\n /** The functions observed: the ones with specs, and the decisions `refines` names that the module exports. */\n readonly names: readonly string[];\n}\n\n/**\n * The modules the scenario's `specs` name, loaded with their specs and\n * their spec files, and every reason the check cannot go ahead: a module\n * that is not there, a spec that does not read, a function name observed\n * in two modules (decisions are logged by name, so it would be ambiguous).\n * The spec files are loaded here, before anything is observed, so the\n * functions their specs hold are the modules' own.\n */\nexport async function selectSpecModules(\n scenario: ScenarioSpec,\n modules: ModuleGlob,\n specEntries: Readonly<Record<string, SpecEntry>>,\n): Promise<{\n readonly selected: readonly SelectedModule[];\n readonly specErrors: readonly SpecError[];\n}> {\n const decisions = scenario.invariants.flatMap((i) => (i.kind === \"refines\" ? [i.decision] : []));\n const specErrors: SpecError[] = [];\n const selected: SelectedModule[] = [];\n for (const path of scenario.specs ?? []) {\n const load = modules[globKey(path)];\n if (!load) {\n specErrors.push({ module: path, line: 0, message: \"no such module next to the scenario\" });\n continue;\n }\n const namespace = (await load()) as Record<string, unknown>;\n const key = specKey(path);\n const entry = Object.hasOwn(specEntries, key) ? specEntries[key] : undefined;\n const specs: ModuleSpecs = entry?.specs ?? { functions: [], errors: [] };\n for (const e of specs.errors)\n specErrors.push({\n module: e.inModule ? path : `${path.replace(/\\.ts$/, \"\")}.props.ts`,\n line: e.line,\n message: e.message,\n });\n const props = entry ? ((await entry.load()) as Record<string, unknown>) : {};\n const exported = decisions.filter((d) => typeof namespace[d] === \"function\");\n const names = [...new Set([...specs.functions.map((f) => f.name), ...exported])];\n selected.push({ path, key, namespace, specs, props, names });\n }\n const observedIn = new Map<string, string>();\n for (const m of selected)\n for (const n of m.names) {\n const other = observedIn.get(n);\n if (other === undefined) observedIn.set(n, m.path);\n else\n specErrors.push({\n module: m.path,\n line: 0,\n message: `${n} is observed in both ${other} and ${m.path}; decisions of one name must come from one module`,\n });\n }\n return { selected, specErrors };\n}\n\n/**\n * What the generated check test passes to `checkInWorkerd`: the scenario, the bindings and test helpers,\n * the modules and SQL files beside the scenario, the callees, and the exploration options.\n */\nexport interface WorkerdCheckInput {\n /** The scenario module's default export. */\n readonly scenario: ScenarioSpec;\n /** `env` from `cloudflare:workers`. */\n readonly env: object;\n /** The `cloudflare:test` module, for Durable Objects. */\n readonly durableObjects: DurableObjectTestHelpers;\n /** The raw text of the `.sql` files next to the scenario. */\n readonly sqlFiles: Readonly<Record<string, string>>;\n /** The TypeScript modules next to the scenario (the Worker and the spec modules among them). */\n readonly modules: ModuleGlob;\n /** The generated `specs.ts` entries, by module key. */\n readonly specEntries: Readonly<Record<string, SpecEntry>>;\n /** The Worker's module, imported by the generated test when its entry lies outside the scenario's directory. */\n readonly worker?: Readonly<Record<string, unknown>>;\n /** The callees the scenario names, by binding: each one's Worker name and module exports, imported by the generated test. */\n readonly callees?: Readonly<Record<string, CalleeModule>>;\n /** SQL files outside the scenario's directory, by the key `schemasFor` looks up. */\n readonly extraSql?: Readonly<Record<string, string>>;\n /** Qualified binding names that are aliases of the caller's bindings (shared resources). */\n readonly aliases?: Readonly<Record<string, string>>;\n readonly seed: string;\n readonly maxRuns?: number;\n readonly budgetMs?: number;\n readonly exhaustive?: boolean;\n}\n\n/** Run the scenario's check, with its specs observed, and return what the CLI reads back. */\nexport async function checkInWorkerd(input: WorkerdCheckInput): Promise<CheckTransport> {\n const { scenario } = input;\n const schemas = schemasFor(scenario, { ...input.sqlFiles, ...input.extraSql });\n const load = input.modules[globKey(scenario.worker.entry)];\n if (!input.worker && !load)\n throw new Error(`worker entry ${scenario.worker.entry} not found next to the scenario`);\n const worker = (input.worker ?? (await load?.())) as { default: WorkerHandler } & Record<\n string,\n unknown\n >;\n const platform = createCloudflarePlatform({\n env: input.env,\n handler: worker.default,\n schemas,\n durableObjects: input.durableObjects,\n exports: worker,\n ...(input.callees === undefined ? {} : { callees: input.callees }),\n ...(input.aliases === undefined ? {} : { aliases: input.aliases }),\n });\n const { selected, specErrors } = await selectSpecModules(\n scenario,\n input.modules,\n input.specEntries,\n );\n const transportBase = {\n worker: scenario.worker,\n setup: scenario.setup,\n drive: scenario.drive,\n ...(input.callees === undefined\n ? {}\n : {\n callees: Object.fromEntries(\n Object.entries(input.callees).map(([binding, c]) => [\n binding,\n {\n name: c.name,\n ...(c.entrypoint === undefined ? {} : { entrypoint: c.entrypoint }),\n ...(c.props === undefined ? {} : { props: c.props }),\n ...(c.self ? { self: true } : {}),\n },\n ]),\n ),\n }),\n ...(input.aliases === undefined ? {} : { aliases: input.aliases }),\n };\n if (specErrors.length > 0) return { report: null, specErrors, ...transportBase };\n const observers = selected.map((m) => observeCore(m.namespace, m.names));\n let verdict: Awaited<ReturnType<typeof check>>;\n try {\n verdict = await check(scenario, platform, {\n seed: input.seed,\n ...(input.maxRuns === undefined ? {} : { maxRuns: input.maxRuns }),\n ...(input.budgetMs === undefined ? {} : { budgetMs: input.budgetMs }),\n ...(input.exhaustive ? { exhaustive: true } : {}),\n });\n } finally {\n for (const o of observers) o.restore();\n }\n // CHECKED on the calls the exploration recorded, then TESTED on inputs drawn from the check's seed.\n const specs: SpecVerdict[] = selected.flatMap((m, i) =>\n checkSpecModule(\n m.key,\n m.specs,\n m.props,\n m.namespace as Record<string, unknown>,\n observers[i] as ReturnType<typeof observeCore>,\n { tested: { seed: input.seed } },\n ),\n );\n return {\n report: JSON.parse(renderJson(verdict, specs)) as unknown,\n ...transportBase,\n observed: selected.map((m) => ({ module: m.path, functions: m.names })),\n };\n}\n"],"mappings":";;;;;;;;;AAqBA,MAAM,eAAe;;;;;AAMrB,SAAgBA,eAAa,YAA4B;CACvD,OAAO,eAAe,UAAU,UAAU;AAC5C;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