eutaxy 0.5.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +96 -12
- package/dist/aws.d.mts +7 -5
- package/dist/aws.d.mts.map +1 -1
- package/dist/aws.mjs +44 -138
- package/dist/aws.mjs.map +1 -1
- package/dist/bin.mjs +2 -2
- package/dist/{checksum-DhS6ofSm.mjs → checksum-DHr5qb3Y.mjs} +2 -2
- package/dist/{checksum-DhS6ofSm.mjs.map → checksum-DHr5qb3Y.mjs.map} +1 -1
- package/dist/cli-CsiVEsS-.mjs +2 -0
- package/dist/cli.d.mts.map +1 -1
- package/dist/cli.mjs +2 -2
- package/dist/cloudflare.d.mts +156 -54
- package/dist/cloudflare.d.mts.map +1 -1
- package/dist/cloudflare.mjs +3 -1815
- package/dist/delivery-invariants-BraYqcYN.d.mts +5 -0
- package/dist/delivery-invariants-BraYqcYN.d.mts.map +1 -0
- package/dist/delivery-invariants-hmhwh_qD.mjs +39 -0
- package/dist/delivery-invariants-hmhwh_qD.mjs.map +1 -0
- package/dist/{event-streams-BANyO9xt.mjs → event-streams-i8OGzuFN.mjs} +2 -2
- package/dist/{event-streams-BANyO9xt.mjs.map → event-streams-i8OGzuFN.mjs.map} +1 -1
- package/dist/explore-CDpJA9zX.d.mts +342 -0
- package/dist/explore-CDpJA9zX.d.mts.map +1 -0
- package/dist/index.d.mts +84 -195
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +10 -191
- package/dist/index.mjs.map +1 -1
- package/dist/{platform-eVgCMbX0.d.mts → platform-DfMwknw1.d.mts} +94 -73
- package/dist/platform-DfMwknw1.d.mts.map +1 -0
- package/dist/{src-C19_yfMM.mjs → src-BO7I3f-1.mjs} +961 -543
- package/dist/src-BO7I3f-1.mjs.map +1 -0
- package/dist/src-C43iUZgr.mjs +5039 -0
- package/dist/src-C43iUZgr.mjs.map +1 -0
- package/dist/{src-CgfGiH25.mjs → src-Cs4Mg55e.mjs} +1148 -22
- package/dist/src-Cs4Mg55e.mjs.map +1 -0
- package/package.json +16 -1
- package/dist/cli-NqY61bpo.mjs +0 -2
- package/dist/cloudflare.mjs.map +0 -1
- package/dist/explore-BHYvAZKN.d.mts +0 -84
- package/dist/explore-BHYvAZKN.d.mts.map +0 -1
- package/dist/platform-eVgCMbX0.d.mts.map +0 -1
- package/dist/src-BD3jkjgG.mjs +0 -477
- package/dist/src-BD3jkjgG.mjs.map +0 -1
- package/dist/src-C19_yfMM.mjs.map +0 -1
- package/dist/src-CgfGiH25.mjs.map +0 -1
- package/dist/src-s6uYyC0B.mjs +0 -89
- package/dist/src-s6uYyC0B.mjs.map +0 -1
- package/dist/verdict-evEM5Gxx.mjs +0 -12
- package/dist/verdict-evEM5Gxx.mjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"src-C43iUZgr.mjs","names":["WRITE","READ","retryDelayMs","coreAtLeastOncePerMessage","retryDelayMs"],"sources":["../../cli/src/args.ts","../../prover-lean/src/subset.ts","../../prover-lean/src/emit.ts","../../prover-lean/src/lean.ts","../../prover-lean/src/prove.ts","../../cli/src/generate.ts","../../cli/src/regression.ts","../../cli/src/keys.ts","../../cli/src/specs.ts","../../cli/src/check.ts","../../cli/src/main.ts","../../cloudflare/src/check.ts","../../cloudflare/src/d1.ts","../../cloudflare/src/background.ts","../../cloudflare/src/scenario.ts","../../cloudflare/src/http.ts","../../cloudflare/src/alarms.ts","../../cloudflare/src/durable-objects.ts","../../cloudflare/src/queues.ts","../../cloudflare/src/r2.ts","../../cloudflare/src/workflows.ts","../../cloudflare/src/platform.ts","../../cloudflare/src/differential.ts","../../cli/src/workerd.ts"],"sourcesContent":["/** A small argument parser: positionals, `--flag value`, `--flag=value` and boolean `--flag`. */\n\nexport interface ParsedArgs {\n readonly positionals: readonly string[];\n readonly flags: Readonly<Record<string, string | true>>;\n}\n\nexport function parseArgs(argv: readonly string[], booleans: readonly string[] = []): ParsedArgs {\n const positionals: string[] = [];\n const flags: Record<string, string | true> = {};\n for (let i = 0; i < argv.length; i++) {\n const a = argv[i] as string;\n if (!a.startsWith(\"--\")) {\n positionals.push(a);\n continue;\n }\n const eq = a.indexOf(\"=\");\n if (eq !== -1) {\n flags[a.slice(2, eq)] = a.slice(eq + 1);\n continue;\n }\n const name = a.slice(2);\n const next = argv[i + 1];\n if (booleans.includes(name) || next === undefined || next.startsWith(\"--\")) {\n flags[name] = true;\n } else {\n flags[name] = next;\n i++;\n }\n }\n return { positionals, flags };\n}\n","/**\n * The pure TypeScript subset the first-party engine accepts, read into a\n * small tree: exported functions over `number` (as unbounded integers),\n * `boolean` and `string`, returning those or a record type declared in the\n * same module;\n * bodies made of `const` bindings, `if` with early returns, `return`, and\n * expressions from integer arithmetic (`+ - *`), comparisons, `&& || !`,\n * the conditional operator, record literals and field reads, and calls to\n * the module's own functions. Anything else is `OutsideSubset`, with the\n * construct named: the subset is specified by the contract corpus and\n * widens one characterised class at a time.\n */\n\nimport { type Token, TokenizeError, templateSubstitutions, tokenize } from \"@eutaxy/spec\";\n\nexport class OutsideSubset extends Error {\n readonly line: number;\n constructor(message: string, line: number) {\n super(message);\n this.line = line;\n }\n}\n\nexport type SubsetType =\n | { readonly kind: \"int\" }\n | { readonly kind: \"bool\" }\n | { readonly kind: \"string\" }\n | { readonly kind: \"record\"; readonly name: string };\n\nexport interface Field {\n readonly name: string;\n readonly type: SubsetType;\n}\n\nexport interface RecordType {\n readonly name: string;\n readonly fields: readonly Field[];\n}\n\nexport type BinaryOp = \"+\" | \"-\" | \"*\" | \"<\" | \"<=\" | \">\" | \">=\" | \"===\" | \"!==\" | \"&&\" | \"||\";\n\nexport type Expr =\n | { readonly kind: \"int\"; readonly value: string }\n | { readonly kind: \"bool\"; readonly value: boolean }\n | { readonly kind: \"string\"; readonly value: string }\n | { readonly kind: \"var\"; readonly name: string }\n | { readonly kind: \"neg\"; readonly operand: Expr }\n | { readonly kind: \"not\"; readonly operand: Expr }\n | { readonly kind: \"binary\"; readonly op: BinaryOp; readonly left: Expr; readonly right: Expr }\n | { readonly kind: \"cond\"; readonly test: Expr; readonly ifTrue: Expr; readonly ifFalse: Expr }\n | { readonly kind: \"call\"; readonly callee: string; readonly args: readonly Expr[] }\n | { readonly kind: \"field\"; readonly object: Expr; readonly field: string }\n | {\n readonly kind: \"record\";\n readonly fields: readonly { readonly name: string; readonly value: Expr }[];\n }\n | { readonly kind: \"let\"; readonly name: string; readonly value: Expr; readonly body: Expr };\n\nexport interface Param {\n readonly name: string;\n readonly type: SubsetType;\n}\n\n/** A function's header, with the token index its body starts at. */\ninterface Signature {\n readonly name: string;\n readonly params: readonly Param[];\n readonly returns: SubsetType;\n readonly line: number;\n readonly offset: number;\n readonly body: number;\n}\n\nexport interface SubsetFunction {\n readonly name: string;\n readonly params: readonly Param[];\n readonly returns: SubsetType;\n readonly body: Expr;\n /** 1-based line of the declaration. */\n readonly line: number;\n /** Offset of the `(` opening its parameters: the declaration's identity, as the spec extractor records it. */\n readonly offset: number;\n}\n\n/** A function the subset does not take, and why. */\nexport interface OutsideFunction {\n readonly name: string;\n readonly line: number;\n readonly message: string;\n}\n\nexport interface SubsetModule {\n readonly records: readonly RecordType[];\n /** The functions in the subset, in source order, callees before callers. */\n readonly functions: readonly SubsetFunction[];\n /** The module's other functions: outside the subset themselves, or calling one that is. */\n readonly outside: readonly OutsideFunction[];\n}\n\n/** Binary operators by precedence, loosest first; all left-associative here. */\nconst levels: readonly (readonly BinaryOp[])[] = [\n [\"||\"],\n [\"&&\"],\n [\"===\", \"!==\"],\n [\"<\", \"<=\", \">\", \">=\"],\n [\"+\", \"-\"],\n [\"*\"],\n];\n\nclass Reader {\n at = 0;\n readonly tokens: readonly Token[];\n private readonly lineOf: (offset: number) => number;\n constructor(tokens: readonly Token[], lineOf: (offset: number) => number) {\n this.tokens = tokens;\n this.lineOf = lineOf;\n }\n\n peek(n = 0): Token | undefined {\n return this.tokens[this.at + n];\n }\n\n line(t: Token | undefined = this.peek()): number {\n return t ? this.lineOf(t.start) : this.lineOf(this.tokens.at(-1)?.end ?? 0);\n }\n\n fail(what: string, t: Token | undefined = this.peek()): never {\n throw new OutsideSubset(what, this.line(t));\n }\n\n isPunct(text: string, n = 0): boolean {\n const t = this.peek(n);\n return t?.kind === \"punct\" && t.text === text;\n }\n\n isWord(text: string, n = 0): boolean {\n const t = this.peek(n);\n return t?.kind === \"ident\" && t.text === text;\n }\n\n take(): Token {\n const t = this.peek();\n if (!t) this.fail(\"the module ends early\");\n this.at++;\n return t;\n }\n\n expectPunct(text: string): void {\n if (!this.isPunct(text)) this.fail(`expected ${text}, found ${this.peek()?.text ?? \"the end\"}`);\n this.at++;\n }\n\n ident(): string {\n const t = this.peek();\n if (t?.kind !== \"ident\") this.fail(`expected a name, found ${t?.text ?? \"the end\"}`);\n this.at++;\n return t.text;\n }\n}\n\n/** Whether a string holds a surrogate code unit without its pair: no Lean character corresponds to it. */\nexport function hasLoneSurrogate(s: string): boolean {\n return /[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?<![\\uD800-\\uDBFF])[\\uDC00-\\uDFFF]/.test(s);\n}\n\n/**\n * The value of a string literal token. Simple escapes and `\\xHH`, `\\uHHHH`,\n * `\\u{H…}` are decoded; a line continuation, an octal escape or a lone\n * surrogate (which Lean's strings cannot hold) is outside the subset.\n */\nfunction stringLiteralValue(text: string, r: Reader, t: Token): string {\n const body = text.slice(1, -1);\n let out = \"\";\n for (let i = 0; i < body.length; i++) {\n const c = body[i] as string;\n if (c !== \"\\\\\") {\n out += c;\n continue;\n }\n const e = body[++i];\n const simple: Record<string, string> = {\n n: \"\\n\",\n t: \"\\t\",\n r: \"\\r\",\n b: \"\\b\",\n f: \"\\f\",\n v: \"\\v\",\n \"0\": \"\\0\",\n \"\\\\\": \"\\\\\",\n '\"': '\"',\n \"'\": \"'\",\n };\n if (e !== undefined && e in simple && !(e === \"0\" && /[0-9]/.test(body[i + 1] ?? \"\"))) {\n out += simple[e];\n continue;\n }\n if (e === \"x\" && /^[0-9a-fA-F]{2}$/.test(body.slice(i + 1, i + 3))) {\n out += String.fromCharCode(Number.parseInt(body.slice(i + 1, i + 3), 16));\n i += 2;\n continue;\n }\n if (e === \"u\") {\n const m = /^\\{([0-9a-fA-F]{1,6})\\}|^([0-9a-fA-F]{4})/.exec(body.slice(i + 1));\n if (m) {\n const code = Number.parseInt((m[1] ?? m[2]) as string, 16);\n if (code > 0x10ffff) r.fail(`a code point escape beyond U+10FFFF in a string literal`, t);\n out += String.fromCodePoint(code);\n i += m[0].length;\n continue;\n }\n }\n r.fail(`an escape sequence \\\\${e ?? \"\"} in a string literal`, t);\n }\n if (hasLoneSurrogate(out))\n r.fail(\"a string literal with a lone surrogate, which Lean's strings cannot hold\", t);\n return out;\n}\n\n/** Record types the module declares but the subset does not take, with why. */\ntype BadRecords = ReadonlyMap<string, string>;\n\nfunction typeAnnotation(\n r: Reader,\n records: ReadonlySet<string>,\n bad: BadRecords = new Map(),\n): SubsetType {\n const t = r.take();\n if (t.kind === \"string\") {\n // A union of string literals is a string whose values the module restricts; the proof covers every\n // string, which is more than the type admits. `null` or `undefined` in the union is outside.\n while (r.isPunct(\"|\")) {\n r.at++;\n const next = r.take();\n if (next.kind !== \"string\")\n r.fail(\n `a union mixing string literals with ${next.text} (only string literals are read, as string)`,\n next,\n );\n }\n return { kind: \"string\" };\n }\n if (t.kind !== \"ident\") r.fail(`a type that is not a name: ${t.text}`, t);\n const why = bad.get(t.text);\n if (why !== undefined) r.fail(`record type ${t.text} is outside the subset: ${why}`, t);\n if (r.isPunct(\"[\") || r.isPunct(\"<\") || r.isPunct(\"|\") || r.isPunct(\"&\"))\n r.fail(\n `type ${t.text}${r.peek()?.text}… (arrays, generics, unions and intersections are outside the subset)`,\n t,\n );\n if (t.text === \"number\") return { kind: \"int\" };\n if (t.text === \"boolean\") return { kind: \"bool\" };\n if (t.text === \"string\") return { kind: \"string\" };\n if (records.has(t.text)) return { kind: \"record\", name: t.text };\n r.fail(\n `type ${t.text} (the subset has number, boolean, string and the module's own record types)`,\n t,\n );\n}\n\n/** Names a Lean structure declaration generates itself, which a field cannot take. */\nconst structureNames = new Set([\n \"mk\",\n \"rec\",\n \"recOn\",\n \"casesOn\",\n \"noConfusion\",\n \"noConfusionType\",\n \"injEq\",\n]);\n\n/** `interface Name { a: T; b: U }` or `type Name = { ... }` at the reader, after any `export`. */\nfunction recordAt(r: Reader, records: ReadonlySet<string>): RecordType | undefined {\n const start = r.at;\n if (r.isWord(\"export\")) r.at++;\n const alias = r.isWord(\"type\");\n if (!r.isWord(\"interface\") && !alias) {\n r.at = start;\n return undefined;\n }\n r.at++;\n const name = r.ident();\n if (alias) r.expectPunct(\"=\");\n if (r.isWord(\"extends\")) r.fail(\"interface inheritance\", r.peek());\n r.expectPunct(\"{\");\n const fields: Field[] = [];\n while (!r.isPunct(\"}\")) {\n if (r.isWord(\"readonly\")) r.at++;\n const fname = r.ident();\n if (r.isPunct(\"?\")) r.fail(`optional field ${fname}`);\n if (structureNames.has(fname)) r.fail(`field ${fname} takes a name Lean's structures reserve`);\n if (fname === \"__proto__\") r.fail(\"a field named __proto__, which JavaScript treats specially\");\n r.expectPunct(\":\");\n fields.push({ name: fname, type: typeAnnotation(r, records) });\n if (r.isPunct(\";\") || r.isPunct(\",\")) r.at++;\n }\n r.expectPunct(\"}\");\n if (r.isPunct(\";\")) r.at++;\n return { name, fields };\n}\n\n/** Skip a balanced bracket group starting at the reader. */\nfunction skipGroup(r: Reader): void {\n const open = r.take();\n const close = { \"(\": \")\", \"[\": \"]\", \"{\": \"}\" }[open.text];\n let depth = 1;\n while (depth > 0) {\n const t = r.take();\n if (t.kind !== \"punct\") continue;\n if (t.text === open.text) depth++;\n else if (t.text === close) depth--;\n }\n}\n\n/**\n * Whether the `function` token at `i` starts a declaration: at the start of\n * the module or after a statement end, with `export` and `async` allowed in\n * front. A `function` after `=`, `(`, `,`, `return` or `:` is an\n * expression, whose name is its own, not the module's.\n */\nfunction isDeclaration(\n tokens: readonly Token[],\n i: number,\n lineOf: (offset: number) => number,\n): boolean {\n let k = i - 1;\n while (\n tokens[k]?.kind === \"ident\" &&\n [\"async\", \"export\", \"default\"].includes(tokens[k]?.text ?? \"\")\n )\n k--;\n const before = tokens[k];\n if (before === undefined) return true;\n if (before.kind === \"punct\" && (before.text === \";\" || before.text === \"}\")) return true;\n // A line break ends the previous statement (automatic semicolon insertion) unless that statement\n // is unfinished: an operator, an open bracket or a keyword still waiting for its operand.\n if (lineOf(before.end) === lineOf(tokens[i]?.start ?? 0)) return false;\n if (before.kind === \"punct\") return [\")\", \"]\", \"++\", \"--\"].includes(before.text);\n if (before.kind === \"ident\")\n return !\"return typeof void new else case in of do yield await delete instanceof throw export default async\"\n .split(\" \")\n .includes(before.text);\n return true; // a literal\n}\n\n/**\n * Names used as values anywhere in the token stream, with the line of the\n * first use: a bare identifier that is not being called (`f(`), not a\n * property (`o.f`), not an object key (`{ f: … }`) and not the name in its\n * own declaration (`function f`, `const f`). A function used that way may\n * be reassigned, wrapped, aliased or passed on, so what runs under its name\n * is not what its declaration says; one rule covers every assignment form\n * (`f = …`, `f! = …`, `f as T = …`, `[f] = …`, `for (f of …)`) and the\n * aliases besides. Template substitutions are code too and are scanned.\n */\nfunction valueUses(\n tokens: readonly Token[],\n lineOf: (offset: number) => number,\n): Map<string, number> {\n const out = new Map<string, number>();\n const isPunct = (t: Token | undefined, text: string) => t?.kind === \"punct\" && t.text === text;\n tokens.forEach((t, i) => {\n if (t.kind === \"template\") {\n for (const sub of templateSubstitutions(t.text))\n for (const [name, line] of valueUses(tokenize(sub), () => lineOf(t.start)))\n if (!out.has(name)) out.set(name, line);\n return;\n }\n if (t.kind !== \"ident\") return;\n const before = tokens[i - 1];\n const after = tokens[i + 1];\n if (isPunct(after, \"(\")) return; // a call\n if (isPunct(before, \".\") || isPunct(before, \"?.\")) return; // a property of something else\n if (isPunct(after, \":\") && (isPunct(before, \"{\") || isPunct(before, \",\"))) return; // an object key\n if (before?.kind === \"ident\" && [\"function\", \"const\", \"let\", \"var\"].includes(before.text))\n return;\n if (!out.has(t.text)) out.set(t.text, lineOf(t.start));\n });\n return out;\n}\n\n/** The line of the first token matching, template substitutions included (recursively). */\nfunction firstLine(\n tokens: readonly Token[],\n lineOf: (offset: number) => number,\n matches: (t: Token, before: Token | undefined) => boolean,\n): number | undefined {\n for (let i = 0; i < tokens.length; i++) {\n const t = tokens[i] as Token;\n if (t.kind === \"template\") {\n for (const sub of templateSubstitutions(t.text)) {\n let inner: Token[];\n try {\n inner = tokenize(sub);\n } catch (err) {\n if (!(err instanceof TokenizeError)) throw err;\n return lineOf(t.start); // what cannot be read cannot be cleared\n }\n if (firstLine(inner, () => lineOf(t.start), matches) !== undefined) return lineOf(t.start);\n }\n continue;\n }\n if (matches(t, tokens[i - 1])) return lineOf(t.start);\n }\n return undefined;\n}\n\n/** The line of the first `eval` that is not a property of something else, template substitutions included. */\nfunction mentionsEval(\n tokens: readonly Token[],\n lineOf: (offset: number) => number,\n): number | undefined {\n return firstLine(\n tokens,\n lineOf,\n (t, before) =>\n t.kind === \"ident\" &&\n t.text === \"eval\" &&\n !(before?.kind === \"punct\" && (before.text === \".\" || before.text === \"?.\")),\n );\n}\n\n/** Words that start a declaration at module level, where a declaration the reader skips must stop. */\nconst declarationStarts = new Set(\n \"export import function interface type const let var class enum declare async\".split(\" \"),\n);\n\n/** Skip the rest of a declaration the subset does not take: to its `;`, or to the next declaration. */\nfunction skipDeclaration(r: Reader): void {\n while (r.at < r.tokens.length) {\n const t = r.peek() as Token;\n if (t.kind === \"punct\" && t.text === \";\") {\n r.at++;\n return;\n }\n if (t.kind === \"punct\" && [\"(\", \"[\", \"{\"].includes(t.text)) {\n skipGroup(r);\n continue;\n }\n if (t.kind === \"ident\" && declarationStarts.has(t.text)) return;\n r.at++;\n }\n}\n\nclass FunctionParser {\n private readonly r: Reader;\n private readonly records: ReadonlyMap<string, RecordType>;\n private readonly functions: ReadonlySet<string>;\n /** Every function the module declares, in the subset or not, for messages. */\n private readonly declared: ReadonlySet<string>;\n private readonly badRecords: BadRecords;\n readonly signatures = new Map<string, CalleeSignature>();\n constructor(\n r: Reader,\n records: ReadonlyMap<string, RecordType>,\n functions: ReadonlySet<string>,\n badRecords: BadRecords = new Map(),\n declared: ReadonlySet<string> = functions,\n ) {\n this.r = r;\n this.records = records;\n this.functions = functions;\n this.badRecords = badRecords;\n this.declared = declared;\n }\n\n /** `export function name(params): Type` at the reader, up to and including the body's `{`. */\n signature(): Signature {\n const r: Reader = this.r;\n const line = r.line();\n if (r.isWord(\"export\")) r.at++;\n if (r.isWord(\"async\")) r.fail(\"an async function (core functions are synchronous)\");\n if (!r.isWord(\"function\")) r.fail(`a declaration that is not a function: ${r.peek()?.text}`);\n r.at++;\n if (r.isPunct(\"*\")) r.fail(\"a generator function\");\n const name = r.ident();\n if (r.isPunct(\"<\")) r.fail(\"type parameters\");\n const offset = r.peek()?.start ?? -1;\n r.expectPunct(\"(\");\n const params: Param[] = [];\n while (!r.isPunct(\")\")) {\n if (r.isPunct(\"{\") || r.isPunct(\"[\")) r.fail(\"a destructured parameter\");\n if (r.isPunct(\"...\")) r.fail(\"a rest parameter\");\n const pname = r.ident();\n // `this: T` annotates the receiver and is erased; it is no argument the function is called with.\n if (pname === \"this\") r.fail(\"a this parameter (the receiver is not modelled)\");\n if (r.isPunct(\"?\")) r.fail(`optional parameter ${pname}`);\n if (!r.isPunct(\":\")) r.fail(`parameter ${pname} without a type`);\n r.at++;\n const type = typeAnnotation(r, new Set(this.records.keys()), this.badRecords);\n if (r.isPunct(\"=\")) r.fail(`a default value for ${pname}`);\n params.push({ name: pname, type });\n if (r.isPunct(\",\")) r.at++;\n }\n r.expectPunct(\")\");\n if (!r.isPunct(\":\"))\n r.fail(`${name} without a return type (the subset needs it to name the record returned)`);\n r.at++;\n const returns = typeAnnotation(r, new Set(this.records.keys()), this.badRecords);\n r.expectPunct(\"{\");\n return { name, params, returns, line, offset, body: r.at };\n }\n\n /** The function, its body read from where the signature stopped. */\n declaration(sig: Signature): SubsetFunction {\n this.r.at = sig.body;\n const scope = new Map(sig.params.map((p) => [p.name, p.type]));\n const body = this.block(scope, sig.returns);\n // Typing the whole body here: a record literal of no declared type, a field read on an integer or\n // a body of another type than declared are all outside the subset, found now rather than by Lean.\n const actual = this.typeOfExpr(body, scope);\n if (JSON.stringify(actual) !== JSON.stringify(sig.returns))\n this.r.fail(\n `${sig.name} returns a ${actual.kind === \"record\" ? actual.name : actual.kind} but declares ${sig.returns.kind === \"record\" ? sig.returns.name : sig.returns.kind}`,\n );\n return {\n name: sig.name,\n params: sig.params,\n returns: sig.returns,\n body,\n line: sig.line,\n offset: sig.offset,\n };\n }\n\n /**\n * The statements up to the closing `}` as one expression: `const` becomes\n * `let`, `if (c) return a; rest` becomes a conditional, and the last\n * statement must return. Every path ends in a `return`.\n */\n private block(scope: Map<string, SubsetType>, returns: SubsetType): Expr {\n const r: Reader = this.r;\n if (r.isWord(\"const\")) {\n r.at++;\n const name = r.ident();\n // A const shadows a module function throughout its block, from before its own line (the temporal\n // dead zone): a call above it would throw where the reader would see the function. Refused outright.\n if (this.declared.has(name))\n r.fail(`const ${name} shadows the module's function ${name} in its block`);\n if (scope.has(name)) r.fail(`const ${name} redeclares a name already bound here`);\n let annotated: SubsetType | undefined;\n if (r.isPunct(\":\")) {\n r.at++;\n annotated = typeAnnotation(r, new Set(this.records.keys()), this.badRecords);\n }\n r.expectPunct(\"=\");\n const value = this.expression(scope);\n if (r.isPunct(\";\")) r.at++;\n const inner = new Map(scope);\n const inferred = this.typeOfExpr(value, scope);\n if (annotated && JSON.stringify(annotated) !== JSON.stringify(inferred))\n r.fail(\n `const ${name} is annotated ${describe(annotated)} but holds a ${describe(inferred)}`,\n );\n inner.set(name, inferred);\n const body = this.block(inner, returns);\n return { kind: \"let\", name, value, body };\n }\n if (r.isWord(\"if\")) {\n r.at++;\n r.expectPunct(\"(\");\n const test = this.expression(scope);\n r.expectPunct(\")\");\n const then = this.branch(scope, returns);\n let otherwise: Expr;\n if (r.isWord(\"else\")) {\n r.at++;\n otherwise = this.branch(scope, returns);\n if (!r.isPunct(\"}\")) r.fail(\"statements after an if/else that both return\");\n r.at++; // the block's closing brace, as the return path consumes it\n } else otherwise = this.block(scope, returns);\n return { kind: \"cond\", test, ifTrue: then, ifFalse: otherwise };\n }\n if (r.isWord(\"return\")) {\n const value = this.returned(scope);\n if (!r.isPunct(\"}\")) r.fail(\"statements after a return\");\n r.at++;\n return value;\n }\n if (r.isWord(\"let\") || r.isWord(\"var\")) r.fail(\"a mutable binding (use const)\");\n if (r.isWord(\"for\") || r.isWord(\"while\") || r.isWord(\"do\")) r.fail(\"a loop\");\n if (r.isWord(\"throw\")) r.fail(\"throw\");\n if (r.isWord(\"switch\")) r.fail(\"switch\");\n if (r.isWord(\"try\")) r.fail(\"try\");\n if (r.isPunct(\"}\")) r.fail(\"a path that does not return\");\n r.fail(`statement starting with ${r.peek()?.text}`);\n }\n\n /** An `if` branch: `return e;` or `{ ...statements ending in return }`. */\n private branch(scope: Map<string, SubsetType>, returns: SubsetType): Expr {\n const r: Reader = this.r;\n if (r.isPunct(\"{\")) {\n r.at++;\n return this.block(scope, returns);\n }\n if (!r.isWord(\"return\")) r.fail(\"an if branch that does not return\");\n return this.returned(scope);\n }\n\n /** `return e;` at the reader. A line break after `return` makes JavaScript return undefined, so it is refused. */\n private returned(scope: ReadonlyMap<string, SubsetType>): Expr {\n const r: Reader = this.r;\n const keyword = r.take();\n if (r.isPunct(\";\") || r.isPunct(\"}\")) r.fail(\"a return without a value\", keyword);\n if (r.line() !== r.line(keyword))\n r.fail(\n \"a line break after return (JavaScript inserts a semicolon and returns undefined)\",\n keyword,\n );\n const value = this.expression(scope);\n if (r.isPunct(\";\")) r.at++;\n return value;\n }\n\n expression(scope: ReadonlyMap<string, SubsetType>): Expr {\n const r: Reader = this.r;\n const left = this.binary(scope, 0);\n if (r.isPunct(\"?\")) {\n r.at++;\n const then = this.expression(scope);\n r.expectPunct(\":\");\n const otherwise = this.expression(scope);\n return { kind: \"cond\", test: left, ifTrue: then, ifFalse: otherwise };\n }\n return left;\n }\n\n private binary(scope: ReadonlyMap<string, SubsetType>, level: number): Expr {\n if (level >= levels.length) return this.unary(scope);\n let left = this.binary(scope, level + 1);\n const ops = levels[level] as readonly BinaryOp[];\n for (;;) {\n const t = this.r.peek();\n if (t?.kind !== \"punct\" || !ops.includes(t.text as BinaryOp)) {\n if (\n t?.kind === \"punct\" &&\n [\"==\", \"!=\", \"/\", \"%\", \"**\", \"??\", \"<<\", \">>\", \"&\", \"|\", \"^\"].includes(t.text)\n )\n this.r.fail(`the ${t.text} operator`, t);\n return left;\n }\n this.r.at++;\n const right = this.binary(scope, level + 1);\n left = { kind: \"binary\", op: t.text as BinaryOp, left, right };\n }\n }\n\n private unary(scope: ReadonlyMap<string, SubsetType>): Expr {\n const r: Reader = this.r;\n if (r.isPunct(\"!\")) {\n r.at++;\n return { kind: \"not\", operand: this.unary(scope) };\n }\n if (r.isPunct(\"-\")) {\n r.at++;\n const operand = this.unary(scope);\n // A negated literal stays a literal with its sign flipped, so -(-1) is 1, never the text `--1`.\n return operand.kind === \"int\"\n ? {\n kind: \"int\",\n value: operand.value.startsWith(\"-\") ? operand.value.slice(1) : `-${operand.value}`,\n }\n : { kind: \"neg\", operand };\n }\n if (r.isPunct(\"+\")) r.fail(\"unary plus\");\n if (r.isWord(\"typeof\") || r.isWord(\"void\") || r.isWord(\"await\") || r.isWord(\"new\"))\n r.fail(`the ${r.peek()?.text} operator`);\n return this.postfix(scope, this.primary(scope));\n }\n\n private postfix(scope: ReadonlyMap<string, SubsetType>, base: Expr): Expr {\n const r: Reader = this.r;\n let e = base;\n for (;;) {\n if (r.isPunct(\".\")) {\n r.at++;\n const field = r.ident();\n e = { kind: \"field\", object: e, field };\n continue;\n }\n if (r.isPunct(\"?.\")) r.fail(\"optional chaining\");\n if (r.isPunct(\"[\")) r.fail(\"index access\");\n if (r.isPunct(\"(\")) {\n // A binder or local named like a function shadows it: the call is to a number, which throws.\n if (e.kind === \"var\" && scope.has(e.name))\n r.fail(`a call to ${e.name}, which names a value here, not the module's function`);\n if (e.kind !== \"var\" || !this.functions.has(e.name))\n r.fail(\n e.kind !== \"var\"\n ? \"a call to a computed callee\"\n : this.declared.has(e.name)\n ? `a call to ${e.name}, which is outside the subset`\n : `a call to ${e.name}, which this module does not declare`,\n );\n r.at++;\n const args: Expr[] = [];\n while (!r.isPunct(\")\")) {\n args.push(this.expression(scope));\n if (r.isPunct(\",\")) r.at++;\n }\n r.at++;\n e = { kind: \"call\", callee: e.name, args };\n continue;\n }\n if (r.isWord(\"as\") || r.isWord(\"satisfies\")) r.fail(`the ${r.peek()?.text} operator`);\n return e;\n }\n }\n\n private primary(scope: ReadonlyMap<string, SubsetType>): Expr {\n const r: Reader = this.r;\n const t = r.take();\n switch (t.kind) {\n case \"number\":\n if (!/^[0-9](_?[0-9])*$/.test(t.text))\n r.fail(`the numeric literal ${t.text} (integers in decimal only)`, t);\n return { kind: \"int\", value: t.text.replace(/_/g, \"\") };\n case \"string\":\n return { kind: \"string\", value: stringLiteralValue(t.text, r, t) };\n case \"template\":\n r.fail(\"a template literal\", t);\n break;\n case \"regex\":\n r.fail(\"a regular expression\", t);\n break;\n case \"ident\":\n if (t.text === \"true\" || t.text === \"false\")\n return { kind: \"bool\", value: t.text === \"true\" };\n if (t.text === \"null\" || t.text === \"undefined\") r.fail(`${t.text}`, t);\n if (scope.has(t.text) || this.declared.has(t.text)) return { kind: \"var\", name: t.text };\n r.fail(`${t.text}, which is neither a parameter, a const nor a function of this module`, t);\n break;\n case \"punct\":\n if (t.text === \"(\") {\n const e = this.expression(scope);\n r.expectPunct(\")\");\n return e;\n }\n if (t.text === \"{\") return this.record(scope);\n if (t.text === \"[\") r.fail(\"an array literal\", t);\n r.fail(`unexpected ${t.text}`, t);\n break;\n default:\n r.fail(`unexpected ${t.text}`, t);\n }\n }\n\n private record(scope: ReadonlyMap<string, SubsetType>): Expr {\n const r: Reader = this.r;\n const fields: { name: string; value: Expr }[] = [];\n while (!r.isPunct(\"}\")) {\n if (r.isPunct(\"...\")) r.fail(\"spread in a record literal\");\n if (r.isPunct(\"[\")) r.fail(\"a computed key\");\n const t = r.take();\n if (t.kind !== \"ident\") r.fail(`a key that is not a name: ${t.text}`, t);\n if (t.text === \"__proto__\")\n r.fail(\"a __proto__ key, which sets the prototype, not a field\", t);\n if (r.isPunct(\"(\")) r.fail(`a method ${t.text}`, t);\n if (r.isPunct(\":\")) {\n r.at++;\n fields.push({ name: t.text, value: this.expression(scope) });\n } else {\n if (!scope.has(t.text)) r.fail(`shorthand ${t.text} names nothing in scope`, t);\n fields.push({ name: t.text, value: { kind: \"var\", name: t.text } });\n }\n if (r.isPunct(\",\")) r.at++;\n }\n r.at++;\n return { kind: \"record\", fields };\n }\n\n typeOfExpr(e: Expr, scope: ReadonlyMap<string, SubsetType>): SubsetType {\n return typeOf(e, scope, { records: this.records, signatures: this.signatures }, (m) =>\n this.r.fail(m),\n );\n }\n}\n\n/** A type, for messages. */\nfunction describe(t: SubsetType): string {\n return t.kind === \"record\" ? t.name : t.kind;\n}\n\n/** A function's parameters and return type, for typing calls. */\nexport interface CalleeSignature {\n readonly params: readonly Param[];\n readonly returns: SubsetType;\n}\n\n/** What typing an expression needs to know about its module. */\nexport interface TypeContext {\n readonly records: ReadonlyMap<string, RecordType>;\n readonly signatures: ReadonlyMap<string, CalleeSignature>;\n}\n\n/** The type of an expression in a scope; records are matched by their fields' names. */\nexport function typeOf(\n e: Expr,\n scope: ReadonlyMap<string, SubsetType>,\n ctx: TypeContext,\n fail: (message: string) => never,\n): SubsetType {\n switch (e.kind) {\n case \"int\":\n return { kind: \"int\" };\n case \"bool\":\n return { kind: \"bool\" };\n case \"string\":\n return { kind: \"string\" };\n case \"var\": {\n const t = scope.get(e.name);\n if (!t) fail(`${e.name} is not in scope`);\n return t;\n }\n case \"binary\": {\n const l = typeOf(e.left, scope, ctx, fail);\n const r = typeOf(e.right, scope, ctx, fail);\n // `+` joins two strings; every other arithmetic or ordering operator is on integers only\n // (ordering strings compares UTF-16 code units in JavaScript and characters in Lean: not the same).\n if (e.op === \"+\" && l.kind === \"string\" && r.kind === \"string\") return { kind: \"string\" };\n const arithmetic = [\"+\", \"-\", \"*\", \"<\", \"<=\", \">\", \">=\"].includes(e.op);\n if (arithmetic && (l.kind !== \"int\" || r.kind !== \"int\"))\n fail(\n `${e.op} on a ${l.kind} and a ${r.kind} (the subset has it on integers${e.op === \"+\" ? \", and + on two strings\" : \"\"})`,\n );\n if ((e.op === \"&&\" || e.op === \"||\") && (l.kind !== \"bool\" || r.kind !== \"bool\"))\n fail(`${e.op} on a ${l.kind} and a ${r.kind} (the subset has it on booleans)`);\n if ((e.op === \"===\" || e.op === \"!==\") && JSON.stringify(l) !== JSON.stringify(r))\n fail(`${e.op} between a ${l.kind} and a ${r.kind}`);\n if ((e.op === \"===\" || e.op === \"!==\") && l.kind === \"record\")\n fail(`${e.op} on records compares references in JavaScript; compare their fields instead`);\n return [\"+\", \"-\", \"*\"].includes(e.op) ? { kind: \"int\" } : { kind: \"bool\" };\n }\n case \"neg\": {\n const t = typeOf(e.operand, scope, ctx, fail);\n if (t.kind !== \"int\") fail(`unary minus on a ${t.kind}`);\n return { kind: \"int\" };\n }\n case \"not\": {\n const t = typeOf(e.operand, scope, ctx, fail);\n if (t.kind !== \"bool\") fail(`! on a ${t.kind}`);\n return { kind: \"bool\" };\n }\n case \"cond\": {\n const test = typeOf(e.test, scope, ctx, fail);\n if (test.kind !== \"bool\")\n fail(\n `a condition that is a ${describe(test)} (truthiness is not in the subset; compare it)`,\n );\n const a = typeOf(e.ifTrue, scope, ctx, fail);\n const b = typeOf(e.ifFalse, scope, ctx, fail);\n if (JSON.stringify(a) !== JSON.stringify(b))\n fail(\"the branches of a conditional have different types\");\n return a;\n }\n case \"let\":\n return typeOf(\n e.body,\n new Map([...scope, [e.name, typeOf(e.value, scope, ctx, fail)]]),\n ctx,\n fail,\n );\n case \"call\": {\n const sig = ctx.signatures.get(e.callee);\n if (!sig) fail(`the signature of ${e.callee} is not known`);\n if (sig.params.length !== e.args.length)\n fail(`${e.callee} takes ${sig.params.length} argument(s), called with ${e.args.length}`);\n e.args.forEach((a, i) => {\n const want = sig.params[i]?.type as SubsetType;\n const got = typeOf(a, scope, ctx, fail);\n if (JSON.stringify(want) !== JSON.stringify(got))\n fail(`argument ${i + 1} of ${e.callee} is a ${got.kind}, not the ${want.kind} it takes`);\n });\n return sig.returns;\n }\n case \"field\": {\n const o = typeOf(e.object, scope, ctx, fail);\n if (o.kind !== \"record\") fail(`field ${e.field} read from a ${o.kind}`);\n const f = ctx.records.get(o.name)?.fields.find((x) => x.name === e.field);\n if (!f) fail(`${o.name} has no field ${e.field}`);\n return f.type;\n }\n case \"record\": {\n // The record types whose fields are exactly these names, then those whose field types the values fit.\n const names = e.fields\n .map((f) => f.name)\n .sort()\n .join(\",\");\n const byNames = [...ctx.records.values()].filter(\n (rec) =>\n rec.fields\n .map((f) => f.name)\n .sort()\n .join(\",\") === names,\n );\n if (byNames.length === 0)\n fail(`a record literal with fields ${names} matches no declared record type`);\n const types = new Map(e.fields.map((f) => [f.name, typeOf(f.value, scope, ctx, fail)]));\n const fits = byNames.filter((rec) =>\n rec.fields.every((f) => JSON.stringify(types.get(f.name)) === JSON.stringify(f.type)),\n );\n if (fits.length === 0) {\n const rec = byNames[0] as RecordType;\n const off = rec.fields.find(\n (f) => JSON.stringify(types.get(f.name)) !== JSON.stringify(f.type),\n ) as Field;\n fail(\n `field ${off.name} of a ${rec.name} literal holds a ${describe(types.get(off.name) as SubsetType)}, not a ${describe(off.type)}`,\n );\n }\n if (fits.length > 1)\n fail(\n `a record literal with fields ${names} matches ${fits.map((r) => r.name).join(\" and \")} alike`,\n );\n return { kind: \"record\", name: (fits[0] as RecordType).name };\n }\n }\n}\n\n/**\n * One TypeScript expression (a Lemma atom or equation side, say) in a\n * scope of typed names, over a module already read. The whole text must\n * be the expression.\n */\nexport function readExpression(\n text: string,\n scope: ReadonlyMap<string, SubsetType>,\n module: SubsetModule,\n): Expr {\n const r = new Reader(tokenize(text), () => 0);\n const records = new Map(module.records.map((rec) => [rec.name, rec]));\n const inSubset = new Set(module.functions.map((f) => f.name));\n const declared = new Set([...inSubset, ...module.outside.map((o) => o.name)]);\n const parser = new FunctionParser(r, records, inSubset, new Map(), declared);\n for (const f of module.functions)\n parser.signatures.set(f.name, { params: f.params, returns: f.returns });\n const e = parser.expression(scope);\n if (r.at < r.tokens.length) r.fail(`unexpected ${r.peek()?.text} after the expression`);\n return e;\n}\n\n/** The functions an expression calls. */\nfunction callees(e: Expr, out = new Set<string>()): Set<string> {\n switch (e.kind) {\n case \"int\":\n case \"bool\":\n case \"string\":\n case \"var\":\n return out;\n case \"neg\":\n case \"not\":\n return callees(e.operand, out);\n case \"binary\":\n callees(e.left, out);\n return callees(e.right, out);\n case \"cond\":\n callees(e.test, out);\n callees(e.ifTrue, out);\n return callees(e.ifFalse, out);\n case \"call\":\n out.add(e.callee);\n for (const a of e.args) callees(a, out);\n return out;\n case \"field\":\n return callees(e.object, out);\n case \"record\":\n for (const f of e.fields) callees(f.value, out);\n return out;\n case \"let\":\n callees(e.value, out);\n return callees(e.body, out);\n }\n}\n\n/**\n * Read a module: its record types, every function the subset takes (in\n * source order, so callees come before callers) and, for the others, why\n * not. A function calling one outside the subset is outside it too. The\n * names given are what the caller cares about; one the module does not\n * declare at its top level is reported among the others, not thrown.\n */\nexport function readSubset(source: string, functions?: readonly string[]): SubsetModule {\n // Every JavaScript line terminator counts (LF, CR, CRLF as one, U+2028, U+2029): a return\n // followed by any of them returns undefined.\n const lineOf = (offset: number): number => {\n let line = 1;\n for (let i = 0; i < offset && i < source.length; i++) {\n const c = source[i];\n if (c === \"\\r\") {\n line++;\n if (source[i + 1] === \"\\n\") i++;\n } else if (c === \"\\n\" || c === \"\\u2028\" || c === \"\\u2029\") line++;\n }\n return line;\n };\n let tokens: Token[];\n try {\n tokens = tokenize(source);\n } catch (err) {\n // Source the scanner cannot read is source the reader cannot trust: every name asked for is outside.\n if (!(err instanceof TokenizeError)) throw err;\n return {\n records: [],\n functions: [],\n outside: (functions ?? []).map((name) => ({\n name,\n line: 0,\n message: `the module could not be tokenized: ${err.message}`,\n })),\n };\n }\n const r = new Reader(tokens, lineOf);\n // Pass 1: record types, and where every function declaration starts.\n const records = new Map<string, RecordType>();\n const badRecords = new Map<string, string>();\n const declared = new Set<string>();\n const assigned = new Map<string, number>();\n const starts: number[] = [];\n while (r.at < tokens.length) {\n const t = r.peek() as Token;\n if (t.kind === \"ident\" && t.text === \"import\") {\n // An import (type-only or not) declares nothing the subset reads.\n r.at++;\n skipDeclaration(r);\n continue;\n }\n if (\n t.kind === \"ident\" &&\n (t.text === \"interface\" || t.text === \"type\" || t.text === \"export\")\n ) {\n const save = r.at;\n try {\n const rec = recordAt(r, new Set(records.keys()));\n if (rec) {\n records.set(rec.name, rec);\n continue;\n }\n } catch (err) {\n // A record type the subset does not take: noted, so a function using it says why, and skipped.\n if (!(err instanceof OutsideSubset)) throw err;\n r.at = save;\n if (r.isWord(\"export\")) r.at++;\n r.at++;\n // `export type { A }` and friends name no record; a named one is noted so its users say why.\n if (r.peek()?.kind === \"ident\") badRecords.set(r.ident(), err.message);\n skipDeclaration(r);\n continue;\n }\n r.at = save;\n }\n if (t.kind === \"ident\" && t.text === \"function\" && isDeclaration(tokens, r.at, lineOf)) {\n // `function* f` is a generator: its name is recorded so the signature pass can refuse it by name.\n const name = r.isPunct(\"*\", 1) ? r.peek(2) : r.peek(1);\n if (name?.kind === \"ident\") declared.add(name.text);\n // The declaration starts at its modifiers, which the second pass reads (and refuses, for async).\n let start = r.at;\n if (r.isWord(\"async\", start - r.at - 1)) start--;\n if (r.isWord(\"export\", start - r.at - 1)) start--;\n starts.push(start);\n r.at++;\n continue;\n }\n if (t.kind === \"punct\" && [\"(\", \"[\", \"{\"].includes(t.text)) {\n skipGroup(r);\n continue;\n }\n r.at++;\n }\n // A declared function used as a value anywhere in the module (assigned to, aliased, passed on) may not\n // be what its declaration says when called; such a function, and its callers, are outside.\n for (const [name, line] of valueUses(tokens, lineOf)) assigned.set(name, line);\n const outside = new Map<string, OutsideFunction>();\n // A name asked for that is no module-level declaration (inside a namespace, say) is reported, not thrown.\n for (const name of functions ?? [])\n if (!declared.has(name))\n outside.set(name, {\n name,\n line: 0,\n message: `the module declares no function ${name} at its top level`,\n });\n // A direct eval can rebind any declaration of the module without naming it, so any mention of `eval`\n // that is not a property of something else (`globalThis.eval` is indirect, and cannot) puts the whole\n // module outside: `eval(…)`, `(eval)(…)`, inside a template substitution alike.\n const evalLine = mentionsEval(tokens, lineOf);\n if (evalLine !== undefined)\n for (const name of declared)\n outside.set(name, {\n name,\n line: evalLine,\n message: \"the module mentions eval directly, which can rebind any of its declarations\",\n });\n // An identifier escape (`\\u0066` for `f`) spells a name the scans above cannot match: nothing is trusted.\n const escapeLine = firstLine(tokens, lineOf, (t) => t.kind === \"punct\" && t.text === \"\\\\\");\n if (escapeLine !== undefined)\n for (const name of declared)\n if (!outside.has(name))\n outside.set(name, {\n name,\n line: escapeLine,\n message:\n \"the module uses an identifier escape sequence (\\\\u…), so its names cannot be matched by spelling\",\n });\n for (const [name, line] of assigned)\n if (declared.has(name) && !outside.has(name))\n outside.set(name, {\n name,\n line,\n message: `${name} is used as a value in the module (not only called), so what runs under its name may not be its declaration`,\n });\n // Pass 2: signatures, so every function's return type is known before any body is read.\n const parser = new FunctionParser(r, records, declared, badRecords);\n const signatures: Signature[] = [];\n for (const start of starts) {\n r.at = start;\n try {\n const sig = parser.signature();\n // Callers of a reassigned function still type-check against its declaration; they are then outside with it.\n parser.signatures.set(sig.name, { params: sig.params, returns: sig.returns });\n if (!outside.has(sig.name)) signatures.push(sig);\n } catch (err) {\n if (!(err instanceof OutsideSubset)) throw err;\n // The name after `function`, past a generator's `*`.\n const head = tokens.slice(start, start + 5);\n const fnAt = head.findIndex((t) => t.kind === \"ident\" && t.text === \"function\");\n const after = head[fnAt + 1]?.text === \"*\" ? head[fnAt + 2] : head[fnAt + 1];\n const name = after?.kind === \"ident\" ? after.text : undefined;\n if (name) outside.set(name, { name, line: err.line, message: err.message });\n }\n }\n // Pass 3: bodies.\n const read = new Map<string, SubsetFunction>();\n for (const sig of signatures) {\n try {\n read.set(sig.name, parser.declaration(sig));\n } catch (err) {\n if (!(err instanceof OutsideSubset)) throw err;\n outside.set(sig.name, { name: sig.name, line: err.line, message: err.message });\n }\n }\n // A caller of a function outside the subset is outside it too, however many steps away.\n for (let changed = true; changed; ) {\n changed = false;\n for (const [name, fn] of read) {\n const bad = [...callees(fn.body)].find((c) => outside.has(c));\n if (bad === undefined) continue;\n read.delete(name);\n outside.set(name, {\n name,\n line: fn.line,\n message: `calls ${bad}, which is outside the subset: ${outside.get(bad)?.message}`,\n });\n changed = true;\n }\n }\n // Recursion is not in the subset yet: a function reaching itself through its callees is outside, and so are its callers.\n const reaches = (from: string, target: string, seen = new Set<string>()): boolean => {\n const fn = read.get(from);\n if (!fn) return false;\n for (const c of callees(fn.body)) {\n if (c === target) return true;\n if (!seen.has(c)) {\n seen.add(c);\n if (reaches(c, target, seen)) return true;\n }\n }\n return false;\n };\n for (const [name, fn] of [...read])\n if (reaches(name, name)) {\n read.delete(name);\n outside.set(name, {\n name,\n line: fn.line,\n message: `${name} is recursive (it reaches itself through its calls); recursion is not in the subset yet`,\n });\n }\n for (let changed = true; changed; ) {\n changed = false;\n for (const [name, fn] of read) {\n const bad = [...callees(fn.body)].find((c) => outside.has(c));\n if (bad === undefined) continue;\n read.delete(name);\n outside.set(name, {\n name,\n line: fn.line,\n message: `calls ${bad}, which is outside the subset: ${outside.get(bad)?.message}`,\n });\n changed = true;\n }\n }\n // Callees before callers, whatever the source order: Lean needs a definition before its use.\n const ordered: SubsetFunction[] = [];\n const placed = new Set<string>();\n while (ordered.length < read.size)\n for (const [name, fn] of read)\n if (!placed.has(name) && [...callees(fn.body)].every((c) => placed.has(c))) {\n ordered.push(fn);\n placed.add(name);\n }\n return { records: [...records.values()], functions: ordered, outside: [...outside.values()] };\n}\n","/**\n * Lean 4 for a module in the subset and the Lemma properties on it. The\n * module's record types become structures, its functions definitions over\n * `Int` and `Bool`, each property a theorem whose statement is the\n * property's formula over its binders, with the binders' domains, guards\n * and preconditions as hypotheses. Booleans stay `Bool` in terms, as in\n * TypeScript, and become propositions with `= true` where a formula needs\n * one; comparisons are `decide`d. Every theorem is closed by one tactic\n * script, so what Lean checks is the statement, not a hand proof.\n */\n\nimport type { Binder, Formula, NamedProperty, Property } from \"@eutaxy/spec\";\nimport {\n type Expr,\n hasLoneSurrogate,\n OutsideSubset,\n type RecordType,\n readExpression,\n type SubsetFunction,\n type SubsetModule,\n type SubsetType,\n type TypeContext,\n typeOf,\n} from \"./subset.ts\";\n\n/**\n * TypeScript names as Lean identifiers that can clash with nothing Lean\n * defines and not with each other: functions get `f_`, record types `R_`,\n * variables `v_`, theorems `t_`. The schemes differ in their first letter,\n * so no two names from different kinds coincide whatever the author\n * wrote (`ts_f` and `f_` would, under suffixing), and Lean's prelude has\n * no names of these shapes, so a function called `decide` or a parameter\n * called `max` stays what the author meant.\n */\nexport const ident = {\n fn: (name: string) => quote(`f_${name}`),\n record: (name: string) => quote(`R_${name}`),\n variable: (name: string) => quote(`v_${name}`),\n // Fields keep their names, which may be Lean keywords: those are quoted.\n field: (name: string) => (leanKeywords.has(name) ? `«${name}»` : quote(name)),\n};\n\n/** Lean's keywords, which a field name may coincide with. */\nconst leanKeywords = new Set(\n \"at by calc def deriving do else end example export extends from fun have if import in inductive instance lemma let macro match mutual namespace open private protected return section set_option show structure syntax termination_by then theorem universe variable where with abbrev axiom class opaque partial noncomputable unsafe nomatch nofun omit include local scoped attribute initialize builtin_initialize elab notation infix infixl infixr prefix postfix declare_syntax_cat macro_rules elab_rules syntax_rules suffices obtain exists forall Type Prop Sort true false fun\".split(\n \" \",\n ),\n);\n\nfunction quote(name: string): string {\n return /^[A-Za-z_][A-Za-z0-9_]*$/.test(name) ? name : `«${name}»`;\n}\n\nfunction leanType(t: SubsetType): string {\n switch (t.kind) {\n case \"int\":\n return \"Int\";\n case \"bool\":\n return \"Bool\";\n case \"string\":\n return \"String\";\n case \"record\":\n return ident.record(t.name);\n }\n}\n\nexport function emitRecord(r: RecordType): string {\n return [\n `structure ${ident.record(r.name)} where`,\n ...r.fields.map((f) => ` ${ident.field(f.name)} : ${leanType(f.type)}`),\n \" deriving Repr, DecidableEq\",\n ].join(\"\\n\");\n}\n\ninterface Env {\n readonly module: SubsetModule;\n readonly ctx: TypeContext;\n}\n\nfunction env(module: SubsetModule): Env {\n return {\n module,\n ctx: {\n records: new Map(module.records.map((r) => [r.name, r])),\n signatures: new Map(\n module.functions.map((f) => [f.name, { params: f.params, returns: f.returns }]),\n ),\n },\n };\n}\n\nconst fail: (message: string) => never = (message) => {\n throw new OutsideSubset(message, 0);\n};\n\n/** A term of the expression's TypeScript type: `Int`, `Bool` or a structure. */\nexport function term(e: Expr, scope: ReadonlyMap<string, SubsetType>, env: Env): string {\n const t = (x: Expr) => term(x, scope, env);\n switch (e.kind) {\n case \"int\":\n return `(${e.value} : Int)`;\n case \"bool\":\n return e.value ? \"true\" : \"false\";\n case \"string\":\n return leanString(e.value);\n case \"var\":\n return ident.variable(e.name);\n case \"neg\":\n return `(-${t(e.operand)})`;\n case \"not\":\n return `(!${t(e.operand)})`;\n case \"binary\":\n switch (e.op) {\n case \"+\": {\n const lt = typeOf(e.left, scope, env.ctx, fail);\n return `(${t(e.left)} ${lt.kind === \"string\" ? \"++\" : \"+\"} ${t(e.right)})`;\n }\n case \"-\":\n case \"*\":\n return `(${t(e.left)} ${e.op} ${t(e.right)})`;\n case \"<\":\n case \">\":\n return `(decide (${t(e.left)} ${e.op} ${t(e.right)}))`;\n case \"<=\":\n return `(decide (${t(e.left)} ≤ ${t(e.right)}))`;\n case \">=\":\n return `(decide (${t(e.left)} ≥ ${t(e.right)}))`;\n case \"===\":\n case \"!==\": {\n // === on objects compares references in JavaScript; Lean's = would compare the fields.\n const lt = typeOf(e.left, scope, env.ctx, fail);\n if (lt.kind === \"record\")\n fail(\n `${e.op} on records compares references in JavaScript; compare their fields instead`,\n );\n return `(decide (${t(e.left)} ${e.op === \"===\" ? \"=\" : \"≠\"} ${t(e.right)}))`;\n }\n case \"&&\":\n return `(${t(e.left)} && ${t(e.right)})`;\n case \"||\":\n return `(${t(e.left)} || ${t(e.right)})`;\n }\n break;\n case \"cond\":\n return `(if ${t(e.test)} = true then ${t(e.ifTrue)} else ${t(e.ifFalse)})`;\n case \"call\":\n return `(${ident.fn(e.callee)}${e.args.map((a) => ` ${t(a)}`).join(\"\")})`;\n case \"field\":\n return `${t(e.object)}.${ident.field(e.field)}`;\n case \"record\": {\n const type = typeOf(e, scope, env.ctx, fail);\n const name =\n type.kind === \"record\"\n ? ident.record(type.name)\n : fail(\"a record literal of no record type\");\n return `({ ${e.fields.map((f) => `${ident.field(f.name)} := ${t(f.value)}`).join(\", \")} } : ${name})`;\n }\n case \"let\": {\n const inner = new Map(scope);\n inner.set(e.name, typeOf(e.value, scope, env.ctx, fail));\n return `(let ${ident.variable(e.name)} := ${t(e.value)}; ${term(e.body, inner, env)})`;\n }\n }\n}\n\nexport function emitFunction(f: SubsetFunction, module: SubsetModule): string {\n const e = env(module);\n const scope = new Map(f.params.map((p) => [p.name, p.type]));\n const params = f.params.map((p) => `(${ident.variable(p.name)} : ${leanType(p.type)})`).join(\" \");\n return `def ${ident.fn(f.name)} ${params} : ${leanType(f.returns)} :=\\n ${term(f.body, scope, e)}`;\n}\n\n/** The Lean type a binder ranges over, or `OutsideSubset`. */\nfunction binderType(b: Binder): SubsetType {\n switch (b.domain) {\n case \"int\":\n case \"nat\":\n return { kind: \"int\" };\n case \"boolean\":\n return { kind: \"bool\" };\n case \"bigint\":\n // A BigInt passed to a function over number throws on the first mixed operation in JavaScript.\n fail(\n `binder ${b.name} over bigint: the subset has no bigint, and a bigint argument to a number function throws`,\n );\n break;\n case \"number\":\n fail(`binder ${b.name} over number: the engine models integers, not doubles`);\n break;\n case \"string\":\n return { kind: \"string\" };\n }\n}\n\n/** The hypotheses a binder's domain and guard add. */\nfunction binderHypotheses(b: Binder): string[] {\n const out: string[] = [];\n const x = ident.variable(b.name);\n if (b.domain === \"nat\") out.push(`0 ≤ ${x}`);\n const g = b.guard;\n if (!g) return out;\n if (g.kind === \"regex\")\n fail(`a regex guard on ${b.name}: the engine does not model regular expressions`);\n const literal = (v: string) => v.replace(/_/g, \"\").replace(/n$/, \"\");\n if (!g.lower.value.endsWith(\"∞\"))\n out.push(`(${literal(g.lower.value)} : Int) ${g.lower.inclusive ? \"≤\" : \"<\"} ${x}`);\n if (!g.upper.value.endsWith(\"∞\"))\n out.push(`${x} ${g.upper.inclusive ? \"≤\" : \"<\"} (${literal(g.upper.value)} : Int)`);\n return out;\n}\n\n/** A formula as a proposition. */\nfunction prop(f: Formula, scope: ReadonlyMap<string, SubsetType>, e: Env): string {\n const p = (x: Formula) => prop(x, scope, e);\n const expr = (text: string) => readExpression(text, scope, e.module);\n switch (f.kind) {\n case \"atom\": {\n const x = expr(f.text);\n const t = typeOf(x, scope, e.ctx, fail);\n if (t.kind !== \"bool\") fail(`atom ${f.text.trim()} is not boolean`);\n return `(${term(x, scope, e)} = true)`;\n }\n case \"equation\": {\n const l = expr(f.left);\n const r = expr(f.right);\n const lt = typeOf(l, scope, e.ctx, fail);\n const rt = typeOf(r, scope, e.ctx, fail);\n if (leanType(lt) !== leanType(rt))\n fail(`${f.left.trim()} and ${f.right.trim()} have different types`);\n if (lt.kind === \"record\")\n fail(\n `${f.left.trim()} ≡ ${f.right.trim()} compares records: SameValue on objects is reference identity in JavaScript; compare their fields instead`,\n );\n if (lt.kind === \"int\")\n fail(\n `${f.left.trim()} ≡ ${f.right.trim()} compares numbers by SameValue, which tells -0 from 0; the integer model does not, so use === for numeric equality`,\n );\n return `(${term(l, scope, e)} ${f.negated ? \"≠\" : \"=\"} ${term(r, scope, e)})`;\n }\n case \"not\":\n return `(¬ ${p(f.operand)})`;\n case \"and\":\n return `(${f.operands.map(p).join(\" ∧ \")})`;\n case \"or\":\n return `(${f.operands.map(p).join(\" ∨ \")})`;\n case \"implies\":\n return `(${[...f.antecedents, f.consequent].map(p).join(\" → \")})`;\n case \"iff\":\n return `(${p(f.left)} ↔ ${p(f.right)})`;\n }\n}\n\n/** The proposition a property claims: binders universally quantified, hypotheses in front. */\nexport function statement(property: Property, module: SubsetModule): string {\n return stated(property, module).text;\n}\n\n/** The statement and how many hypotheses stand before the claim (the tactic script introduces them by name). */\nexport function stated(\n property: Property,\n module: SubsetModule,\n): { readonly text: string; readonly hypotheses: number } {\n const e = env(module);\n const scope = new Map(property.binders.map((b) => [b.name, binderType(b)]));\n const binders = property.binders\n .map((b) => `(${ident.variable(b.name)} : ${leanType(binderType(b))})`)\n .join(\" \");\n const hyps = [\n ...property.binders.flatMap(binderHypotheses),\n ...property.requires.map((r) => prop(r, scope, e)),\n ];\n const claim = prop(property.claim, scope, e);\n return {\n text: `∀ ${binders},\\n ${[...hyps, claim].join(\" →\\n \")}`,\n hypotheses: hyps.length,\n };\n}\n\n/**\n * The tactic script every theorem is closed by. Booleans become\n * propositions first, while the `Decidable` instances in the statement\n * still match their propositions (unfolding under `decide` first leaves\n * them stale and stops `simp`); Bool binders are cased, so boolean claims\n * are decided by enumeration; then the module's definitions unfold, each\n * conditional splits, and linear integer arithmetic (`omega`) closes what\n * remains. Nothing here is specific to a property; what Lean checks is\n * the statement.\n */\nexport function tactics(module: SubsetModule, property: Property, hypotheses: number): string {\n const defs = module.functions.map((f) => ident.fn(f.name)).join(\", \");\n const names = property.binders.map((b) => ident.variable(b.name));\n const hyps = Array.from({ length: hypotheses }, (_, i) => `h${i}_`);\n const bools = property.binders\n .filter((b) => b.domain === \"boolean\")\n .map((b) => ident.variable(b.name));\n return [\n ` intro ${[...names, ...hyps].join(\" \")}`,\n ...(bools.length > 0 ? [` ${bools.map((b) => `cases ${b}`).join(\" <;> \")}`] : []),\n \" all_goals (try simp_all)\",\n ` all_goals (try simp only [${defs}] at *)`,\n \" all_goals (repeat' (split <;> simp_all))\",\n \" all_goals (try simp_all)\",\n \" all_goals (first | decide | trivial | omega)\",\n ].join(\"\\n\");\n}\n\n/** A Lean-safe theorem name: unique by position, readable by the function's and property's names. */\nexport function theoremName(index: number, fn: string, property: string): string {\n return `t${index}_${fn}_${property}`.replace(/[^A-Za-z0-9_]/g, \"_\");\n}\n\nexport interface EmittedTheorem {\n readonly function: string;\n readonly property: string;\n readonly name: string;\n /** 1-based lines of the theorem in the emitted file, inclusive. */\n readonly from: number;\n readonly to: number;\n}\n\nexport interface Emitted {\n readonly source: string;\n readonly theorems: readonly EmittedTheorem[];\n /** Properties the emitter could not state, with why. */\n readonly skipped: readonly {\n readonly function: string;\n readonly property: string;\n readonly reason: string;\n }[];\n}\n\n/** The whole file: structures, definitions, one theorem per property, then any extra lines (translation checks). */\nexport function emitModule(\n module: SubsetModule,\n properties: readonly { readonly function: string; readonly property: NamedProperty }[],\n extra: readonly string[] = [],\n): Emitted {\n const parts: string[] = [\n \"-- Generated by Eutaxy's first-party engine from the annotated module; the theorems are its properties.\",\n \"set_option linter.unusedSimpArgs false\",\n ...module.records.map(emitRecord),\n ...module.functions.map((f) => emitFunction(f, module)),\n ];\n const theorems: EmittedTheorem[] = [];\n const skipped: Emitted[\"skipped\"][number][] = [];\n for (const { function: fn, property } of properties) {\n let body: { text: string; hypotheses: number };\n try {\n body = stated(property.property, module);\n } catch (err) {\n if (!(err instanceof OutsideSubset)) throw err;\n skipped.push({ function: fn, property: property.name, reason: err.message });\n continue;\n }\n const name = theoremName(theorems.length + skipped.length, fn, property.name);\n const text = `theorem ${name} :\\n ${body.text} := by\\n${tactics(module, property.property, body.hypotheses)}`;\n const from = parts.join(\"\\n\\n\").split(\"\\n\").length + 2;\n parts.push(text);\n theorems.push({\n function: fn,\n property: property.name,\n name,\n from,\n to: from + text.split(\"\\n\").length - 1,\n });\n }\n parts.push(...extra);\n return { source: `${parts.join(\"\\n\\n\")}\\n`, theorems, skipped };\n}\n\n/**\n * A JavaScript string as a Lean string literal: `\"` and `\\` escaped, control\n * characters as `\\xHH`, everything else written as it is (Lean source is\n * UTF-8). A lone surrogate has no Lean character and is refused.\n */\nexport function leanString(value: string): string {\n if (hasLoneSurrogate(value))\n fail(\"a string with a lone surrogate, which Lean's strings cannot hold\");\n let out = '\"';\n for (const c of value) {\n const code = c.codePointAt(0) as number;\n if (c === '\"') out += '\\\\\"';\n else if (c === \"\\\\\") out += \"\\\\\\\\\";\n else if (code < 0x20 || code === 0x7f) out += `\\\\x${code.toString(16).padStart(2, \"0\")}`;\n else out += c;\n }\n return `${out}\"`;\n}\n\n/** A TypeScript value of a subset type as a Lean term, for translation checks. */\nexport function value(v: unknown, t: SubsetType, module: SubsetModule): string {\n switch (t.kind) {\n case \"int\":\n if (typeof v !== \"number\" || !Number.isInteger(v)) fail(`${String(v)} is not an integer`);\n return `(${v} : Int)`;\n case \"bool\":\n if (typeof v !== \"boolean\") fail(`${String(v)} is not a boolean`);\n return v ? \"true\" : \"false\";\n case \"string\":\n if (typeof v !== \"string\") fail(`${String(v)} is not a string`);\n return leanString(v);\n case \"record\": {\n const rec = module.records.find((r) => r.name === t.name) ?? fail(`no record ${t.name}`);\n if (typeof v !== \"object\" || v === null) fail(`${String(v)} is not a record`);\n const o = v as Record<string, unknown>;\n const extra = Object.keys(o).filter((k) => !rec.fields.some((f) => f.name === k));\n if (extra.length > 0) fail(`${t.name} value has unexpected fields ${extra.join(\", \")}`);\n return `({ ${rec.fields.map((f) => `${ident.field(f.name)} := ${value(o[f.name], f.type, module)}`).join(\", \")} } : ${ident.record(t.name)})`;\n }\n }\n}\n","/**\n * Running Lean over a process boundary. The engine is pinned to one Lean\n * release: `elan` (Lean's toolchain manager) is asked for it by name, and a\n * `lean` found without `elan` must report that version. Nothing is ever\n * downloaded during a check; a missing toolchain is `unavailable`, with the\n * command that installs it. Diagnostics come back as `file:line:col:\n * severity: message` lines, which the engine maps to theorems.\n */\n\nimport { spawn } from \"node:child_process\";\nimport { mkdtempSync, rmSync, writeFileSync } from \"node:fs\";\nimport { homedir, tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\n\n/** The Lean release the engine's contract corpus is checked against. */\nexport const leanToolchain = \"leanprover/lean4:v4.35.0\";\nexport const leanVersion = \"4.35.0\";\n/** How to put the pinned toolchain on this machine. */\nexport const installHint = `install elan (https://elan.lean-lang.org) and run: elan toolchain install ${leanToolchain}`;\n\nexport interface LeanRun {\n readonly code: number | null;\n readonly stdout: string;\n readonly stderr: string;\n readonly timedOut: boolean;\n}\n\nexport interface LeanDiagnostic {\n readonly line: number;\n readonly column: number;\n readonly severity: \"error\" | \"warning\" | \"info\";\n readonly message: string;\n}\n\nexport interface LeanToolchain {\n /** The `lean` executable to run, with the arguments that select the pinned toolchain. */\n readonly command: string;\n readonly args: readonly string[];\n readonly version: string;\n}\n\nfunction run(\n command: string,\n args: readonly string[],\n options: { readonly cwd?: string; readonly timeoutMs: number },\n): Promise<LeanRun> {\n return new Promise((resolve) => {\n let child: ReturnType<typeof spawn>;\n try {\n // Its own process group, so a timeout kills `lean` under `elan run`, not just elan.\n child = spawn(command, args, {\n cwd: options.cwd,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n detached: process.platform !== \"win32\",\n });\n } catch (err) {\n resolve({ code: null, stdout: \"\", stderr: String(err), timedOut: false });\n return;\n }\n let stdout = \"\";\n let stderr = \"\";\n let timedOut = false;\n const timer = setTimeout(() => {\n timedOut = true;\n try {\n if (process.platform !== \"win32\" && child.pid !== undefined)\n process.kill(-child.pid, \"SIGKILL\");\n else child.kill(\"SIGKILL\");\n } catch {\n child.kill(\"SIGKILL\");\n }\n }, options.timeoutMs);\n child.stdout?.on(\"data\", (d: Buffer) => {\n stdout += d.toString();\n });\n child.stderr?.on(\"data\", (d: Buffer) => {\n stderr += d.toString();\n });\n child.on(\"error\", (err) => {\n clearTimeout(timer);\n resolve({ code: null, stdout, stderr: `${stderr}${String(err)}`, timedOut });\n });\n child.on(\"close\", (code) => {\n clearTimeout(timer);\n resolve({ code, stdout, stderr, timedOut });\n });\n });\n}\n\n/** Candidates for the `elan` and `lean` executables: the PATH, then elan's default home. */\nfunction candidates(name: string): string[] {\n const home = process.env[\"ELAN_HOME\"] ?? join(homedir(), \".elan\");\n return [name, join(home, \"bin\", name)];\n}\n\n/**\n * The pinned toolchain if it is installed: through `elan run <toolchain>`\n * when elan is present (and only when it already has the toolchain, so\n * nothing is downloaded), else a bare `lean` of exactly that version.\n */\nexport async function findLean(): Promise<LeanToolchain | { readonly unavailable: string }> {\n for (const elan of candidates(\"elan\")) {\n const list = await run(elan, [\"toolchain\", \"list\"], { timeoutMs: 20_000 });\n if (list.code !== 0) continue;\n if (!list.stdout.split(\"\\n\").some((l) => l.trim().split(\" \")[0] === leanToolchain))\n return {\n unavailable: `elan has no ${leanToolchain}; run: elan toolchain install ${leanToolchain}`,\n };\n return { command: elan, args: [\"run\", leanToolchain, \"lean\"], version: leanVersion };\n }\n for (const lean of candidates(\"lean\")) {\n const v = await run(lean, [\"--version\"], { timeoutMs: 20_000 });\n if (v.code !== 0) continue;\n const m = /Lean \\(version ([^,]+),/.exec(v.stdout);\n if (m?.[1] === leanVersion) return { command: lean, args: [], version: leanVersion };\n return {\n unavailable: `lean ${m?.[1] ?? \"of unknown version\"} found, but the engine is pinned to ${leanVersion}; ${installHint}`,\n };\n }\n return { unavailable: `no Lean toolchain found; ${installHint}` };\n}\n\n/** Parse Lean's diagnostics for the one file it was given. */\nexport function diagnostics(output: string): LeanDiagnostic[] {\n const out: LeanDiagnostic[] = [];\n const re = /^(?:.*?):(\\d+):(\\d+): (error|warning|info): (.*)$/;\n let current:\n | { line: number; column: number; severity: LeanDiagnostic[\"severity\"]; lines: string[] }\n | undefined;\n const flush = (c: NonNullable<typeof current>) =>\n out.push({\n line: c.line,\n column: c.column,\n severity: c.severity,\n message: c.lines.join(\"\\n\").trimEnd(),\n });\n for (const raw of output.split(\"\\n\")) {\n const m = re.exec(raw);\n if (m) {\n if (current) flush(current);\n current = {\n line: Number(m[1]),\n column: Number(m[2]),\n severity: m[3] as LeanDiagnostic[\"severity\"],\n lines: [m[4] as string],\n };\n } else if (current) current.lines.push(raw);\n }\n if (current) flush(current);\n return out;\n}\n\nexport interface CheckedFile {\n readonly run: LeanRun;\n readonly diagnostics: readonly LeanDiagnostic[];\n}\n\n/** Write the source to a scratch directory pinned to the toolchain and check it. */\nexport async function checkLean(\n toolchain: LeanToolchain,\n source: string,\n options: { readonly timeoutMs?: number; readonly keep?: boolean } = {},\n): Promise<CheckedFile> {\n const dir = mkdtempSync(join(tmpdir(), \"eutaxy-lean-\"));\n try {\n writeFileSync(join(dir, \"lean-toolchain\"), `${leanToolchain}\\n`);\n writeFileSync(join(dir, \"Eutaxy.lean\"), source);\n const result = await run(toolchain.command, [...toolchain.args, \"Eutaxy.lean\"], {\n cwd: dir,\n timeoutMs: options.timeoutMs ?? 120_000,\n });\n return { run: result, diagnostics: diagnostics(`${result.stdout}\\n${result.stderr}`) };\n } finally {\n if (!options.keep) rmSync(dir, { recursive: true, force: true });\n }\n}\n","/**\n * The engine: an annotated module's functions through the subset reader,\n * the emitter and Lean, and each property's outcome back. One Lean run per\n * module; errors are mapped to theorems by line, so one failed proof does\n * not hide another. A proof that fails is `gave_up` (the engine is weak or\n * the claim is false; Lean does not say which), a function or property\n * outside the subset is `unsupported`, and no pinned toolchain is\n * `unavailable`. `@total` is proved by Lean accepting the definition.\n */\n\nimport type {\n ModuleProofs,\n ProofOutcome,\n PropertyProof,\n Prover,\n ProveInput as ProverInput,\n} from \"@eutaxy/prover\";\nimport { extractSpecs, type FunctionSpec, type SpecError } from \"@eutaxy/spec\";\nimport { type Emitted, emitModule } from \"./emit.ts\";\nimport { checkLean, findLean, type LeanDiagnostic, leanVersion } from \"./lean.ts\";\nimport { OutsideSubset, readSubset, type SubsetModule } from \"./subset.ts\";\n\nexport const engineName = \"lean\";\n\nexport type { ModuleProofs, ProofOutcome, PropertyProof } from \"@eutaxy/prover\";\n\nexport interface ProveInput extends ProverInput {\n /** Extra Lean lines appended after the theorems (translation checks). */\n readonly extra?: readonly string[];\n}\n\n/** This engine's report, with the Lean it checked. */\nexport interface LeanModuleProofs extends ModuleProofs {\n /** The Lean source checked, when any function was in the subset. */\n readonly lean?: string;\n}\n\n/** What every PROVEN verdict of this engine rests on. */\nexport const engineAssumptions: readonly string[] = [\n \"number is modelled as the unbounded integers: no overflow, no fractions, no NaN\",\n \"string is modelled as Lean's String, a sequence of Unicode characters: a lone surrogate, which a JavaScript string can hold, is outside every string binder's domain\",\n \"the function and its callees are the module's own, pure and total; nothing outside the module is modelled\",\n `the proof was checked by the Lean ${leanVersion} kernel on the emitted statement, not by Eutaxy`,\n];\n\nconst proven: Extract<ProofOutcome, { kind: \"PROVEN\" }> = {\n kind: \"PROVEN\",\n engine: { name: engineName, version: leanVersion },\n assumptions: engineAssumptions,\n};\n\nconst unknown = (\n cause: \"gave_up\" | \"unsupported\" | \"unavailable\",\n reason: string,\n): ProofOutcome => ({\n kind: \"UNKNOWN\",\n cause,\n reason,\n});\n\nfunction propertiesOf(fn: FunctionSpec): string[] {\n return [...fn.ensures.map((p) => p.name), ...(fn.total ? [\"@total\"] : [])];\n}\n\n/** Every property of the functions, with one outcome. */\nfunction allWith(fns: readonly FunctionSpec[], outcome: ProofOutcome): PropertyProof[] {\n return fns.flatMap((fn) =>\n propertiesOf(fn).map((property) => ({ function: fn.name, property, outcome })),\n );\n}\n\n/** The emitted Lean for the module's functions in the subset, and the annotated functions outside it with why. */\nexport interface Prepared {\n readonly module: SubsetModule;\n readonly emitted: Emitted;\n /** The annotated functions to report on. */\n readonly fns: readonly FunctionSpec[];\n /** Those of them the subset does not take, with the reason. */\n readonly outside: ReadonlyMap<string, string>;\n /** Annotations that did not parse. */\n readonly specErrors: readonly SpecError[];\n}\n\n/**\n * Read and emit. Every function the subset takes is emitted (callees\n * included); properties are stated for the annotated ones among them.\n */\nexport function prepare(input: ProveInput): Prepared {\n const specs = input.specs ?? extractSpecs(input.source);\n const wanted = input.functions ? new Set(input.functions) : undefined;\n const fns = specs.functions.filter((f) => !wanted || wanted.has(f.name));\n const module = readSubset(\n input.source,\n fns.map((f) => f.name),\n );\n const outside = new Map<string, string>();\n for (const o of module.outside)\n if (fns.some((f) => f.name === o.name))\n outside.set(\n o.name,\n `outside the engine's subset${o.line > 0 ? ` (line ${o.line})` : \"\"}: ${o.message}`,\n );\n // An annotation belongs to one declaration: the one on its line. A nested function (in a namespace,\n // say) named like a top-level one must not lend its properties to the top-level body.\n for (const fn of fns) {\n const read = module.functions.find((f) => f.name === fn.name);\n if (read && read.offset !== fn.offset)\n outside.set(\n fn.name,\n `outside the engine's subset (line ${fn.line}): the annotated ${fn.name} is not the module's top-level declaration of that name (line ${read.line})`,\n );\n }\n const properties = fns\n .filter((fn) => !outside.has(fn.name))\n .flatMap((fn) => fn.ensures.map((property) => ({ function: fn.name, property })));\n const specErrors = specs.errors;\n try {\n return {\n module,\n emitted: emitModule(module, properties, input.extra),\n fns,\n outside,\n specErrors,\n };\n } catch (err) {\n // The emitter refusing something the reader let through is an engine gap: every function is unsupported, none guessed.\n if (!(err instanceof OutsideSubset)) throw err;\n for (const fn of fns) outside.set(fn.name, `outside the engine's subset: ${err.message}`);\n const empty: Emitted = { source: \"\", theorems: [], skipped: [] };\n return { module, emitted: empty, fns, outside, specErrors };\n }\n}\n\n/** Prove a module's properties with the pinned Lean. */\nexport async function proveModule(input: ProveInput): Promise<LeanModuleProofs> {\n const { emitted, fns, outside, specErrors } = prepare(input);\n const inSubset = fns.filter((f) => !outside.has(f.name));\n const unsupported = fns\n .filter((f) => outside.has(f.name))\n .flatMap((f) =>\n propertiesOf(f).map((property) => ({\n function: f.name,\n property,\n outcome: unknown(\"unsupported\", outside.get(f.name) as string),\n })),\n );\n if (inSubset.length === 0) return { results: unsupported, specErrors };\n const lean = emitted.source;\n const rest = (outcome: ProofOutcome): LeanModuleProofs => ({\n results: [...unsupported, ...allWith(inSubset, outcome)],\n lean,\n specErrors,\n });\n const toolchain = await findLean();\n if (\"unavailable\" in toolchain) return rest(unknown(\"unavailable\", toolchain.unavailable));\n const timeoutMs = input.timeoutMs ?? 120_000;\n const checked = await checkLean(toolchain, lean, { timeoutMs });\n if (checked.run.timedOut)\n return rest(unknown(\"gave_up\", `Lean did not finish within ${timeoutMs} ms`));\n const errors = checked.diagnostics.filter((d) => d.severity === \"error\");\n const inTheorem = (d: LeanDiagnostic) =>\n emitted.theorems.find((t) => d.line >= t.from && d.line <= t.to);\n if (checked.run.code === null || (checked.run.code !== 0 && errors.length === 0))\n return rest(\n unknown(\n \"unavailable\",\n `Lean could not be run: ${checked.run.stderr.trim() || `exit ${checked.run.code}`}`,\n ),\n );\n const elsewhere = errors.filter((d) => !inTheorem(d));\n if (elsewhere.length > 0) {\n // The emitted definitions themselves did not compile: an engine gap, never a verdict on the property.\n const where = elsewhere.map((d) => `line ${d.line}: ${d.message.split(\"\\n\")[0]}`).join(\"; \");\n return rest(unknown(\"unsupported\", `the emitted Lean did not compile: ${where}`));\n }\n const results: PropertyProof[] = [...unsupported];\n for (const fn of inSubset) {\n for (const property of fn.ensures) {\n const skipped = emitted.skipped.find(\n (s) => s.function === fn.name && s.property === property.name,\n );\n if (skipped) {\n results.push({\n function: fn.name,\n property: property.name,\n outcome: unknown(\"unsupported\", skipped.reason),\n });\n continue;\n }\n const theorem = emitted.theorems.find(\n (t) => t.function === fn.name && t.property === property.name,\n );\n const failed = theorem\n ? errors.filter((d) => d.line >= theorem.from && d.line <= theorem.to)\n : [];\n results.push({\n function: fn.name,\n property: property.name,\n outcome:\n failed.length === 0\n ? proven\n : unknown(\n \"gave_up\",\n `Lean could not close the proof: ${(failed[0] as LeanDiagnostic).message.split(\"\\n\")[0]}`,\n ),\n });\n }\n if (fn.total)\n results.push({\n function: fn.name,\n property: \"@total\",\n outcome: {\n ...proven,\n assumptions: [\n ...engineAssumptions,\n \"Lean accepted the definition, so it terminates on every input\",\n ],\n },\n });\n }\n return { results, lean, specErrors };\n}\n\n/** The engine as a `Prover`: available when the pinned toolchain is installed. */\nexport const leanProver: Prover = {\n name: engineName,\n async available() {\n const toolchain = await findLean();\n return \"unavailable\" in toolchain ? toolchain : { version: toolchain.version };\n },\n prove: (input) => proveModule(input),\n};\n","/**\n * The files `eutaxy check` writes into `<scenario dir>/.eutaxy/` before\n * running Vitest: a test that performs the check inside workerd and prints\n * the verdict on one marked line, and a Vitest config with the Cloudflare\n * plugin pointed at the scenario's wrangler config.\n */\n\n/** Key under which the generated test stores its result in the Vitest task meta, read back from the JSON reporter. */\nexport const metaKey = \"eutaxy\";\n\nexport interface GeneratedCheck {\n readonly seed: string;\n readonly maxRuns?: number;\n /** Replaces the scenario's time budget. */\n readonly budgetMs?: number;\n /** Exhaustive exploration instead of seeded. */\n readonly exhaustive?: boolean;\n /** Import specifier of the scenario from the generated test (e.g. \"../scenario.sim.ts\"). */\n readonly scenarioImport: string;\n}\n\n/**\n * The generated test: the module globs (Vite resolves them at build time,\n * so they must be written in the test) and one call to `checkInWorkerd`,\n * which does the rest.\n */\nexport function checkTestSource(g: GeneratedCheck): string {\n const options =\n `seed: ${JSON.stringify(g.seed)}` +\n (g.maxRuns === undefined ? \"\" : `, maxRuns: ${g.maxRuns}`) +\n (g.budgetMs === undefined ? \"\" : `, budgetMs: ${g.budgetMs}`) +\n (g.exhaustive ? \", exhaustive: true\" : \"\");\n return `// Generated by eutaxy check; deleted after the run.\nimport { checkInWorkerd } from \"eutaxy/cloudflare\";\nimport { env } from \"cloudflare:workers\";\nimport * as durableObjects from \"cloudflare:test\";\nimport { test } from \"vitest\";\nimport scenario from ${JSON.stringify(g.scenarioImport)};\nimport { specLoaders } from \"./specs.ts\";\n\nconst sqlFiles = import.meta.glob(\"../**/*.sql\", { query: \"?raw\", import: \"default\", eager: true }) as Record<string, string>;\nconst modules = import.meta.glob([\"../**/*.ts\", \"!../**/*.test.ts\", \"!../**/*.sim.ts\", \"!../**/node_modules/**\", \"!../**/.eutaxy/**\"]);\n\ntest(\"eutaxy check\", async ({ task }) => {\n task.meta[${JSON.stringify(metaKey)}] = await checkInWorkerd({ scenario, env, durableObjects, sqlFiles, modules, specLoaders, ${options} });\n});\n`;\n}\n\nexport function vitestConfigSource(\n wranglerConfigPath: string,\n testPath: string,\n outputFile: string,\n): string {\n return `// Generated by eutaxy check; deleted after the run.\nimport { cloudflareTest } from \"@cloudflare/vitest-plugin\";\nimport { defineConfig } from \"vitest/config\";\n\nexport default defineConfig({\n plugins: [cloudflareTest({ wrangler: { configPath: ${JSON.stringify(wranglerConfigPath)} } })],\n test: {\n include: [${JSON.stringify(testPath)}],\n testTimeout: 600_000,\n reporters: [\"json\"],\n outputFile: ${JSON.stringify(outputFile)},\n },\n});\n`;\n}\n","import type { Violated } from \"@eutaxy/core\";\nimport { emitRegressionTest } from \"@eutaxy/report\";\n\nexport interface CloudflareRegressionOptions {\n /** Import path of the scenario module, relative to the emitted file. */\n readonly scenarioPath: string;\n /** Import path of the Worker module. */\n readonly workerPath: string;\n /** D1 binding name to schema file path, imported with `?raw`. */\n readonly schemaPaths: Readonly<Record<string, string>>;\n /**\n * The time budget the check ran with, when it replaced the scenario's: the\n * replay gets the same, so I/O that finished within it does not time out.\n */\n readonly budgetMs?: number;\n /** The platform's retry limit, when the scenario was checked with a non-default one. */\n readonly maxRetries?: number;\n /** The scenario sets up Durable Objects: pass the Cloudflare test helpers to the platform. */\n readonly durableObjects?: boolean;\n /** The scenario sets up Workflows: pass the Worker module's exports, where their classes are. */\n readonly workflows?: boolean;\n readonly expect?: \"holds\" | \"violates\";\n readonly engineModule?: string;\n /** Core modules to observe during the replay (import path, functions), for `refines`. */\n readonly specModules?: readonly {\n readonly path: string;\n readonly functions: readonly string[];\n }[];\n}\n\n/** A Vitest regression test for a Cloudflare scenario, to run under the Cloudflare Vitest plugin. */\nexport function cloudflareRegressionTest(\n verdict: Violated,\n options: CloudflareRegressionOptions,\n): string {\n const bindings = Object.keys(options.schemaPaths).sort();\n const imports = [\n 'import { createCloudflarePlatform } from \"eutaxy/cloudflare\";',\n 'import { env } from \"cloudflare:workers\";',\n ...(options.durableObjects ? ['import * as cloudflareTest from \"cloudflare:test\";'] : []),\n `import scenario from ${JSON.stringify(options.scenarioPath)};`,\n ...bindings.map(\n (b) => `import schema_${b} from ${JSON.stringify(`${options.schemaPaths[b]}?raw`)};`,\n ),\n options.workflows\n ? `import * as worker from ${JSON.stringify(options.workerPath)};`\n : `import handler from ${JSON.stringify(options.workerPath)};`,\n ...(options.specModules ?? []).map(\n (m, i) => `import * as core_${i} from ${JSON.stringify(m.path)};`,\n ),\n ];\n const schemas = `{ ${bindings.map((b) => `${b}: schema_${b}`).join(\", \")} }`;\n const retries = options.maxRetries === undefined ? \"\" : `, maxRetries: ${options.maxRetries}`;\n const objects = options.durableObjects ? \", durableObjects: cloudflareTest\" : \"\";\n const handler = options.workflows ? \"handler: worker.default\" : \"handler\";\n const exports = options.workflows ? \", exports: worker\" : \"\";\n return emitRegressionTest(verdict, {\n imports,\n platform: `createCloudflarePlatform({ env, ${handler}, schemas: ${schemas}${retries}${objects}${exports} })`,\n scenario:\n options.budgetMs === undefined\n ? \"scenario\"\n : `{ ...scenario, bounds: { ...scenario.bounds, budgetMs: ${options.budgetMs} } }`,\n ...(options.expect ? { expect: options.expect } : {}),\n ...(options.engineModule ? { engineModule: options.engineModule } : {}),\n ...(options.specModules && options.specModules.length > 0\n ? {\n observe: options.specModules.map((m, i) => ({\n namespace: `core_${i}`,\n functions: m.functions,\n })),\n }\n : {}),\n });\n}\n","/** How the two halves of `eutaxy check` name a module next to the scenario. Imports nothing, so workerd can load it. */\n\n/** Normalize a module path from a scenario's `specs` to a key: \"./domain.ts\". */\nexport function specKey(path: string): string {\n const posix = path\n .split(\"\\\\\")\n .join(\"/\")\n .replace(/^(\\.\\/)+/, \"\");\n return `./${posix}`;\n}\n\n/** The key Vite's `import.meta.glob` gives a path next to the scenario, seen from `.eutaxy/`. */\nexport function globKey(path: string): string {\n return `.${specKey(path)}`;\n}\n","/**\n * Spec modules for `eutaxy check`: every TypeScript module next to the\n * scenario with Lemma annotations, and the generated module that holds\n * their predicates as compiled code (workerd runs no `eval`). Which of them\n * a run checks is the scenario's `specs`, read where the scenario is loaded,\n * inside the generated test.\n */\n\nimport { readdirSync, readFileSync } from \"node:fs\";\nimport { join, relative } from \"node:path\";\nimport { extractSpecs, type ModuleSpecs, predicateSource } from \"@eutaxy/spec\";\nimport { specKey } from \"./keys.ts\";\n\nexport { specKey } from \"./keys.ts\";\n\nexport interface SpecModule {\n /** The path relative to the scenario's directory, as a scenario names it: \"./domain.ts\". */\n readonly key: string;\n readonly path: string;\n readonly specs: ModuleSpecs;\n}\n\nconst skipDirs = new Set([\"node_modules\", \".eutaxy\", \"dist\", \".git\"]);\n\n/** Annotated modules under `dir`, tests and scenarios excepted. */\nexport function findSpecModules(dir: string): SpecModule[] {\n const out: SpecModule[] = [];\n const walk = (at: string): void => {\n for (const entry of readdirSync(at, { withFileTypes: true })) {\n const path = join(at, entry.name);\n if (entry.isDirectory()) {\n if (!skipDirs.has(entry.name)) walk(path);\n continue;\n }\n const name = entry.name;\n if (\n !name.endsWith(\".ts\") ||\n name.endsWith(\".d.ts\") ||\n name.endsWith(\".test.ts\") ||\n name.endsWith(\".sim.ts\")\n )\n continue;\n const source = readFileSync(path, \"utf8\");\n if (!/@(ensures|total|throws)\\b/.test(source)) continue;\n const specs = extractSpecs(source);\n if (specs.functions.length === 0 && specs.errors.length === 0) continue;\n out.push({ key: specKey(relative(dir, path)), path, specs });\n }\n };\n walk(dir);\n return out.sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0));\n}\n\n/** The generated module's own names; each predicate takes them as parameters, so nothing in a property shadows them. */\nconst helpers = {\n bool: \"__eutaxyBool\",\n same: \"__eutaxySame\",\n scope: \"__eutaxyNamespace\",\n unresolved: \"__eutaxyUnresolved\",\n};\n\n/** A file `eutaxy check` writes into `.eutaxy/`, by its path there. */\nexport interface GeneratedFile {\n readonly name: string;\n readonly source: string;\n}\n\n/**\n * The generated spec files: `specs.ts`, which maps each annotated module's\n * key to a loader, and one file per module with its extracted specs and a\n * function from its namespace to its predicates. A module's file loads only\n * when a scenario names the module, so an annotation elsewhere that does not\n * compile cannot stop a check. Each predicate binds its free names from the\n * namespace (else the globals) when it is built, which happens before\n * anything is observed, so checking a property never counts as a call the\n * simulator made.\n */\nexport function specFiles(modules: readonly SpecModule[]): GeneratedFile[] {\n // The `any`s: these files run in the user's Vitest, which does not type-check them, and must\n // import nothing; `SpecEntry` in workerd.ts is the shape they have.\n const header = \"// Generated by eutaxy check; deleted after the run.\";\n const index = [\n header,\n \"export const specLoaders: Record<string, () => Promise<any>> = {\",\n ...modules.map((m, i) => ` ${JSON.stringify(m.key)}: () => import(\"./specs/m${i}.ts\"),`),\n \"};\",\n ];\n const files = modules.map((m, i) => {\n const lines = [\n header,\n `const ${helpers.same} = Object.is;`,\n \"\",\n `export const specs = ${JSON.stringify(m.specs)};`,\n \"\",\n // The atom and unresolved-name checks come in as parameters: the file imports nothing.\n `export const predicates = (${helpers.scope}: any, ${helpers.bool}: any, ${helpers.unresolved}: any) => ({`,\n ];\n for (const fn of m.specs.functions) {\n // Computed keys: a name like __proto__ stays an ordinary entry.\n lines.push(` [${JSON.stringify(fn.name)}]: {`);\n for (const p of fn.ensures) {\n const source = predicateSource(p.property, helpers).split(\"\\n\").join(\"\\n \");\n lines.push(` [${JSON.stringify(p.name)}]: ${source},`);\n }\n lines.push(\" },\");\n }\n lines.push(\"});\");\n return { name: `specs/m${i}.ts`, source: `${lines.join(\"\\n\")}\\n` };\n });\n return [{ name: \"specs.ts\", source: `${index.join(\"\\n\")}\\n` }, ...files];\n}\n","/**\n * `eutaxy check <scenario.sim.ts>`: run a scenario inside workerd through\n * the user's Vitest and the Cloudflare plugin, print the verdict as text or\n * JSON, and on a violation write a regression test next to the scenario.\n */\n\nimport { spawn } from \"node:child_process\";\nimport { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { basename, dirname, join, relative, resolve } from \"node:path\";\nimport {\n canonicalJson,\n type JsonValue,\n type ScenarioVerdict,\n type SpecVerdict,\n type Violated,\n} from \"@eutaxy/core\";\nimport { aggregate, type EngineReport, type Prover } from \"@eutaxy/prover\";\nimport { leanProver } from \"@eutaxy/prover-lean\";\nimport { renderSpecs, renderText } from \"@eutaxy/report\";\nimport { checkTestSource, metaKey, vitestConfigSource } from \"./generate.ts\";\nimport { cloudflareRegressionTest } from \"./regression.ts\";\nimport { findSpecModules, specFiles, specKey } from \"./specs.ts\";\nimport type { CheckTransport } from \"./workerd.ts\";\n\nexport interface CheckOptions {\n readonly scenario: string;\n readonly cwd: string;\n readonly wrangler?: string;\n readonly seed?: string;\n readonly maxRuns?: number;\n /** Replaces the scenario's time budget. */\n readonly budgetMs?: number;\n /** Run every schedule within the bounds once instead of drawing them from the seed. */\n readonly exhaustive?: boolean;\n /** Engines to run the PROVEN rung with, by name, on the scenario's spec modules. */\n readonly provers?: readonly string[];\n readonly json: boolean;\n /** Where to write the regression test on a violation; default `<name>.regression.test.ts` beside the scenario. */\n readonly out?: string;\n readonly noRegression: boolean;\n /** Emit a regression test that asserts the violation (for corpora) rather than one that expects it fixed. */\n readonly expectViolation: boolean;\n /** Keep the generated `.eutaxy/` files for inspection. */\n readonly keep: boolean;\n readonly stdout: (text: string) => void;\n readonly stderr: (text: string) => void;\n}\n\nexport const exitCodes = { BOUNDED: 0, VIOLATED: 1, UNSUPPORTED: 2, error: 3 } as const;\n\n/** The engines `--prover` can name. */\nexport const provers: Readonly<Record<string, Prover>> = { lean: leanProver };\n\n/**\n * The PROVEN rung, on the Node side: each engine on each observed spec\n * module's source, the outcomes folded into the simulator's verdicts.\n * An engine that is not installed proves nothing and says so.\n */\nexport async function proveSpecs(\n dir: string,\n observed: readonly { readonly module: string; readonly functions: readonly string[] }[],\n specs: readonly SpecVerdict[],\n engines: readonly Prover[],\n): Promise<readonly SpecVerdict[]> {\n let out = specs;\n for (const m of observed) {\n // Verdicts carry the module as a normalized key (\"./domain.ts\"); the observed path is as the scenario wrote it.\n const key = specKey(m.module);\n const source = readFileSync(resolve(dir, key), \"utf8\");\n const annotated = m.functions.filter((f) =>\n specs.some((v) => v.module === key && v.function === f),\n );\n if (annotated.length === 0) continue;\n const reports: EngineReport[] = [];\n for (const engine of engines)\n reports.push({\n engine: engine.name,\n proofs: await engine.prove({ source, functions: annotated }),\n });\n out = aggregate(key, out, reports);\n }\n return out;\n}\n\nfunction findWrangler(dir: string, explicit: string | undefined, cwd: string): string | null {\n if (explicit) return resolve(cwd, explicit);\n for (const name of [\"wrangler.jsonc\", \"wrangler.json\", \"wrangler.toml\"]) {\n const p = join(dir, name);\n if (existsSync(p)) return p;\n }\n return null;\n}\n\nfunction vitestBin(from: string): string {\n const req = createRequire(join(from, \"package.json\"));\n return join(dirname(req.resolve(\"vitest/package.json\")), \"vitest.mjs\");\n}\n\nfunction runVitest(\n bin: string,\n configPath: string,\n cwd: string,\n): Promise<{ code: number; output: string }> {\n return new Promise((resolveRun) => {\n const child = spawn(process.execPath, [bin, \"run\", \"--config\", configPath], {\n cwd,\n env: { ...process.env, CI: \"1\", FORCE_COLOR: \"0\" },\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n });\n let output = \"\";\n child.stdout.on(\"data\", (d: Buffer) => {\n output += d.toString();\n });\n child.stderr.on(\"data\", (d: Buffer) => {\n output += d.toString();\n });\n child.on(\"close\", (code) => resolveRun({ code: code ?? 1, output }));\n });\n}\n\n/** The transport the generated test left in its task meta, via Vitest's JSON reporter. */\nfunction readTransport(reportPath: string): CheckTransport | null {\n if (!existsSync(reportPath)) return null;\n const report = JSON.parse(readFileSync(reportPath, \"utf8\")) as {\n testResults?: { assertionResults?: { meta?: Record<string, unknown> }[] }[];\n };\n for (const file of report.testResults ?? []) {\n for (const t of file.assertionResults ?? []) {\n const m = t.meta?.[metaKey];\n if (m) return m as CheckTransport;\n }\n }\n return null;\n}\n\nfunction toPosix(p: string): string {\n const s = p.split(\"\\\\\").join(\"/\");\n return s.startsWith(\".\") ? s : `./${s}`;\n}\n\nexport async function runCheck(o: CheckOptions): Promise<number> {\n const scenarioPath = resolve(o.cwd, o.scenario);\n if (!existsSync(scenarioPath)) {\n o.stderr(`scenario not found: ${scenarioPath}\\n`);\n return exitCodes.error;\n }\n const dir = dirname(scenarioPath);\n const name = basename(scenarioPath)\n .replace(/\\.sim\\.ts$/, \"\")\n .replace(/\\.ts$/, \"\");\n const wrangler = findWrangler(dir, o.wrangler, o.cwd);\n if (!wrangler || !existsSync(wrangler)) {\n o.stderr(`no wrangler config found next to the scenario; pass --wrangler <path>\\n`);\n return exitCodes.error;\n }\n const workDir = join(dir, \".eutaxy\");\n const testPath = join(workDir, `${name}.check.test.ts`);\n const configPath = join(workDir, \"vitest.config.mts\");\n mkdirSync(workDir, { recursive: true });\n try {\n writeFileSync(\n testPath,\n checkTestSource({\n seed: o.seed ?? name,\n ...(o.maxRuns === undefined ? {} : { maxRuns: o.maxRuns }),\n ...(o.budgetMs === undefined ? {} : { budgetMs: o.budgetMs }),\n ...(o.exhaustive ? { exhaustive: true } : {}),\n scenarioImport: `../${basename(scenarioPath)}`,\n }),\n );\n for (const f of specFiles(findSpecModules(dir))) {\n mkdirSync(dirname(join(workDir, f.name)), { recursive: true });\n writeFileSync(join(workDir, f.name), f.source);\n }\n const reportPath = join(workDir, \"vitest-report.json\");\n rmSync(reportPath, { force: true }); // never read a report left by an earlier --keep run\n writeFileSync(configPath, vitestConfigSource(wrangler, testPath, reportPath));\n const { code, output } = await runVitest(vitestBin(dir), configPath, dir);\n const transport = code === 0 ? readTransport(reportPath) : null;\n if (!transport) {\n o.stderr(`eutaxy check could not read a verdict from Vitest (exit ${code}):\\n${output}\\n`);\n return exitCodes.error;\n }\n if (transport.specErrors && transport.specErrors.length > 0) {\n for (const e of transport.specErrors)\n o.stderr(`${e.module}${e.line > 0 ? `:${e.line}` : \"\"}: ${e.message}\\n`);\n return exitCodes.error;\n }\n const report = transport.report as { verdict: ScenarioVerdict; specs?: readonly SpecVerdict[] };\n const verdict = report.verdict;\n let specs = report.specs ?? [];\n if (o.provers && o.provers.length > 0) {\n const engines: Prover[] = [];\n for (const name of o.provers) {\n const engine = provers[name];\n if (!engine) {\n o.stderr(`unknown prover ${name}; known: ${Object.keys(provers).join(\", \")}\\n`);\n return exitCodes.error;\n }\n engines.push(engine);\n }\n specs = await proveSpecs(dir, transport.observed ?? [], specs, engines);\n }\n const printed =\n o.provers && o.provers.length > 0\n ? { ...(transport.report as object), specs }\n : transport.report;\n if (o.json) o.stdout(`${canonicalJson(printed as JsonValue)}\\n`);\n else o.stdout(`${renderText(verdict)}\\n${specs.length > 0 ? `\\n${renderSpecs(specs)}\\n` : \"\"}`);\n\n if (verdict.kind === \"VIOLATED\" && !o.noRegression) {\n const outPath = o.out ? resolve(o.cwd, o.out) : join(dir, `${name}.regression.test.ts`);\n const outDir = dirname(outPath);\n const schemaPaths: Record<string, string> = {};\n for (const step of transport.setup) {\n if (step.kind === \"d1\") {\n schemaPaths[String(step[\"binding\"])] = toPosix(\n relative(outDir, resolve(dir, String(step[\"schemaFile\"]))),\n );\n }\n }\n const source = cloudflareRegressionTest(verdict as Violated, {\n scenarioPath: toPosix(relative(outDir, scenarioPath)),\n workerPath: toPosix(relative(outDir, resolve(dir, transport.worker.entry))),\n schemaPaths,\n ...(o.budgetMs === undefined ? {} : { budgetMs: o.budgetMs }),\n ...(transport.setup.some((s) => s.kind === \"durable_object\")\n ? { durableObjects: true }\n : {}),\n ...(transport.setup.some((s) => s.kind === \"workflow\") ? { workflows: true } : {}),\n ...(o.expectViolation ? { expect: \"violates\" as const } : {}),\n ...((transport.observed ?? []).length > 0\n ? {\n specModules: (transport.observed ?? []).map((m) => ({\n path: toPosix(relative(outDir, resolve(dir, m.module))),\n functions: m.functions,\n })),\n }\n : {}),\n });\n mkdirSync(outDir, { recursive: true });\n writeFileSync(outPath, source);\n if (!o.json)\n o.stdout(`\\nRegression test written to ${relative(o.cwd, outPath) || outPath}\\n`);\n }\n // A refuted spec fails the check like a violation does; so does a conflict between engines.\n if (\n verdict.kind !== \"VIOLATED\" &&\n specs.some((v) => v.kind === \"REFUTED\" || v.kind === \"CONFLICT\")\n )\n return exitCodes.VIOLATED;\n return exitCodes[verdict.kind];\n } finally {\n if (!o.keep) rmSync(workDir, { recursive: true, force: true });\n }\n}\n","import { parseArgs } from \"./args.ts\";\nimport { exitCodes, runCheck } from \"./check.ts\";\n\nconst usage = `eutaxy — deterministic simulation checks for Cloudflare Workers\n\nUsage:\n eutaxy check <scenario.sim.ts> [options]\n\nOptions:\n --wrangler <path> wrangler config (default: wrangler.jsonc/json/toml beside the scenario)\n --seed <seed> exploration seed (default: the scenario file name)\n --max-runs <n> cap on exploration runs in addition to the scenario's time budget\n --budget-ms <n> replace the scenario's time budget (with --max-runs, the run cap decides)\n --exhaustive run every schedule within the bounds once (with partial-order reduction)\n --prover <names> also run the PROVEN rung with these engines on the scenario's specs\n (comma-separated; known: lean)\n --json print the versioned JSON report instead of text\n --out <path> where to write the regression test on a violation\n --no-regression do not write a regression test\n --expect-violation write a regression test that asserts the violation (for corpora)\n --keep keep the generated .eutaxy/ files\n\nExit codes: 0 BOUNDED, 1 VIOLATED or a REFUTED or CONFLICT spec, 2 UNSUPPORTED, 3 error.\n`;\n\nexport interface Io {\n readonly cwd: string;\n readonly stdout: (text: string) => void;\n readonly stderr: (text: string) => void;\n}\n\nexport async function main(argv: readonly string[], io: Io): Promise<number> {\n const { positionals, flags } = parseArgs(argv, [\n \"json\",\n \"no-regression\",\n \"expect-violation\",\n \"keep\",\n \"help\",\n \"exhaustive\",\n ]);\n const command = positionals[0];\n if (!command || command === \"help\" || flags[\"help\"] === true) {\n io.stdout(usage);\n return command ? exitCodes.BOUNDED : exitCodes.error;\n }\n if (command !== \"check\") {\n io.stderr(`unknown command ${command}\\n\\n${usage}`);\n return exitCodes.error;\n }\n const scenario = positionals[1];\n if (!scenario) {\n io.stderr(`check needs a scenario file\\n\\n${usage}`);\n return exitCodes.error;\n }\n const str = (k: string): string | undefined =>\n typeof flags[k] === \"string\" ? (flags[k] as string) : undefined;\n const maxRunsText = str(\"max-runs\");\n const maxRuns = maxRunsText === undefined ? undefined : Number(maxRunsText);\n if (maxRuns !== undefined && !(Number.isInteger(maxRuns) && maxRuns > 0)) {\n io.stderr(`--max-runs must be a positive integer, got ${JSON.stringify(maxRunsText)}\\n`);\n return exitCodes.error;\n }\n const budgetText = str(\"budget-ms\");\n const budgetMs = budgetText === undefined ? undefined : Number(budgetText);\n if (budgetMs !== undefined && !(Number.isInteger(budgetMs) && budgetMs > 0)) {\n io.stderr(`--budget-ms must be a positive integer, got ${JSON.stringify(budgetText)}\\n`);\n return exitCodes.error;\n }\n const provers = (str(\"prover\") ?? \"\")\n .split(\",\")\n .map((n) => n.trim())\n .filter((n) => n.length > 0);\n return runCheck({\n scenario,\n cwd: io.cwd,\n ...(provers.length > 0 ? { provers } : {}),\n ...(str(\"wrangler\") ? { wrangler: str(\"wrangler\") as string } : {}),\n ...(str(\"seed\") ? { seed: str(\"seed\") as string } : {}),\n ...(maxRuns === undefined ? {} : { maxRuns }),\n ...(budgetMs === undefined ? {} : { budgetMs }),\n exhaustive: flags[\"exhaustive\"] === true,\n json: flags[\"json\"] === true,\n ...(str(\"out\") ? { out: str(\"out\") as string } : {}),\n noRegression: flags[\"no-regression\"] === true,\n expectViolation: flags[\"expect-violation\"] === true,\n keep: flags[\"keep\"] === true,\n stdout: io.stdout,\n stderr: io.stderr,\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 * 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.\n */\n\nimport {\n canonicalJson,\n type EffectPoint,\n type FaultKind,\n type JsonValue,\n type RunHooks,\n toJson,\n} from \"@eutaxy/core\";\n\nconst WRITE: readonly FaultKind[] = [\"crash_before\", \"crash_after\", \"ambiguous\", \"error\"];\nconst READ: readonly FaultKind[] = [\"crash_before\", \"crash_after\", \"error\"];\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 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}\n\nfunction point(\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\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(), WRITE),\n () => 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(), READ),\n () => 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 READ,\n ),\n () => (colName === undefined ? this.real.first<T>() : this.real.first<T>(colName)),\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(), READ),\n () =>\n (options\n ? this.real.raw<T>(options as { columnNames: true })\n : this.real.raw<T>()) as Promise<T[]>,\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, WRITE),\n () => 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 }, WRITE),\n () => 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 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 for (const { name } of tables.results) {\n await real.prepare(`DROP TABLE IF EXISTS \"${name.replace(/\"/g, '\"\"')}\"`).run();\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","/** 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 } from \"@eutaxy/engine\";\nimport type { WorkerHandler } from \"./platform.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/** The `ExecutionContext` handed to a handler; `waitUntil` work is collected to run after it returns. */\nexport function executionContext(background: Promise<unknown>[]): ExecutionContext {\n return {\n waitUntil: (promise: Promise<unknown>) => {\n background.push(\n promise.then(\n () => undefined,\n () => undefined,\n ),\n );\n },\n passThroughOnException: () => {},\n 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 hooks.effectSync(\n {\n invocation,\n target,\n op: \"background\",\n args: { pending: background.length },\n allowed: CUT_OFF,\n },\n () => null,\n () => null,\n );\n await Promise.race([hooks.settle(Promise.all(background), invocation), inv.crashed]);\n return false;\n } catch (err) {\n if (!(err instanceof CrashSignal)) throw err;\n return true;\n }\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 EveryRow,\n type ExternalDecl,\n type Implies,\n type Invariant,\n type JsonValue,\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 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\nexport interface HttpCallerOptions {\n readonly retries?: number;\n readonly retryOn?: \"non-2xx\" | \"5xx\";\n readonly delaysMs?: readonly number[];\n readonly deadlineMs?: number;\n}\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/** The virtual delay before resend number `resend` (1 for the first), per the drive's caller. */\nexport function retryDelayMs(drive: HttpDrive, resend: number): number {\n const delays = drive.delaysMs ?? [];\n return delays[Math.min(resend, delays.length) - 1] ?? 0;\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}\n\nexport function durableObject(\n binding: string,\n objects: { readonly [name: string]: { readonly [key: string]: JsonValue } } = {},\n options: { readonly alarmsPerObject?: number } = {},\n): DurableObjectSetup {\n return {\n kind: \"durable_object\",\n binding,\n objects,\n ...(options.alarmsPerObject === undefined ? {} : { alarmsPerObject: options.alarmsPerObject }),\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\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\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/** 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/** 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\nexport interface CloudflareScenarioInput {\n readonly name: string;\n readonly worker: WorkerRef;\n readonly drive:\n | QueueDrive\n | HttpDrive\n | {\n readonly kind: \"queue\";\n readonly queue: string;\n readonly messages: readonly QueueMessage[];\n };\n readonly setup?: readonly (D1Setup | DurableObjectSetup | R2Setup | WorkflowSetup)[];\n readonly externals?: readonly ExternalDecl[];\n readonly invariants: readonly Invariant[];\n readonly bounds?: Partial<Bounds>;\n /** Modules of pure core functions with Lemma specs, relative to the scenario (see ScenarioSpec.specs). */\n readonly specs?: readonly string[];\n}\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\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) `bodyKey` value must appear at least once\n * as `key` in a selected effect: nothing the drive delivered may be lost.\n */\nexport function atLeastOncePerMessage(\n name: string,\n drive: QueueDrive | HttpDrive,\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 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 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/** 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 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 if (!(Number.isInteger(drive.retries) && drive.retries >= 0))\n errors.push(\"http drive retries must be a non-negative integer\");\n (drive.delaysMs ?? []).forEach((d, i) => {\n if (!(Number.isInteger(d) && d >= 0))\n errors.push(`http 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(\"http drive deadlineMs must be a positive integer\");\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: QueueDrive | HttpDrive =\n input.drive.kind === \"http\" ? input.drive : queue(input.drive.queue, input.drive.messages);\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 };\n const errors = [\n ...validateScenario(spec),\n ...(drive.kind === \"http\" ? validateHttpDrive(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","/** Inbound HTTP delivery: one invocation per attempt of a request the drive's caller sends. */\n\nimport type {\n DeliveryResult,\n EventRef,\n FaultKind,\n JsonValue,\n RunHooks,\n ScenarioSpec,\n} from \"@eutaxy/core\";\nimport { CrashSignal, InjectedEffectError } from \"@eutaxy/engine\";\nimport { drainBackground, executionContext, type RunningWorker } from \"./background.ts\";\nimport { type HttpDrive, type HttpRequestSpec, retryDelayMs } from \"./scenario.ts\";\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/** 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 // Virtual time: when the caller sent this attempt, for its deadline.\n const started = Date.now();\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 deadline = drive.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 redeliveries = event.attempt - 1;\n if (redeliveries < drive.retries && redeliveries < spec.bounds.maxRedeliveries) {\n const resendAt = Math.max(at + retryDelayMs(drive, event.attempt), Date.now());\n hooks.enqueue({\n ...event,\n attempt: event.attempt + 1,\n ...(resendAt > Date.now() ? { at: resendAt } : {}),\n });\n } else {\n hooks.effectSync(\n {\n invocation: hooks.bookkeeping(),\n target,\n op: \"gave_up\",\n args: { requestId: event.id, attempts: event.attempt },\n allowed: [],\n },\n () => null,\n () => null,\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 let response: Response | undefined;\n const outcome = Promise.resolve()\n .then(() =>\n handler.call(worker.handler, requestFor(req), worker.env, executionContext(background)),\n )\n .then(\n (r) => {\n response = r;\n return \"completed\" as const;\n },\n (err: unknown) => (err instanceof CrashSignal ? (\"crashed\" as const) : (\"errored\" as const)),\n );\n let status = await Promise.race([\n hooks.settle(outcome, invocation),\n inv.crashed.then(() => \"crashed\" as const),\n ]);\n\n let summary: { status: number; ok: boolean } | null = null;\n let read: { status: number; ok: boolean; body: JsonValue } | \"crashed\" | \"errored\" = \"errored\";\n if (status === \"completed\" && response) {\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 read = await Promise.race([\n hooks.settle(summarizeResponse(response), invocation).then(\n (s) => s as { status: number; ok: boolean; body: JsonValue },\n (err: unknown) =>\n err instanceof CrashSignal ? (\"crashed\" as const) : (\"errored\" as const),\n ),\n inv.crashed.then(() => \"crashed\" as const),\n ]);\n if (read === \"crashed\" || read === \"errored\") status = read;\n }\n let late = lateAt !== undefined && Date.now() > lateAt;\n const allowed = deadline === undefined ? RESPOND : RESPOND_WITH_DEADLINE;\n if (status === \"completed\" && typeof read === \"object\") {\n const s = read;\n try {\n hooks.effectSync(\n { invocation, target, op: \"response\", args, allowed },\n () => s,\n (v) => v,\n );\n summary = s;\n } catch (err) {\n if (err instanceof CrashSignal) status = \"crashed\";\n else if (err instanceof InjectedEffectError) {\n // Sent, but after the caller's deadline: the handler carries on, the caller resends.\n summary = s;\n late = true;\n } else throw err;\n }\n } else if (status === \"errored\") {\n // Cloudflare answers an uncaught exception with a 500 (workers runtime behaviour); the caller sees that.\n const s = { status: 500, ok: false, body: \"\" };\n hooks.effectSync(\n { invocation, target, op: \"response\", args, allowed: [] },\n () => s,\n (v) => v,\n );\n summary = s;\n }\n\n // The caller decides as soon as it has an answer or gives up, before background work ends.\n if (deadlineTimer !== undefined) clearTimeout(deadlineTimer);\n const accepted =\n summary !== null && !late && (drive.retryOn === \"5xx\" ? summary.status < 500 : summary.ok);\n if (accepted) decided = true;\n else giveUp(late && lateAt !== undefined ? lateAt : Date.now());\n\n if (await drainBackground(hooks, inv, invocation, target, background)) status = \"crashed\";\n return { status, followUps: [] };\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.\n */\n\nimport type { DeliveryResult, EventRef, FaultKind, JsonValue, RunHooks } from \"@eutaxy/core\";\nimport { CrashSignal } from \"@eutaxy/engine\";\n\n/** `EventRef.source` of an alarm event. */\nexport const alarmSource = \"durable_object_alarm\";\n\n/** Crash before: the handler never ran. Crash after: it ran and committed, but counts as failed. */\nconst ALARM: readonly FaultKind[] = [\"crash_before\", \"crash_after\", \"error\"];\n\n/** Cloudflare retries a failed alarm handler up to six times, after 2 s, 4 s, 8 s, ... */\nconst maxRetries = 6;\nconst firstRetryMs = 2_000;\n\n/** One object's alarm, kept across its instances for the run. */\ninterface AlarmEntry {\n time: number | null;\n /** Alarm changes for this object so far, for unique event ids. */\n seq: number;\n /**\n * The current alarm's generation: every setAlarm or deleteAlarm starts a\n * new one, and an event or retry of an older generation is superseded.\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 time: number;\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, seq: 0, 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.seq++;\n entry.gen = entry.seq;\n const data: AlarmData = { binding, gen: entry.gen, id, object, time, retryCount: 0 };\n const now = Date.now();\n hooks().enqueue({\n id: `alarm:${binding}:${object}:${entry.seq}`,\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.seq++;\n entry.gen = entry.seq;\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 /** Run the handler inside the object, after taking over its alarms. */\n readonly runAlarm: (\n id: string,\n object: string,\n info: { readonly retryCount: number; readonly isRetry: boolean },\n gen: number,\n ) => Promise<void>;\n /** Record a platform action (an alarm not fired, a handler given up on). */\n readonly bookkeep: (op: string, args: JsonValue) => void;\n /** Reset the object, when the alarm's invocation crashes inside its handler. */\n readonly abort: (id: string) => void;\n /** Whether an effect the handler makes may wait for a turn (not inside blockConcurrencyWhile). */\n readonly mayPark: (id: string) => boolean;\n /** Drop the object's instance, when its alarm invocation crashed around the handler. */\n readonly evict: (id: string) => Promise<void>;\n}\n\n/**\n * Fire an alarm event: skip it when the object's alarm has since moved or\n * been deleted, run `alarm()` as one effect otherwise, and schedule a retry\n * with backoff when the handler fails, crashes, or a fault says it 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 (entry.gen !== a.gen) return { status: \"completed\", followUps: [] };\n if (a.retryCount === 0) {\n if (entry.time !== a.time) return { status: \"completed\", followUps: [] };\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 = `${event.id}#${event.attempt}`;\n const inv = hooks.startInvocation(invocation);\n const info = { retryCount: a.retryCount, isRetry: a.retryCount > 0 };\n const outcome = hooks\n .effect(\n {\n invocation,\n target: `DO:${d.binding}`,\n op: \"alarm\",\n args: { object: a.object, retryCount: a.retryCount },\n allowed: ALARM,\n hostsEffects: true,\n },\n async () => {\n await d.runAlarm(a.id, a.object, info, a.gen);\n return null;\n },\n () => null,\n { onAbandon: () => d.abort(a.id), mayPark: () => d.mayPark(a.id) },\n )\n .then(\n () => \"completed\" as const,\n (err: unknown) => (err instanceof CrashSignal ? (\"crashed\" as const) : (\"errored\" as const)),\n );\n const status = await Promise.race([\n hooks.settle(outcome, invocation),\n inv.crashed.then(() => \"crashed\" as const),\n ]);\n // A crash is the object's: its in-memory state goes with the instance, whatever the handler did.\n if (status === \"crashed\") await d.evict(a.id);\n if (status !== \"completed\") {\n if (a.retryCount < maxRetries && a.retryCount < maxRedeliveries) {\n const retryAt = Date.now() + firstRetryMs * 2 ** 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 (entry.gen === a.gen) entry.time = retryAt;\n hooks.enqueue({\n ...event,\n attempt: event.attempt + 1,\n data: data as unknown as JsonValue,\n at: retryAt,\n });\n } else {\n // Given up on: no longer pending, unless a newer alarm replaced it meanwhile.\n if (entry.gen === a.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 { type FaultKind, type JsonValue, toJson } from \"@eutaxy/core\";\nimport { withoutNetwork } from \"@eutaxy/engine\";\nimport { AlarmBook, alarmControl, takenOver, takeOverAlarms } from \"./alarms.ts\";\nimport type { ProxyContext } from \"./d1.ts\";\n\nconst CALL: readonly FaultKind[] = [\"crash_before\", \"crash_after\", \"ambiguous\", \"error\"];\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\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/** 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/**\n * Record when an object holds its input gate with blockConcurrencyWhile,\n * on the state prototype so constructors are covered too; the wrapper only\n * records and calls the native method.\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 return native.call(this, async () => {\n gateDepth.set(this, (gateDepth.get(this) ?? 0) + 1);\n try {\n return await callback();\n } finally {\n gateDepth.set(this, (gateDepth.get(this) ?? 1) - 1);\n }\n });\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 /** 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 }\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 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 }\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/** 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, touched, alarms: book } = 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, and take over its alarms first. */\n async function reach(real: DurableObjectStub): 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 touched.add(id);\n await typed(helpers).runInDurableObject(real, (_instance, live) => {\n watchGate(live);\n state.states.set(id, live);\n return takeOverAlarms(\n live.storage,\n alarmControl(book, binding, id, object, () => ctx.hooks),\n );\n });\n }\n }\n\n /** A result passed back to the Worker; 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 }\n return 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: CALL,\n hostsEffects: true,\n },\n perform,\n summarize,\n {\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);\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 return plain(await Reflect.apply(method, real, args));\n }),\n );\n const read = () =>\n onObject(prop, { object, property: true }, async () => {\n await reach(real);\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 ctx.hooks.unsupported(\n `${binding}.newUniqueId() is random and differs on replay; use idFromName`,\n );\n return target.newUniqueId(options);\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/** 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 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 function alarmRunner(\n real: DurableObjectNamespace,\n binding: string,\n ctx: ProxyContext,\n helpers: DurableObjectTestHelpers | undefined,\n state: BindingState,\n): (\n id: string,\n object: string,\n info: { readonly retryCount: number; readonly isRetry: boolean },\n gen: number,\n) => Promise<void> {\n return async (id, object, info, gen) => {\n if (!helpers) {\n ctx.hooks.unsupported(`Durable Object binding ${binding} needs the Cloudflare test helpers`);\n return;\n }\n state.touched.add(id);\n await typed(helpers).runInDurableObject(\n real.get(real.idFromString(id)),\n async (instance, live) => {\n watchGate(live);\n state.states.set(id, live);\n await takeOverAlarms(\n live.storage,\n alarmControl(state.alarms, binding, id, object, () => ctx.hooks),\n );\n // Superseded while the effect waited for its turn: the handler of a cancelled alarm never runs.\n const entry = state.alarms.entry(id);\n if (entry.gen !== 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 ctx.hooks.unsupported(\n `Durable Object ${binding} ${object} set an alarm but has no alarm() handler`,\n );\n return;\n }\n await handler.call(instance, info);\n },\n );\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: { readonly [name: string]: { readonly [key: string]: JsonValue } },\n): Promise<void> {\n // Clearing an object constructs it, outside the simulation: its constructor must not reach the network.\n const { requested } = await withoutNetwork(() => clearAndSeed(real, helpers, names, objects));\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}\n\nasync function clearAndSeed(\n real: DurableObjectNamespace,\n helpers: DurableObjectTestHelpers,\n names: ObjectNames,\n objects: { readonly [name: string]: { readonly [key: string]: JsonValue } },\n): Promise<void> {\n const ids = await objectIds(real, helpers, names, Object.keys(objects));\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 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 await state.storage.deleteAll();\n await deleteRealAlarm(state.storage);\n if (entries && Object.keys(entries).length > 0) await state.storage.put(entries);\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}\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: { readonly [name: string]: { readonly [key: string]: JsonValue } },\n onIndirect: (object: string) => void,\n onUnsupported: (reason: string) => void,\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(real, helpers, names, touched, objects, onIndirect, onUnsupported),\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: { readonly [name: string]: { readonly [key: string]: JsonValue } },\n onIndirect: (object: string) => void,\n onUnsupported: (reason: string) => void,\n): Promise<{ readonly [object: string]: readonly JsonValue[] }> {\n const out: Record<string, JsonValue[]> = {};\n for (const id of await objectIds(real, helpers, names, Object.keys(objects))) {\n const name = names.get(id.toString()) ?? id.toString();\n if (!touched.has(id.toString())) {\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 (!Object.hasOwn(objects, name)) continue;\n }\n const entries = touched.has(id.toString())\n ? [\n ...(await typed(helpers).runInDurableObject(real.get(id), (_instance, state) => {\n // Storage Eutaxy never took over belongs to an instance built after the run's calls.\n if (!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 return state.storage.list();\n })),\n ]\n : Object.entries(Object.hasOwn(objects, name) ? (objects[name] ?? {}) : {});\n // Defined, not assigned: an object may be named \"__proto__\".\n Object.defineProperty(out, name, {\n value: entries\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n .map(([key, value]) => ({ key, value: toJson(value) })),\n enumerable: true,\n writable: true,\n configurable: true,\n });\n }\n return out;\n}\n","/** Queue delivery: one invocation per delivery of a message, redelivered until acked or dead-lettered. */\n\nimport type {\n DeliveryResult,\n EventRef,\n FaultKind,\n JsonValue,\n RunHooks,\n ScenarioSpec,\n} from \"@eutaxy/core\";\nimport { CrashSignal } from \"@eutaxy/engine\";\nimport { drainBackground, executionContext, type RunningWorker } from \"./background.ts\";\nimport type { QueueDrive } from \"./scenario.ts\";\n\nconst ACK: readonly FaultKind[] = [\"crash_before\", \"crash_after\"];\n\n/** Deep-copy JSON data so a handler that mutates its message cannot leak into other runs. */\nfunction 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 /** Cloudflare honours the first ack or retry decision per message; later ones are ignored. */\n const state: { decision: \"ack\" | \"retry\" | null } = { decision: null };\n const background: Promise<unknown>[] = [];\n\n /** Records the call; the result says whether it took effect (the first decision wins). */\n const decide = (op: \"ack\" | \"retry\", args: JsonValue): void => {\n hooks.effectSync(\n { invocation, target: queueTarget, op, args, allowed: ACK },\n () => {\n if (state.decision !== null) return false;\n state.decision = op;\n return true;\n },\n (effective) => ({ effective }),\n );\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: () => decide(\"ack\", { messageId: event.id, implicit: false, body: event.data }),\n retry: () => decide(\"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 const outcome = Promise.resolve()\n .then(() => handler.call(worker.handler, batch, worker.env, execution))\n .then(\n () => \"completed\" as const,\n (err: unknown) => (err instanceof CrashSignal ? (\"crashed\" as const) : (\"errored\" as const)),\n );\n let status = await Promise.race([\n hooks.settle(outcome, invocation),\n inv.crashed.then(() => \"crashed\" as const),\n ]);\n\n if (status === \"completed\" && state.decision === null) {\n try {\n decide(\"ack\", { messageId: event.id, implicit: true, body: event.data });\n } catch (err) {\n if (err instanceof CrashSignal) status = \"crashed\";\n else throw err;\n }\n }\n\n if (await drainBackground(hooks, inv, invocation, queueTarget, background)) status = \"crashed\";\n\n const followUps: EventRef[] = [];\n if (state.decision !== \"ack\") {\n const redeliveries = event.attempt - 1;\n if (event.attempt <= maxRetries && redeliveries < spec.bounds.maxRedeliveries) {\n followUps.push({ ...event, attempt: event.attempt + 1 });\n } else {\n hooks.effectSync(\n {\n invocation: hooks.bookkeeping(),\n target: queueTarget,\n op: \"dead_letter\",\n args: { messageId: event.id, attempts: event.attempt },\n allowed: [],\n },\n () => null,\n () => null,\n );\n }\n }\n return { status, followUps };\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.\n */\n\nimport { type EffectPoint, type FaultKind, type JsonValue, toJson } from \"@eutaxy/core\";\nimport type { ProxyContext } from \"./d1.ts\";\n\nconst WRITE: readonly FaultKind[] = [\"crash_before\", \"crash_after\", \"ambiguous\", \"error\"];\nconst READ: readonly FaultKind[] = [\"crash_before\", \"crash_after\", \"error\"];\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 invocation: ctx.currentInvocation(),\n target,\n op,\n args,\n allowed,\n });\n const notModelled = (what: string): never => {\n const reason = `R2 ${binding}: ${what} is not modelled`;\n ctx.hooks.unsupported(reason);\n throw new Error(`eutaxy: ${reason}`);\n };\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) }, WRITE),\n 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] }, WRITE),\n () => real.delete(keys),\n () => null,\n ),\n get: (key: string, options?: R2GetOptions) =>\n ctx.hooks.effect(\n point(\"get\", getArgs(key, options), READ),\n 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 }, READ),\n 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 ?? {}), READ),\n 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 * 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 type JsonValue,\n type RunHooks,\n toJson,\n} from \"@eutaxy/core\";\nimport { CrashSignal, InjectedEffectError } from \"@eutaxy/engine\";\nimport { drainBackground, executionContext } from \"./background.ts\";\nimport type { ProxyContext } from \"./d1.ts\";\n\n/** The `EventRef.source` of a Workflow instance's run. */\nexport const workflowSource = \"workflow\";\n\n/** `create` is a call to the engine: it may never arrive, or arrive with its answer lost. */\nconst CREATE: readonly FaultKind[] = [\"crash_before\", \"crash_after\", \"ambiguous\", \"error\"];\n/** Before a step's callback: the engine restarts before the step runs. */\nconst STEP_START: readonly FaultKind[] = [\"crash_before\"];\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 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/** A persisted step result; a failure is kept as the engine keeps it, serialised (built-in types survive). */\ntype Outcome =\n | { readonly ok: true; readonly value: unknown }\n | { readonly ok: false; readonly error: unknown };\n\nexport interface Instance {\n readonly id: string;\n readonly params: unknown;\n readonly createdAt: number;\n status: \"queued\" | \"running\" | \"complete\" | \"errored\";\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): boolean {\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/** The binding's proxy: instances live in the registry and run as events, never in the real engine. */\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 const reason = `Workflow ${binding}: ${what} is not modelled`;\n ctx.hooks.unsupported(reason);\n throw new Error(`eutaxy: ${reason}`);\n };\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 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: () => unsupported(\"sendEvent()\"),\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 allowed: CREATE,\n },\n 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 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 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/** Sets `ctx` and `env` as `WorkflowEntrypoint` does, 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 `WorkflowEntrypoint` subclass outside the runtime. workerd's\n * base constructor accepts only a native ExecutionContext, so for this one\n * synchronous `new` the class that extends it directly extends a stand-in\n * instead; its own constructor and field initialisers run as written, and\n * the base is put back before anything else can run.\n */\nexport function constructWorkflow(cls: unknown, ctx: unknown, env: unknown): 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 WorkflowEntrypoint`);\n if ((parent as { name: string }).name === \"WorkflowEntrypoint\") break;\n direct = parent;\n }\n const base = 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, base);\n }\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 = `${event.id}#${event.attempt}`;\n const inv = hooks.startInvocation(invocation);\n const target = `Workflow:${d.binding}`;\n const instance = d.instance;\n instance.status = \"running\";\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 throw structuredClone(o.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 (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.\n await hooks.effect(\n { invocation, target, op: \"step\", args, allowed: STEP_START },\n async () => null,\n () => null,\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 try {\n returned = { value: await fn(stepContext) };\n } catch (err) {\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, 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 let kept: unknown;\n try {\n kept = structuredClone(thrown);\n } catch {\n kept = new Error(String(thrown));\n }\n instance.persisted.set(k, { ok: false, error: kept });\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: () => {\n hooks.unsupported(`Workflow ${d.binding}: step.waitForEvent is not modelled`);\n throw new Error(\"eutaxy: step.waitForEvent is not modelled\");\n },\n };\n async function sleepStep(k: string, name: string, ms: number, until?: number): Promise<void> {\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 hooks.effectSync(\n {\n invocation,\n target,\n op: \"sleep\",\n args: { instance: instance.id, step: name, ms, ...(until === undefined ? {} : { until }) },\n allowed: [],\n },\n () => null,\n () => null,\n );\n await sleep(ms);\n instance.persisted.set(k, { ok: true, value: null });\n }\n\n const outcome = Promise.resolve()\n .then(() => {\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 flow.run(workflowEvent, step);\n })\n .then(\n (value) => {\n // The engine keeps the result serialised: one it cannot keep fails the instance.\n try {\n return { status: \"completed\" as const, 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\" as const,\n error: new Error(\"run() returned a value that is not structured-cloneable\"),\n };\n }\n },\n (error: unknown) =>\n error instanceof CrashSignal\n ? { status: \"crashed\" as const }\n : { status: \"errored\" as const, error },\n );\n const result = await Promise.race([\n hooks.settle(outcome, invocation),\n inv.crashed.then(() => ({ status: \"crashed\" as const })),\n ]);\n let status = result.status;\n if (result.status === \"completed\") {\n instance.status = \"complete\";\n instance.output = result.value;\n hooks.effectSync(\n {\n invocation,\n target,\n op: \"complete\",\n args: { instance: instance.id, output: toJson(instance.output) },\n allowed: [],\n },\n () => null,\n () => null,\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 hooks.effectSync(\n {\n invocation,\n target,\n op: \"errored\",\n args: { instance: instance.id, error: `${instance.error.name}: ${instance.error.message}` },\n allowed: [],\n },\n () => null,\n () => null,\n );\n }\n if (await drainBackground(hooks, inv, invocation, target, background)) status = \"crashed\";\n // The engine restarts a crashed instance from the start of `run`; crashes come from faults, so few.\n const followUps =\n status === \"crashed\" && instance.status === \"running\" && event.attempt <= d.maxFaultsPerRun\n ? [{ ...event, attempt: event.attempt + 1 }]\n : [];\n return { status, followUps };\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 * 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 type {\n DeliveryResult,\n EventRef,\n JsonValue,\n Platform,\n RunHooks,\n ScenarioSpec,\n} from \"@eutaxy/core\";\nimport { alarmSource, deliverAlarm } from \"./alarms.ts\";\nimport type { RunningWorker } from \"./background.ts\";\nimport { isD1, type ProxyContext, proxyD1, resetD1, snapshotD1 } from \"./d1.ts\";\nimport {\n alarmRunner,\n BindingState,\n type DurableObjectTestHelpers,\n evictObject,\n isDurableObjectNamespace,\n proxyNamespace,\n resetNamespace,\n snapshotNamespace,\n} from \"./durable-objects.ts\";\nimport { deliverRequest } from \"./http.ts\";\nimport { deliverMessage } from \"./queues.ts\";\nimport { isR2, proxyR2, resetR2, snapshotR2, VersionBook } from \"./r2.ts\";\nimport {\n type DurableObjectSetup,\n defaultAlarmsPerObject,\n type HttpDrive,\n type QueueDrive,\n type R2Setup,\n type WorkflowSetup,\n} from \"./scenario.ts\";\nimport {\n deliverWorkflow,\n isWorkflowBinding,\n proxyWorkflow,\n WorkflowRegistry,\n workflowSource,\n} from \"./workflows.ts\";\n\n/** The Worker's default export, as far as the platform drives it. */\nexport interface WorkerHandler {\n queue?(batch: MessageBatch<unknown>, env: unknown, ctx: ExecutionContext): void | Promise<void>;\n fetch?(request: Request, env: unknown, ctx: ExecutionContext): Response | Promise<Response>;\n}\n\nexport interface CloudflarePlatformOptions {\n /** The bindings from `cloudflare:workers`. */\n readonly env: object;\n /** The Worker's default export. */\n readonly handler: WorkerHandler;\n /** Schema SQL per D1 binding named in the scenario's setup. */\n readonly schemas: Readonly<Record<string, string>>;\n /** Cloudflare's default when the consumer does not set max_retries. */\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\nfunction isBindingLike(value: unknown): boolean {\n if (typeof value === \"function\") return true;\n if (typeof value !== \"object\" || value === null) return false;\n const proto = Object.getPrototypeOf(value) as object | null;\n const names = [...Object.getOwnPropertyNames(value), ...Object.getOwnPropertyNames(proto ?? {})];\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\",\n \"message.timestamp is the virtual clock's time at delivery\",\n \"only D1, Durable Object, R2 and Workflow bindings are proxied; touching any other binding makes the run UNSUPPORTED\",\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; storage operations are not turns (the input gate holds other events during them); the object's own binding calls are not recorded; objects are cleared, seeded and evicted before each run and their storage is snapshotted after 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: the attempt ran but counted as failed, 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; step timeouts are not measured (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];\n\nexport function createCloudflarePlatform(options: CloudflarePlatformOptions): Platform {\n const env = options.env as Record<string, unknown>;\n const maxRetries = options.maxRetries ?? 3;\n let hooksRef: RunHooks | null = null;\n\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 };\n\n const d1Proxies = new Map<string, D1Database>();\n const doProxies = new Map<string, DurableObjectNamespace>();\n /** The Durable Object bindings the current scenario's setup resets before each run. */\n let resetBindings = new Set<string>();\n /** Per binding, what the current run knows about its objects. */\n const bindingStates = new Map<string, BindingState>();\n const stateFor = (binding: string): BindingState => {\n let state = bindingStates.get(binding);\n if (!state) {\n state = new BindingState();\n bindingStates.set(binding, state);\n }\n return state;\n };\n /** Per binding, alarm firings allowed per object in the current run. */\n let alarmLimits = new Map<string, number>();\n /** The Workflow bindings the current scenario sets up, with the class each runs. */\n let workflowClasses = 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 workflowProxies = new Map<string, object>();\n /** The R2 buckets the current scenario sets up, and their proxies' version stand-ins. */\n let r2Bindings = new Set<string>();\n const r2Proxies = new Map<string, R2Bucket>();\n const versions = new VersionBook();\n const namespace = (binding: string): DurableObjectNamespace => {\n const real = env[binding];\n if (!isDurableObjectNamespace(real))\n throw new Error(`env.${binding} is not a Durable Object namespace`);\n return real;\n };\n const helpers = (): DurableObjectTestHelpers => {\n if (!options.durableObjects)\n throw new Error(\n 'Durable Object setup needs the Cloudflare test helpers: createCloudflarePlatform({ ..., durableObjects: await import(\"cloudflare:test\") })',\n );\n return options.durableObjects;\n };\n const proxiedEnv = new Proxy(env, {\n get(target, prop, receiver) {\n const value = Reflect.get(target, prop, receiver) as unknown;\n if (typeof prop !== \"string\") return value;\n if (isD1(value)) {\n let p = d1Proxies.get(prop);\n if (!p) {\n p = proxyD1(value, prop, ctx);\n d1Proxies.set(prop, p);\n }\n return p;\n }\n if (isDurableObjectNamespace(value)) {\n let p = doProxies.get(prop);\n if (!p) {\n p = proxyNamespace(value, prop, ctx, stateFor(prop), options.durableObjects, () =>\n resetBindings.has(prop),\n );\n doProxies.set(prop, p);\n }\n return p;\n }\n if (isR2(value)) {\n if (!r2Bindings.has(prop))\n ctx.hooks.unsupported(\n `R2 binding ${prop} needs an r2Bucket() setup step, which empties it before each run`,\n );\n let p = r2Proxies.get(prop);\n if (!p) {\n p = proxyR2(value, prop, ctx, versions);\n r2Proxies.set(prop, p);\n }\n return p;\n }\n if (isWorkflowBinding(value)) {\n if (!workflowClasses.has(prop)) {\n ctx.hooks.unsupported(\n `Workflow binding ${prop} 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(prop, ctx, new WorkflowRegistry());\n }\n let p = workflowProxies.get(prop);\n if (!p) {\n p = proxyWorkflow(prop, ctx, registryFor(prop));\n workflowProxies.set(prop, p);\n }\n return p;\n }\n if (isBindingLike(value)) ctx.hooks.unsupported(`binding ${prop} is not proxied`);\n return value;\n },\n });\n const worker: RunningWorker = { handler: options.handler, env: proxiedEnv };\n\n return {\n name: \"cloudflare\",\n assumptions,\n concurrent: true,\n\n async reset(spec: ScenarioSpec): Promise<void> {\n resetBindings = new Set();\n alarmLimits = new Map();\n workflowClasses = new Map();\n r2Bindings = new Set();\n versions.clear();\n for (const state of bindingStates.values()) state.clear();\n for (const registry of registries.values()) registry.clear();\n for (const step of spec.setup) {\n if (step.kind === \"workflow\") {\n const setup = step as WorkflowSetup;\n workflowClasses.set(setup.binding, setup);\n continue;\n }\n if (step.kind === \"r2\") {\n const setup = step as R2Setup;\n const real = env[setup.binding];\n if (!isR2(real)) throw new Error(`env.${setup.binding} is not an R2 bucket`);\n r2Bindings.add(setup.binding);\n await resetR2(real, setup.objects);\n continue;\n }\n if (step.kind === \"durable_object\") {\n const setup = step as DurableObjectSetup;\n resetBindings.add(setup.binding);\n alarmLimits.set(setup.binding, setup.alarmsPerObject ?? defaultAlarmsPerObject);\n await resetNamespace(\n namespace(setup.binding),\n helpers(),\n stateFor(setup.binding).names,\n setup.objects,\n );\n continue;\n }\n if (step.kind !== \"d1\") continue;\n const binding = String(step[\"binding\"]);\n const schema = options.schemas[binding];\n if (schema === undefined) throw new Error(`no schema provided for D1 binding ${binding}`);\n const real = env[binding];\n if (!isD1(real)) throw new Error(`env.${binding} is not a D1 binding`);\n await resetD1(real, schema);\n }\n },\n\n restrictEvents(spec: ScenarioSpec, keepIds: readonly string[]): ScenarioSpec {\n const drive = spec.drive as QueueDrive | HttpDrive;\n if (drive.kind === \"http\") {\n return {\n ...spec,\n drive: { ...drive, requests: drive.requests.filter((r) => keepIds.includes(r.id)) },\n };\n }\n return {\n ...spec,\n drive: { ...drive, messages: drive.messages.filter((m) => keepIds.includes(m.id)) },\n };\n },\n\n async finish(spec: ScenarioSpec, hooks: RunHooks): Promise<void> {\n for (const step of spec.setup) {\n if (step.kind === \"r2\") {\n const binding = (step as R2Setup).binding;\n const real = env[binding];\n if (isR2(real))\n hooks.snapshot(hooks.bookkeeping(), `R2:${binding}`, {\n tables: { objects: await snapshotR2(real) },\n });\n continue;\n }\n if (step.kind === \"workflow\") {\n const binding = (step as WorkflowSetup).binding;\n hooks.snapshot(hooks.bookkeeping(), `Workflow:${binding}`, {\n tables: { instances: registryFor(binding).rows() },\n });\n continue;\n }\n if (step.kind === \"durable_object\") {\n const setup = step as DurableObjectSetup;\n const binding = setup.binding;\n const tables = await snapshotNamespace(\n namespace(binding),\n helpers(),\n stateFor(binding).names,\n stateFor(binding).touched,\n setup.objects,\n (object) =>\n hooks.unsupported(\n `Durable Object ${binding} ${object} was reached without a call Eutaxy saw (through another object's binding); calls between objects are not proxied yet`,\n ),\n (reason) => hooks.unsupported(reason),\n );\n hooks.snapshot(hooks.bookkeeping(), `DO:${binding}`, { tables });\n continue;\n }\n if (step.kind !== \"d1\") continue;\n const binding = String(step[\"binding\"]);\n const real = env[binding];\n if (!isD1(real)) continue;\n const tables = await snapshotD1(real);\n hooks.snapshot(hooks.bookkeeping(), `D1:${binding}`, { tables });\n }\n },\n\n initialEvents(spec: ScenarioSpec): readonly EventRef[] {\n const drive = spec.drive as QueueDrive | HttpDrive;\n if (drive.kind === \"http\") {\n return drive.requests.map((r) => ({\n id: r.id,\n attempt: 1,\n data: r as unknown as JsonValue,\n }));\n }\n return drive.messages.map((m) => ({ id: m.id, attempt: 1, data: m.body }));\n },\n\n async deliver(event: EventRef, hooks: RunHooks, spec: ScenarioSpec): Promise<DeliveryResult> {\n const drive = spec.drive as QueueDrive | HttpDrive;\n const invocation = `${event.id}#${event.attempt}`;\n hooksRef = hooks;\n if (event.source === workflowSource) {\n const { binding, id } = event.data as { binding: string; id: string };\n const setup = workflowClasses.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 const cls = options.exports?.[className];\n const instance = registryFor(binding).instances.get(id);\n if (typeof cls !== \"function\" || !instance) {\n hooks.unsupported(\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: proxiedEnv,\n maxFaultsPerRun: spec.bounds.maxFaultsPerRun,\n maxRedeliveries: spec.bounds.maxRedeliveries,\n });\n }\n if (event.source === alarmSource) {\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 runAlarm: alarmRunner(\n namespace(binding),\n binding,\n ctx,\n options.durableObjects,\n stateFor(binding),\n ),\n abort: (id) => stateFor(binding).abort(id),\n mayPark: (id) => stateFor(binding).mayPark(id),\n evict: (id) => evictObject(namespace(binding), options.durableObjects, id),\n bookkeep: (op, args) =>\n hooks.effectSync(\n {\n invocation: hooks.bookkeeping(),\n target: `DO:${binding}`,\n op,\n args,\n allowed: [],\n },\n () => null,\n () => null,\n ),\n });\n }\n return drive.kind === \"http\"\n ? await deliverRequest(event, hooks, spec, drive, invocation, worker)\n : await deliverMessage(event, hooks, spec, drive, invocation, worker, maxRetries);\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 by hand on the raw side. Any difference in the per-attempt decisions or in\n * the final D1 and R2 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; what it does not share is any proxy code.\n */\n\nimport { type EventRef, getPath, type JsonValue, type ScenarioSpec } from \"@eutaxy/core\";\nimport {\n CrashSignal,\n compareSides,\n DifferentialStuck,\n effectLatencyMs,\n installScriptedFetch,\n patchGlobals,\n proxiedSide,\n settleOn,\n type VirtualClock,\n} from \"@eutaxy/engine\";\nimport { executionContext } from \"./background.ts\";\nimport { isD1, resetD1, snapshotD1 } from \"./d1.ts\";\nimport { requestFor } from \"./http.ts\";\nimport { type CloudflarePlatformOptions, createCloudflarePlatform } from \"./platform.ts\";\nimport { isR2, resetR2, snapshotR2 } from \"./r2.ts\";\nimport type { HttpDrive, HttpRequestSpec, QueueDrive, R2Setup } from \"./scenario.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. */\n readonly decision: \"ack\" | \"retry\" | null;\n /** HTTP drive: the response status the caller saw (500 for an uncaught exception). */\n readonly response?: number;\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\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\nasync function snapshotAll(\n spec: ScenarioSpec,\n options: CloudflarePlatformOptions,\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 step of spec.setup) {\n if (step.kind === \"r2\") {\n const binding = (step as R2Setup).binding;\n const real = env[binding];\n if (isR2(real)) out[binding] = { objects: await snapshotR2(real) };\n continue;\n }\n if (step.kind !== \"d1\") continue;\n const binding = String(step[\"binding\"]);\n const real = env[binding];\n if (isD1(real)) out[binding] = await snapshotD1(real);\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): 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 = `${event.id}#${event.attempt}`;\n const mine = entries.filter((e) => e.invocation === invocation);\n const decision = 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 return {\n event: event.id,\n attempt: event.attempt,\n status: result.status === \"completed\" ? \"completed\" : \"errored\",\n decision: decision ?? null,\n ...(response ? { response: getPath(response.payload, \"result.status\") as number } : {}),\n };\n },\n );\n return { attempts, state: await snapshotAll(spec, options), 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 raw side: the handler called directly with the real bindings and plain message or Request objects. */\nasync function rawSide(spec: ScenarioSpec, options: CloudflarePlatformOptions): Promise<Side> {\n const env = options.env as Record<string, unknown>;\n const drive = spec.drive as QueueDrive | HttpDrive;\n const maxRetries = options.maxRetries ?? 3;\n for (const step of spec.setup) {\n if (step.kind === \"r2\") {\n const setup = step as R2Setup;\n const real = env[setup.binding];\n if (isR2(real)) await resetR2(real, setup.objects);\n continue;\n }\n if (step.kind !== \"d1\") continue;\n const binding = String(step[\"binding\"]);\n const schema = options.schemas[binding];\n const real = env[binding];\n if (schema !== undefined && isD1(real)) await resetD1(real, schema);\n }\n const attempts: AttemptRecord[] = [];\n const pending: EventRef[] =\n drive.kind === \"http\"\n ? drive.requests.map((r) => ({ id: r.id, attempt: 1, data: r as unknown as JsonValue }))\n : drive.messages.map((m) => ({ id: m.id, attempt: 1, data: m.body }));\n // The same virtual globals as the proxied side, from the same seed, so Date.now and randomness agree,\n // and the same scripted externals, without recording.\n const patched = patchGlobals(0);\n const unsupported: string[] = [];\n const restoreFetch = installScriptedFetch(\n spec.externals,\n null,\n (r) => unsupported.push(r),\n () => patched.clock.advance(effectLatencyMs), // the proxied side advances per effect; match it\n );\n const io = { n: 0 };\n const counting = new Map<string, D1Database | R2Bucket>();\n const countedEnv = new Proxy(env, {\n get(target, prop, receiver) {\n const value = Reflect.get(target, prop, receiver) as unknown;\n if (typeof prop !== \"string\" || !(isD1(value) || isR2(value))) return value;\n let c = counting.get(prop);\n if (!c) {\n c = isD1(value)\n ? countingD1(value, io, patched.clock)\n : countingR2(value, io, patched.clock);\n counting.set(prop, c);\n }\n return c;\n },\n });\n const settle = <T>(p: Promise<T>): Promise<T> =>\n settleOn(p, {\n clock: patched.clock,\n inFlight: () => io.n,\n crashed: () => false,\n stuck: () => {\n throw new DifferentialStuck();\n },\n });\n try {\n if (drive.kind === \"http\") {\n const handler = options.handler.fetch;\n if (!handler) throw new Error(\"the Worker has no fetch() handler\");\n while (pending.length > 0) {\n const event = pending.shift() as EventRef;\n const req = event.data as unknown as HttpRequestSpec;\n const background: Promise<unknown>[] = [];\n let status: \"completed\" | \"errored\";\n let response = 500;\n try {\n const r = await settle(\n Promise.resolve().then(() =>\n handler.call(\n options.handler,\n requestFor(req),\n countedEnv,\n executionContext(background),\n ),\n ),\n );\n await settle(r.clone().text());\n response = r.status;\n status = \"completed\";\n } catch (err) {\n if (err instanceof CrashSignal || err instanceof DifferentialStuck) throw err;\n status = \"errored\";\n }\n await settle(Promise.all(background));\n attempts.push({\n event: event.id,\n attempt: event.attempt,\n status,\n decision: null,\n response,\n });\n const accepted =\n drive.retryOn === \"5xx\" ? response < 500 : response >= 200 && response < 300;\n if (\n !accepted &&\n event.attempt - 1 < drive.retries &&\n event.attempt - 1 < spec.bounds.maxRedeliveries\n ) {\n pending.push({ ...event, attempt: event.attempt + 1 });\n }\n }\n } else {\n const handler = options.handler.queue;\n if (!handler) throw new Error(\"the Worker has no queue() handler\");\n while (pending.length > 0) {\n const event = pending.shift() as EventRef;\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: JSON.parse(JSON.stringify(event.data)) as JsonValue,\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 ctx = executionContext(background);\n let status: \"completed\" | \"errored\";\n try {\n await settle(\n Promise.resolve().then(() => handler.call(options.handler, batch, countedEnv, ctx)),\n );\n status = \"completed\";\n } catch (err) {\n if (err instanceof CrashSignal || err instanceof DifferentialStuck) throw err;\n status = \"errored\";\n }\n if (status === \"completed\") decision ??= \"ack\";\n await settle(Promise.all(background));\n attempts.push({ event: event.id, attempt: event.attempt, status, decision });\n if (\n decision !== \"ack\" &&\n event.attempt <= maxRetries &&\n event.attempt - 1 < spec.bounds.maxRedeliveries\n ) {\n pending.push({ ...event, attempt: event.attempt + 1 });\n }\n }\n }\n } finally {\n restoreFetch();\n patched.restore();\n }\n if (unsupported.length > 0) throw new DifferentialStuck(`raw side: ${unsupported.join(\"; \")}`);\n return { attempts, state: await snapshotAll(spec, options) };\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 (spec.drive.kind === \"http\" && (\"delaysMs\" in spec.drive || \"deadlineMs\" in spec.drive)) {\n throw new Error(\"runDifferential does not model the caller's delaysMs or deadlineMs yet\");\n }\n const { unsupported, ...eutaxy } = await eutaxySide(spec, options);\n const raw = await rawSide(spec, options);\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 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, lemmaBool, lemmaUnresolved, type ModulePredicates } 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 annotations. */\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 core modules observed (as the scenario's specs name them) and the functions on each. */\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 module: the module's extracted specs and its compiled predicates. */\nexport interface SpecEntry {\n readonly specs: ModuleSpecs;\n readonly predicates: (\n namespace: object,\n bool: typeof lemmaBool,\n unresolved: typeof lemmaUnresolved,\n ) => ModulePredicates;\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/** Each D1 binding's schema, read from the `.sql` files next to the scenario. */\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 schemas[String(step[\"binding\"])] = 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 readonly predicates: ModulePredicates;\n /** The functions observed: the annotated ones, 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 * every reason the check cannot go ahead: a module that is not there, an\n * annotation that does not parse, a function name observed in two modules\n * (decisions are logged by name, so it would be ambiguous).\n */\nexport async function selectSpecModules(\n scenario: ScenarioSpec,\n modules: ModuleGlob,\n specLoaders: Readonly<Record<string, () => Promise<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 loadSpec = Object.hasOwn(specLoaders, key) ? specLoaders[key] : undefined;\n const entry = loadSpec ? await loadSpec() : undefined;\n const specs: ModuleSpecs = entry?.specs ?? { functions: [], exports: [], errors: [] };\n for (const e of specs.errors) specErrors.push({ module: path, ...e });\n const exported = decisions.filter((d) => typeof namespace[d] === \"function\");\n const names = [...new Set([...specs.functions.map((f) => f.name), ...exported])];\n const predicates = entry ? entry.predicates(namespace, lemmaBool, lemmaUnresolved) : {};\n selected.push({ path, key, namespace, specs, predicates, 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\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` loaders, by module key. */\n readonly specLoaders: Readonly<Record<string, () => Promise<SpecEntry>>>;\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);\n const load = input.modules[globKey(scenario.worker.entry)];\n if (!load)\n throw new Error(`worker entry ${scenario.worker.entry} not found next to the scenario`);\n const worker = (await load()) as { default: WorkerHandler } & Record<string, unknown>;\n const platform = createCloudflarePlatform({\n env: input.env,\n handler: worker.default,\n schemas,\n durableObjects: input.durableObjects,\n exports: worker,\n });\n const { selected, specErrors } = await selectSpecModules(\n scenario,\n input.modules,\n input.specLoaders,\n );\n const transportBase = { worker: scenario.worker, setup: scenario.setup };\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(m.key, m.specs, m.predicates, 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":";;;;;;;;;AAOA,SAAgB,UAAU,MAAyB,WAA8B,CAAC,GAAe;CAC/F,MAAM,cAAwB,CAAC;CAC/B,MAAM,QAAuC,CAAC;CAC9C,KAAK,IAAI,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;EACpC,MAAM,IAAI,KAAK;EACf,IAAI,CAAC,EAAE,WAAW,IAAI,GAAG;GACvB,YAAY,KAAK,CAAC;GAClB;EACF;EACA,MAAM,KAAK,EAAE,QAAQ,GAA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