eutaxy 0.9.1 → 0.10.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.
Files changed (34) hide show
  1. package/README.md +10 -8
  2. package/dist/aws.d.mts +2 -2
  3. package/dist/aws.d.mts.map +1 -1
  4. package/dist/aws.mjs +20 -36
  5. package/dist/aws.mjs.map +1 -1
  6. package/dist/bin.mjs +2 -2
  7. package/dist/cli-Di86EM3f.mjs +2 -0
  8. package/dist/cli.mjs +2 -2
  9. package/dist/cloudflare.d.mts +149 -14
  10. package/dist/cloudflare.d.mts.map +1 -1
  11. package/dist/cloudflare.mjs +3 -3
  12. package/dist/delivery-invariants-Br29H7Rg.mjs +62 -0
  13. package/dist/delivery-invariants-Br29H7Rg.mjs.map +1 -0
  14. package/dist/{delivery-invariants-DfPkJL0Q.d.mts → delivery-invariants-DZOBkCMR.d.mts} +2 -2
  15. package/dist/{delivery-invariants-DfPkJL0Q.d.mts.map → delivery-invariants-DZOBkCMR.d.mts.map} +1 -1
  16. package/dist/{explore-Rwe1PPqX.d.mts → explore-B7aR_5Hy.d.mts} +2 -2
  17. package/dist/{explore-Rwe1PPqX.d.mts.map → explore-B7aR_5Hy.d.mts.map} +1 -1
  18. package/dist/index.d.mts +2 -2
  19. package/dist/index.mjs +2 -2
  20. package/dist/{platform-Bpnav0kn.d.mts → platform-CCz48WF9.d.mts} +30 -30
  21. package/dist/platform-CCz48WF9.d.mts.map +1 -0
  22. package/dist/{src-Db2r3ZDr.mjs → src-CWVQEhTr.mjs} +2 -2
  23. package/dist/{src-Db2r3ZDr.mjs.map → src-CWVQEhTr.mjs.map} +1 -1
  24. package/dist/{src-BRjmbzMV.mjs → src-DGh7w877.mjs} +365 -246
  25. package/dist/src-DGh7w877.mjs.map +1 -0
  26. package/dist/{src-BnTcWa-4.mjs → src-MX90l1IH.mjs} +2747 -1737
  27. package/dist/src-MX90l1IH.mjs.map +1 -0
  28. package/package.json +1 -1
  29. package/dist/cli-CVdHb_gU.mjs +0 -2
  30. package/dist/delivery-invariants-Cg3eVKSw.mjs +0 -39
  31. package/dist/delivery-invariants-Cg3eVKSw.mjs.map +0 -1
  32. package/dist/platform-Bpnav0kn.d.mts.map +0 -1
  33. package/dist/src-BRjmbzMV.mjs.map +0 -1
  34. package/dist/src-BnTcWa-4.mjs.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"src-BnTcWa-4.mjs","names":["join","ident","fail","env","term","emitFunction","binderType","arrowTerm","installHint","run","candidates","engineName","engineAssumptions","proven","unknown","prepare","proveModule","WRITE","READ","retryDelayMs","coreAtLeastOncePerMessage","retryDelayMs"],"sources":["../../cli/src/args.ts","../../prover/src/reader/compiler.ts","../../prover/src/reader/expressions.ts","../../prover/src/reader/types.ts","../../prover/src/reader/subset.ts","../../prover/src/reader/specs.ts","../../prover-lean/src/emit.ts","../../prover-lean/src/lean.ts","../../prover-lean/src/supplied.ts","../../prover-lean/src/prove.ts","../../prover-smt/src/emit.ts","../../prover-smt/src/z3.ts","../../prover-smt/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/report.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 TypeScript compiler, through its API (7.1): one compiler process per\n * Node process, started on first use; a program per read, over an\n * in-memory layer holding the files being read on top of the host's own\n * files, so imports resolve as the user's compiler resolves them; a\n * standalone source file for text that is not a module (a spec file's\n * arrow, read back from its text). Every handle the compiler process\n * holds for a read is released when the read ends. Nothing else in Eutaxy\n * imports the compiler API: a change to it lands here.\n */\n\nimport {\n type FunctionLikeBase,\n type Identifier,\n ModifierFlags,\n type ModifiersBase,\n type Node,\n NodeFlags,\n type SourceFile,\n SyntaxKind,\n type VariableDeclarationList,\n} from \"typescript/ast\";\nimport { createFileSystemLayer } from \"typescript/fs\";\nimport { API, type Checker, DiagnosticCategory, type Program } from \"typescript/sync\";\n\nlet api: API | undefined;\n\nfunction compiler(): API {\n api ??= new API({});\n return api;\n}\n\n/** Stop the compiler process; the next read starts another. */\nexport function closeCompiler(): void {\n api?.close();\n api = undefined;\n}\n\n/**\n * The options every read compiles under: strict, the latest language\n * level, bundler-style resolution with `.ts` imports allowed, and the\n * standard library alone (`types: []`), so a module's own types resolve\n * and nothing is emitted. The user's configuration is not read: a type\n * Eutaxy cannot resolve under these options is reported unknown, never\n * guessed.\n */\nconst options = {\n strict: true,\n target: 99, // ScriptTarget.ESNext\n module: 99, // ModuleKind.ESNext\n moduleResolution: 100, // ModuleResolutionKind.Bundler\n allowImportingTsExtensions: true,\n noEmit: true,\n skipLibCheck: true,\n types: [] as string[],\n lib: [\"es2023\"],\n};\n\n/** A file given to a read: its path, under which imports resolve, and its text, which stands in for the file on disk. */\nexport interface InputFile {\n readonly path: string;\n readonly text: string;\n}\n\n/** A program over the input files, with its checker. */\nexport interface Opened {\n readonly program: Program;\n readonly checker: Checker;\n /** The source file of an input path. */\n readonly file: (path: string) => SourceFile;\n /** The first parse error of an input file, if any. */\n readonly parseError: (path: string) => { line: number; message: string } | undefined;\n /** The compiler's errors in a file of the program: text ranges (offsets into the file), with the message and its line. */\n readonly typeErrors: (path: string) => readonly CompilerError[];\n /**\n * Whether an identifier names the global of its name: the compiler\n * resolves it to a symbol declared in its default library alone\n * (`lib.*.d.ts`). A declaration, import or block-scoped shadow of the\n * name in scope, a global declared by the project's own declaration\n * files, or a name the compiler cannot resolve is not; a type-only\n * import of the name is, since the compiler resolves a value past it,\n * and so is an interface augmentation of its type (`declare global {\n * interface Number { … } }`), which changes no value.\n */\n readonly standardGlobal: (id: Identifier) => boolean;\n}\n\n/** One compiler error in a file: its text range, message and 1-based line. */\nexport interface CompilerError {\n readonly pos: number;\n readonly end: number;\n readonly message: string;\n readonly line: number;\n}\n\n/** Run `fn` over a program whose root files are the inputs, released afterwards. */\nexport function withProgram<T>(files: readonly InputFile[], fn: (opened: Opened) => T): T {\n const snapshot = compiler().createSnapshot({\n fileSystem: createFileSystemLayer(files.map((f) => [f.path, f.text] as const)),\n createPrograms: [{ rootFiles: files.map((f) => f.path), compilerOptions: options }],\n });\n try {\n const program = snapshot.operation.createdPrograms[0];\n const checker = program.getProject().checker;\n const file = (path: string): SourceFile => {\n const sf = program.getSourceFile(path);\n if (!sf) throw new Error(`the compiler holds no source file for ${path}`);\n return sf;\n };\n const parseError = (path: string) => {\n const first = program.getSyntacticDiagnostics(path)[0];\n return first\n ? { line: (first.startPosition?.line ?? 0) + 1, message: first.text }\n : undefined;\n };\n const errors = new Map<string, readonly CompilerError[]>();\n const typeErrors = (path: string) => {\n let found = errors.get(path);\n if (!found) {\n found = program\n .getSemanticDiagnostics(path)\n .filter((d) => d.category === DiagnosticCategory.Error)\n .map((d) => ({\n pos: d.pos,\n end: d.end,\n message: d.text,\n line: (d.startPosition?.line ?? 0) + 1,\n }));\n errors.set(path, found);\n }\n return found;\n };\n // Answers by symbol: the global `Math` is one symbol however often it is named. Interface and\n // type alias declarations merge into a symbol without touching its value, so only the others decide.\n const standard = new Map<number, boolean>();\n const typeOnly = new Set([SyntaxKind.InterfaceDeclaration, SyntaxKind.TypeAliasDeclaration]);\n const standardGlobal = (id: Identifier): boolean => {\n const symbol = checker.getSymbolAtLocation(id);\n if (!symbol) return false;\n let known = standard.get(symbol.id);\n if (known === undefined) {\n const values = symbol.declarations.filter((d) => !typeOnly.has(d.kind));\n known =\n values.length > 0 &&\n values.every((d) => {\n const sf = d.resolve()?.getSourceFile();\n return sf !== undefined && program.isSourceFileDefaultLibrary(sf);\n });\n standard.set(symbol.id, known);\n }\n return known;\n };\n return fn({ program, checker, file, parseError, typeErrors, standardGlobal });\n } finally {\n snapshot.dispose();\n }\n}\n\n/** Run `fn` over a source file parsed from `text` alone (no program, no checker), released afterwards. */\nexport function withSourceFile<T>(text: string, fn: (sf: SourceFile) => T): T {\n const lease = compiler().createSourceFile(\"/eutaxy/reader/fragment.ts\", text);\n try {\n return fn(lease.sourceFile);\n } finally {\n lease.dispose();\n }\n}\n\n/** 1-based line of a node's first token. */\nexport function lineAt(sf: SourceFile, node: Node): number {\n return sf.getLineAndCharacterOfPosition(node.getStart(sf)).line + 1;\n}\n\n/** A node's text, leading trivia excluded. */\nexport function textOf(sf: SourceFile, node: Node): string {\n return sf.text.slice(node.getStart(sf), node.end);\n}\n\nexport function isExported(node: ModifiersBase): boolean {\n return (node.modifierFlags & ModifierFlags.Export) !== 0;\n}\n\nexport function isAsync(node: ModifiersBase): boolean {\n return (node.modifierFlags & ModifierFlags.Async) !== 0;\n}\n\nexport function isConst(list: VariableDeclarationList): boolean {\n return (list.flags & NodeFlags.Const) !== 0;\n}\n\n/**\n * The offset of the `(` opening a function's parameter list: the\n * declaration's identity, as the spec reader and the subset reader both\n * record it. Undefined for an arrow written without parentheses.\n */\nexport function openParen(sf: SourceFile, fn: FunctionLikeBase): number | undefined {\n const at = fn.parameters.pos - 1;\n return sf.text[at] === \"(\" ? at : undefined;\n}\n\n/** The name of a syntax kind, for messages. */\nexport function kindName(kind: SyntaxKind): string {\n return SyntaxKind[kind] ?? String(kind);\n}\n","/**\n * Function bodies and spec arrows read from the compiler's syntax tree\n * into the subset's `Expr`: `const` bindings, `if` with early returns,\n * `return`, and expressions from arithmetic, comparisons, `&& || !`, the\n * conditional operator, record and array literals, field reads, list\n * methods and calls to the module's own functions. What a name stands\n * for comes from the scope (parameters and consts) and from `Names`: the\n * module's own functions when the text is the module, the spec file's\n * imports when it is an arrow. Anything else is `OutsideSubset` with the\n * construct named and its line.\n */\n\nimport {\n type ArrowFunction,\n type BinaryExpression,\n type Block,\n type CallExpression,\n type Expression,\n type Identifier,\n type Node,\n type ObjectLiteralExpression,\n type ReturnStatement,\n type SourceFile,\n type Statement,\n SyntaxKind,\n type TypeNode,\n} from \"typescript/ast\";\nimport * as is from \"typescript/ast/is\";\nimport { isAsync, isConst, kindName, lineAt, textOf } from \"./compiler.ts\";\nimport {\n type BinaryOp,\n type Expr,\n hasLoneSurrogate,\n insertNarrows,\n OutsideSubset,\n type SubsetType,\n type TypeContext,\n tagOf,\n typeOf,\n} from \"./subset.ts\";\nimport type { Refuse } from \"./types.ts\";\n\n/**\n * A call to a function the text cannot call by name (a generic one, or one\n * imported from another file) read as that function's body, bound to the\n * arguments: undefined when the callee is no such function, so the call is\n * refused as before. `readArgs` reads the arguments in the caller's scope,\n * a record literal argument typed as the parameter it is passed for when\n * that type is given; `fail` refuses at the call.\n */\nexport type Inline = (\n call: CallExpression,\n callee: Identifier,\n scope: Scope,\n readArgs: (types: readonly (SubsetType | undefined)[]) => Expr[],\n fail: (what: string) => never,\n) => Expr | undefined;\n\n/**\n * A name the text reads that is neither in scope nor a function: a\n * module-level `const` of the text's file or one it imports, read as its\n * initializer (a `const` holding a pure value is that value wherever it is\n * read). Undefined when the name is no such constant, so it is refused as\n * before; `fail` refuses at the name.\n */\nexport type Constant = (name: Identifier, fail: (what: string) => never) => Expr | undefined;\n\n/** What the bare names of the text being read stand for, outside any local scope. */\nexport interface Names {\n /** A function the subset may call under this name. */\n readonly callable: (name: string) => boolean;\n /** The module function a callable name stands for (a spec file's local name resolves to the module's). */\n readonly target: (name: string) => string;\n /** A function the text may name at all, in the subset or not: for messages. */\n readonly declared: (name: string) => boolean;\n /** Whether the text is a spec file's, whose names are its imports, never the module's. */\n readonly spec: boolean;\n /**\n * Whether an identifier is the global of its name (`Math`, `Number`):\n * for a module, the compiler resolves it to its standard library; for a\n * spec file's arrow, read from its text alone, every built-in it names\n * has been checked so by the spec reader, so any is.\n */\n readonly global: (id: Identifier) => boolean;\n}\n\n/** Where the types a body mentions come from: the compiler for the module, the module's own declared types for an arrow. */\nexport interface TypeSource {\n /** The subset type a `const` annotation names. */\n readonly annotation: (node: TypeNode, refuse: Refuse) => SubsetType;\n /** The type the context gives a record literal, when the compiler knows one the subset takes. */\n readonly contextual: (node: ObjectLiteralExpression) => SubsetType | undefined;\n}\n\nexport type Scope = ReadonlyMap<string, SubsetType>;\n\nconst binaryOps: Partial<Record<SyntaxKind, BinaryOp>> = {\n [SyntaxKind.PlusToken]: \"+\",\n [SyntaxKind.MinusToken]: \"-\",\n [SyntaxKind.AsteriskToken]: \"*\",\n [SyntaxKind.SlashToken]: \"/\",\n [SyntaxKind.LessThanToken]: \"<\",\n [SyntaxKind.LessThanEqualsToken]: \"<=\",\n [SyntaxKind.GreaterThanToken]: \">\",\n [SyntaxKind.GreaterThanEqualsToken]: \">=\",\n [SyntaxKind.EqualsEqualsEqualsToken]: \"===\",\n [SyntaxKind.ExclamationEqualsEqualsToken]: \"!==\",\n [SyntaxKind.AmpersandAmpersandToken]: \"&&\",\n [SyntaxKind.BarBarToken]: \"||\",\n};\n\nconst methods = new Set([\"slice\", \"map\", \"flatMap\", \"every\", \"some\", \"reduce\"]);\n\n/** The reader of one text: a function body, or an arrow of the spec file. */\nexport class ExprReader {\n readonly sf: SourceFile;\n readonly names: Names;\n readonly types: TypeSource;\n readonly ctx: TypeContext;\n /** The line a refusal reports for a node: the file's, or none for text whose position the caller knows. */\n private readonly lineOf: (node: Node) => number;\n private readonly inline: Inline | undefined;\n private readonly constant: Constant | undefined;\n /** Record literals typed by the call they are passed to, in place of the compiler's contextual type. */\n private readonly typedAs = new Map<Node, SubsetType>();\n\n constructor(\n sf: SourceFile,\n names: Names,\n types: TypeSource,\n ctx: TypeContext,\n lineOf: (node: Node) => number = (node) => lineAt(sf, node),\n inline?: Inline,\n constant?: Constant,\n ) {\n this.sf = sf;\n this.names = names;\n this.types = types;\n this.ctx = ctx;\n this.lineOf = lineOf;\n this.inline = inline;\n this.constant = constant;\n }\n\n /** Whether an identifier is the global of its name here: no scope or function shadows it, and the names confirm it. */\n private global(id: Identifier, scope: Scope): boolean {\n return !scope.has(id.text) && !this.names.declared(id.text) && this.names.global(id);\n }\n\n fail(what: string, at: Node): never {\n throw new OutsideSubset(what, this.lineOf(at));\n }\n\n /** `OutsideSubset` at a node, for a type read there. */\n refuseAt(at: Node): Refuse {\n return (what) => this.fail(what, at);\n }\n\n text(node: Node): string {\n return textOf(this.sf, node);\n }\n\n /** The expression with `narrow` nodes inserted where a null check guards a nullable name. */\n narrowed(e: Expr, scope: Scope, at: Node): Expr {\n return insertNarrows(e, scope, this.ctx, (m) => this.fail(m, at));\n }\n\n typeOfExpr(e: Expr, scope: Scope, at: Node, expected?: SubsetType): SubsetType {\n return typeOf(e, scope, this.ctx, (m) => this.fail(m, at), expected);\n }\n\n /**\n * A block's statements as one expression: `const` becomes `let`, `if (c)\n * return a; rest` a conditional, and the last statement must return:\n * every path ends in a `return`.\n */\n block(statements: readonly Statement[], scope: Scope, end: Node): Expr {\n return this.statements(statements, 0, scope, end);\n }\n\n private statements(statements: readonly Statement[], i: number, scope: Scope, end: Node): Expr {\n const s = statements[i];\n if (!s) this.fail(\"a path that does not return\", end);\n if (is.isEmptyStatement(s)) return this.statements(statements, i + 1, scope, end);\n if (is.isVariableStatement(s)) {\n const list = s.declarationList;\n if (!isConst(list)) this.fail(\"a mutable binding (use const)\", s);\n const [decl, second] = list.declarations;\n if (!decl || second) this.fail(\"several bindings in one const\", s);\n if (!is.isIdentifier(decl.name)) this.fail(\"a destructured const\", decl.name);\n const name = decl.name.text;\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.names.declared(name))\n this.fail(`const ${name} shadows the module's function ${name} in its block`, decl.name);\n if (scope.has(name))\n this.fail(`const ${name} redeclares a name already bound here`, decl.name);\n const annotated = decl.type\n ? this.types.annotation(decl.type, this.refuseAt(decl.type))\n : undefined;\n if (!decl.initializer) this.fail(`const ${name} without a value`, decl);\n const value = this.expression(decl.initializer, scope);\n // While reading, the scope carries names; types come from `typeOf` once null checks have narrowed\n // the tree, so an initializer under a guard is typed as the guard allows. The annotation is the\n // binding's type (a null initializer is then a nullable, not null); `typeOf` checks it fits.\n const inner = new Map(scope);\n inner.set(name, annotated ?? { kind: \"null\" });\n const body = this.statements(statements, i + 1, inner, end);\n return { kind: \"let\", name, value, body, ...(annotated ? { type: annotated } : {}) };\n }\n if (is.isIfStatement(s)) {\n const test = this.expression(s.expression, scope);\n const then = this.branch(s.thenStatement, scope);\n if (s.elseStatement) {\n const otherwise = this.branch(s.elseStatement, scope);\n const after = statements[i + 1];\n if (after) this.fail(\"statements after an if/else that both return\", after);\n return { kind: \"cond\", test, ifTrue: then, ifFalse: otherwise };\n }\n return {\n kind: \"cond\",\n test,\n ifTrue: then,\n ifFalse: this.statements(statements, i + 1, scope, end),\n };\n }\n if (is.isReturnStatement(s)) {\n const after = statements[i + 1];\n // `return` then a line break: JavaScript inserts a semicolon and returns undefined.\n if (!s.expression && after) {\n const gap = this.sf.text.slice(\n s.getStart(this.sf) + \"return\".length,\n after.getStart(this.sf),\n );\n if (/[\\n\\r\\u2028\\u2029]/.test(gap))\n this.fail(\n \"a line break after return (JavaScript inserts a semicolon and returns undefined)\",\n s,\n );\n }\n const value = this.returned(s, scope);\n if (after) this.fail(\"statements after a return\", after);\n return value;\n }\n if (\n is.isForStatement(s) ||\n is.isForOfStatement(s) ||\n is.isForInStatement(s) ||\n is.isWhileStatement(s) ||\n is.isDoStatement(s)\n )\n this.fail(\"a loop\", s);\n if (is.isThrowStatement(s)) this.fail(\"throw\", s);\n if (is.isSwitchStatement(s)) this.fail(\"switch\", s);\n if (is.isTryStatement(s)) this.fail(\"try\", s);\n if (is.isFunctionDeclaration(s)) this.fail(\"a nested function\", s);\n this.fail(`statement starting with ${this.text(s).split(/\\s/)[0] ?? kindName(s.kind)}`, s);\n }\n\n /** An `if` branch: `return e;` or `{ ...statements ending in return }`. */\n private branch(s: Statement, scope: Scope): Expr {\n if (is.isBlock(s)) return this.block(s.statements, scope, s);\n if (is.isReturnStatement(s)) return this.returned(s, scope);\n this.fail(\"an if branch that does not return\", s);\n }\n\n /** `return e;`. A line break after `return` makes JavaScript return undefined: no value, refused. */\n private returned(s: ReturnStatement, scope: Scope): Expr {\n if (!s.expression) this.fail(\"a return without a value\", s);\n return this.expression(s.expression, scope);\n }\n\n expression(node: Expression, scope: Scope): Expr {\n if (is.isParenthesizedExpression(node)) return this.expression(node.expression, scope);\n if (is.isIdentifier(node)) return this.identifier(node, scope);\n if (is.isNumericLiteral(node)) {\n const raw = this.text(node);\n if (!/^[0-9](_?[0-9])*$/.test(raw))\n this.fail(`the numeric literal ${raw} (integers in decimal only)`, node);\n return { kind: \"int\", value: raw.replace(/_/g, \"\") };\n }\n if (is.isBigIntLiteral(node)) this.fail(`the bigint literal ${this.text(node)}`, node);\n if (is.isStringLiteral(node)) {\n if (hasLoneSurrogate(node.text))\n this.fail(\"a string literal with a lone surrogate, which Lean's strings cannot hold\", node);\n return { kind: \"string\", value: node.text };\n }\n if (is.isNoSubstitutionTemplateLiteral(node) || is.isTemplateExpression(node))\n this.fail(\"a template literal\", node);\n if (is.isRegularExpressionLiteral(node)) this.fail(\"a regular expression\", node);\n if (node.kind === SyntaxKind.TrueKeyword) return { kind: \"bool\", value: true };\n if (node.kind === SyntaxKind.FalseKeyword) return { kind: \"bool\", value: false };\n if (node.kind === SyntaxKind.NullKeyword) return { kind: \"null\" };\n if (is.isPrefixUnaryExpression(node)) {\n if (node.operator === SyntaxKind.ExclamationToken)\n return { kind: \"not\", operand: this.expression(node.operand, scope) };\n if (node.operator === SyntaxKind.MinusToken) {\n const operand = this.expression(node.operand, 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 (node.operator === SyntaxKind.PlusToken) this.fail(\"unary plus\", node);\n this.fail(`the ${this.text(node).slice(0, 2)} operator`, node);\n }\n if (is.isPostfixUnaryExpression(node))\n this.fail(`the ${this.text(node).slice(-2)} operator`, node);\n if (is.isTypeOfExpression(node)) this.fail(\"the typeof operator\", node);\n if (is.isVoidExpression(node)) this.fail(\"the void operator\", node);\n if (is.isAwaitExpression(node)) this.fail(\"the await operator\", node);\n if (is.isNewExpression(node)) this.fail(\"the new operator\", node);\n if (is.isDeleteExpression(node)) this.fail(\"the delete operator\", node);\n if (is.isBinaryExpression(node)) return this.binary(node, scope);\n if (is.isConditionalExpression(node))\n return {\n kind: \"cond\",\n test: this.expression(node.condition, scope),\n ifTrue: this.expression(node.whenTrue, scope),\n ifFalse: this.expression(node.whenFalse, scope),\n };\n if (is.isCallExpression(node)) return this.call(node, scope);\n if (is.isPropertyAccessExpression(node)) {\n if (node.questionDotToken) this.fail(\"optional chaining\", node);\n if (!is.isIdentifier(node.name)) this.fail(\"a private field\", node.name);\n return {\n kind: \"field\",\n object: this.expression(node.expression, scope),\n field: node.name.text,\n };\n }\n if (is.isElementAccessExpression(node)) {\n if (this.isHead(node))\n this.fail(\"xs[0] without ?? fallback (it is undefined on an empty list)\", node);\n this.fail(\"index access other than xs[0] ?? fallback\", node);\n }\n if (is.isObjectLiteralExpression(node)) return this.record(node, scope);\n if (is.isArrayLiteralExpression(node)) {\n const items: Expr[] = [];\n let rest: Expr | undefined;\n for (const item of node.elements) {\n if (rest) this.fail(\"a spread that is not last in an array literal\", item);\n if (is.isSpreadElement(item)) rest = this.expression(item.expression, scope);\n else if (is.isOmittedExpression(item)) this.fail(\"a hole in an array literal\", item);\n else items.push(this.expression(item, scope));\n }\n return { kind: \"list\", items, ...(rest ? { rest } : {}) };\n }\n if (is.isArrowFunction(node) || is.isFunctionExpression(node))\n this.fail(\"a function expression (the subset has callbacks of list methods only)\", node);\n if (is.isAsExpression(node)) this.fail(\"the as operator\", node);\n if (is.isSatisfiesExpression(node)) this.fail(\"the satisfies operator\", node);\n if (is.isNonNullExpression(node)) this.fail(\"the ! assertion\", node);\n if (is.isTypeAssertion(node)) this.fail(\"a type assertion\", node);\n if (node.kind === SyntaxKind.ThisKeyword) this.fail(\"this\", node);\n this.fail(`unexpected ${this.text(node) || kindName(node.kind)}`, node);\n }\n\n private identifier(node: Identifier, scope: Scope): Expr {\n const name = node.text;\n if (name === \"undefined\") this.fail(\"undefined (the subset has null)\", node);\n if (scope.has(name) || this.names.declared(name)) return { kind: \"var\", name };\n const constant = this.constant?.(node, (what) => this.fail(what, node));\n if (constant) return constant;\n // A built-in the compiler resolves to something other than its standard library: an import of the\n // name, say. (`Math.abs` reaches here too, as the global: its method is what the subset lacks.)\n if ((name === \"Math\" || name === \"Number\") && !this.names.global(node))\n this.fail(\n `${name}, which is not the standard ${name} here: a declaration of it other than the compiler's is in scope`,\n node,\n );\n this.fail(\n this.names.spec\n ? `${name}, which is neither a parameter, a const nor a function imported from the module beside the spec file`\n : `${name}, which is neither a parameter, a const nor a function of this module`,\n node,\n );\n }\n\n /** Whether an element access is `xs[0]`. */\n private isHead(node: Node): boolean {\n return (\n is.isElementAccessExpression(node) &&\n is.isNumericLiteral(node.argumentExpression) &&\n this.text(node.argumentExpression) === \"0\"\n );\n }\n\n private binary(node: BinaryExpression, scope: Scope): Expr {\n const kind = node.operatorToken.kind;\n const op = binaryOps[kind];\n if (op) {\n return {\n kind: \"binary\",\n op,\n left: this.expression(node.left, scope),\n right: this.expression(node.right, scope),\n };\n }\n if (kind === SyntaxKind.QuestionQuestionToken) {\n // `xs[0] ?? fallback` only: any other index may be past the end, which is undefined.\n if (is.isBinaryExpression(node.left) && node.left.operatorToken.kind === kind)\n this.fail(\"a chain of ??\", node);\n if (is.isElementAccessExpression(node.left) && !this.isHead(node.left))\n this.fail(\"index access other than xs[0] ?? fallback\", node.left);\n if (!is.isElementAccessExpression(node.left))\n this.fail(\n \"?? after anything but xs[0] (write xs[0] ?? fallback, parenthesized where it meets other operators)\",\n node,\n );\n if (node.left.questionDotToken) this.fail(\"optional chaining\", node.left);\n return {\n kind: \"headOr\",\n list: this.expression(node.left.expression, scope),\n fallback: this.expression(node.right, scope),\n };\n }\n if (kind >= SyntaxKind.FirstAssignment && kind <= SyntaxKind.LastAssignment)\n this.fail(\"an assignment\", node);\n if (kind === SyntaxKind.CommaToken) this.fail(\"the comma operator\", node);\n if (kind === SyntaxKind.InKeyword || kind === SyntaxKind.InstanceOfKeyword)\n this.fail(`the ${this.text(node.operatorToken)} operator`, node);\n this.fail(`the ${this.text(node.operatorToken)} operator`, node);\n }\n\n private call(node: CallExpression, scope: Scope): Expr {\n if (node.questionDotToken) this.fail(\"optional chaining\", node);\n let callee = node.expression;\n while (is.isParenthesizedExpression(callee)) callee = callee.expression;\n if (is.isPropertyAccessExpression(callee)) {\n if (callee.questionDotToken) this.fail(\"optional chaining\", callee);\n if (!is.isIdentifier(callee.name)) this.fail(\"a private method\", callee.name);\n const method = callee.name.text;\n const receiver = callee.expression;\n if (\n is.isIdentifier(receiver) &&\n receiver.text === \"Number\" &&\n method === \"isInteger\" &&\n this.global(receiver, scope)\n ) {\n const [arg, extra] = node.arguments;\n if (!arg || extra) this.fail(\"Number.isInteger takes one argument\", node);\n return { kind: \"isInteger\", operand: this.expression(arg, scope) };\n }\n if (\n is.isIdentifier(receiver) &&\n receiver.text === \"Math\" &&\n method === \"floor\" &&\n this.global(receiver, scope)\n ) {\n const [arg, extra] = node.arguments;\n if (!arg || extra) this.fail(\"Math.floor takes one argument\", node);\n return { kind: \"floor\", operand: this.expression(arg, scope) };\n }\n // The receiver first: `Math.abs` fails on `Math`, a name of nothing here, before its method.\n const list = this.expression(receiver, scope);\n if (!methods.has(method))\n this.fail(\n `the method ${method} (the subset has slice(1), map, flatMap, every, some and reduce)`,\n callee.name,\n );\n return this.method(node, list, method, scope);\n }\n if (!is.isIdentifier(callee)) this.fail(\"a call to a computed callee\", callee);\n const name = callee.text;\n // A binder or local named like a function shadows it: the call is to a number, which throws.\n if (scope.has(name))\n this.fail(`a call to ${name}, which names a value here, not the module's function`, callee);\n if (!this.names.callable(name) && this.inline) {\n const readArgs = (types: readonly (SubsetType | undefined)[]): Expr[] =>\n node.arguments.map((a, i) => {\n if (is.isSpreadElement(a)) this.fail(\"a spread argument\", a);\n const type = types[i];\n if (!type) return this.expression(a, scope);\n // The literals the argument evaluates to: itself, or a conditional's branches.\n const literals: Node[] = [];\n const collect = (e: Expression): void => {\n if (is.isParenthesizedExpression(e)) collect(e.expression);\n else if (is.isConditionalExpression(e)) {\n collect(e.whenTrue);\n collect(e.whenFalse);\n } else if (is.isObjectLiteralExpression(e)) literals.push(e);\n };\n collect(a);\n for (const l of literals) this.typedAs.set(l, type);\n try {\n return this.expression(a, scope);\n } finally {\n for (const l of literals) this.typedAs.delete(l);\n }\n });\n const inlined = this.inline(node, callee, scope, readArgs, (what) => this.fail(what, node));\n if (inlined) return inlined;\n }\n if (!this.names.declared(name)) this.identifier(callee, scope); // names nothing here: its message\n if (!this.names.callable(name))\n this.fail(`a call to ${name}, which is outside the subset`, callee);\n return {\n kind: \"call\",\n callee: this.names.target(name),\n args: node.arguments.map((a) => {\n if (is.isSpreadElement(a)) this.fail(\"a spread argument\", a);\n return this.expression(a, scope);\n }),\n };\n }\n\n /** `(a, b) => body` or `a => body`, an expression body only; the names it binds go into scope. */\n private callback(\n node: Expression,\n scope: Scope,\n arity: number,\n what: string,\n ): { names: string[]; body: Expr } {\n if (!is.isArrowFunction(node)) this.fail(`${what} takes an arrow function`, node);\n const arrow: ArrowFunction = node;\n // An async callback returns a promise, truthy whatever the body computes.\n if (isAsync(arrow)) this.fail(`an async callback in ${what}`, arrow);\n const names: string[] = [];\n for (const p of arrow.parameters) {\n if (!is.isIdentifier(p.name)) this.fail(`a destructured parameter of ${what}'s callback`, p);\n if (p.type) this.fail(`a type annotation on ${what}'s parameter`, p.type);\n if (p.initializer) this.fail(`a default value on ${what}'s parameter`, p);\n if (p.dotDotDotToken) this.fail(`a rest parameter on ${what}'s callback`, p);\n names.push(p.name.text);\n }\n if (names.length === 0 || names.length > arity)\n this.fail(\n `${what} takes a callback of 1 to ${arity} parameter(s), given ${names.length}`,\n arrow,\n );\n for (const n of names)\n if (scope.has(n) || this.names.declared(n))\n this.fail(`${what}'s parameter ${n} shadows a name already bound here`, arrow);\n if (new Set(names).size !== names.length)\n this.fail(`${what}'s parameters repeat a name`, arrow);\n if (is.isBlock(arrow.body))\n this.fail(`a block body in ${what}'s callback (write an expression)`, arrow.body);\n const inner = new Map(scope);\n for (const n of names) inner.set(n, { kind: \"null\" });\n return { names, body: this.expression(arrow.body, inner) };\n }\n\n /** A method call on a list: slice(1), map, flatMap, every, some, reduce. */\n private method(node: CallExpression, list: Expr, name: string, scope: Scope): Expr {\n const args = node.arguments;\n if (name === \"slice\") {\n const [one, extra] = args;\n if (!one || extra || !is.isNumericLiteral(one) || this.text(one) !== \"1\")\n this.fail(\"slice with an argument other than 1\", one ?? node);\n return { kind: \"tail\", list };\n }\n if (name === \"reduce\") {\n const [cb, init, extra] = args;\n if (!cb || !init || extra) this.fail(\"reduce takes a callback and an initial value\", node);\n const { names, body } = this.callback(cb, scope, 2, \"reduce\");\n if (names.length !== 2) this.fail(\"reduce takes a callback of (accumulator, item)\", cb);\n return {\n kind: \"fold\",\n list,\n acc: names[0] as string,\n item: names[1] as string,\n body,\n init: this.expression(init, scope),\n };\n }\n const [cb, extra] = args;\n if (!cb || extra) this.fail(`${name} takes one callback`, node);\n const { names, body } = this.callback(cb, scope, 2, name);\n return {\n kind: \"iterate\",\n op: name as \"map\" | \"flatMap\" | \"every\" | \"some\",\n list,\n item: names[0] as string,\n ...(names[1] === undefined ? {} : { index: names[1] }),\n body,\n };\n }\n\n private record(node: ObjectLiteralExpression, scope: Scope): Expr {\n const fields: { name: string; value: Expr }[] = [];\n for (const p of node.properties) {\n if (is.isSpreadAssignment(p)) this.fail(\"spread in a record literal\", p);\n if (is.isShorthandPropertyAssignment(p)) {\n if (!is.isIdentifier(p.name))\n this.fail(`a key that is not a name: ${this.text(p.name)}`, p.name);\n const name = p.name.text;\n if (name === \"__proto__\")\n this.fail(\"a __proto__ key, which sets the prototype, not a field\", p);\n if (!scope.has(name)) this.fail(`shorthand ${name} names nothing in scope`, p);\n fields.push({ name, value: { kind: \"var\", name } });\n continue;\n }\n if (!is.isPropertyAssignment(p)) this.fail(`a method ${this.text(p).split(\"(\")[0] ?? \"\"}`, p);\n if (is.isComputedPropertyName(p.name)) this.fail(\"a computed key\", p.name);\n if (!is.isIdentifier(p.name))\n this.fail(`a key that is not a name: ${this.text(p.name)}`, p.name);\n if (p.name.text === \"__proto__\")\n this.fail(\"a __proto__ key, which sets the prototype, not a field\", p.name);\n fields.push({ name: p.name.text, value: this.expression(p.initializer, scope) });\n }\n const type = this.typedAs.get(node) ?? this.types.contextual(node);\n const literal = (fs: typeof fields): Expr => ({\n kind: \"record\",\n fields: fs,\n ...(type ? { type } : {}),\n });\n // A member of a union picked by a conditional tag (`{ type: c ? \"a\" : \"b\", at }`) is one literal\n // per branch: the conditional moves out, the other fields go into each as written. The fields\n // are pure, so evaluating the test first computes the same value.\n const tag = type?.kind === \"union\" ? tagOf(type.name, this.ctx) : undefined;\n const chosen = tag === undefined ? undefined : fields.find((f) => f.name === tag);\n if (chosen?.value.kind === \"cond\") {\n const split = (value: Expr): Expr =>\n value.kind === \"cond\"\n ? {\n kind: \"cond\",\n test: value.test,\n ifTrue: split(value.ifTrue),\n ifFalse: split(value.ifFalse),\n }\n : literal(fields.map((f) => (f === chosen ? { name: f.name, value } : f)));\n return split(chosen.value);\n }\n return literal(fields);\n }\n}\n\n/**\n * A `const` annotation inside a spec arrow, read from its syntax against\n * the module's declared types: no compiler stands behind an arrow's\n * text, so a name must be a record or union the module reads, and the\n * forms are the primitives, `null`, literals, unions of those and arrays.\n */\nexport function syntacticType(\n sf: SourceFile,\n node: TypeNode,\n records: ReadonlySet<string>,\n unions: ReadonlySet<string>,\n refuse: Refuse,\n): SubsetType {\n const go = (n: TypeNode): SubsetType => syntacticType(sf, n, records, unions, refuse);\n if (is.isParenthesizedTypeNode(node)) return go(node.type);\n if (is.isTypeOperatorNode(node) && node.operator === SyntaxKind.ReadonlyKeyword) {\n if (!is.isArrayTypeNode(node.type))\n return refuse(\"readonly before a type that is not an array\");\n return go(node.type);\n }\n if (is.isArrayTypeNode(node)) return { kind: \"list\", element: go(node.elementType) };\n if (node.kind === SyntaxKind.NumberKeyword) return { kind: \"int\" };\n if (node.kind === SyntaxKind.BooleanKeyword) return { kind: \"bool\" };\n if (node.kind === SyntaxKind.StringKeyword) return { kind: \"string\" };\n if (node.kind === SyntaxKind.UndefinedKeyword)\n return refuse(\"undefined in a type (the subset has null)\");\n if (is.isLiteralTypeNode(node)) {\n const lit = node.literal;\n if (lit.kind === SyntaxKind.NullKeyword) return { kind: \"null\" };\n if (lit.kind === SyntaxKind.TrueKeyword || lit.kind === SyntaxKind.FalseKeyword)\n return { kind: \"bool\" };\n if (is.isStringLiteral(lit)) return { kind: \"string\" };\n return refuse(`the literal type ${textOf(sf, node)}`);\n }\n if (is.isTypeReferenceNode(node)) {\n if (node.typeArguments)\n return refuse(`type ${textOf(sf, node)} (a generic type in an arrow's const)`);\n if (!is.isIdentifier(node.typeName)) return refuse(`type ${textOf(sf, node)}`);\n const name = node.typeName.text;\n if (records.has(name)) return { kind: \"record\", name };\n if (unions.has(name)) return { kind: \"union\", name };\n return refuse(\n `type ${name} (the subset has number, boolean, string, null, and the module's own record types and unions)`,\n );\n }\n if (is.isUnionTypeNode(node)) {\n const members = node.types.map(go);\n const nulls = members.filter((m) => m.kind === \"null\");\n const rest = members.filter((m) => m.kind !== \"null\");\n const first = rest[0];\n if (!first) return refuse(\"null alone is not a type the subset takes\");\n if (!rest.every((m) => JSON.stringify(m) === JSON.stringify(first)))\n return refuse(\"a union of several types (declare it as a type alias in the module)\");\n if (nulls.length === 0) return first;\n return first.kind === \"nullable\" ? first : { kind: \"nullable\", inner: first };\n }\n return refuse(`type ${textOf(sf, node)}`);\n}\n\n/**\n * The block body of an arrow read from a parsed fragment: the statements\n * between the braces, every path returning.\n */\nexport function blockOf(sf: SourceFile): Block | undefined {\n const [first, second] = sf.statements;\n return first && !second && is.isBlock(first) ? first : undefined;\n}\n","/**\n * The compiler's types read two ways. `specTypeOf` reads a type into\n * `SpecType` as far as the spec surface describes it (primitives,\n * literals, records, unions, arrays), marking the rest `unknown` with its\n * text: binder domains for the simulator's rungs. `SubsetTypes` reads a\n * type into the subset's own types (integers, booleans, strings, records,\n * nullable types, tagged unions, lists), naming every record and union it\n * meets so the engines can declare them: a declared type by its name, an\n * instantiated generic or an inline object type as the compiler prints\n * it, a union member declared inline by its union and its tag. Both read\n * what the compiler resolved, so a type declared later in the file, in\n * another file, or through a generic alias reads as its structure.\n */\n\nimport type { SpecType } from \"@eutaxy/spec\";\nimport { SyntaxKind } from \"typescript/ast\";\nimport * as is from \"typescript/ast/is\";\nimport {\n type Checker,\n SymbolFlags,\n type Type,\n TypeFlags,\n TypeFormatFlags,\n type TypeReference,\n} from \"typescript/sync\";\nimport type { Field, RecordType, SubsetType, UnionType } from \"./subset.ts\";\n\n/** Levels of records and lists inside one another a type may hold before it is cut (a generic instantiating itself anew at each level never repeats). */\nconst maxDepth = 16;\n\n/**\n * Why an object type is not plain data, or undefined when it is: a class\n * (an instance is more than its fields: nominal, with private ones), or an\n * interface over a base the compiler could not resolve (it then shows the\n * interface's own fields alone) or over a class.\n */\nexport function notPlain(\n checker: Checker,\n type: Type,\n seen: Set<number> = new Set(),\n): string | undefined {\n const symbol = type.getSymbol();\n if (!symbol || seen.has(type.id)) return undefined;\n seen.add(type.id);\n if ((symbol.flags & SymbolFlags.Class) !== 0)\n return \"a class (an instance is more than a record of its fields)\";\n if ((symbol.flags & SymbolFlags.Interface) === 0) return undefined;\n for (const handle of symbol.declarations) {\n if (handle.kind !== SyntaxKind.InterfaceDeclaration) continue;\n const decl = handle.resolve();\n if (!decl || !is.isInterfaceDeclaration(decl)) continue;\n for (const clause of decl.heritageClauses ?? [])\n for (const base of clause.types) {\n const baseType = checker.getTypeAtLocation(base);\n if (baseType.isErrorType()) return `extends ${base.getText()}, which does not resolve`;\n // The whole ancestry: a class anywhere up makes the interface nominal.\n const why = notPlain(checker, baseType, seen);\n if (why !== undefined) return `extends ${base.getText()}: ${why}`;\n }\n }\n return undefined;\n}\n\n/** A type as the compiler prints it, in full. */\nexport function printType(checker: Checker, type: Type): string {\n return checker.typeToString(type, undefined, TypeFormatFlags.NoTruncation);\n}\n\n/**\n * The name a record or union goes by: its alias or interface name when\n * declared without type arguments, otherwise the type as the compiler\n * prints it (`Result<true, Locked>`, `{ readonly ok: boolean; }`).\n */\nexport function nameOfType(checker: Checker, type: Type): string {\n const alias = type.getAliasSymbol();\n if (alias)\n return type.getAliasTypeArguments().length === 0 ? alias.name : printType(checker, type);\n const symbol = type.getSymbol();\n if (\n symbol &&\n (symbol.flags & (SymbolFlags.Interface | SymbolFlags.Class)) !== 0 &&\n !(type.isTypeReference() && checker.getTypeArguments(type).length > 0)\n )\n return symbol.name;\n return printType(checker, type);\n}\n\n/** A union's members with `true | false` folded back into `boolean`, which the compiler keeps apart. */\nfunction foldBooleans(members: readonly Type[]): (Type | \"boolean\")[] {\n const isTrue = (t: Type) => t.isBooleanLiteralType() && t.value === true;\n const isFalse = (t: Type) => t.isBooleanLiteralType() && t.value === false;\n if (!members.some(isTrue) || !members.some(isFalse)) return [...members];\n const out: (Type | \"boolean\")[] = [];\n let folded = false;\n for (const m of members) {\n if (isTrue(m) || isFalse(m)) {\n if (!folded) out.push(\"boolean\");\n folded = true;\n } else out.push(m);\n }\n return out;\n}\n\n/** The members of a union as one type: flattened, deduplicated, one member alone. */\nexport function unionOf(members: readonly SpecType[]): SpecType {\n const flat = members.flatMap((m) => (m.kind === \"union\" ? m.members : [m]));\n const seen = new Set<string>();\n const unique = flat.filter((m) => {\n const key = JSON.stringify(m);\n if (seen.has(key)) return false;\n seen.add(key);\n return true;\n });\n return unique.length === 1 ? (unique[0] as SpecType) : { kind: \"union\", members: unique };\n}\n\n/** A type into `SpecType`; what the spec surface does not describe is `unknown` with the type's text. */\nexport function specTypeOf(\n checker: Checker,\n type: Type,\n seen: ReadonlySet<number> = new Set(),\n): SpecType {\n const unknown = (): SpecType => ({ kind: \"unknown\", text: printType(checker, type) });\n const flags = type.flags;\n if (type.isErrorType()) return unknown();\n if (flags & TypeFlags.Number) return { kind: \"number\" };\n if (flags & TypeFlags.String) return { kind: \"string\" };\n if (flags & TypeFlags.Boolean) return { kind: \"boolean\" };\n if (flags & TypeFlags.BigInt) return { kind: \"bigint\" };\n if (type.isStringLiteralType() || type.isNumberLiteralType() || type.isBooleanLiteralType())\n return { kind: \"literal\", value: type.value };\n if (flags & TypeFlags.Null) return { kind: \"null\" };\n if (flags & (TypeFlags.Undefined | TypeFlags.Void)) return { kind: \"undefined\" };\n if (type.isUnionType())\n return unionOf(\n foldBooleans(type.getTypes()).map((m) =>\n m === \"boolean\" ? { kind: \"boolean\" } : specTypeOf(checker, m, seen),\n ),\n );\n if (!type.isObjectType()) return unknown();\n // A type reaching itself through a field or an element: the cycle is cut with the type's name;\n // one that nests without repeating is cut at a depth.\n if (seen.has(type.id) || seen.size >= maxDepth) return unknown();\n const inner = new Set(seen).add(type.id);\n if (checker.isArrayType(type)) {\n const element = checker.getTypeArguments(type as TypeReference)[0];\n return element ? { kind: \"array\", element: specTypeOf(checker, element, inner) } : unknown();\n }\n if (\n type.isTupleType() ||\n type.getCallSignatures().length > 0 ||\n type.getConstructSignatures().length > 0 ||\n type.getIndexInfos().length > 0\n )\n return unknown();\n if (notPlain(checker, type) !== undefined) return unknown();\n const properties = type.getProperties();\n // An object with a method or an accessor is no record of plain data (a Map, a class instance), and\n // neither is one keyed by a symbol (the compiler names it `__@key@…`, which no string names).\n const computed = SymbolFlags.Method | SymbolFlags.GetAccessor | SymbolFlags.SetAccessor;\n if (properties.some((p) => (p.flags & computed) !== 0 || isSymbolKey(p.name))) return unknown();\n const fields = properties.map((p) => ({\n name: p.name,\n type: specTypeOf(checker, checker.getTypeOfSymbol(p), inner),\n }));\n return { kind: \"record\", name: nameOfType(checker, type), fields };\n}\n\n/** Whether a property's name is the compiler's spelling of a symbol key, which no string names. */\nconst isSymbolKey = (name: string): boolean => name.startsWith(\"__@\");\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/** `OutsideSubset` at the type being read, by the reader that asked. */\nexport type Refuse = (what: string) => never;\n\n/**\n * The subset's types read from the compiler's, with every record and\n * union met along the way kept by name, in the order met, for the engines\n * to declare. One type is read once: a second meeting gives the same\n * record, and so does another compiler type of the same name and the\n * same fields (an inline type written twice). A type the subset does not\n * take is refused with the construct named, and a read that is refused\n * leaves nothing behind: whatever it registered on the way is taken back,\n * so no record belongs to a union that was never declared.\n */\nexport class SubsetTypes {\n readonly records = new Map<string, RecordType>();\n readonly unions: UnionType[] = [];\n private readonly checker: Checker;\n /** By the compiler's type id. */\n private readonly byId = new Map<number, SubsetType>();\n private readonly idOfName = new Map<string, number>();\n /** Types being read now, to refuse a type that holds itself. */\n private readonly reading = new Set<number>();\n\n constructor(checker: Checker) {\n this.checker = checker;\n }\n\n /** The subset type of a compiler type, or a refusal, after which nothing of the read remains. */\n of(type: Type, refuse: Refuse): SubsetType {\n const cached = this.byId.get(type.id);\n if (cached) return cached;\n if (this.reading.size > 0) return this.enter(type, refuse);\n // The outermost read of a type: all or nothing.\n const saved = {\n records: new Map(this.records),\n idOfName: new Map(this.idOfName),\n byId: new Map(this.byId),\n unions: this.unions.length,\n };\n try {\n return this.enter(type, refuse);\n } catch (err) {\n this.records.clear();\n for (const [k, v] of saved.records) this.records.set(k, v);\n this.idOfName.clear();\n for (const [k, v] of saved.idOfName) this.idOfName.set(k, v);\n this.byId.clear();\n for (const [k, v] of saved.byId) this.byId.set(k, v);\n this.unions.length = saved.unions;\n throw err;\n }\n }\n\n /** A type read under the recursion guard. */\n private enter(type: Type, refuse: Refuse): SubsetType {\n // A type reaching itself, through a field or an element, is refused rather than followed.\n if (this.reading.has(type.id))\n return refuse(`${nameOfType(this.checker, type)} holds itself (a recursive type)`);\n if (this.reading.size >= maxDepth)\n return refuse(\n `${nameOfType(this.checker, type)} is nested too deep (more than ${maxDepth} levels)`,\n );\n this.reading.add(type.id);\n try {\n const out = this.read(type, refuse);\n this.byId.set(type.id, out);\n return out;\n } finally {\n this.reading.delete(type.id);\n }\n }\n\n private read(type: Type, refuse: Refuse): SubsetType {\n const checker = this.checker;\n const text = () => printType(checker, type);\n const flags = type.flags;\n if (type.isErrorType()) return refuse(`type ${text()}, which does not resolve`);\n if (flags & TypeFlags.Number) return { kind: \"int\" };\n if (flags & (TypeFlags.String | TypeFlags.StringLiteral)) return { kind: \"string\" };\n if (flags & (TypeFlags.Boolean | TypeFlags.BooleanLiteral)) return { kind: \"bool\" };\n if (flags & TypeFlags.Null) return refuse(\"null alone is not a type the subset takes\");\n if (flags & (TypeFlags.Undefined | TypeFlags.Void))\n return refuse(\"undefined in a type (the subset has null)\");\n if (flags & TypeFlags.NumberLiteral)\n return refuse(`the numeric literal type ${text()} (the subset has number)`);\n if (flags & TypeFlags.BigInt) return refuse(\"bigint (the subset has number)\");\n if (flags & TypeFlags.TypeParameter) return refuse(\"type parameters\");\n if (type.isUnionType()) return this.union(type, refuse);\n if (type.isIntersectionType()) return refuse(\"an intersection type\");\n if (!type.isObjectType())\n return refuse(\n `type ${text()} (the subset has number, boolean, string, null, and record types, unions and arrays of them)`,\n );\n if (checker.isArrayType(type)) {\n const element = checker.getTypeArguments(type as TypeReference)[0];\n if (!element) return refuse(`type ${text()}`);\n return { kind: \"list\", element: this.of(element, refuse) };\n }\n if (type.isTupleType()) return refuse(\"a tuple type\");\n if (type.getCallSignatures().length > 0 || type.getConstructSignatures().length > 0)\n return refuse(\"a function type\");\n if (type.getIndexInfos().length > 0) return refuse(\"an index signature\");\n const why = notPlain(checker, type);\n if (why !== undefined) return refuse(`type ${text()} is outside the subset: ${why}`);\n const record = this.record(type, nameOfType(checker, type), refuse);\n return { kind: \"record\", name: record.name };\n }\n\n /** A union: `T | null` a nullable, literals their base type, several records a tagged union. */\n private union(type: Type, refuse: Refuse): SubsetType {\n const members = type.isUnionType() ? type.getTypes() : [type];\n if (members.some((m) => (m.flags & (TypeFlags.Undefined | TypeFlags.Void)) !== 0))\n return refuse(\"undefined in a type (the subset has null)\");\n const nulls = members.filter((m) => (m.flags & TypeFlags.Null) !== 0);\n const rest = members.filter((m) => (m.flags & TypeFlags.Null) === 0);\n const bare = nulls.length === 0 ? type : type.getNonNullableType();\n let base: SubsetType;\n if (rest.length === 0) return refuse(\"null alone is not a type the subset takes\");\n else if (rest.every((m) => (m.flags & (TypeFlags.String | TypeFlags.StringLiteral)) !== 0))\n base = { kind: \"string\" };\n else if (rest.every((m) => (m.flags & (TypeFlags.Boolean | TypeFlags.BooleanLiteral)) !== 0))\n base = { kind: \"bool\" };\n else if (rest.length === 1) base = this.of(rest[0] as Type, refuse);\n else if (rest.every((m) => m.isObjectType() && !this.checker.isArrayType(m)))\n base = this.taggedUnion(bare, rest, refuse);\n else if (rest.some((m) => m.isObjectType()))\n return refuse(\"a union mixing records with other types\");\n else if (rest.every((m) => (m.flags & TypeFlags.NumberLiteral) !== 0))\n return refuse(\n `the numeric literal type ${printType(this.checker, type)} (the subset has number)`,\n );\n else\n return refuse(\n `a union of several types (${printType(this.checker, type)}): the subset has a union of literals of one kind, a tagged union of records, and either with null`,\n );\n if (nulls.length === 0) return base;\n if (base.kind === \"nullable\") return base;\n return { kind: \"nullable\", inner: base };\n }\n\n /**\n * A union of records, told apart by a tag: a literal-typed field every\n * member has, holding a different literal in each. Members declared\n * inline are named by the union and their tag (`Outcome.true`); a\n * record declared on its own keeps its name, and may be a member of several unions.\n */\n private taggedUnion(type: Type, members: readonly Type[], refuse: Refuse): SubsetType {\n const cached = this.byId.get(type.id);\n if (cached) return cached;\n const checker = this.checker;\n const name = nameOfType(checker, type);\n // One name, one type: a second union of the name, or a record of it, is a clash.\n const taken = this.idOfName.get(name);\n if (taken !== undefined && taken !== type.id) return refuse(`two types named ${name}`);\n if (taken === undefined && (this.records.has(name) || this.unions.some((u) => u.name === name)))\n return refuse(`two types named ${name}`);\n const literalFields = (m: Type): Map<string, string | boolean> => {\n const out = new Map<string, string | boolean>();\n for (const p of m.getProperties()) {\n const t = checker.getTypeOfSymbol(p);\n if (t.isStringLiteralType() || t.isBooleanLiteralType()) out.set(p.name, t.value);\n }\n return out;\n };\n const literals = members.map(literalFields);\n const tag = [...(literals[0] as Map<string, string | boolean>).keys()].find(\n (field) =>\n literals.every((l) => l.has(field)) &&\n new Set(literals.map((l) => JSON.stringify(l.get(field)))).size === literals.length,\n );\n if (tag === undefined)\n return refuse(\n `${name}: a union of records without a tag (a literal-typed field every member has, different in each)`,\n );\n const isAnonymous = (m: Type) =>\n !m.getAliasSymbol() &&\n ((m.getSymbol()?.flags ?? 0) & (SymbolFlags.Interface | SymbolFlags.Class)) === 0;\n const read = members.map((m, i) => {\n const value = (literals[i] as Map<string, string | boolean>).get(tag) as string | boolean;\n const memberName = isAnonymous(m) ? `${name}.${String(value)}` : nameOfType(checker, m);\n const record = this.record(m, memberName, refuse, name);\n return { tag: value, record: record.name };\n });\n const union: UnionType = { name, tag, members: read };\n this.unions.push(union);\n this.idOfName.set(name, type.id);\n const out: SubsetType = { kind: \"union\", name };\n this.byId.set(type.id, out);\n return out;\n }\n\n /** A record under `name`: its fields read, the record kept; a member of `union` when given. */\n private record(type: Type, name: string, refuse: Refuse, union?: string): RecordType {\n let known = this.records.get(name);\n // A union of the name is a clash: one name, one type.\n if (!known && this.unions.some((u) => u.name === name))\n return refuse(`two types named ${name}`);\n if (known && this.idOfName.get(name) !== type.id) {\n // Another compiler type of the same name (an inline type written twice, say) is the same\n // record when it has the same fields, and a clash otherwise.\n const fields = this.fieldsOf(type, name, refuse);\n if (JSON.stringify(fields) !== JSON.stringify(known.fields))\n return refuse(`two types named ${name}`);\n this.byId.set(type.id, { kind: \"record\", name });\n }\n if (known) {\n if (union !== undefined && !known.unions?.includes(union)) {\n known = { ...known, unions: [...(known.unions ?? []), union] };\n this.records.set(name, known);\n }\n return known;\n }\n const fields = this.fieldsOf(type, name, refuse);\n const record: RecordType = {\n name,\n fields,\n ...(union === undefined ? {} : { unions: [union] }),\n };\n this.records.set(name, record);\n this.idOfName.set(name, type.id);\n this.byId.set(type.id, { kind: \"record\", name });\n return record;\n }\n\n /** The fields of a record type, each a stored value the subset takes. */\n private fieldsOf(type: Type, name: string, refuse: Refuse): Field[] {\n // A member read straight from its union is guarded here; one read through `of` already is.\n const guard = !this.reading.has(type.id);\n if (guard) this.reading.add(type.id);\n try {\n const checker = this.checker;\n const fields: Field[] = [];\n const outside: Refuse = (what) => refuse(`type ${name} is outside the subset: ${what}`);\n for (const p of type.getProperties()) {\n if (isSymbolKey(p.name)) return outside(\"a field keyed by a symbol\");\n if ((p.flags & SymbolFlags.Optional) !== 0) return outside(`optional field ${p.name}`);\n if ((p.flags & SymbolFlags.Method) !== 0) return outside(`a method ${p.name}`);\n // A getter computes; a stored field it is not.\n if ((p.flags & (SymbolFlags.GetAccessor | SymbolFlags.SetAccessor)) !== 0)\n return outside(`an accessor ${p.name}`);\n if (structureNames.has(p.name))\n return outside(`field ${p.name} takes a name Lean's structures reserve`);\n if (p.name === \"__proto__\")\n return outside(\"a field named __proto__, which JavaScript treats specially\");\n const fieldType = checker.getTypeOfSymbol(p);\n const read = this.of(fieldType, (what) => outside(`field ${p.name}: ${what}`));\n const literal = fieldType.isStringLiteralType()\n ? fieldType.value\n : fieldType.isBooleanLiteralType()\n ? fieldType.value\n : undefined;\n fields.push({ name: p.name, type: read, ...(literal === undefined ? {} : { literal }) });\n }\n return fields;\n } finally {\n if (guard) this.reading.delete(type.id);\n }\n }\n}\n","/**\n * The pure TypeScript subset the first-party engines accept, read into a\n * small tree: exported functions (declarations, and arrows a module-level\n * `const` holds) over `number`, `boolean` and `string`,\n * record types, nullable types (`T | null`) and tagged unions of records,\n * lists of any of those, returning any of those; bodies made of `const`\n * bindings, `if` with early returns, `return`, and expressions from\n * arithmetic (`+ - *`), comparisons, `=== !==` (`null` included, which\n * narrows a nullable name in the branch it guards), `&& || !`, the\n * conditional operator, record and array literals, field reads (on a\n * union, only a field every member has), list methods and calls to the\n * module's own functions. Types are whatever the compiler resolves them\n * to: declared anywhere in the file, imported from another file, or an\n * instantiated generic. 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. What each engine takes of it\n * is the engine's business (`restrictModule`). This module holds the\n * subset's meaning: its types and tree, typing, narrowing, renaming and\n * the three passes over a module; `expressions.ts` reads the syntax and\n * `types.ts` the compiler's types.\n */\n\nimport type { Arrow } from \"@eutaxy/spec\";\nimport {\n type ArrowFunction,\n type AsExpression,\n type Expression,\n type FunctionDeclaration,\n type FunctionExpression,\n forEachLeadingCommentRange,\n forEachTrailingCommentRange,\n type Identifier,\n InternalSymbolName,\n type Node,\n type NonNullExpression,\n type ObjectLiteralExpression,\n type ParenthesizedExpression,\n type SatisfiesExpression,\n type SourceFile,\n SyntaxKind,\n type TypeAssertion,\n} from \"typescript/ast\";\nimport * as is from \"typescript/ast/is\";\nimport { type Checker, SymbolFlags, type Type } from \"typescript/sync\";\nimport {\n type CompilerError,\n type InputFile,\n isAsync,\n isConst,\n lineAt,\n openParen,\n textOf,\n withProgram,\n withSourceFile,\n} from \"./compiler.ts\";\nimport {\n blockOf,\n type Constant,\n ExprReader,\n type Inline,\n type Names,\n syntacticType,\n type TypeSource,\n} from \"./expressions.ts\";\nimport { SubsetTypes } from \"./types.ts\";\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 /** `T | null`. */\n | { readonly kind: \"nullable\"; readonly inner: SubsetType }\n /** A tagged union of records declared as a type alias; its members are records of the module. */\n | { readonly kind: \"union\"; readonly name: string }\n /** The type of the literal `null` itself, which only a nullable type accepts. */\n | { readonly kind: \"null\" }\n /** `readonly T[]` or `T[]`: a list of values of one type (Lean's `List`). */\n | { readonly kind: \"list\"; readonly element: SubsetType }\n /** The element type of `[]`, which fits in a list of any type. */\n | { readonly kind: \"nothing\" };\n\nexport interface Field {\n readonly name: string;\n readonly type: SubsetType;\n /** The one value a literal-typed field holds (`ok: true`, `type: \"locked\"`): a union member's tag. */\n readonly literal?: string | boolean;\n}\n\nexport interface RecordType {\n readonly name: string;\n readonly fields: readonly Field[];\n /**\n * The tagged unions this record is a member of, in the order they were\n * read: `Err<E>` is one in `Result<A, E>` and in `Result<B, E>`. A member\n * written inline in a union is named `<union>.<tag>` after the first.\n */\n readonly unions?: readonly string[];\n}\n\n/** Whether a record is a member of a union. */\nexport function isMember(record: RecordType | undefined, union: string): boolean {\n return record?.unions?.includes(union) ?? false;\n}\n\n/** A union's members among the records known, in the order they were read. */\nfunction membersIn(union: string, ctx: TypeContext): RecordType[] {\n return [...ctx.records.values()].filter((rec) => isMember(rec, union));\n}\n\n/** A tagged union: records told apart by one field, the tag, which holds a different literal in each. */\nexport interface UnionType {\n readonly name: string;\n readonly tag: string;\n /** The member records, in declaration order, by their tag's value. */\n readonly members: readonly { readonly tag: string | boolean; readonly record: string }[];\n}\n\nexport type BinaryOp =\n | \"+\"\n | \"-\"\n | \"*\"\n | \"/\"\n | \"<\"\n | \"<=\"\n | \">\"\n | \">=\"\n | \"===\"\n | \"!==\"\n | \"&&\"\n | \"||\";\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: \"null\" }\n | { readonly kind: \"var\"; readonly name: string }\n /** In `body`, `name` (a nullable in scope) stands for its non-null value: inserted where a null check guards. */\n | { readonly kind: \"narrow\"; readonly name: string; readonly body: Expr }\n /** In `body`, `name` (a union in scope) is its member `member`: inserted where a test of the union's tag guards. */\n | {\n readonly kind: \"narrowTag\";\n readonly name: string;\n readonly member: string;\n readonly body: Expr;\n }\n | { readonly kind: \"neg\"; readonly operand: Expr }\n | { readonly kind: \"not\"; readonly operand: Expr }\n /** `Number.isInteger(e)`: always true of an integer in the engines' integer model, the real predicate on doubles. */\n | { readonly kind: \"isInteger\"; readonly operand: Expr }\n /** `Math.floor(e)`: rounding toward negative infinity on doubles; the identity on the integers. */\n | { readonly kind: \"floor\"; 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 /** The type its context gives the literal (a declared return type, a const annotation, a parameter), as the compiler sees it: a record, or the union a member is picked from. */\n readonly type?: SubsetType;\n }\n | {\n readonly kind: \"let\";\n readonly name: string;\n readonly value: Expr;\n readonly body: Expr;\n /** The `const`'s annotation, when it has one: the binding's type, whatever the initializer's. */\n readonly type?: SubsetType;\n }\n /** `[a, b]`, or `[a, b, ...rest]` with the spread last. `xs.length` is a `field` read on a list. */\n | { readonly kind: \"list\"; readonly items: readonly Expr[]; readonly rest?: Expr }\n /** `xs.slice(1)`: every element but the first. */\n | { readonly kind: \"tail\"; readonly list: Expr }\n /** `xs[0] ?? fallback`: the first element, or the fallback for an empty list. */\n | { readonly kind: \"headOr\"; readonly list: Expr; readonly fallback: Expr }\n /** `xs.map`, `xs.flatMap`, `xs.every` or `xs.some` with `(item, index?) => body`. */\n | {\n readonly kind: \"iterate\";\n readonly op: \"map\" | \"flatMap\" | \"every\" | \"some\";\n readonly list: Expr;\n readonly item: string;\n readonly index?: string;\n readonly body: Expr;\n }\n /** `xs.reduce((acc, item) => body, init)`: a left fold. */\n | {\n readonly kind: \"fold\";\n readonly list: Expr;\n readonly acc: string;\n readonly item: string;\n readonly body: Expr;\n readonly init: Expr;\n };\n\nexport interface Param {\n readonly name: string;\n readonly type: SubsetType;\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 * For a recursive function, the list parameter it recurses on (its\n * index): the body tests that list's length against 0 first, and every\n * call to itself, in the other branch, passes that list's slice(1).\n */\n readonly structural?: 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 readonly unions: readonly UnionType[];\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/** 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/** A type, for messages. */\nexport function describe(t: SubsetType): string {\n switch (t.kind) {\n case \"record\":\n case \"union\":\n return t.name;\n case \"nullable\":\n return `${describe(t.inner)} | null`;\n case \"list\":\n return t.element.kind === \"nullable\"\n ? `(${describe(t.element)})[]`\n : `${describe(t.element)}[]`;\n default:\n return t.kind;\n }\n}\n\nconst sameType = (a: SubsetType, b: SubsetType): boolean => JSON.stringify(a) === JSON.stringify(b);\n\n/**\n * Whether a value of one type may stand where another is expected: the\n * same type; a member record where its union is; `null`, or the inner\n * type, where a nullable is.\n */\nexport function fits(actual: SubsetType, expected: SubsetType, ctx: TypeContext): boolean {\n if (sameType(actual, expected)) return true;\n // The element of `[]` is no value at all, so it stands for any; a list fits where its elements do.\n if (actual.kind === \"nothing\") return true;\n if (actual.kind === \"list\" && expected.kind === \"list\")\n return fits(actual.element, expected.element, ctx);\n if (expected.kind === \"union\")\n return actual.kind === \"record\" && isMember(ctx.records.get(actual.name), expected.name);\n if (expected.kind === \"nullable\")\n return (\n actual.kind === \"null\" ||\n (actual.kind === \"nullable\"\n ? fits(actual.inner, expected.inner, ctx)\n : fits(actual, expected.inner, ctx))\n );\n return false;\n}\n\n/** The type two branches share, or undefined when they share none. */\nfunction join(a: SubsetType, b: SubsetType, ctx: TypeContext): SubsetType | undefined {\n if (fits(a, b, ctx)) return b;\n if (fits(b, a, ctx)) return a;\n if (a.kind === \"list\" && b.kind === \"list\") {\n const element = join(a.element, b.element, ctx);\n return element && { kind: \"list\", element };\n }\n if (a.kind === \"record\" && b.kind === \"record\") {\n // Two members of one union join to it; members of several unions in common join to none,\n // since nothing says which (an expected type, where one is given, decides instead).\n const ub = ctx.records.get(b.name)?.unions ?? [];\n const common = (ctx.records.get(a.name)?.unions ?? []).filter((u) => ub.includes(u));\n if (common.length === 1) return { kind: \"union\", name: common[0] as string };\n }\n if (a.kind === \"nullable\" && b.kind === \"nullable\") {\n const inner = join(a.inner, b.inner, ctx);\n return inner && { kind: \"nullable\", inner };\n }\n if (a.kind === \"null\" && b.kind !== \"null\") return { kind: \"nullable\", inner: b };\n if (b.kind === \"null\" && a.kind !== \"null\") return { kind: \"nullable\", inner: a };\n if (a.kind === \"nullable\" && b.kind !== \"null\" && b.kind !== \"nullable\") {\n const inner = join(a.inner, b, ctx);\n return inner && { kind: \"nullable\", inner };\n }\n if (b.kind === \"nullable\" && a.kind !== \"null\" && a.kind !== \"nullable\") {\n const inner = join(a, b.inner, ctx);\n return inner && { kind: \"nullable\", inner };\n }\n return undefined;\n}\n\n/** Whether `===` between the two types is in the subset, and on records (references in JavaScript) it is not. */\nfunction comparable(l: SubsetType, r: SubsetType): boolean {\n const base = (t: SubsetType): SubsetType => (t.kind === \"nullable\" ? t.inner : t);\n if (l.kind === \"null\" && r.kind === \"null\") return false;\n if (l.kind === \"null\") return r.kind === \"nullable\";\n if (r.kind === \"null\") return l.kind === \"nullable\";\n return sameType(base(l), base(r)) && !isReference(base(l));\n}\n\nconst isReference = (t: SubsetType): boolean =>\n t.kind === \"record\" || t.kind === \"union\" || t.kind === \"list\";\n\n/**\n * The names a test, holding or failing, shows to be non-null: `x !== null`\n * holding, `x === null` failing, through `!`, `&&` (holding) and `||`\n * (failing).\n */\nexport function narrowsOf(test: Expr, holds: boolean): string[] {\n // A narrowing already inserted around an operand (the right side of `&&`) hides nothing.\n if (test.kind === \"narrow\" || test.kind === \"narrowTag\") return narrowsOf(test.body, holds);\n const isNull = (e: Expr) => e.kind === \"null\";\n if (test.kind === \"binary\" && (test.op === \"===\" || test.op === \"!==\")) {\n const other = isNull(test.right) ? test.left : isNull(test.left) ? test.right : undefined;\n if (other?.kind !== \"var\") return [];\n return (test.op === \"!==\") === holds ? [other.name] : [];\n }\n if (test.kind === \"not\") return narrowsOf(test.operand, !holds);\n if (test.kind === \"binary\" && test.op === \"&&\" && holds)\n return [...narrowsOf(test.left, true), ...narrowsOf(test.right, true)];\n if (test.kind === \"binary\" && test.op === \"||\" && !holds)\n return [...narrowsOf(test.left, false), ...narrowsOf(test.right, false)];\n return [];\n}\n\n/** The field that tells a union's members apart: literal-typed in every member, with a different literal in each. */\nexport function tagOf(union: string, ctx: TypeContext): string | undefined {\n const members = membersIn(union, ctx);\n const first = members[0];\n if (!first) return undefined;\n return first.fields\n .filter((f) => f.literal !== undefined)\n .map((f) => f.name)\n .find((name) => {\n const values = members.map((m) => m.fields.find((f) => f.name === name)?.literal);\n return (\n values.every((v) => v !== undefined) &&\n new Set(values.map((v) => JSON.stringify(v))).size === values.length\n );\n });\n}\n\n/**\n * The names a test, holding or failing, shows to be one member of their\n * union, with that member: `x.tag === \"a\"` holding (or `!==` failing)\n * names the member tagged `\"a\"`; failing, the other member when the\n * union has two; `x.ok` alone is the test of a boolean tag; through `!`,\n * `&&` (holding) and `||` (failing) as null checks are.\n */\nexport function tagNarrowsOf(\n test: Expr,\n holds: boolean,\n scope: ReadonlyMap<string, SubsetType>,\n ctx: TypeContext,\n): { name: string; member: string }[] {\n // The union a `x.tag` read is the tag of, with its members by tag value.\n const tagged = (e: Expr): { name: string; members: readonly RecordType[] } | undefined => {\n if (e.kind !== \"field\" || e.object.kind !== \"var\") return undefined;\n const t = scope.get(e.object.name);\n if (t?.kind !== \"union\" || tagOf(t.name, ctx) !== e.field) return undefined;\n return {\n name: e.object.name,\n members: membersIn(t.name, ctx),\n };\n };\n const byTag = (\n read: { name: string; members: readonly RecordType[] },\n tag: string,\n value: string | boolean,\n isIt: boolean,\n ): { name: string; member: string }[] => {\n const same = read.members.filter(\n (m) => m.fields.find((f) => f.name === tag)?.literal === value,\n );\n const chosen = isIt ? same : read.members.filter((m) => !same.includes(m));\n return chosen.length === 1 ? [{ name: read.name, member: (chosen[0] as RecordType).name }] : [];\n };\n if (test.kind === \"narrow\" || test.kind === \"narrowTag\")\n return tagNarrowsOf(test.body, holds, scope, ctx);\n if (test.kind === \"binary\" && (test.op === \"===\" || test.op === \"!==\")) {\n const literal = (e: Expr) => (e.kind === \"string\" || e.kind === \"bool\" ? e.value : undefined);\n const [field, value] =\n literal(test.right) !== undefined\n ? [test.left, literal(test.right)]\n : [test.right, literal(test.left)];\n if (value === undefined || field.kind !== \"field\") return [];\n const read = tagged(field);\n if (!read) return [];\n return byTag(read, field.field, value, (test.op === \"===\") === holds);\n }\n if (test.kind === \"field\") {\n const read = tagged(test);\n return read ? byTag(read, test.field, holds, true) : [];\n }\n if (test.kind === \"not\") return tagNarrowsOf(test.operand, !holds, scope, ctx);\n if (test.kind === \"binary\" && test.op === \"&&\" && holds)\n return [\n ...tagNarrowsOf(test.left, true, scope, ctx),\n ...tagNarrowsOf(test.right, true, scope, ctx),\n ];\n if (test.kind === \"binary\" && test.op === \"||\" && !holds)\n return [\n ...tagNarrowsOf(test.left, false, scope, ctx),\n ...tagNarrowsOf(test.right, false, scope, ctx),\n ];\n return [];\n}\n\n/**\n * `narrow` and `narrowTag` nodes inserted where a test guards: in a\n * conditional's branches, and in the right operand of `&&` and `||`, for\n * each nullable name the test shows to be non-null there and each union\n * name it shows to be one member there.\n */\nexport function insertNarrows(\n e: Expr,\n scope: ReadonlyMap<string, SubsetType>,\n ctx: TypeContext,\n fail: (message: string) => never,\n): Expr {\n const go = (x: Expr, sc: ReadonlyMap<string, SubsetType>): Expr =>\n insertNarrows(x, sc, ctx, fail);\n // Where JavaScript tests truthiness (a condition, the operand of `!`), a nullable record or union\n // is falsy exactly when it is null, since an object is always truthy: `c` there is `c !== null`,\n // which then narrows as a null check does. A nullable number or string is no object, and stays.\n const probe = Symbol(\"untyped\");\n const condition = (x: Expr, sc: ReadonlyMap<string, SubsetType>): Expr => {\n if (x.kind === \"binary\" && (x.op === \"&&\" || x.op === \"||\"))\n return { ...x, left: condition(x.left, sc), right: condition(x.right, sc) };\n if (x.kind === \"not\") return { kind: \"not\", operand: condition(x.operand, sc) };\n let t: SubsetType;\n try {\n t = typeOf(x, sc, ctx, () => {\n throw probe;\n });\n } catch (err) {\n if (err === probe) return x;\n throw err;\n }\n if (t.kind === \"nullable\" && (t.inner.kind === \"record\" || t.inner.kind === \"union\"))\n return { kind: \"binary\", op: \"!==\", left: x, right: { kind: \"null\" } };\n return x;\n };\n const wrap = (\n body: Expr,\n test: Expr,\n holds: boolean,\n sc: ReadonlyMap<string, SubsetType>,\n ): Expr => {\n const inner = new Map(sc);\n let out = body;\n const nullable = [...new Set(narrowsOf(test, holds))].filter(\n (n) => sc.get(n)?.kind === \"nullable\",\n );\n for (const n of nullable) inner.set(n, (sc.get(n) as { inner: SubsetType }).inner);\n // Tag tests are read in the scope null checks leave: `x !== null && x.ok` narrows x twice.\n const tags: { name: string; member: string }[] = [];\n for (const t of tagNarrowsOf(test, holds, inner, ctx))\n if (!tags.some((x) => x.name === t.name)) {\n tags.push(t);\n inner.set(t.name, { kind: \"record\", name: t.member });\n }\n out = go(out, inner);\n for (const t of tags.reverse())\n out = { kind: \"narrowTag\", name: t.name, member: t.member, body: out };\n for (const n of nullable.reverse()) out = { kind: \"narrow\", name: n, body: out };\n return out;\n };\n switch (e.kind) {\n case \"int\":\n case \"bool\":\n case \"string\":\n case \"null\":\n case \"var\":\n return e;\n case \"not\":\n return { kind: \"not\", operand: go(condition(e.operand, scope), scope) };\n case \"neg\":\n case \"isInteger\":\n case \"floor\":\n return { kind: e.kind, operand: go(e.operand, scope) };\n case \"narrow\":\n case \"narrowTag\":\n return e;\n case \"binary\": {\n const left = go(e.left, scope);\n if (e.op === \"&&\")\n return { kind: \"binary\", op: e.op, left, right: wrap(e.right, left, true, scope) };\n if (e.op === \"||\")\n return { kind: \"binary\", op: e.op, left, right: wrap(e.right, left, false, scope) };\n return { kind: \"binary\", op: e.op, left, right: go(e.right, scope) };\n }\n case \"cond\": {\n const test = go(condition(e.test, scope), scope);\n return {\n kind: \"cond\",\n test,\n ifTrue: wrap(e.ifTrue, test, true, scope),\n ifFalse: wrap(e.ifFalse, test, false, scope),\n };\n }\n case \"call\":\n return { kind: \"call\", callee: e.callee, args: e.args.map((a) => go(a, scope)) };\n case \"field\":\n return { kind: \"field\", object: go(e.object, scope), field: e.field };\n case \"record\":\n return { ...e, fields: e.fields.map((f) => ({ name: f.name, value: go(f.value, scope) })) };\n case \"let\": {\n const value = go(e.value, scope);\n const inner = new Map(scope);\n inner.set(e.name, e.type ?? typeOf(value, scope, ctx, fail));\n return { ...e, value, body: go(e.body, inner) };\n }\n case \"list\":\n return {\n kind: \"list\",\n items: e.items.map((x) => go(x, scope)),\n ...(e.rest ? { rest: go(e.rest, scope) } : {}),\n };\n case \"tail\":\n return { kind: \"tail\", list: go(e.list, scope) };\n case \"headOr\":\n return { kind: \"headOr\", list: go(e.list, scope), fallback: go(e.fallback, scope) };\n case \"iterate\": {\n const list = go(e.list, scope);\n return { ...e, list, body: go(e.body, iterateScope(e, list, scope, ctx, fail)) };\n }\n case \"fold\": {\n const list = go(e.list, scope);\n const init = go(e.init, scope);\n // The callback's names before its body is typed: its null checks narrow first, as in map.\n const inner = new Map(scope);\n inner.set(e.acc, typeOf(init, scope, ctx, fail));\n inner.set(e.item, elementOf(typeOf(list, scope, ctx, fail), \"reduce\", fail));\n return { ...e, list, init, body: go(e.body, inner) };\n }\n }\n}\n\n/**\n * The element type of a list expression's type. An operation on an empty\n * array no type is given for (`[].length`, `[].slice(1)`) is refused: an\n * engine could only guess the element type, and such code has a plain\n * value to write instead; `const xs: T[] = []` gives one.\n */\nfunction elementOf(t: SubsetType, what: string, fail: (message: string) => never): SubsetType {\n if (t.kind !== \"list\") fail(`${what} on a ${describe(t)}, not a list`);\n if (holdsNothing(t))\n fail(`${what} on an empty array of no declared type (annotate it: const xs: T[] = [])`);\n return t.element;\n}\n\n/** Whether a type holds the element type of an empty array literal anywhere in it (`[[]]` does). */\nfunction holdsNothing(t: SubsetType): boolean {\n if (t.kind === \"nothing\") return true;\n if (t.kind === \"list\") return holdsNothing(t.element);\n if (t.kind === \"nullable\") return holdsNothing(t.inner);\n return false;\n}\n\n/** The scope inside an iteration's callback: the item an element, the index an integer. */\nfunction iterateScope(\n e: Extract<Expr, { kind: \"iterate\" }>,\n list: Expr,\n scope: ReadonlyMap<string, SubsetType>,\n ctx: TypeContext,\n fail: (message: string) => never,\n): Map<string, SubsetType> {\n const inner = new Map(scope);\n inner.set(e.item, elementOf(typeOf(list, scope, ctx, fail), e.op, fail));\n if (e.index !== undefined) inner.set(e.index, { kind: \"int\" });\n return inner;\n}\n\n/**\n * The scope inside a fold's callback and the accumulator's type: the\n * initial value's, widened once to the body's when the body's holds it.\n * A callback that takes the accumulator apart as a list needs the initial\n * value typed (`xs.reduce((acc, x) => [x, ...acc], [])` does not\n * type-check in TypeScript either).\n */\nfunction foldScope(\n e: Extract<Expr, { kind: \"fold\" }>,\n list: Expr,\n init: Expr,\n scope: ReadonlyMap<string, SubsetType>,\n ctx: TypeContext,\n fail: (message: string) => never,\n): { scope: Map<string, SubsetType>; acc: SubsetType } {\n const item = elementOf(typeOf(list, scope, ctx, fail), \"reduce\", fail);\n const at = (acc: SubsetType) => new Map([...scope, [e.acc, acc], [e.item, item]]);\n const start = typeOf(init, scope, ctx, fail);\n const body = typeOf(e.body, at(start), ctx, fail);\n if (fits(body, start, ctx)) return { scope: at(start), acc: start };\n if (fits(start, body, ctx) && fits(typeOf(e.body, at(body), ctx, fail), body, ctx))\n return { scope: at(body), acc: body };\n fail(`reduce's callback makes a ${describe(body)} from an accumulator of ${describe(start)}`);\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 /**\n * The type the context declares for `e` (a return type, a const's\n * annotation, a parameter): it decides a conditional whose branches are\n * members of several unions in common, where they alone join to none.\n */\n expected?: SubsetType,\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 \"null\":\n return { kind: \"null\" };\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 \"narrow\": {\n const t = scope.get(e.name);\n if (!t) fail(`${e.name} is not in scope`);\n if (t.kind !== \"nullable\")\n fail(`${e.name} is narrowed but is a ${describe(t)}, not a nullable`);\n return typeOf(e.body, new Map([...scope, [e.name, t.inner]]), ctx, fail, expected);\n }\n case \"narrowTag\": {\n const t = scope.get(e.name);\n if (!t) fail(`${e.name} is not in scope`);\n if (t.kind !== \"union\")\n fail(`${e.name} is narrowed by a tag but is a ${describe(t)}, not a union`);\n if (!isMember(ctx.records.get(e.member), t.name))\n fail(`${e.member} is not a member of ${t.name}`);\n return typeOf(\n e.body,\n new Map([...scope, [e.name, { kind: \"record\", name: e.member }]]),\n ctx,\n fail,\n expected,\n );\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 === \"!==\") {\n // Against null, any nullable; otherwise records and unions are references in JavaScript.\n const againstNull = l.kind === \"null\" || r.kind === \"null\";\n const base = (t: SubsetType): SubsetType => (t.kind === \"nullable\" ? t.inner : t);\n if (!againstNull && (isReference(base(l)) || isReference(base(r))))\n fail(\n `${e.op} on records compares references in JavaScript; compare their fields instead`,\n );\n if (!comparable(l, r)) fail(`${e.op} between a ${describe(l)} and a ${describe(r)}`);\n }\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 \"isInteger\": {\n const t = typeOf(e.operand, scope, ctx, fail);\n if (t.kind !== \"int\") fail(`Number.isInteger on a ${t.kind}`);\n return { kind: \"bool\" };\n }\n case \"floor\": {\n const t = typeOf(e.operand, scope, ctx, fail);\n if (t.kind !== \"int\") fail(`Math.floor on a ${t.kind}`);\n return { kind: \"int\" };\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, expected);\n const b = typeOf(e.ifFalse, scope, ctx, fail, expected);\n const joined = join(a, b, ctx);\n if (joined) return joined;\n if (expected && fits(a, expected, ctx) && fits(b, expected, ctx)) return expected;\n return fail(\n `the branches of a conditional have different types (${describe(a)} and ${describe(b)})`,\n );\n }\n case \"let\": {\n const inferred = typeOf(e.value, scope, ctx, fail, e.type);\n if (e.type && !fits(inferred, e.type, ctx))\n fail(`const ${e.name} is annotated ${describe(e.type)} but holds a ${describe(inferred)}`);\n if (!e.type && holdsNothing(inferred))\n fail(\n `const ${e.name} holds an empty array of no declared type (annotate it: const ${e.name}: T[] = [])`,\n );\n return typeOf(e.body, new Map([...scope, [e.name, e.type ?? inferred]]), ctx, fail, expected);\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, want);\n if (!fits(got, want, ctx))\n fail(\n `argument ${i + 1} of ${e.callee} is a ${describe(got)}, not the ${describe(want)} it takes`,\n );\n });\n return sig.returns;\n }\n case \"field\": {\n const o = typeOf(e.object, scope, ctx, fail);\n if (o.kind === \"list\") {\n if (e.field !== \"length\") fail(`${e.field} read from a list (the subset has length)`);\n elementOf(o, \"length\", fail);\n return { kind: \"int\" };\n }\n if (o.kind === \"nullable\")\n fail(\n `field ${e.field} read from a ${describe(o)}: compare it with null first, which narrows it`,\n );\n if (o.kind === \"union\") {\n // Only a field every member has, with one type: the tag, typically. Narrowing by the tag is not in the subset yet.\n const members = membersIn(o.name, ctx);\n const types = members.map((rec) => rec.fields.find((x) => x.name === e.field)?.type);\n if (types.some((t) => t === undefined))\n fail(\n `field ${e.field} is not on every member of ${o.name} (test the tag first, which narrows it)`,\n );\n const first = types[0] as SubsetType;\n if (!types.every((t) => sameType(t as SubsetType, first)))\n fail(`field ${e.field} has different types across the members of ${o.name}`);\n return first;\n }\n if (o.kind !== \"record\") fail(`field ${e.field} read from a ${describe(o)}`);\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 // The context's type, when the compiler gave one, narrows the candidates: the record itself, or a union's members.\n const context = e.type;\n const candidates =\n context?.kind === \"record\"\n ? [...ctx.records.values()].filter((rec) => rec.name === context.name)\n : context?.kind === \"union\"\n ? membersIn(context.name, ctx)\n : [...ctx.records.values()];\n const byNames = candidates.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 fitting = byNames.filter((rec) =>\n rec.fields.every((f) => fits(types.get(f.name) as SubsetType, f.type, ctx)),\n );\n if (fitting.length === 0) {\n const rec = byNames[0] as RecordType;\n const off = rec.fields.find(\n (f) => !fits(types.get(f.name) as SubsetType, f.type, ctx),\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 // Among a union's members, the literal's tag tells them apart.\n const literalOf = (name: string): string | boolean | undefined => {\n const v = e.fields.find((f) => f.name === name)?.value;\n return v?.kind === \"string\" || v?.kind === \"bool\" ? v.value : undefined;\n };\n const tagged = fitting.filter((rec) =>\n rec.fields.every((f) => f.literal === undefined || literalOf(f.name) === f.literal),\n );\n const chosen = tagged.length > 0 ? tagged : fitting;\n if (chosen.length > 1)\n fail(\n `a record literal with fields ${names} matches ${chosen.map((r) => r.name).join(\" and \")} alike`,\n );\n return { kind: \"record\", name: (chosen[0] as RecordType).name };\n }\n case \"list\": {\n let element: SubsetType = { kind: \"nothing\" };\n const add = (t: SubsetType) => {\n const joined = join(element, t, ctx);\n if (!joined) fail(`an array literal of a ${describe(element)} and a ${describe(t)}`);\n element = joined;\n };\n for (const item of e.items) add(typeOf(item, scope, ctx, fail));\n if (e.rest) add(elementOf(typeOf(e.rest, scope, ctx, fail), \"a spread\", fail));\n return { kind: \"list\", element };\n }\n case \"tail\": {\n const t = typeOf(e.list, scope, ctx, fail);\n elementOf(t, \"slice\", fail);\n return t;\n }\n case \"headOr\": {\n const element = elementOf(typeOf(e.list, scope, ctx, fail), \"[0]\", fail);\n // `??` replaces null as well as the missing head: on a list of a nullable type it is not headD.\n if (element.kind === \"nullable\" || element.kind === \"null\")\n fail(\"xs[0] ?? on a list of a nullable type (?? replaces a null element too)\");\n const fallback = typeOf(e.fallback, scope, ctx, fail);\n const joined = join(element, fallback, ctx);\n if (!joined) fail(`?? between a ${describe(element)} and a ${describe(fallback)}`);\n return joined;\n }\n case \"iterate\": {\n const body = typeOf(e.body, iterateScope(e, e.list, scope, ctx, fail), ctx, fail);\n if (e.op === \"map\") return { kind: \"list\", element: body };\n if (e.op === \"flatMap\")\n return { kind: \"list\", element: elementOf(body, \"flatMap's callback result\", fail) };\n if (body.kind !== \"bool\")\n fail(`${e.op}'s callback returns a ${describe(body)}, not a boolean`);\n return { kind: \"bool\" };\n }\n case \"fold\":\n return foldScope(e, e.list, e.init, scope, ctx, fail).acc;\n }\n}\n\n/** Every name an expression binds or refers to: its variables and its lets. */\nfunction boundNames(e: Expr, out = new Set<string>()): Set<string> {\n switch (e.kind) {\n case \"int\":\n case \"bool\":\n case \"string\":\n case \"null\":\n return out;\n case \"var\":\n out.add(e.name);\n return out;\n case \"narrow\":\n case \"narrowTag\":\n out.add(e.name);\n return boundNames(e.body, out);\n case \"neg\":\n case \"not\":\n case \"isInteger\":\n case \"floor\":\n return boundNames(e.operand, out);\n case \"binary\":\n boundNames(e.left, out);\n return boundNames(e.right, out);\n case \"cond\":\n boundNames(e.test, out);\n boundNames(e.ifTrue, out);\n return boundNames(e.ifFalse, out);\n case \"call\":\n for (const a of e.args) boundNames(a, out);\n return out;\n case \"field\":\n return boundNames(e.object, out);\n case \"record\":\n for (const f of e.fields) boundNames(f.value, out);\n return out;\n case \"let\":\n out.add(e.name);\n boundNames(e.value, out);\n return boundNames(e.body, out);\n case \"list\":\n for (const x of e.items) boundNames(x, out);\n return e.rest ? boundNames(e.rest, out) : out;\n case \"tail\":\n return boundNames(e.list, out);\n case \"headOr\":\n boundNames(e.list, out);\n return boundNames(e.fallback, out);\n case \"iterate\":\n out.add(e.item);\n if (e.index !== undefined) out.add(e.index);\n boundNames(e.list, out);\n return boundNames(e.body, out);\n case \"fold\":\n out.add(e.acc);\n out.add(e.item);\n boundNames(e.list, out);\n boundNames(e.init, out);\n return boundNames(e.body, out);\n }\n}\n\n/** A name not among `taken`: the name with underscores appended. */\nfunction fresh(name: string, taken: ReadonlySet<string>): string {\n let out = `${name}_`;\n while (taken.has(out)) out += \"_\";\n return out;\n}\n\n/**\n * The expression with its variables renamed (an arrow's own parameter\n * names to the binders'). A `let` whose name is a rename's target would\n * capture the renamed references in its body, so such a let is renamed to\n * a fresh name first; a let whose name is a rename's source shadows it.\n */\nexport function renameVars(\n e: Expr,\n names: ReadonlyMap<string, string>,\n taken: ReadonlySet<string> = new Set([...names.keys(), ...names.values(), ...boundNames(e)]),\n /** Names no binder in `e` may keep (the scope `e` is inlined into): such a binder moves to a fresh name. */\n avoid: ReadonlySet<string> = new Set(),\n): Expr {\n const go = (x: Expr): Expr => renameVars(x, names, taken, avoid);\n switch (e.kind) {\n case \"int\":\n case \"bool\":\n case \"string\":\n case \"null\":\n return e;\n case \"var\":\n return { kind: \"var\", name: names.get(e.name) ?? e.name };\n case \"narrow\":\n return { kind: \"narrow\", name: names.get(e.name) ?? e.name, body: go(e.body) };\n case \"narrowTag\":\n return { ...e, name: names.get(e.name) ?? e.name, body: go(e.body) };\n case \"neg\":\n case \"not\":\n case \"isInteger\":\n case \"floor\":\n return { kind: e.kind, operand: go(e.operand) };\n case \"binary\":\n return { kind: \"binary\", op: e.op, left: go(e.left), right: go(e.right) };\n case \"cond\":\n return { kind: \"cond\", test: go(e.test), ifTrue: go(e.ifTrue), ifFalse: go(e.ifFalse) };\n case \"call\":\n return { kind: \"call\", callee: e.callee, args: e.args.map(go) };\n case \"field\":\n return { kind: \"field\", object: go(e.object), field: e.field };\n case \"record\":\n return { ...e, fields: e.fields.map((f) => ({ name: f.name, value: go(f.value) })) };\n case \"let\": {\n // A let binds its own name; a binder of that name is shadowed inside, as in the source.\n const inner = new Map(names);\n inner.delete(e.name);\n let bound = e.name;\n const targets = new Set([...names.values(), ...avoid]);\n if (targets.has(e.name)) {\n // The let would capture a renamed reference: the let itself moves out of the way, to a name\n // nothing in the expression uses (another let may already be spelled with the underscore).\n bound = fresh(e.name, taken);\n inner.set(e.name, bound);\n }\n return {\n ...e,\n name: bound,\n value: go(e.value),\n body: renameVars(e.body, inner, new Set([...taken, bound]), avoid),\n };\n }\n case \"list\":\n return { kind: \"list\", items: e.items.map(go), ...(e.rest ? { rest: go(e.rest) } : {}) };\n case \"tail\":\n return { kind: \"tail\", list: go(e.list) };\n case \"headOr\":\n return { kind: \"headOr\", list: go(e.list), fallback: go(e.fallback) };\n case \"iterate\": {\n const own = [e.item, ...(e.index === undefined ? [] : [e.index])];\n const { inner, bound, scoped } = bindAll(own, names, taken, avoid);\n return {\n ...e,\n list: go(e.list),\n item: bound[0] as string,\n ...(e.index === undefined ? {} : { index: bound[1] as string }),\n body: renameVars(e.body, inner, scoped, avoid),\n };\n }\n case \"fold\": {\n const { inner, bound, scoped } = bindAll([e.acc, e.item], names, taken, avoid);\n return {\n ...e,\n list: go(e.list),\n init: go(e.init),\n acc: bound[0] as string,\n item: bound[1] as string,\n body: renameVars(e.body, inner, scoped, avoid),\n };\n }\n }\n}\n\n/**\n * The renames inside a callback that binds `own` names, as for a let:\n * each shadows a rename of its own name, and one that is a rename's target\n * moves to a fresh name so it captures nothing.\n */\nfunction bindAll(\n own: readonly string[],\n names: ReadonlyMap<string, string>,\n taken: ReadonlySet<string>,\n avoid: ReadonlySet<string>,\n): { inner: Map<string, string>; bound: string[]; scoped: Set<string> } {\n const inner = new Map(names);\n const targets = new Set([...names.values(), ...avoid]);\n const scoped = new Set(taken);\n const bound = own.map((n) => {\n inner.delete(n);\n if (!targets.has(n)) return n;\n const moved = fresh(n, scoped);\n scoped.add(moved);\n inner.set(n, moved);\n return moved;\n });\n return { inner, bound, scoped };\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 \"null\":\n case \"var\":\n return out;\n case \"narrow\":\n case \"narrowTag\":\n return callees(e.body, out);\n case \"neg\":\n case \"not\":\n case \"isInteger\":\n case \"floor\":\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 case \"list\":\n for (const x of e.items) callees(x, out);\n return e.rest ? callees(e.rest, out) : out;\n case \"tail\":\n return callees(e.list, out);\n case \"headOr\":\n callees(e.list, out);\n return callees(e.fallback, out);\n case \"iterate\":\n callees(e.list, out);\n return callees(e.body, out);\n case \"fold\":\n callees(e.list, out);\n callees(e.init, out);\n return callees(e.body, out);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Reading: a module through the compiler, an arrow from its text.\n\n/** The path a module read from text alone is compiled under: an import of another file does not resolve from it. */\nconst virtualModulePath = \"/eutaxy/reader/module.ts\";\n\nexport interface ReadSubsetOptions {\n /** The module's path on disk, under which its imports resolve. Without it the module stands alone. */\n readonly path?: string;\n /** Other files the read sees in place of (or beside) the files on disk, by path. */\n readonly files?: readonly InputFile[];\n}\n\n/** What typing a module's expressions needs, shared by every function read. */\nfunction moduleContext(records: Map<string, RecordType>): {\n ctx: TypeContext;\n signatures: Map<string, CalleeSignature>;\n} {\n const signatures = new Map<string, CalleeSignature>();\n return { ctx: { records, signatures }, signatures };\n}\n\n/** The contextual type the compiler gives a record literal, as the subset reads it; undefined where it has none the subset takes. */\nfunction contextualType(\n checker: Checker,\n types: SubsetTypes,\n node: ObjectLiteralExpression,\n): SubsetType | undefined {\n const type = checker.getContextualType(node);\n if (!type) return undefined;\n // A context inferred from the literal itself (a callback's result, say) declares nothing: the\n // literal is matched against the declared records instead.\n const fromLiteral = (t: Type): boolean =>\n t.isObjectType() && t.getSymbol()?.name === InternalSymbolName.Object;\n if (fromLiteral(type) || (type.isUnionType() && type.getTypes().some(fromLiteral)))\n return undefined;\n const skip = Symbol(\"outside\");\n try {\n const read = types.of(type, () => {\n throw skip;\n });\n return read.kind === \"nullable\" ? read.inner : read;\n } catch (err) {\n if (err === skip) return undefined;\n throw err;\n }\n}\n\n/** The line of the first direct `eval` in the file: a mention that is not a property of something else. */\nfunction directEval(sf: SourceFile): number | undefined {\n let line: number | undefined;\n const visit = (node: Node): void => {\n if (line !== undefined) return;\n if (is.isIdentifier(node) && node.text === \"eval\") {\n const parent = node.parent;\n const property =\n (is.isPropertyAccessExpression(parent) && parent.name === node) ||\n (is.isPropertyAssignment(parent) && parent.name === node);\n if (!property) {\n line = lineAt(sf, node);\n return;\n }\n }\n node.forEachChild(visit);\n };\n visit(sf);\n return line;\n}\n\n/** An expression TypeScript lets wrap another without changing what it names: parentheses and assertions. */\ntype Wrapper =\n | ParenthesizedExpression\n | NonNullExpression\n | AsExpression\n | SatisfiesExpression\n | TypeAssertion;\n\nfunction isWrapper(n: Node): n is Wrapper {\n return (\n is.isParenthesizedExpression(n) ||\n is.isNonNullExpression(n) ||\n is.isAsExpression(n) ||\n is.isSatisfiesExpression(n) ||\n is.isTypeAssertion(n)\n );\n}\n\n/** Whether a node is written to: assigned, updated, or bound by a destructuring or a `for` head. */\nfunction isWritten(node: Node): boolean {\n let n: Node = node;\n for (;;) {\n const p: Node = n.parent;\n if (!p) return false;\n if (isWrapper(p) && p.expression === n) {\n n = p;\n continue;\n }\n if (is.isBinaryExpression(p)) {\n const k = p.operatorToken.kind;\n if (p.left === n && k >= SyntaxKind.FirstAssignment && k <= SyntaxKind.LastAssignment)\n return true;\n return false;\n }\n if (is.isPrefixUnaryExpression(p) || is.isPostfixUnaryExpression(p))\n return p.operator === SyntaxKind.PlusPlusToken || p.operator === SyntaxKind.MinusMinusToken;\n if (is.isForInStatement(p) || is.isForOfStatement(p)) return p.initializer === n;\n // Inside a destructuring target, the whole pattern is what gets assigned.\n if (is.isArrayLiteralExpression(p) || is.isSpreadElement(p) || is.isSpreadAssignment(p)) {\n n = p;\n continue;\n }\n if (is.isPropertyAssignment(p) && p.initializer === n) {\n n = p.parent;\n continue;\n }\n if (is.isShorthandPropertyAssignment(p) && p.name === n) {\n n = p.parent;\n continue;\n }\n if (is.isObjectLiteralExpression(p)) {\n n = p;\n continue;\n }\n return false;\n }\n}\n\n/** What every PROVEN rests on besides the engine's model: the reader's assumption about the built-ins. */\nexport const builtinsAssumption =\n \"the built-ins the subset reads (Math, Number and the array methods) are the standard ones: a direct assignment to a global of the standard library or to a property of one, or through globalThis, self or window, in a read file is refused, but one made another way (Object.defineProperty, through an alias) or elsewhere (a polyfill, another module) is not seen\";\n\n/** Names a file reaches the globals through that the library the reads compile against does not declare. */\nconst globalObjects = new Set([\"globalThis\", \"self\", \"window\", \"global\"]);\n\n/**\n * The first direct assignment (or `delete`) in a file whose target is a\n * global of the compiler's standard library or a property of one, at any\n * depth (`Math.floor = …`, `Number[\"isInteger\"] = …`, `Array.prototype.map\n * = …`, `Math = …`), or anything under `globalThis`, `self`, `window` or\n * `global`, with its line; inside a function or not. The chain's root is\n * resolved by the compiler, so a local's `prototype` field is the local's.\n * What reaches a built-in another way (`Object.defineProperty`, an alias)\n * is not seen: `builtinsAssumption` says so.\n */\nexport function rebound(\n sf: SourceFile,\n checker: Checker,\n standardGlobal: (id: Identifier) => boolean,\n): { line: number; target: string } | undefined {\n let found: { line: number; target: string } | undefined;\n // `window` and its kin, by name, unless the name is a parameter or a local of some function here.\n const globalObject = (r: Identifier): boolean => {\n if (!globalObjects.has(r.text)) return false;\n const decl = checker.getSymbolAtLocation(r)?.valueDeclaration?.resolve();\n if (!decl) return true;\n if (decl.kind === SyntaxKind.Parameter) return false;\n return !(is.isVariableDeclaration(decl) && decl.parent.parent.parent !== decl.getSourceFile());\n };\n // The node a `delete` would take: the target with the wrappers around it.\n const outermost = (node: Node): Node => {\n let out: Node = node;\n for (let p: Node = out.parent; p && isWrapper(p) && p.expression === out; p = p.parent) out = p;\n return out;\n };\n const root = (node: Node): Node => {\n let n: Node = node;\n while (is.isPropertyAccessExpression(n) || is.isElementAccessExpression(n) || isWrapper(n))\n n = n.expression;\n return n;\n };\n const builtin = (node: Node): boolean => {\n const r = root(node);\n return is.isIdentifier(r) && (globalObject(r) || standardGlobal(r));\n };\n const visit = (node: Node): void => {\n if (found) return;\n if (\n (is.isPropertyAccessExpression(node) ||\n is.isElementAccessExpression(node) ||\n is.isIdentifier(node)) &&\n (isWritten(node) || is.isDeleteExpression(outermost(node).parent)) &&\n builtin(node)\n ) {\n found = { line: lineAt(sf, node), target: textOf(sf, node) };\n return;\n }\n node.forEachChild(visit);\n };\n visit(sf);\n return found;\n}\n\n/**\n * The first `@ts-ignore` or `@ts-expect-error` directive in a range of a\n * file, with its position: a comment shaped as the compiler reads one (the\n * directive opens a `//` comment, or the last line of a block comment),\n * found as the compiler finds comments, leading or trailing a node's\n * text, so the words in prose or in a string are not one. A comment\n * before a closing token alone (`/* … *\\/ }`) is not seen; what it could\n * hide is on that token's line.\n */\nfunction directiveIn(\n sf: SourceFile,\n start: number,\n end: number,\n): { text: string; pos: number } | undefined {\n const text = sf.text;\n const singleLine = /^\\/\\/\\/?\\s*@ts-(ignore|expect-error)/;\n const lastLine = /^(?:\\/|\\*)*\\s*@ts-(ignore|expect-error)/;\n let found: { text: string; pos: number } | undefined;\n const check = (pos: number, commentEnd: number): void => {\n if (found || pos < start || commentEnd > end) return;\n const comment = text.slice(pos, commentEnd);\n const m = comment.startsWith(\"//\")\n ? singleLine.exec(comment)\n : lastLine.exec(comment.slice(comment.lastIndexOf(\"\\n\") + 1));\n if (m) found = { text: `@ts-${m[1]}`, pos };\n };\n const visit = (node: Node): void => {\n if (found || node.end < start || node.pos > end) return;\n forEachLeadingCommentRange(text, node.pos, check);\n forEachTrailingCommentRange(text, node.end, check);\n node.forEachChild(visit);\n };\n visit(sf);\n return found;\n}\n\n/**\n * The line of a `@ts-nocheck` directive at the top of a file, which turns\n * the compiler's checks off for all of it: as the compiler reads it, a\n * `//` comment opening with it, the last of it and `@ts-check` deciding.\n */\nfunction noCheckDirective(sf: SourceFile): number | undefined {\n const text = sf.text;\n const from = text.startsWith(\"#!\") ? Math.max(0, text.indexOf(\"\\n\")) : 0;\n let line: number | undefined;\n forEachLeadingCommentRange(text, from, (pos, end) => {\n const m = /^\\/\\/\\/?\\s*@ts-(check|nocheck)\\b/.exec(text.slice(pos, end));\n if (m) line = m[1] === \"nocheck\" ? sf.getLineAndCharacterOfPosition(pos).line + 1 : undefined;\n });\n return line;\n}\n\n/** A declaration's text, and the statement's leading comments, where a directive reaches its first line. */\ninterface DeclaredRange {\n readonly start: number;\n readonly end: number;\n readonly lead?: { readonly start: number; readonly end: number };\n}\n\n/**\n * Why a range of a file is not read: the first error the compiler reports\n * inside it, or a `@ts-ignore` or `@ts-expect-error` directive in it or\n * in the leading comments (where a directive reaches the first line),\n * which hides one from the reader. Undefined when the range is clean.\n */\nfunction notCompiled(\n sf: SourceFile,\n typeErrors: (path: string) => readonly CompilerError[],\n { start, end, lead }: DeclaredRange,\n): { message: string; line: number } | undefined {\n const error = typeErrors(sf.fileName).find((e) => e.pos < end && e.end > start);\n if (error)\n return { message: `the compiler reports an error: ${error.message}`, line: error.line };\n const silenced =\n (lead ? directiveIn(sf, lead.start, lead.end) : undefined) ?? directiveIn(sf, start, end);\n if (silenced)\n return {\n message: `a ${silenced.text} comment, which hides a compiler error from the reader`,\n line: sf.getLineAndCharacterOfPosition(silenced.pos).line + 1,\n };\n return undefined;\n}\n\n/**\n * Where a declared function's errors are looked for: its own declaration\n * (in a `const` list, a sibling's error, or a directive in a sibling's\n * body, is the sibling's), and for directives the statement's leading\n * comments too, since a directive above the statement reaches its first\n * line, siblings included.\n */\nfunction rangeOf(d: Declared): DeclaredRange {\n let declaration: Node = d.node;\n while (!is.isFunctionDeclaration(declaration) && !is.isVariableDeclaration(declaration))\n declaration = declaration.parent;\n const sf = d.statement.getSourceFile();\n return {\n start: declaration.pos,\n end: declaration.end,\n lead: { start: d.statement.pos, end: d.statement.getStart(sf) },\n };\n}\n\n/**\n * The declared functions the module assigns to anywhere, with the line\n * of the first assignment: what runs under such a name may not be its\n * declaration. A name is confirmed through the compiler, so a local of\n * the same name assigned in some block is not the function.\n */\nfunction assigned(\n sf: SourceFile,\n checker: Checker,\n declarations: ReadonlyMap<string, Declared>,\n): Map<string, number> {\n const out = new Map<string, number>();\n const symbolIds = new Map<string, number | undefined>();\n const idOf = (name: string): number | undefined => {\n if (!symbolIds.has(name)) {\n const decl = declarations.get(name);\n symbolIds.set(name, decl ? checker.getSymbolAtLocation(decl.name)?.id : undefined);\n }\n return symbolIds.get(name);\n };\n const visit = (node: Node): void => {\n if (\n is.isIdentifier(node) &&\n declarations.has(node.text) &&\n !out.has(node.text) &&\n isWritten(node)\n ) {\n const id = idOf(node.text);\n // In `({ f } = …)` the name is the property's; the value it assigns is the binding's symbol.\n const parent = node.parent;\n const symbol =\n is.isShorthandPropertyAssignment(parent) && parent.name === node\n ? checker.getShorthandAssignmentValueSymbol(parent)\n : checker.getSymbolAtLocation(node);\n if (id !== undefined && symbol?.id === id) out.set(node.text, lineAt(sf, node));\n }\n node.forEachChild(visit);\n };\n visit(sf);\n return out;\n}\n\n/** A function as written: a declaration, or the arrow (or function expression) a module-level binding holds. */\ntype FunctionNode = FunctionDeclaration | ArrowFunction | FunctionExpression;\n\n/** A module-level function: its name, its node, and the statement declaring it (for its line). */\ninterface Declared {\n readonly name: Identifier;\n readonly node: FunctionNode;\n readonly statement: Node;\n}\n\n/** A function's header read: its typed parameters and return type, with the body still to read. */\ninterface Head {\n readonly name: string;\n readonly decl: FunctionNode;\n readonly params: readonly Param[];\n readonly returns: SubsetType;\n readonly line: number;\n readonly offset: number;\n}\n\n/** The parameter names of a function the subset can take at all: synchronous, no generator, plain parameters. */\nfunction shape(reader: ExprReader, decl: FunctionNode): string[] {\n if (isAsync(decl)) reader.fail(\"an async function (core functions are synchronous)\", decl);\n if (!is.isArrowFunction(decl) && decl.asteriskToken) reader.fail(\"a generator function\", decl);\n return decl.parameters.map((p) => {\n if (!is.isIdentifier(p.name)) reader.fail(\"a destructured parameter\", p);\n const pname = p.name.text;\n if (p.dotDotDotToken) reader.fail(\"a rest parameter\", p);\n // `this: T` annotates the receiver and is erased; it is no argument the function is called with.\n if (pname === \"this\") reader.fail(\"a this parameter (the receiver is not modelled)\", p);\n if (p.questionToken) reader.fail(`optional parameter ${pname}`, p);\n if (p.initializer) reader.fail(`a default value for ${pname}`, p);\n return pname;\n });\n}\n\n/** `export function name(params): Type {` or `export const name = (params): Type => …` read, the types through the compiler. */\nfunction head(reader: ExprReader, types: SubsetTypes, checker: Checker, d: Declared): Head {\n const sf = reader.sf;\n const decl = d.node;\n const name = d.name.text;\n const pnames = shape(reader, decl);\n if (decl.typeParameters) reader.fail(\"type parameters\", decl.typeParameters[0] ?? decl);\n const params: Param[] = decl.parameters.map((p, i) => {\n const pname = pnames[i] as string;\n if (!p.type) reader.fail(`parameter ${pname} without a type`, p);\n return {\n name: pname,\n type: types.of(checker.getTypeAtLocation(p.type), reader.refuseAt(p.type)),\n };\n });\n if (!decl.type)\n reader.fail(\n `${name} without a return type (the subset needs it to name the record returned)`,\n decl,\n );\n const returns = types.of(checker.getTypeAtLocation(decl.type), reader.refuseAt(decl.type));\n if (!decl.body) reader.fail(\"a function without a body\", decl);\n const offset = openParen(sf, decl);\n if (offset === undefined) reader.fail(\"a function without a parameter list\", decl);\n return { name, decl, params, returns, line: lineAt(sf, d.statement), offset };\n}\n\n/** The function, its body read and typed against its header. */\nfunction declaration(reader: ExprReader, h: Head): SubsetFunction {\n const body = h.decl.body as NonNullable<FunctionNode[\"body\"]>;\n const scope = new Map(h.params.map((p) => [p.name, p.type]));\n // An arrow's expression body is its one return. Null checks narrow the names they guard in the\n // branches they guard, before anything is typed.\n const statements = is.isBlock(body)\n ? reader.block(body.statements, scope, body)\n : reader.expression(body, scope);\n const read = reader.narrowed(statements, scope, body);\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 an engine.\n const actual = reader.typeOfExpr(read, scope, body, h.returns);\n if (!fits(actual, h.returns, reader.ctx))\n reader.fail(\n `${h.name} returns a ${describe(actual)} but declares ${describe(h.returns)}`,\n body,\n );\n return {\n name: h.name,\n params: h.params,\n returns: h.returns,\n body: read,\n line: h.line,\n offset: h.offset,\n };\n}\n\n/** A file's top-level functions, and the ones whose name may run something else, with why. */\ninterface FileFunctions {\n readonly declarations: ReadonlyMap<string, Declared>;\n readonly overloaded: ReadonlySet<string>;\n readonly untrusted: ReadonlyMap<string, OutsideFunction>;\n /** What puts the whole file outside, functions and constants alike: eval, a built-in assigned to, or the compiler's checks turned off. */\n readonly tainted?: { readonly line: number; readonly message: string };\n}\n\n/**\n * A file's top-level functions: declarations, and the arrows module-level\n * consts hold. A binding that may be reassigned (let, var) or holds a\n * function expression is listed, for its callers' typing, and untrusted;\n * so is every function of a file mentioning eval directly or assigning to\n * a built-in, and a function the file assigns to.\n */\nfunction fileFunctions(\n sf: SourceFile,\n checker: Checker,\n standardGlobal: (id: Identifier) => boolean,\n): FileFunctions {\n const declarations = new Map<string, Declared>();\n const overloaded = new Set<string>();\n const untrusted = new Map<string, OutsideFunction>();\n const declare = (name: Identifier, node: FunctionNode, statement: Node): void => {\n if (declarations.has(name.text)) overloaded.add(name.text);\n else declarations.set(name.text, { name, node, statement });\n };\n for (const st of sf.statements) {\n if (is.isFunctionDeclaration(st)) {\n if (st.name) declare(st.name, st, st);\n continue;\n }\n if (!is.isVariableStatement(st)) continue;\n for (const d of st.declarationList.declarations) {\n if (!is.isIdentifier(d.name) || !d.initializer) continue;\n let init: Expression = d.initializer;\n while (is.isParenthesizedExpression(init)) init = init.expression;\n if (!is.isArrowFunction(init) && !is.isFunctionExpression(init)) continue;\n const name = d.name.text;\n declare(d.name, init, st);\n if (!isConst(st.declarationList))\n untrusted.set(name, {\n name,\n line: lineAt(sf, st),\n message: `${name} is declared with let or var, so what runs under its name may be another function`,\n });\n else if (is.isFunctionExpression(init))\n untrusted.set(name, {\n name,\n line: lineAt(sf, st),\n message: `${name} holds a function expression (write a function declaration or an arrow)`,\n });\n }\n }\n // A direct eval can rebind any declaration of the file without naming it, so any mention of `eval`\n // that is not a property of something else (`globalThis.eval` is indirect, and cannot) puts every\n // function outside: `eval(…)`, `(eval)(…)`, inside a template substitution alike. So does a\n // `@ts-nocheck` comment, which turns off the compiler's checks the reader relies on, and a direct\n // assignment to a built-in the subset reads as standard (`Math.floor = …`, `Array.prototype.map =\n // …`), wherever it is in the file: once it has run, the file's functions compute something else.\n // The engines state the assumption that nothing the reader does not see does this.\n const evalLine = directEval(sf);\n const noCheck = noCheckDirective(sf);\n const patched = rebound(sf, checker, standardGlobal);\n const tainted =\n evalLine !== undefined\n ? {\n line: evalLine,\n message: \"the module mentions eval directly, which can rebind any of its declarations\",\n }\n : noCheck !== undefined\n ? {\n line: noCheck,\n message:\n \"its file has a @ts-nocheck comment, which turns off the compiler's checks the reader relies on\",\n }\n : patched !== undefined\n ? {\n line: patched.line,\n message: `its file assigns to ${patched.target} (line ${patched.line}), so the built-ins its functions use may not be the standard ones`,\n }\n : undefined;\n if (tainted) for (const name of declarations.keys()) untrusted.set(name, { name, ...tainted });\n for (const [name, line] of assigned(sf, checker, declarations))\n if (!untrusted.has(name))\n untrusted.set(name, {\n name,\n line,\n message: `${name} is assigned in the module, so what runs under its name may not be its declaration`,\n });\n return { declarations, overloaded, untrusted, ...(tainted ? { tainted } : {}) };\n}\n\n/** What inlining a module's calls needs from the read it belongs to. */\ninterface InlinerContext {\n readonly checker: Checker;\n readonly types: SubsetTypes;\n readonly typeSource: TypeSource;\n readonly ctx: TypeContext;\n /** The module being read, and its functions. */\n readonly module: SourceFile;\n readonly own: FileFunctions;\n readonly parseError: (path: string) => { line: number; message: string } | undefined;\n readonly typeErrors: (path: string) => readonly CompilerError[];\n /** Whether an identifier names the global of its name (`Math`): the compiler resolves it to its standard library. */\n readonly standardGlobal: (id: Identifier) => boolean;\n}\n\n/**\n * Bind the type parameters in `declared` so that it is `expected`, or a\n * member of `expected` when that is a union: a parameter binds to what it\n * meets, and two instantiations of one alias match argument by argument.\n * Returns the type matched (the union member, say), or undefined, with\n * `bound` unchanged by a member that did not match.\n */\nfunction match(declared: Type, expected: Type, bound: Map<number, Type>): Type | undefined {\n if (declared.isTypeParameter()) {\n const had = bound.get(declared.id);\n if (had && had.id !== expected.id) return undefined;\n bound.set(declared.id, expected);\n return expected;\n }\n const alias = declared.getAliasSymbol();\n const other = expected.getAliasSymbol();\n if (alias && other && alias.id === other.id) {\n const xs = declared.getAliasTypeArguments();\n const ys = expected.getAliasTypeArguments();\n if (xs.length !== ys.length) return undefined;\n const trial = new Map(bound);\n for (let i = 0; i < xs.length; i++)\n if (!match(xs[i] as Type, ys[i] as Type, trial)) return undefined;\n for (const [k, v] of trial) bound.set(k, v);\n return expected;\n }\n if (expected.isUnionType())\n for (const member of expected.getTypes()) {\n const trial = new Map(bound);\n if (match(declared, member, trial)) {\n for (const [k, v] of trial) bound.set(k, v);\n return member;\n }\n }\n return undefined;\n}\n\n/**\n * Calls to functions the module cannot name as its own, read inlined: a\n * generic function (of the module or not) at the call's instantiation,\n * and a function of another file, as the compiler resolves the import.\n * The callee's body is read in its own file under the parameter types the\n * call's resolved signature gives, its literals typed by the resolved\n * return type, its names moved away from the caller's, and bound by `let`\n * to the arguments in order: a pure function called by value computes\n * exactly that. The callee's own calls inline the same way, so the\n * helpers of its file come with it. A callee with no body here (a\n * declaration file), one its file may rebind, or one reached again while\n * it is being inlined (recursion) is outside the subset, with why.\n */\nfunction inliner(c: InlinerContext): { inline: Inline; constant: Constant } {\n const files = new Map<SourceFile, FileFunctions>([[c.module, c.own]]);\n const functionsOf = (file: SourceFile): FileFunctions => {\n let found = files.get(file);\n if (!found) {\n found = fileFunctions(file, c.checker, c.standardGlobal);\n files.set(file, found);\n }\n return found;\n };\n // Whether a declaration's text compiles, once per declaration however often it is read.\n const vetted = new Map<Node, { message: string; line: number } | undefined>();\n const vet = (\n file: SourceFile,\n key: Node,\n range: DeclaredRange,\n ): { message: string; line: number } | undefined => {\n if (!vetted.has(key)) vetted.set(key, notCompiled(file, c.typeErrors, range));\n return vetted.get(key);\n };\n const inlining: string[] = [];\n // The type parameters of the functions being read, bound to the types their calls give them,\n // innermost last: a generic function read inside another sees the outer one's as concrete types.\n const substitutions: Map<number, Type>[] = [];\n const concrete = (t: Type): Type => {\n const top = substitutions[substitutions.length - 1];\n return top && t.isTypeParameter() ? (top.get(t.id) ?? t) : t;\n };\n // `fail` is annotated so that the compiler narrows after a call to it.\n const inline: Inline = (call, callee, scope, readArgs, fail: (what: string) => never) => {\n // A call the compiler rejects (a name imported with `import type`, which does not exist when the\n // code runs; arguments that do not fit) is no call the reader may stand in for.\n const caller = call.getSourceFile();\n const start = call.getStart(caller);\n if (c.typeErrors(caller.fileName).some((e) => e.pos < call.end && e.end > start))\n fail(`the compiler reports an error on this call to ${callee.text}`);\n let symbol = c.checker.getSymbolAtLocation(callee);\n if (!symbol) return undefined;\n if (symbol.flags & SymbolFlags.Alias) symbol = c.checker.getAliasedSymbol(symbol);\n const decl = symbol.valueDeclaration?.resolve();\n if (!decl || !(is.isFunctionDeclaration(decl) || is.isVariableDeclaration(decl)))\n return undefined;\n const file = decl.getSourceFile();\n // The declaration's own name: a default export's symbol is named `default`.\n const name = decl.name && is.isIdentifier(decl.name) ? decl.name.text : symbol.name;\n const where = file === c.module ? name : `${name} (from ${file.fileName})`;\n if (file.isDeclarationFile)\n fail(`${where} has no body to read: it is declared in a declaration file`);\n const fns = functionsOf(file);\n const d = fns.declarations.get(name);\n // Only a top-level function of its file is read; anything else is refused by the usual message.\n if (!d || !decl.name || d.name.pos !== decl.name.pos) return undefined;\n if (c.parseError(file.fileName)) fail(`${where} is in a file the compiler cannot parse`);\n const untrusted = fns.untrusted.get(name);\n if (untrusted) fail(`${where} is outside the subset: ${untrusted.message}`);\n if (fns.overloaded.has(name)) fail(`${where} is declared more than once (overloads)`);\n const body = d.node.body;\n if (!body) fail(`${where} has no body to read`);\n // A callee the compiler reports an error in computes something its text does not say.\n const bad = vet(file, d.node, rangeOf(d));\n if (bad)\n fail(\n `${where} is outside the subset: ${bad.message} (line ${bad.line}${file === c.module ? \"\" : \" of its file\"})`,\n );\n const signature = c.checker.getResolvedSignature(call);\n if (c.checker.isUnknownSignature(signature)) fail(`the call to ${where} does not resolve`);\n const fileNames: Names = {\n callable: () => false,\n target: (n) => n,\n declared: (n) => fns.declarations.has(n),\n spec: false,\n global: c.standardGlobal,\n };\n const typeSource: TypeSource = {\n annotation: (node, refuse) => c.types.of(concrete(c.checker.getTypeAtLocation(node)), refuse),\n contextual: c.typeSource.contextual,\n };\n const reader = new ExprReader(file, fileNames, typeSource, c.ctx, undefined, inline, constant);\n const params = shape(reader, d.node);\n const symbols = signature.getParameters();\n if (symbols.length !== params.length || call.arguments.length !== params.length)\n fail(`${where} takes ${params.length} argument(s), called with ${call.arguments.length}`);\n // A generic callee is instantiated by where its value goes first: the compiler infers `E` in\n // `err({ type: \"locked\" })` from the argument alone, a record of its own, where the caller's\n // declared result names the error union the literal belongs to. What the context leaves open\n // is the compiler's instantiation.\n const bound = new Map<number, Type>();\n const declared = c.checker.getSignatureFromDeclaration(d.node);\n const generalReturn = c.checker.getReturnTypeOfSignature(declared);\n const context = d.node.typeParameters ? c.checker.getContextualType(call) : undefined;\n const matched = context ? match(generalReturn, concrete(context), bound) : undefined;\n const declaredParams = declared.getParameters();\n const generalParams = symbols.map((_, i) => {\n const own = declaredParams[i];\n return own ? c.checker.getTypeOfSymbol(own) : undefined;\n });\n const resolvedParams = symbols.map((p) => concrete(c.checker.getTypeOfSymbol(p)));\n const resolvedReturn = concrete(c.checker.getReturnTypeOfSignature(signature));\n // The callee's own type parameters, for its body: the context's first, the compiler's after.\n generalParams.forEach((g, i) => {\n if (g) match(g, resolvedParams[i] as Type, bound);\n });\n match(generalReturn, resolvedReturn, bound);\n const types = symbols.map((_, i) => {\n const g = generalParams[i];\n const type =\n g?.isTypeParameter() && bound.has(g.id)\n ? concrete(bound.get(g.id) as Type)\n : (resolvedParams[i] as Type);\n return c.types.of(type, (what) =>\n fail(`${where}, parameter ${params[i]} at this call: ${what}`),\n );\n });\n const returns = c.types.of(matched ?? resolvedReturn, (what) =>\n fail(`${where} returns, at this call, ${what}`),\n );\n const own = new Map([...bound].map(([k, v]) => [k, concrete(v)]));\n // The arguments in the caller's scope, before this callee is marked as being read: a nested call\n // to the same function is no recursion.\n const args = readArgs(types);\n const key = `${file.fileName}#${name}`;\n if (inlining.includes(key))\n fail(\n `${where} is recursive, which a function read at its calls cannot be (recursion is in the subset only as a module's own structural recursion)`,\n );\n inlining.push(key);\n substitutions.push(own);\n try {\n const inner = new Map(params.map((p, i) => [p, types[i] as SubsetType]));\n const readBody = (): Expr => {\n const read = returning(\n is.isBlock(body)\n ? reader.block(body.statements, inner, body)\n : reader.expression(body, inner),\n returns,\n );\n const actual = reader.typeOfExpr(reader.narrowed(read, inner, body), inner, body, returns);\n if (!fits(actual, returns, c.ctx))\n reader.fail(\n `returns a ${describe(actual)}, not the ${describe(returns)} called for`,\n body,\n );\n return read;\n };\n let read: Expr;\n try {\n read = readBody();\n } catch (err) {\n if (!(err instanceof OutsideSubset)) throw err;\n fail(\n `${where}, read at this call, is outside the subset: ${err.message} (line ${err.line} of its file)`,\n );\n }\n // Its parameters and its own names move away from every name the caller has here.\n const callerNames = new Set([...scope.keys(), ...args.flatMap((a) => [...boundNames(a)])]);\n // Every parameter name is reserved, used or not, so no fresh name repeats one.\n const taken = new Set([...callerNames, ...boundNames(read), ...params]);\n const renames = new Map<string, string>();\n for (const p of params) {\n const to = callerNames.has(p) ? fresh(p, taken) : p;\n taken.add(to);\n renames.set(p, to);\n }\n const renamed = renameVars(read, renames, taken, callerNames);\n return params.reduceRight<Expr>(\n (rest, p, i) => ({\n kind: \"let\",\n name: renames.get(p) as string,\n value: args[i] as Expr,\n body: rest,\n type: types[i] as SubsetType,\n }),\n renamed,\n );\n } finally {\n substitutions.pop();\n inlining.pop();\n }\n };\n // The constants being read, innermost last: one that reaches itself is refused.\n const reading: string[] = [];\n const constant: Constant = (name, fail: (what: string) => never) => {\n let symbol = c.checker.getSymbolAtLocation(name);\n if (!symbol) return undefined;\n const imported = (symbol.flags & SymbolFlags.Alias) !== 0;\n if (imported) symbol = c.checker.getAliasedSymbol(symbol);\n const decl = symbol.valueDeclaration?.resolve();\n if (!decl || !is.isVariableDeclaration(decl) || !is.isIdentifier(decl.name)) return undefined;\n const list = decl.parent;\n const statement = list.parent;\n const file = decl.getSourceFile();\n // A module-level `const` only: a `let` or `var` may be rebound, a local is not this name.\n if (!is.isVariableDeclarationList(list) || !is.isVariableStatement(statement)) return undefined;\n // A local the compiler resolves the name to, which the reader has not bound, is declared later in\n // its block: a const there throws when used before its line, a var reads undefined.\n if (statement.parent !== file)\n fail(`${name.text}, which is declared after this use in its block`);\n const where = file === c.module ? decl.name.text : `${decl.name.text} (from ${file.fileName})`;\n // A global (Math, say) is declared in the compiler's own declaration files: no constant here.\n if (file.isDeclarationFile && !imported) return undefined;\n if (file.isDeclarationFile)\n fail(`${where} has no value to read: it is declared in a declaration file`);\n if (!isConst(list)) fail(`${where} is a module-level let or var, which may be rebound`);\n // A name the compiler rejects here (used before its declaration, say) is not read.\n const at = name.getSourceFile();\n const start = name.getStart(at);\n if (c.typeErrors(at.fileName).some((e) => e.pos < name.end && e.end > start))\n fail(`the compiler reports an error on ${name.text} here`);\n if (c.parseError(file.fileName)) fail(`${where} is in a file the compiler cannot parse`);\n const init = decl.initializer;\n if (!init) fail(`${where} has no initializer`);\n if (is.isArrowFunction(init) || is.isFunctionExpression(init)) return undefined;\n // The declaration as a whole: a declared type the value does not fit is reported on the name.\n const bad = vet(file, decl, {\n start: decl.pos,\n end: decl.end,\n lead: { start: statement.pos, end: statement.getStart(file) },\n });\n if (bad)\n fail(\n `${where} is outside the subset: ${bad.message} (line ${bad.line}${file === c.module ? \"\" : \" of its file\"})`,\n );\n const key = `${file.fileName}#${decl.name.text}`;\n if (reading.includes(key)) fail(`${where} is defined in terms of itself`);\n const fns = functionsOf(file);\n // A constant of a file that may rebind a built-in, or whose checks are off, is no value to trust.\n if (fns.tainted) fail(`${where} is outside the subset: ${fns.tainted.message}`);\n const fileNames: Names = {\n callable: () => false,\n target: (n) => n,\n declared: (n) => fns.declarations.has(n),\n spec: false,\n global: c.standardGlobal,\n };\n const reader = new ExprReader(\n file,\n fileNames,\n c.typeSource,\n c.ctx,\n undefined,\n undefined,\n constant,\n );\n reading.push(key);\n try {\n const value = reader.expression(init, new Map());\n if (!isValue(value))\n reader.fail(\n `${decl.name.text} holds something other than a number, boolean or string built from literals, operators and other such constants`,\n init,\n );\n return value;\n } catch (err) {\n if (!(err instanceof OutsideSubset)) throw err;\n fail(\n `${where}, read where it is used, is outside the subset: ${err.message} (line ${err.line} of its file)`,\n );\n } finally {\n reading.pop();\n }\n };\n return { inline, constant };\n}\n\n/**\n * Whether an expression is a value a constant may hold: literals of the\n * primitive types and the operators on them, with no name, call or record.\n */\nfunction isValue(e: Expr): boolean {\n switch (e.kind) {\n case \"int\":\n case \"bool\":\n case \"string\":\n return true;\n case \"neg\":\n case \"not\":\n case \"isInteger\":\n case \"floor\":\n return isValue(e.operand);\n case \"binary\":\n return isValue(e.left) && isValue(e.right);\n case \"cond\":\n return isValue(e.test) && isValue(e.ifTrue) && isValue(e.ifFalse);\n default:\n return false;\n }\n}\n\n/**\n * The expression with the record literals it returns typed `t`, where\n * they have no type of their own: a function inlined at a call returns\n * its instantiated type, which a literal in a generic body cannot name.\n */\nfunction returning(e: Expr, t: SubsetType): Expr {\n const target = t.kind === \"nullable\" ? t.inner : t;\n if (target.kind !== \"record\" && target.kind !== \"union\") return e;\n switch (e.kind) {\n case \"record\":\n return e.type ? e : { ...e, type: target };\n case \"let\":\n case \"narrow\":\n case \"narrowTag\":\n return { ...e, body: returning(e.body, t) };\n case \"cond\":\n return { ...e, ifTrue: returning(e.ifTrue, t), ifFalse: returning(e.ifFalse, t) };\n default:\n return e;\n }\n}\n\n/**\n * Read a module: every function the subset takes (in source order, so\n * callees come before callers), the record types and unions they use,\n * and, for the other functions, why not. A function calling one outside\n * the subset is outside it too. The names given are what the caller\n * cares about; one the module does not declare at its top level is\n * reported among the others, not thrown.\n */\nexport function readSubset(\n source: string,\n functions?: readonly string[],\n options: ReadSubsetOptions = {},\n): SubsetModule {\n const path = options.path ?? virtualModulePath;\n return withProgram(\n [{ path, text: source }, ...(options.files ?? [])],\n ({ checker, file, parseError, typeErrors, standardGlobal }) => {\n const sf = file(path);\n // Pass 1: the module's top-level functions, and what makes them untrustworthy. A generic one is\n // no function of the subset (no claim is stated over a type parameter); its callers read it inlined.\n const own = fileFunctions(sf, checker, standardGlobal);\n const { declarations, overloaded } = own;\n const declared = new Set(declarations.keys());\n const generic = new Set(\n [...declarations].filter(([, d]) => d.node.typeParameters).map(([name]) => name),\n );\n const outside = new Map<string, OutsideFunction>();\n const error = parseError(path);\n // Source the compiler cannot parse is source the reader cannot trust: every function is outside.\n if (error) {\n for (const name of new Set([...declared, ...(functions ?? [])]))\n outside.set(name, {\n name,\n line: 0,\n message: `the module could not be parsed: ${error.message} (line ${error.line})`,\n });\n return { records: [], unions: [], functions: [], outside: [...outside.values()] };\n }\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 for (const [name, why] of own.untrusted) if (!outside.has(name)) outside.set(name, why);\n // The module's own declared types first, in their order, so a record literal of no declared type\n // is matched against every record the module declares, and a record belongs to the union declared\n // first. A declared type the subset does not take is left out here; a function using it says why.\n const types = new SubsetTypes(checker);\n const skip = Symbol(\"outside\");\n for (const st of sf.statements) {\n if (!is.isInterfaceDeclaration(st) && !is.isTypeAliasDeclaration(st)) continue;\n if (st.typeParameters) continue; // a generic alias is read where it is instantiated\n const symbol = checker.getSymbolAtLocation(st.name);\n if (!symbol) continue;\n try {\n types.of(checker.getDeclaredTypeOfSymbol(symbol), () => {\n throw skip;\n });\n } catch (err) {\n if (err !== skip) throw err;\n }\n }\n // Pass 2: signatures, so every function's return type is known before any body is read.\n const { ctx, signatures } = moduleContext(types.records);\n const names: Names = {\n callable: (n) => declared.has(n) && !generic.has(n),\n target: (n) => n,\n declared: (n) => declared.has(n),\n spec: false,\n global: standardGlobal,\n };\n const typeSource: TypeSource = {\n annotation: (node, refuse) => types.of(checker.getTypeAtLocation(node), refuse),\n contextual: (node) => contextualType(checker, types, node),\n };\n const { inline, constant } = inliner({\n checker,\n types,\n typeSource,\n ctx,\n module: sf,\n own,\n parseError,\n typeErrors,\n standardGlobal,\n });\n const reader = new ExprReader(sf, names, typeSource, ctx, undefined, inline, constant);\n const heads: Head[] = [];\n for (const [name, decl] of declarations) {\n try {\n if (overloaded.has(name))\n reader.fail(`${name} is declared more than once (overloads)`, decl.statement);\n const h = head(reader, types, checker, decl);\n // Callers of an assigned function still type-check against its declaration; they are then outside with it.\n signatures.set(name, { params: h.params, returns: h.returns });\n if (!outside.has(name)) heads.push(h);\n } catch (err) {\n if (!(err instanceof OutsideSubset)) throw err;\n if (!outside.has(name)) outside.set(name, { name, line: err.line, message: err.message });\n }\n }\n // Pass 3: bodies. Text the compiler rejects (a const used before its declaration, which\n // throws where the reader sees a value) may compute something other than what it says: a\n // function read fine is still outside, with the compiler's message, when it has such an error.\n const read = new Map<string, SubsetFunction>();\n for (const h of heads) {\n try {\n const fn = declaration(reader, h);\n const bad = notCompiled(sf, typeErrors, rangeOf(declarations.get(h.name) as Declared));\n if (bad) throw new OutsideSubset(bad.message, bad.line);\n read.set(h.name, fn);\n } catch (err) {\n if (!(err instanceof OutsideSubset)) throw err;\n outside.set(h.name, { name: h.name, line: err.line, message: err.message });\n }\n }\n closeOverCallees(read, outside);\n // Recursion is in the subset as structural recursion on a list (`structuralOn`), a function calling\n // itself directly; any other recursion 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 const direct = [...callees(fn.body)].every((c) => c === name || !reaches(c, name));\n const on = direct ? structuralOn(fn) : undefined;\n if (on !== undefined) {\n read.set(name, { ...fn, structural: on });\n continue;\n }\n read.delete(name);\n outside.set(name, {\n name,\n line: fn.line,\n message: `${name} is recursive in a way the subset does not take: it takes a function calling itself on a list parameter's slice(1), after a first test of that list's length against 0 (if (xs.length === 0) return …)`,\n });\n }\n closeOverCallees(read, outside);\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 // A structurally recursive function calls itself: that callee needs no placing first.\n for (const [name, fn] of read)\n if (\n !placed.has(name) &&\n [...callees(fn.body)].every((c) => c === name || placed.has(c))\n ) {\n ordered.push(fn);\n placed.add(name);\n }\n return {\n records: [...types.records.values()],\n unions: types.unions,\n functions: ordered,\n outside: [...outside.values()],\n };\n },\n );\n}\n\n/** A caller of a function outside the subset is outside it too, however many steps away. */\nfunction closeOverCallees(\n read: Map<string, SubsetFunction>,\n outside: Map<string, OutsideFunction>,\n): void {\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}\n\n/**\n * A reader over text that is not the module: with `aliases`, the text is\n * a spec file's, whose names for the module's functions are its own\n * imports and nothing else; without, the text sees the module's names.\n * No compiler stands behind the text, so a `const` annotation is read\n * from its syntax against the module's declared types, and a record\n * literal has no contextual type. Lines are not reported: the text's\n * position is the caller's to know.\n */\nfunction arrowReader(\n sf: SourceFile,\n module: SubsetModule,\n aliases?: ReadonlyMap<string, string>,\n): ExprReader {\n const records = new Map(module.records.map((rec) => [rec.name, rec]));\n const unionNames = new Set(module.unions.map((u) => u.name));\n const inSubset = new Set(module.functions.map((f) => f.name));\n let names: Names;\n if (aliases) {\n const declared = new Set(aliases.keys());\n const callable = new Set(\n [...aliases].filter(([, fn]) => inSubset.has(fn)).map(([local]) => local),\n );\n names = {\n callable: (n) => callable.has(n),\n target: (n) => aliases.get(n) ?? n,\n declared: (n) => declared.has(n),\n spec: true,\n global: () => true,\n };\n } else {\n const declared = new Set([...inSubset, ...module.outside.map((o) => o.name)]);\n names = {\n callable: (n) => inSubset.has(n),\n target: (n) => n,\n declared: (n) => declared.has(n),\n spec: false,\n global: () => true,\n };\n }\n const recordNames = new Set(records.keys());\n const typeSource: TypeSource = {\n annotation: (node, refuse) => syntacticType(sf, node, recordNames, unionNames, refuse),\n contextual: () => undefined,\n };\n const signatures = new Map<string, CalleeSignature>(\n module.functions.map((f) => [f.name, { params: f.params, returns: f.returns }]),\n );\n return new ExprReader(sf, names, typeSource, { records, signatures }, () => 0);\n}\n\n/** The one expression a fragment `(text)` parsed to, or why the text is not one expression. */\nfunction fragmentExpression(sf: SourceFile): Expression {\n const [first, second] = sf.statements;\n if (second) throw new OutsideSubset(`unexpected ${textOf(sf, second)} after the expression`, 0);\n if (!first || !is.isExpressionStatement(first) || !is.isParenthesizedExpression(first.expression))\n throw new OutsideSubset(\"could not be parsed as an expression\", 0);\n let broken: string | undefined;\n const visit = (node: Node): void => {\n if (broken !== undefined) return;\n if (is.isIdentifier(node) && node.text === \"\")\n broken = \"could not be parsed (something is missing)\";\n node.forEachChild(visit);\n };\n visit(first);\n if (broken !== undefined) throw new OutsideSubset(broken, 0);\n return first.expression.expression;\n}\n\n/**\n * One TypeScript expression (a claim's body, say) in a scope of typed\n * names, over a module already read. The whole text must be the\n * expression.\n */\nexport function readExpression(\n text: string,\n scope: ReadonlyMap<string, SubsetType>,\n module: SubsetModule,\n aliases?: ReadonlyMap<string, string>,\n): Expr {\n return withSourceFile(`(${text}\\n)`, (sf) => {\n const expr = fragmentExpression(sf);\n return arrowReader(sf, module, aliases).expression(expr, scope);\n });\n}\n\n/**\n * The body of a spec file's arrow (`when` or `ensures`) as a boolean\n * expression: an expression body as it is, a block body through the same\n * statement reader as a function body (`const`, `if`, early returns).\n * The scope maps the arrow's own parameter names to the binders' types;\n * `aliases` maps the spec file's local names to the module's functions,\n * and a free name that is neither is outside the subset: the spec file's\n * scope is its imports, never the module's. `Math` and `Number` are the\n * globals wherever the arrow's own scope does not bind them: `readSpecs`\n * has checked that every built-in a claim names resolves to the standard\n * library in the spec file.\n */\nexport function readArrowBody(\n arrow: Arrow,\n scope: ReadonlyMap<string, SubsetType>,\n module: SubsetModule,\n aliases: ReadonlyMap<string, string> = new Map(),\n): Expr {\n if (!arrow.block)\n return withSourceFile(`(${arrow.body}\\n)`, (sf) => {\n const expr = fragmentExpression(sf);\n const reader = arrowReader(sf, module, aliases);\n return reader.narrowed(reader.expression(expr, scope), scope, sf);\n });\n return withSourceFile(`{${arrow.body}\\n}`, (sf) => {\n const block = blockOf(sf);\n if (!block) throw new OutsideSubset(\"could not be parsed as a block\", 0);\n const reader = arrowReader(sf, module, aliases);\n return reader.narrowed(reader.block(block.statements, new Map(scope), block), scope, sf);\n });\n}\n\n/**\n * The list parameter a function recurses on structurally, or undefined:\n * its body is `if (p.length === 0) … else …` for a list parameter p, the\n * test and the first branch do not call it, and every call to it in the\n * other branch passes `p.slice(1)` for p. Lean takes such a definition as\n * a match on `[]` and `head :: tail`, recursing on the tail.\n */\nfunction structuralOn(fn: SubsetFunction): number | undefined {\n const body = fn.body;\n if (body.kind !== \"cond\") return undefined;\n const t = body.test;\n if (t.kind !== \"binary\" || t.op !== \"===\") return undefined;\n const sides = [t.left, t.right];\n const zero = sides.find((x) => x.kind === \"int\" && x.value === \"0\");\n const len = sides.find((x) => x !== zero);\n if (!zero || len?.kind !== \"field\" || len.field !== \"length\" || len.object.kind !== \"var\")\n return undefined;\n const list = len.object.name;\n const at = fn.params.findIndex((p) => p.name === list && p.type.kind === \"list\");\n if (at < 0) return undefined;\n if (callees(t).has(fn.name) || callees(body.ifTrue).has(fn.name)) return undefined;\n const calls = selfCalls(body.ifFalse, fn.name);\n const onTail = (a: Expr | undefined) =>\n a?.kind === \"tail\" && a.list.kind === \"var\" && a.list.name === list;\n return calls.length > 0 && calls.every((c) => onTail(c.args[at])) ? at : undefined;\n}\n\n/** Every call to `name` in an expression. */\nfunction selfCalls(e: Expr, name: string): Extract<Expr, { kind: \"call\" }>[] {\n const out: Extract<Expr, { kind: \"call\" }>[] = [];\n const walk = (x: Expr): void => {\n if (x.kind === \"call\" && x.callee === name) out.push(x);\n for (const child of children(x)) walk(child);\n };\n walk(e);\n return out;\n}\n\n/** An expression's direct subexpressions. */\nexport function children(e: Expr): Expr[] {\n switch (e.kind) {\n case \"int\":\n case \"bool\":\n case \"string\":\n case \"null\":\n case \"var\":\n return [];\n case \"narrow\":\n case \"narrowTag\":\n return [e.body];\n case \"neg\":\n case \"not\":\n case \"isInteger\":\n case \"floor\":\n return [e.operand];\n case \"binary\":\n return [e.left, e.right];\n case \"cond\":\n return [e.test, e.ifTrue, e.ifFalse];\n case \"call\":\n return [...e.args];\n case \"field\":\n return [e.object];\n case \"record\":\n return e.fields.map((f) => f.value);\n case \"let\":\n return [e.value, e.body];\n case \"list\":\n return [...e.items, ...(e.rest ? [e.rest] : [])];\n case \"tail\":\n return [e.list];\n case \"headOr\":\n return [e.list, e.fallback];\n case \"iterate\":\n return [e.list, e.body];\n case \"fold\":\n return [e.list, e.init, e.body];\n }\n}\n\n/** Whether an expression holds a node of the kinds named. */\nfunction hasNode(e: Expr, kinds: ReadonlySet<Expr[\"kind\"]>): boolean {\n if (kinds.has(e.kind)) return true;\n switch (e.kind) {\n case \"int\":\n case \"bool\":\n case \"string\":\n case \"null\":\n case \"var\":\n return false;\n case \"narrow\":\n case \"narrowTag\":\n return hasNode(e.body, kinds);\n case \"neg\":\n case \"not\":\n case \"isInteger\":\n case \"floor\":\n return hasNode(e.operand, kinds);\n case \"binary\":\n return hasNode(e.left, kinds) || hasNode(e.right, kinds);\n case \"cond\":\n return hasNode(e.test, kinds) || hasNode(e.ifTrue, kinds) || hasNode(e.ifFalse, kinds);\n case \"call\":\n return e.args.some((a) => hasNode(a, kinds));\n case \"field\":\n return hasNode(e.object, kinds);\n case \"record\":\n return e.fields.some((f) => hasNode(f.value, kinds));\n case \"let\":\n return hasNode(e.value, kinds) || hasNode(e.body, kinds);\n case \"list\":\n return e.items.some((x) => hasNode(x, kinds)) || (e.rest ? hasNode(e.rest, kinds) : false);\n case \"tail\":\n return hasNode(e.list, kinds);\n case \"headOr\":\n return hasNode(e.list, kinds) || hasNode(e.fallback, kinds);\n case \"iterate\":\n return hasNode(e.list, kinds) || hasNode(e.body, kinds);\n case \"fold\":\n return hasNode(e.list, kinds) || hasNode(e.init, kinds) || hasNode(e.body, kinds);\n }\n}\n\n/**\n * The module as an engine that takes only some of the subset's types sees\n * it: records with a field of a type it does not take are dropped, and so\n * are functions whose signature holds one, whose body uses what the\n * types bring (`null`, narrowing), or which call such a function; each is\n * reported outside with `reason`.\n */\nexport function restrictModule(\n module: SubsetModule,\n takes: (t: SubsetType) => boolean,\n reason: string,\n /** Expression kinds a function's body may not hold here: by default what nullable types and unions bring. */\n bodies: ReadonlySet<Expr[\"kind\"]> = new Set([\"null\", \"narrow\", \"narrowTag\"]),\n /** A body the engine refuses for what it computes, not its kinds or types (a division, say). */\n refused?: (body: Expr) => boolean,\n): SubsetModule {\n // A record with a field the engine does not take is out, and so is a union with such a member, and\n // so, in turn, is a record with a field of that union: to a fixed point.\n const badRecords = new Set<string>();\n for (const u of module.unions)\n if (!takes({ kind: \"union\", name: u.name })) badRecords.add(`union:${u.name}`);\n for (let changed = true; changed; ) {\n changed = false;\n for (const rec of module.records)\n if (\n !badRecords.has(rec.name) &&\n rec.fields.some((f) => !typeTaken(f.type, takes, badRecords))\n ) {\n badRecords.add(rec.name);\n changed = true;\n }\n for (const u of module.unions) {\n if (!badRecords.has(`union:${u.name}`) && u.members.some((m) => badRecords.has(m.record))) {\n badRecords.add(`union:${u.name}`);\n changed = true;\n }\n // A member of a dropped union stays a record of its own: every record has its own sort, so a\n // member of several unions does not go with one of them.\n }\n }\n const outside = new Map(module.outside.map((o) => [o.name, o]));\n const kept = new Map(module.functions.map((f) => [f.name, f]));\n const uses = (f: SubsetFunction) =>\n !f.params.every((p) => typeTaken(p.type, takes, badRecords)) ||\n !typeTaken(f.returns, takes, badRecords) ||\n annotations(f.body).some((t) => !typeTaken(t, takes, badRecords)) ||\n hasNode(f.body, bodies) ||\n refused?.(f.body) === true;\n for (const f of module.functions)\n if (uses(f)) {\n kept.delete(f.name);\n outside.set(f.name, { name: f.name, line: f.line, message: reason });\n }\n for (let changed = true; changed; ) {\n changed = false;\n for (const [name, f] of kept) {\n const bad = [...callees(f.body)].find((c) => outside.has(c));\n if (bad === undefined) continue;\n kept.delete(name);\n outside.set(name, {\n name,\n line: f.line,\n message: `calls ${bad}, which is outside the engine's subset: ${outside.get(bad)?.message}`,\n });\n changed = true;\n }\n }\n return {\n // A kept record names only the unions kept with it.\n records: module.records\n .filter((r) => !badRecords.has(r.name))\n .map((r) => {\n const unions = r.unions?.filter((u) => !badRecords.has(`union:${u}`));\n if (unions === r.unions) return r;\n const { unions: _, ...rest } = r;\n return unions && unions.length > 0 ? { ...rest, unions } : rest;\n }),\n unions: module.unions.filter((u) => !badRecords.has(`union:${u.name}`)),\n functions: module.functions.filter((f) => kept.has(f.name)),\n outside: [...outside.values()],\n };\n}\n\nfunction typeTaken(\n t: SubsetType,\n takes: (t: SubsetType) => boolean,\n badRecords: ReadonlySet<string>,\n): boolean {\n if (!takes(t)) return false;\n if (t.kind === \"record\") return !badRecords.has(t.name);\n if (t.kind === \"union\") return !badRecords.has(`union:${t.name}`);\n if (t.kind === \"nullable\") return typeTaken(t.inner, takes, badRecords);\n if (t.kind === \"list\") return typeTaken(t.element, takes, badRecords);\n return true;\n}\n\n/** The types a body's `const` annotations and its record literals' contexts name. */\nfunction annotations(e: Expr, out: SubsetType[] = []): SubsetType[] {\n if ((e.kind === \"let\" || e.kind === \"record\") && e.type) out.push(e.type);\n for (const c of children(e)) annotations(c, out);\n return out;\n}\n\n/** An expression only lists bring. */\nexport type ListExpr = Extract<Expr, { kind: \"list\" | \"tail\" | \"headOr\" | \"iterate\" | \"fold\" }>;\n\n/** The expression kinds only lists bring, for an engine that does not take them. */\nexport const listKinds: ReadonlySet<Expr[\"kind\"]> = new Set<ListExpr[\"kind\"]>([\n \"list\",\n \"tail\",\n \"headOr\",\n \"iterate\",\n \"fold\",\n]);\n\n/** Whether an expression is one only lists bring (a type guard over `listKinds`). */\nexport const isListExpr = (e: Expr): e is ListExpr => listKinds.has(e.kind);\n","/**\n * A module and its spec file read into `ModuleSpecs` through the\n * compiler. From the module: the exported functions and their parameter\n * types (`function` declarations and `const` arrows alike), the types as\n * the compiler resolves them. From the spec file: every\n * `export const name = forall(f, { sample, when, ensures })` and\n * `total(f)`, with the combinators imported from `eutaxy/spec` and `f`\n * imported from the module beside the spec file (the import resolved by\n * the compiler); the arrows are kept as text, their parameter names\n * naming the binders, and the precondition's conjuncts about one\n * parameter become that binder's hint. Anything else is an error with a\n * line, never a guess.\n */\n\nimport type {\n Arrow,\n Binder,\n Endpoint,\n FunctionSpec,\n Hint,\n ModuleSpecs,\n Param,\n Property,\n SpecError,\n SpecType,\n} from \"@eutaxy/spec\";\nimport {\n type ArrowFunction,\n type Expression,\n type FunctionLikeBase,\n type ImportDeclaration,\n type Node,\n type SourceFile,\n SyntaxKind,\n} from \"typescript/ast\";\nimport * as is from \"typescript/ast/is\";\nimport type { Checker, Program } from \"typescript/sync\";\nimport { endpointBigInt, endpointNumber } from \"../generate.ts\";\nimport {\n isAsync,\n isConst,\n isExported,\n lineAt,\n type Opened,\n openParen,\n textOf,\n withProgram,\n withSourceFile,\n} from \"./compiler.ts\";\nimport { rebound } from \"./subset.ts\";\nimport { specTypeOf, unionOf } from \"./types.ts\";\n\nexport interface ReadSpecsInput {\n /** The module's source. */\n readonly module: string;\n /** The spec file's source. */\n readonly spec: string;\n /**\n * The module's path, under which its imports resolve; the spec file\n * is beside it unless `specPath` says otherwise. For a module given\n * by text alone, any absolute path the spec file's import of the\n * module resolves to (`/x/domain.ts` for `import … from \"./domain.ts\"`).\n */\n readonly modulePath: string;\n /** The spec file's path; `<module>.props.ts` by default. */\n readonly specPath?: string;\n /** Specifiers the combinators come from; `eutaxy/spec` and the workspace name by default. */\n readonly specSpecifiers?: readonly string[];\n}\n\n// ---------------------------------------------------------------------------\n// The module: exported functions and their parameter types.\n\ninterface Declaration {\n readonly name: string;\n readonly params: readonly Param[];\n readonly line: number;\n readonly offset: number;\n}\n\ninterface ModuleSide {\n readonly declarations: ReadonlyMap<string, Declaration>;\n /** Exported name to local declaration name. */\n readonly exports: ReadonlyMap<string, string>;\n readonly errors: readonly SpecError[];\n}\n\n/** The parameters of a function-like declaration: `name?: T = default`, `...rest`, destructured. */\nfunction readParams(checker: Checker, fn: FunctionLikeBase): Param[] {\n const params: Param[] = [];\n for (const p of fn.parameters) {\n const name = is.isIdentifier(p.name) ? p.name.text : null;\n if (name === \"this\") continue; // a receiver annotation, no argument\n if (p.dotDotDotToken) {\n params.push({ name: null, type: { kind: \"unknown\", text: `...${name ?? \"\"}` } });\n continue;\n }\n let type: SpecType;\n if (p.type) type = specTypeOf(checker, checker.getTypeAtLocation(p.type));\n else if (p.initializer) type = specTypeOf(checker, checker.getTypeAtLocation(p));\n else type = { kind: \"unknown\", text: \"(no type annotation)\" };\n // An optional parameter, or one with a default, may be passed undefined.\n if (p.questionToken || p.initializer) type = unionOf([type, { kind: \"undefined\" }]);\n params.push({ name, type });\n }\n return params;\n}\n\nfunction readModuleSide(sf: SourceFile, checker: Checker): ModuleSide {\n const errors: SpecError[] = [];\n const declarations = new Map<string, Declaration>();\n const exports = new Map<string, string>();\n const declare = (name: string, fn: FunctionLikeBase, at: Node): void => {\n const offset = openParen(sf, fn);\n if (offset === undefined) return; // an arrow without parentheses: no parameter list to point at\n if (declarations.has(name)) {\n errors.push({\n line: lineAt(sf, at),\n message: `${name} is declared more than once (overloads): a spec is checked against one signature`,\n inModule: true,\n });\n return;\n }\n declarations.set(name, { name, params: readParams(checker, fn), line: lineAt(sf, at), offset });\n };\n for (const st of sf.statements) {\n if (is.isFunctionDeclaration(st)) {\n if (!st.name) continue;\n declare(st.name.text, st, st);\n if (isExported(st)) exports.set(st.name.text, st.name.text);\n continue;\n }\n if (is.isVariableStatement(st)) {\n // `export const f = (a: T): R => …` or `= function (a: T) …`: a function by another declaration.\n for (const d of st.declarationList.declarations) {\n if (!is.isIdentifier(d.name) || !d.initializer) continue;\n let init: Expression = d.initializer;\n while (is.isParenthesizedExpression(init)) init = init.expression;\n if (!is.isArrowFunction(init) && !is.isFunctionExpression(init)) continue;\n declare(d.name.text, init, st);\n if (isExported(st)) exports.set(d.name.text, d.name.text);\n }\n continue;\n }\n // `export { a, b as c }`; with `from`, a re-export of another module's names (not this module's).\n if (is.isExportDeclaration(st) && !st.moduleSpecifier && !st.isTypeOnly && st.exportClause) {\n if (!is.isNamedExports(st.exportClause)) continue;\n for (const e of st.exportClause.elements) {\n if (e.isTypeOnly) continue;\n const local = e.propertyName ?? e.name;\n if (is.isIdentifier(local) && is.isIdentifier(e.name)) exports.set(e.name.text, local.text);\n }\n }\n }\n return { declarations, exports, errors };\n}\n\n// ---------------------------------------------------------------------------\n// The spec file.\n\ninterface Imported {\n readonly from: string;\n /** The exported name imported; `*` for a namespace import. */\n readonly name: string;\n readonly declaration: ImportDeclaration;\n}\n\n/** `import { a, b as c } from \"x\"`, `import * as ns from \"x\"`, `import d from \"x\"`; type-only imports skipped. */\nfunction imports(sf: SourceFile): Map<string, Imported> {\n const out = new Map<string, Imported>();\n for (const st of sf.statements) {\n if (!is.isImportDeclaration(st) || !st.importClause) continue;\n const clause = st.importClause;\n if (clause.phaseModifier === SyntaxKind.TypeKeyword) continue;\n if (!is.isStringLiteral(st.moduleSpecifier)) continue;\n const from = st.moduleSpecifier.text;\n if (clause.name) out.set(clause.name.text, { from, name: \"default\", declaration: st });\n const bindings = clause.namedBindings;\n if (!bindings) continue;\n if (is.isNamespaceImport(bindings))\n out.set(bindings.name.text, { from, name: \"*\", declaration: st });\n else\n for (const e of bindings.elements) {\n if (e.isTypeOnly) continue;\n const imported = e.propertyName ?? e.name;\n const name = is.isIdentifier(imported) ? imported.text : imported.text;\n out.set(e.name.text, { from, name, declaration: st });\n }\n }\n return out;\n}\n\n/** `1`, `-1`, `1_000`, `1.5`, `10n` as an endpoint value; undefined otherwise. */\nfunction numberText(sf: SourceFile, node: Expression): string | undefined {\n if (is.isNumericLiteral(node) || is.isBigIntLiteral(node))\n return textOf(sf, node).replace(/_/g, \"\");\n if (\n is.isPrefixUnaryExpression(node) &&\n node.operator === SyntaxKind.MinusToken &&\n (is.isNumericLiteral(node.operand) || is.isBigIntLiteral(node.operand))\n )\n return `-${textOf(sf, node.operand).replace(/_/g, \"\")}`;\n return undefined;\n}\n\n/** The top-level conjuncts of an expression, parentheses stripped. */\nfunction conjuncts(node: Expression, out: Expression[] = []): Expression[] {\n let e = node;\n while (is.isParenthesizedExpression(e)) e = e.expression;\n if (is.isBinaryExpression(e) && e.operatorToken.kind === SyntaxKind.AmpersandAmpersandToken) {\n conjuncts(e.left, out);\n conjuncts(e.right, out);\n } else out.push(e);\n return out;\n}\n\nconst comparisons: Partial<Record<SyntaxKind, string>> = {\n [SyntaxKind.LessThanToken]: \"<\",\n [SyntaxKind.LessThanEqualsToken]: \"<=\",\n [SyntaxKind.GreaterThanToken]: \">\",\n [SyntaxKind.GreaterThanEqualsToken]: \">=\",\n};\n\n/**\n * What an expression says about each of the named parameters on its own:\n * its top-level conjuncts of the forms `Number.isInteger(x)`, `x < n`,\n * `n <= x` (and the other comparisons) and `/re/.test(x)`, by parameter\n * index.\n */\nfunction hintsIn(\n sf: SourceFile,\n body: Expression,\n params: readonly (string | null)[],\n): Map<number, Hint> {\n const out = new Map<number, Hint>();\n const position = new Map<string, number>();\n params.forEach((p, i) => {\n if (p !== null) position.set(p, i);\n });\n const merge = (i: number, h: Hint) => {\n const old = out.get(i) ?? {};\n out.set(i, { ...old, ...h });\n };\n for (const conjunct of conjuncts(body)) {\n if (is.isCallExpression(conjunct)) {\n const callee = conjunct.expression;\n const [arg, extra] = conjunct.arguments;\n if (!is.isPropertyAccessExpression(callee) || !is.isIdentifier(callee.name) || !arg || extra)\n continue;\n if (!is.isIdentifier(arg)) continue;\n const at = position.get(arg.text);\n if (at === undefined) continue;\n // Number.isInteger(x)\n if (\n is.isIdentifier(callee.expression) &&\n callee.expression.text === \"Number\" &&\n callee.name.text === \"isInteger\"\n )\n merge(at, { integer: true });\n // /re/.test(x)\n else if (is.isRegularExpressionLiteral(callee.expression) && callee.name.text === \"test\") {\n const m = /^\\/([\\s\\S]*)\\/([a-z]*)$/.exec(textOf(sf, callee.expression));\n if (m) merge(at, { regex: { pattern: m[1] as string, flags: m[2] as string } });\n }\n continue;\n }\n // x op n, n op x\n if (!is.isBinaryExpression(conjunct)) continue;\n const op = comparisons[conjunct.operatorToken.kind];\n if (op === undefined) continue;\n const bound = (variable: Expression, literal: Expression, variableOnLeft: boolean) => {\n if (!is.isIdentifier(variable)) return;\n const value = numberText(sf, literal);\n if (value === undefined) return;\n const at = position.get(variable.text);\n if (at === undefined) return;\n // `x < n` bounds x above; `n < x` bounds it below.\n const above = variableOnLeft ? op.startsWith(\"<\") : op.startsWith(\">\");\n const endpoint: Endpoint = { value, inclusive: op.endsWith(\"=\") };\n merge(at, above ? { upper: endpoint } : { lower: endpoint });\n };\n if (is.isIdentifier(conjunct.left)) bound(conjunct.left, conjunct.right, true);\n else if (is.isIdentifier(conjunct.right)) bound(conjunct.right, conjunct.left, false);\n }\n return out;\n}\n\n/**\n * What the precondition says about each of its parameters on its own,\n * read from the arrow's text: see `hintsIn`. A block body gives none.\n */\nexport function hintsOf(arrow: Arrow): Map<number, Hint> {\n if (arrow.block) return new Map();\n return withSourceFile(`(${arrow.body}\\n)`, (sf) => {\n const [first, second] = sf.statements;\n if (second || !first || !is.isExpressionStatement(first)) return new Map();\n let e = first.expression;\n while (is.isParenthesizedExpression(e)) e = e.expression;\n return hintsIn(sf, e, arrow.params);\n });\n}\n\ninterface SpecExport {\n readonly name: string;\n readonly kind: \"forall\" | \"total\";\n readonly fn: string;\n readonly sample?: Arrow;\n readonly when?: Arrow;\n readonly ensures?: Arrow;\n readonly text: string;\n readonly line: number;\n /** The hints the sample and the precondition give, combined per binder index. */\n readonly hints: ReadonlyMap<number, Hint>;\n}\n\nclass SpecFail extends Error {\n readonly line: number;\n constructor(message: string, line: number) {\n super(message);\n this.line = line;\n }\n}\n\n/** The module's exports the spec file imports by name, as `local` to exported `name`. */\ninterface ModuleImport {\n readonly local: string;\n readonly name: string;\n}\n\n/** Read the spec file's exports. */\nfunction readSpecSide(\n sf: SourceFile,\n { program, checker, standardGlobal }: Opened,\n modulePath: string,\n moduleKey: string,\n specSpecifiers: ReadonlySet<string>,\n): { specs: SpecExport[]; errors: SpecError[]; imports: ModuleImport[] } {\n const errors: SpecError[] = [];\n const bound = imports(sf);\n const specs: SpecExport[] = [];\n function fail(message: string, at: Node): never {\n throw new SpecFail(message, lineAt(sf, at));\n }\n // Whether an import's specifier resolves to the module beside the spec file.\n const resolvesToModule = new Map<string, boolean>();\n const fromModule = (imp: Imported): boolean => {\n const known = resolvesToModule.get(imp.from);\n if (known !== undefined) return known;\n const resolved = program.getResolvedModuleFromModuleSpecifier(\n imp.declaration.moduleSpecifier as Parameters<\n Program[\"getResolvedModuleFromModuleSpecifier\"]\n >[0],\n sf.fileName,\n );\n const target = resolved ? program.getSourceFile(resolved.resolvedFileName) : undefined;\n const is = target !== undefined && target.path === moduleKey;\n resolvesToModule.set(imp.from, is);\n return is;\n };\n /** The combinator a callee names (`forall`, `ns.forall`), or undefined. */\n const combinator = (callee: Expression): \"forall\" | \"total\" | undefined => {\n if (is.isPropertyAccessExpression(callee)) {\n if (!is.isIdentifier(callee.expression) || !is.isIdentifier(callee.name)) return undefined;\n const ns = bound.get(callee.expression.text);\n const member = callee.name.text;\n if (\n ns?.name === \"*\" &&\n specSpecifiers.has(ns.from) &&\n (member === \"forall\" || member === \"total\")\n )\n return member;\n return undefined;\n }\n if (!is.isIdentifier(callee)) return undefined;\n const imp = bound.get(callee.text);\n if (imp && specSpecifiers.has(imp.from) && (imp.name === \"forall\" || imp.name === \"total\"))\n return imp.name;\n return undefined;\n };\n /** The module function a first argument names, or why not. */\n const functionArg = (arg: Expression | undefined, call: Node): string => {\n if (!arg)\n return fail(\"the first argument must name a function of the module, found the end\", call);\n if (\n is.isPropertyAccessExpression(arg) &&\n is.isIdentifier(arg.expression) &&\n is.isIdentifier(arg.name)\n ) {\n const ns = bound.get(arg.expression.text);\n if (ns?.name === \"*\" && fromModule(ns)) return arg.name.text;\n return fail(`${textOf(sf, arg)} is not a function imported from the module`, arg);\n }\n if (!is.isIdentifier(arg))\n return fail(\n `the first argument must name a function of the module, found ${textOf(sf, arg)}`,\n arg,\n );\n const imp = bound.get(arg.text);\n if (!imp)\n return fail(\n `${arg.text} is not imported from the module (import it from ./${modulePath.split(\"/\").pop()})`,\n arg,\n );\n if (!fromModule(imp))\n return fail(\n `${arg.text} is imported from ${JSON.stringify(imp.from)}, not from the module beside this spec file`,\n arg,\n );\n if (imp.name === \"*\" || imp.name === \"default\")\n return fail(`${arg.text} must be a named import of the module's function`, arg);\n return imp.name;\n };\n /**\n * A claim is read from its arrow's text alone, where `Math` and `Number`\n * are the globals unless the arrow binds them itself: an arrow naming\n * one that resolves to anything else here (a binding of the spec file,\n * an import, a const of the arrow's own block declared after the use)\n * is refused, so a claim is never read as something it does not\n * compute. A parameter or const of the arrow bound before the use is\n * the arrow reader's own name for it (a parameter named `Math` reads as\n * that parameter), and a binding the claims do not name, or a type-only\n * import, is fine.\n */\n const builtins = (arrow: ArrowFunction, node: Node, what: string): void => {\n if (\n is.isPropertyAccessExpression(node) &&\n is.isIdentifier(node.expression) &&\n (node.expression.text === \"Math\" || node.expression.text === \"Number\") &&\n !standardGlobal(node.expression)\n ) {\n const id = node.expression;\n const bound = checker.getSymbolAtLocation(id)?.declarations[0]?.resolve();\n const own =\n bound !== undefined &&\n bound.getSourceFile() === sf &&\n bound.pos >= arrow.pos &&\n bound.end <= arrow.end &&\n bound.getStart(sf) < id.getStart(sf);\n if (!own) {\n const file = bound?.getSourceFile();\n const where =\n bound && file\n ? ` (bound at line ${lineAt(file, bound)}${file === sf ? \"\" : ` of ${file.fileName}`})`\n : \"\";\n fail(\n `${what} names ${id.text}, which is not the global ${id.text} here${where}; rename the binding`,\n id,\n );\n }\n }\n node.forEachChild((child) => builtins(arrow, child, what));\n };\n /** An arrow function: its params, body text and whether the body is a block. */\n const arrow = (node: Expression, what: string): { arrow: Arrow; node: ArrowFunction } => {\n if (!is.isArrowFunction(node))\n return fail(\n `${what} must be an arrow function, found ${textOf(sf, node).split(/\\s/)[0] ?? \"\"}`,\n node,\n );\n if (isAsync(node)) fail(`${what} is an async arrow; it must be synchronous`, node);\n builtins(node, node.body, what);\n // A rest or destructured parameter has no name of its own: the binder keeps the function's.\n const params = node.parameters.map((p) =>\n !p.dotDotDotToken && is.isIdentifier(p.name) ? p.name.text : null,\n );\n const body = node.body;\n const line = lineAt(sf, node);\n if (is.isBlock(body))\n return {\n arrow: {\n params,\n body: sf.text.slice(body.getStart(sf) + 1, body.end - 1),\n block: true,\n line,\n },\n node,\n };\n return { arrow: { params, body: textOf(sf, body), block: false, line }, node };\n };\n for (const st of sf.statements) {\n if (!is.isVariableStatement(st)) continue;\n const exported = isExported(st);\n const constant = isConst(st.declarationList);\n for (const d of st.declarationList.declarations) {\n if (!is.isIdentifier(d.name) || !d.initializer) continue;\n const name = d.name.text;\n // `satisfies`, `as`, `!` and parentheses change nothing at runtime: the call is inside them.\n let init: Expression = d.initializer;\n while (\n is.isParenthesizedExpression(init) ||\n is.isSatisfiesExpression(init) ||\n is.isAsExpression(init) ||\n is.isNonNullExpression(init)\n )\n init = init.expression;\n if (!is.isCallExpression(init)) continue;\n const kind = combinator(init.expression);\n if (!kind) continue;\n const line = lineAt(sf, st);\n try {\n if (!exported) fail(`${name} is a spec but not exported, so nothing would check it`, st);\n if (!constant)\n fail(\n `a spec must be a const export, not ${textOf(sf, st).split(/\\s/)[exported ? 1 : 0] ?? \"let\"}`,\n st,\n );\n const [first, second, third] = init.arguments;\n const fn = functionArg(first, init);\n if (kind === \"total\") {\n if (second) fail(\"total takes the function alone\", second);\n specs.push({ name, kind: \"total\", fn, text: `total(${fn})`, line, hints: new Map() });\n continue;\n }\n if (!second) return fail(\"forall takes the function, then { when, ensures }\", init);\n if (third) return fail(`unexpected ${textOf(sf, third)} after forall's arguments`, third);\n if (!is.isObjectLiteralExpression(second))\n return fail(\n \"forall's second argument must be an object literal { when, ensures }\",\n second,\n );\n let sample: { arrow: Arrow; node: ArrowFunction } | undefined;\n let when: { arrow: Arrow; node: ArrowFunction } | undefined;\n let ensures: { arrow: Arrow; node: ArrowFunction } | undefined;\n for (const prop of second.properties) {\n const key =\n is.isPropertyAssignment(prop) ||\n is.isShorthandPropertyAssignment(prop) ||\n is.isMethodDeclaration(prop)\n ? prop.name\n : undefined;\n const keyName =\n key && is.isIdentifier(key) ? key.text : key ? textOf(sf, key) : textOf(sf, prop);\n if (keyName !== \"sample\" && keyName !== \"when\" && keyName !== \"ensures\")\n fail(`forall's properties are sample, when and ensures, found ${keyName}`, prop);\n if (!is.isPropertyAssignment(prop))\n fail(`${keyName} must be written as ${keyName}: (…) => …`, prop);\n const read = arrow(prop.initializer, keyName);\n if (keyName === \"sample\") {\n if (sample) fail(\"sample is given twice\", prop);\n sample = read;\n } else if (keyName === \"when\") {\n if (when) fail(\"when is given twice\", prop);\n when = read;\n } else {\n if (ensures) fail(\"ensures is given twice\", prop);\n ensures = read;\n }\n }\n if (!ensures) return fail(\"forall needs an ensures\", second);\n // The precondition and the sample both steer the draws, combined per binder.\n const hintsOfArrow = (\n a: { arrow: Arrow; node: ArrowFunction } | undefined,\n ): Map<number, Hint> =>\n a && !is.isBlock(a.node.body) ? hintsIn(sf, a.node.body, a.arrow.params) : new Map();\n const fromSample = hintsOfArrow(sample);\n const fromWhen = hintsOfArrow(when);\n const hints = new Map<number, Hint>();\n for (const i of new Set([...fromSample.keys(), ...fromWhen.keys()])) {\n const h = combineHints(fromWhen.get(i), fromSample.get(i));\n if (h) hints.set(i, h);\n }\n specs.push({\n name,\n kind: \"forall\",\n fn,\n ...(sample ? { sample: sample.arrow } : {}),\n ...(when ? { when: when.arrow } : {}),\n ensures: ensures.arrow,\n text: ensures.arrow.body.replace(/\\s+/g, \" \").trim(),\n line,\n hints,\n });\n } catch (err) {\n if (!(err instanceof SpecFail)) throw err;\n errors.push({ line: err.line, message: `${name}: ${err.message}` });\n }\n }\n }\n const moduleImports: ModuleImport[] = [...bound]\n .filter(([, imp]) => imp.name !== \"*\" && imp.name !== \"default\" && fromModule(imp))\n .map(([local, imp]) => ({ local, name: imp.name }));\n return { specs, errors, imports: moduleImports };\n}\n\n/** The tighter of two endpoints on one side; the first when they cannot be compared. */\nfunction tighter(\n first: Endpoint | undefined,\n second: Endpoint | undefined,\n side: \"lower\" | \"upper\",\n): Endpoint | undefined {\n if (!first) return second;\n if (!second) return first;\n // Integral literals compare exactly (bigints reach past every double); others as doubles.\n const integral = (e: Endpoint) => !/[.eE]/.test(e.value);\n let order: number;\n try {\n if (integral(first) && integral(second)) {\n const a = endpointBigInt(first.value);\n const b = endpointBigInt(second.value);\n order = a === b ? 0 : a > b ? 1 : -1;\n } else {\n const a = endpointNumber(first.value);\n const b = endpointNumber(second.value);\n if (Number.isNaN(a) || Number.isNaN(b)) return first;\n order = a === b ? 0 : a > b ? 1 : -1;\n }\n } catch {\n return first;\n }\n if (order !== 0) return (side === \"lower\" ? order > 0 : order < 0) ? first : second;\n return first.inclusive ? second : first;\n}\n\n/**\n * Two hints on one binder as one: integer when either says so, the\n * tighter bound on each side, the first's regex (two cannot be combined,\n * and the draws are checked against both arrows anyway).\n */\nfunction combineHints(first: Hint | undefined, second: Hint | undefined): Hint | undefined {\n if (!first) return second;\n if (!second) return first;\n const lower = tighter(first.lower, second.lower, \"lower\");\n const upper = tighter(first.upper, second.upper, \"upper\");\n const regex = first.regex ?? second.regex;\n return {\n ...(first.integer || second.integer ? { integer: true as const } : {}),\n ...(lower ? { lower } : {}),\n ...(upper ? { upper } : {}),\n ...(regex ? { regex } : {}),\n };\n}\n\n/** Read a module and its spec file. */\nexport function readSpecs(input: ReadSpecsInput): ModuleSpecs {\n const modulePath = input.modulePath;\n const specPath = input.specPath ?? modulePath.replace(/\\.ts$/, \".props.ts\");\n return withProgram(\n [\n { path: modulePath, text: input.module },\n { path: specPath, text: input.spec },\n ],\n (opened) => {\n const { checker, file, parseError } = opened;\n const moduleError = parseError(modulePath);\n const specError = parseError(specPath);\n const errors: SpecError[] = [];\n if (moduleError)\n errors.push({\n line: moduleError.line,\n message: `the module could not be parsed: ${moduleError.message}`,\n inModule: true,\n });\n if (specError)\n errors.push({\n line: specError.line,\n message: `the spec file could not be parsed: ${specError.message}`,\n });\n if (moduleError || specError) return { functions: [], errors };\n const moduleFile = file(modulePath);\n const moduleSide = readModuleSide(moduleFile, checker);\n const specSide = readSpecSide(\n file(specPath),\n opened,\n modulePath,\n moduleFile.path,\n new Set(input.specSpecifiers ?? [\"eutaxy/spec\", \"@eutaxy/spec\"]),\n );\n errors.push(...moduleSide.errors, ...specSide.errors);\n // The spec file runs whenever it is imported (the TESTED rung imports it): an assignment to a\n // built-in there makes the claims compute something other than what they are read as.\n const patched = rebound(file(specPath), checker, opened.standardGlobal);\n if (patched)\n errors.push({\n line: patched.line,\n message: `the spec file assigns to ${patched.target}, so the built-ins its claims are read with may not be the standard ones`,\n });\n // The claims' free names: the spec file's local names for the module's declarations.\n const imports = specSide.imports.flatMap((i) => {\n const fn = moduleSide.exports.get(i.name);\n return fn === undefined ? [] : [{ local: i.local, fn }];\n });\n const byFunction = new Map<string, { decl: Declaration; properties: Property[] }>();\n for (const s of specSide.specs) {\n const local = moduleSide.exports.get(s.fn);\n const decl = local === undefined ? undefined : moduleSide.declarations.get(local);\n if (!decl) {\n errors.push({\n line: s.line,\n message: `${s.name}: the module exports no function ${s.fn} whose parameters the reader can read (a function declaration or a const arrow)`,\n });\n continue;\n }\n const entry = byFunction.get(s.fn) ?? { decl, properties: [] };\n if (entry.properties.some((p) => p.name === s.name)) {\n errors.push({ line: s.line, message: `${s.name} is exported twice` });\n continue;\n }\n const binders: Binder[] = decl.params.map((p, i) => {\n const fromEnsures = s.ensures?.params[i];\n const name = fromEnsures ?? p.name ?? `arg${i}`;\n const hint = s.hints.get(i);\n return { name, type: p.type, ...(hint ? { hint } : {}) };\n });\n entry.properties.push({\n name: s.name,\n kind: s.kind,\n binders,\n ...(s.sample ? { sample: s.sample } : {}),\n ...(s.when ? { when: s.when } : {}),\n ...(s.ensures ? { ensures: s.ensures } : {}),\n imports,\n text: s.text,\n line: s.line,\n });\n byFunction.set(s.fn, entry);\n }\n const functions: FunctionSpec[] = [...byFunction.entries()].map(\n ([name, { decl, properties }]) => ({\n name,\n params: decl.params,\n properties,\n line: decl.line,\n offset: decl.offset,\n }),\n );\n return { functions, errors };\n },\n );\n}\n","/**\n * Lean 4 for a module in the subset and the properties on it. The\n * module's record types become structures, its functions definitions over\n * `Int`, `Bool` and `String`, each property a theorem whose statement is\n * the claim over its binders, with the precondition as a hypothesis.\n * Booleans stay `Bool` in terms, as in TypeScript, and become propositions\n * with `= true` where a statement needs one; comparisons are `decide`d.\n * Every theorem is closed by one tactic script, except where a proof is\n * supplied beside the spec file (`supplied.ts`): then the statement is\n * fixed as a definition first, and the supplied tactics must prove it.\n */\n\nimport {\n children,\n type Expr,\n hasLoneSurrogate,\n OutsideSubset,\n type RecordType,\n readArrowBody,\n renameVars,\n type SubsetFunction,\n type SubsetModule,\n type SubsetType,\n type TypeContext,\n typeOf,\n} from \"@eutaxy/prover/reader\";\nimport { type Arrow, describeType, type Property, type SpecType } from \"@eutaxy/spec\";\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 // Guillemets hold anything but guillemets: those are escaped as `%ab` and `%bb`, with `%` itself\n // as `%25` first, in every name, so two names never meet in one identifier.\n const escaped = name.replace(/%/g, \"%25\").replace(/«/g, \"%ab\").replace(/»/g, \"%bb\");\n return /^[A-Za-z_][A-Za-z0-9_]*$/.test(escaped) ? escaped : `«${escaped}»`;\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 case \"list\":\n return `(List ${leanType(t.element)})`;\n case \"nothing\":\n return fail(\"the element type of an empty array, which nothing gives\");\n case \"nullable\":\n case \"union\":\n case \"null\":\n return fail(`a ${t.kind} type, which the Lean engine does not take yet`);\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 * In the non-empty branch of a structurally recursive function: the list\n * parameter is `head :: tail` there, so `xs[0] ?? d` is the head,\n * `xs.slice(1)` the tail (what the recursive call must be given for Lean\n * to see the recursion is structural), and `xs` itself `head :: tail`.\n */\n readonly cons?: { readonly list: string; readonly head: string; readonly tail: string };\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\nexport const divisionOutside =\n \"division other than Math.floor(x / c) with c a positive integer constant: this engine models numbers as integers, which / leaves (the SMT engine takes it)\";\n\n/** Whether an expression divides other than as Math.floor(x / c), c a positive integer constant. */\nexport function dividesOutside(e: Expr): boolean {\n if (e.kind === \"floor\" && e.operand.kind === \"binary\" && e.operand.op === \"/\") {\n const c = integerValue(e.operand.right);\n if (c !== undefined && c > 0n) return dividesOutside(e.operand.left);\n }\n if (e.kind === \"binary\" && e.op === \"/\") return true;\n return children(e).some(dividesOutside);\n}\n\n/** The value of an integer expression built from literals by + - * and negation, if it is one. */\nfunction integerValue(e: Expr): bigint | undefined {\n if (e.kind === \"int\") return BigInt(e.value);\n if (e.kind === \"neg\") {\n const v = integerValue(e.operand);\n return v === undefined ? undefined : -v;\n }\n if (e.kind !== \"binary\") return undefined;\n const l = integerValue(e.left);\n const r = integerValue(e.right);\n if (l === undefined || r === undefined) return undefined;\n if (e.op === \"+\") return l + r;\n if (e.op === \"-\") return l - r;\n if (e.op === \"*\") return l * r;\n return undefined;\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`, `String` 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 if (env.cons?.list === e.name) return `(${env.cons.head} :: ${env.cons.tail})`;\n return ident.variable(e.name);\n case \"null\":\n case \"narrow\":\n return fail(\"null, which the Lean engine does not take yet\");\n case \"narrowTag\":\n return fail(\"a union, which the Lean engine does not take yet\");\n case \"neg\":\n return `(-${t(e.operand)})`;\n case \"not\":\n return `(!${t(e.operand)})`;\n case \"isInteger\":\n // Every number is an integer in this engine's model. The operand is still emitted, so what\n // this engine refuses in it (a division) is refused here too, not dropped with it.\n typeOf(e.operand, scope, env.ctx, fail);\n t(e.operand);\n return \"true\";\n case \"floor\": {\n // Of an integer, Math.floor is the integer; of x / c, with c a positive integer constant, it is\n // Lean's Int division, which rounds toward negative infinity as Math.floor does.\n const o = e.operand;\n if (o.kind !== \"binary\" || o.op !== \"/\") return t(o);\n const c = integerValue(o.right);\n if (c === undefined || c <= 0n) fail(divisionOutside);\n return `(${t(o.left)} / (${c} : Int))`;\n }\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 return fail(divisionOutside);\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 // A list's length is a natural number in Lean; the subset counts in Int.\n if (typeOf(e.object, scope, env.ctx, fail).kind === \"list\")\n return `(Int.ofNat (List.length ${t(e.object)}))`;\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 const bound = e.type ?? typeOf(e.value, scope, env.ctx, fail);\n inner.set(e.name, bound);\n // The annotation, when there is one, types the binding in Lean too (`const xs: number[] = []`).\n const annotated = e.type ? ` : ${leanType(e.type)}` : \"\";\n return `(let ${ident.variable(e.name)}${annotated} := ${t(e.value)}; ${term(e.body, inner, env)})`;\n }\n case \"list\": {\n if (e.items.length === 0 && !e.rest) return \"[]\";\n if (!e.rest) return `[${e.items.map(t).join(\", \")}]`;\n return `(${[...e.items.map(t), t(e.rest)].join(\" :: \")})`;\n }\n case \"tail\":\n if (e.list.kind === \"var\" && env.cons?.list === e.list.name) return env.cons.tail;\n return `(List.tail ${t(e.list)})`;\n case \"headOr\":\n if (e.list.kind === \"var\" && env.cons?.list === e.list.name) return env.cons.head;\n return `(List.headD ${t(e.list)} ${t(e.fallback)})`;\n case \"iterate\": {\n const listType = typeOf(e.list, scope, env.ctx, fail);\n if (listType.kind !== \"list\") fail(`${e.op} on a ${listType.kind}`);\n const inner = new Map(scope);\n inner.set(e.item, listType.element);\n if (e.index !== undefined) inner.set(e.index, { kind: \"int\" });\n const body = term(e.body, inner, env);\n // The index counts from 0 as a natural number; the subset's is an Int.\n const nat = e.index === undefined ? \"\" : quote(`nv_${e.index}`);\n const fn =\n e.index === undefined\n ? `(fun ${ident.variable(e.item)} => ${body})`\n : `(fun (${ident.variable(e.item)}, ${nat}) => let ${ident.variable(e.index)} := Int.ofNat ${nat}; ${body})`;\n const list = e.index === undefined ? t(e.list) : `(List.zipIdx ${t(e.list)})`;\n // map and flatMap take the function first; all and any take the list first.\n if (e.op === \"map\") return `(List.map ${fn} ${list})`;\n if (e.op === \"flatMap\") return `(List.flatMap ${fn} ${list})`;\n return `(${e.op === \"every\" ? \"List.all\" : \"List.any\"} ${list} ${fn})`;\n }\n case \"fold\": {\n const listType = typeOf(e.list, scope, env.ctx, fail);\n if (listType.kind !== \"list\") fail(`reduce on a ${listType.kind}`);\n const inner = new Map(scope);\n inner.set(e.acc, typeOf(e, scope, env.ctx, fail));\n inner.set(e.item, listType.element);\n return `(List.foldl (fun ${ident.variable(e.acc)} ${ident.variable(e.item)} => ${term(e.body, inner, env)}) ${t(e.init)} ${t(e.list)})`;\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 const head = `def ${ident.fn(f.name)} ${params} : ${leanType(f.returns)} :=`;\n if (f.structural === undefined || f.body.kind !== \"cond\")\n return `${head}\\n ${term(f.body, scope, e)}`;\n // Structural recursion: a match on the list the body tests against 0, recursing on its tail.\n // `vh_`/`vt_` names cannot meet a variable, whose names all start `v_`.\n const list = (f.params[f.structural] as { name: string }).name;\n const cons = { list, head: quote(`vh_${list}`), tail: quote(`vt_${list}`) };\n return [\n head,\n ` match ${ident.variable(list)} with`,\n ` | [] => ${term(f.body.ifTrue, scope, e)}`,\n ` | ${cons.head} :: ${cons.tail} => ${term(f.body.ifFalse, scope, { ...e, cons })}`,\n ].join(\"\\n\");\n}\n\n/**\n * The subset type a binder ranges over, or `OutsideSubset`: `number` is\n * `Int` (the engine's integer model, an assumption every PROVEN carries),\n * a union of string literals is `String` (the proof covers every string,\n * more than the type admits), a record is the module's structure of that\n * name. Nullable types, tagged unions, bigint and whatever the reader\n * could not read are outside.\n */\nexport function binderType(name: string, t: SpecType, module: SubsetModule): SubsetType {\n switch (t.kind) {\n case \"number\":\n return { kind: \"int\" };\n case \"boolean\":\n return { kind: \"bool\" };\n case \"string\":\n return { kind: \"string\" };\n case \"literal\":\n if (typeof t.value === \"string\") return { kind: \"string\" };\n if (typeof t.value === \"boolean\") return { kind: \"bool\" };\n return { kind: \"int\" };\n case \"bigint\":\n // A BigInt passed to a function over number throws on the first mixed operation in JavaScript.\n fail(`binder ${name} over bigint: the subset has no bigint`);\n break;\n case \"union\":\n if (t.members.every((m) => m.kind === \"literal\" && typeof m.value === \"string\"))\n return { kind: \"string\" };\n if (t.members.some((m) => m.kind === \"null\" || m.kind === \"undefined\"))\n fail(\n `binder ${name} over ${describeType(t)}: nullable types are not in the engine's subset yet`,\n );\n fail(`binder ${name} over ${describeType(t)}: unions are not in the engine's subset yet`);\n break;\n case \"record\":\n if (t.name !== undefined && module.records.some((r) => r.name === t.name))\n return { kind: \"record\", name: t.name };\n fail(\n `binder ${name} over ${describeType(t)}: ${t.name === undefined ? \"an inline record type\" : `record type ${t.name} is outside the subset`}`,\n );\n break;\n case \"null\":\n case \"undefined\":\n fail(`binder ${name} over ${t.kind}`);\n break;\n case \"array\":\n return { kind: \"list\", element: binderType(name, t.element, module) };\n case \"unknown\":\n fail(`binder ${name} over ${t.text}, which the reader could not read`);\n }\n}\n\n/** An arrow of the spec file as a Bool term over the binders, its own parameter names renamed to theirs. */\nfunction arrowTerm(\n arrow: Arrow,\n what: \"when\" | \"ensures\",\n property: Property,\n types: readonly SubsetType[],\n e: Env,\n): string {\n try {\n return arrowTermAt(arrow, what, property, types, e);\n } catch (err) {\n // What the subset refused, located in the spec file.\n if (!(err instanceof OutsideSubset)) throw err;\n throw new OutsideSubset(`${what} (spec file line ${arrow.line}): ${err.message}`, arrow.line);\n }\n}\n\nfunction arrowTermAt(\n arrow: Arrow,\n what: \"when\" | \"ensures\",\n property: Property,\n types: readonly SubsetType[],\n e: Env,\n): string {\n const binders = property.binders;\n const scope = new Map<string, SubsetType>();\n const names = new Map<string, string>();\n arrow.params.forEach((p, i) => {\n const binder = binders[i];\n const type = types[i];\n if (p === null) fail(`a destructured parameter in ${what}`);\n if (!binder || !type) fail(`${what} takes more parameters than the function has`);\n scope.set(p, type);\n names.set(p, binder.name);\n });\n const aliases = new Map(property.imports.map((i) => [i.local, i.fn]));\n const read = readArrowBody(arrow, scope, e.module, aliases);\n const t = typeOf(read, scope, e.ctx, fail);\n if (t.kind !== \"bool\")\n fail(`${what} is not boolean (a ${t.kind === \"record\" ? t.name : t.kind})`);\n const renamed = renameVars(read, names);\n const binderScope = new Map(binders.map((b, i) => [b.name, types[i] as SubsetType]));\n return term(renamed, binderScope, e);\n}\n\n/** The proposition a property claims: binders universally quantified, the precondition 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 if (property.kind !== \"forall\" || !property.ensures) fail(\"not a forall property\");\n const e = env(module);\n const types = property.binders.map((b) => binderType(b.name, b.type, module));\n const binders = property.binders\n .map((b, i) => `(${ident.variable(b.name)} : ${leanType(types[i] as SubsetType)})`)\n .join(\" \");\n const hyps = property.when\n ? [`(${arrowTerm(property.when, \"when\", property, types, e)} = true)`]\n : [];\n const claim = `(${arrowTerm(property.ensures, \"ensures\", property, types, e)} = true)`;\n const body = [...hyps, claim].join(\" →\\n \");\n return {\n // A function of no parameters has nothing to quantify over: the proposition stands alone.\n text: binders === \"\" ? body : `∀ ${binders},\\n ${body}`,\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(\n (b) =>\n b.type.kind === \"boolean\" ||\n (b.type.kind === \"literal\" && typeof b.type.value === \"boolean\"),\n )\n .map((b) => ident.variable(b.name));\n const introduced = [...names, ...hyps];\n return [\n ...(introduced.length > 0 ? [` intro ${introduced.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 /** Closed by a supplied proof, not the tactic script. */\n readonly supplied?: true;\n /** For a supplied proof: the 1-based line of the `#print axioms` that audits it. */\n readonly axiomsLine?: number;\n /** For a supplied proof: the 1-based line of the `#check` that shows its type, which must be the statement alone. */\n readonly typeLine?: 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 /** 1-based lines of the supplied lemmas in the emitted file, inclusive, when there are any. */\n readonly lemmas?: { readonly from: number; readonly to: number };\n}\n\n/** The supplied proofs to use: lemmas, and each property's tactic proof by name. */\nexport interface SuppliedText {\n readonly lemmas: string;\n readonly proofs: ReadonlyMap<string, string>;\n}\n\n/** A tactic block at the indentation a `by` takes: its common indentation stripped, two spaces put back. */\nfunction indented(block: string): string {\n const lines = block.split(\"\\n\");\n const widths = lines.filter((l) => l.trim() !== \"\").map((l) => /^ */.exec(l)?.[0].length ?? 0);\n const common = widths.length > 0 ? Math.min(...widths) : 0;\n return lines.map((l) => (l.trim() === \"\" ? \"\" : ` ${l.slice(common)}`)).join(\"\\n\");\n}\n\n/**\n * The whole file: structures, definitions, one theorem per property, any\n * extra lines (translation checks), then the properties with supplied\n * proofs: each statement fixed as a definition before any supplied text,\n * the supplied lemmas, each theorem proving its definition with the\n * supplied tactics, and `#print axioms` for each.\n */\nexport function emitModule(\n module: SubsetModule,\n properties: readonly { readonly function: string; readonly property: Property }[],\n extra: readonly string[] = [],\n supplied?: SuppliedText,\n): Emitted {\n const parts: string[] = [\n \"-- Generated by Eutaxy's first-party engine from the module and its spec file; the theorems are its properties.\",\n \"set_option linter.unusedSimpArgs false\",\n \"set_option linter.unusedVariables 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 const later: { fn: string; property: string; name: string; statement: string; proof: string }[] =\n [];\n for (const { function: fn, property } of properties) {\n let body: { text: string; hypotheses: number };\n try {\n body = stated(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 + later.length, fn, property.name);\n const proof = supplied?.proofs.get(property.name);\n if (proof !== undefined) {\n later.push({ fn, property: property.name, name, statement: body.text, proof });\n continue;\n }\n const text = `theorem ${name} :\\n ${body.text} := by\\n${tactics(module, 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 const lineAfter = () => parts.join(\"\\n\\n\").split(\"\\n\").length + 2;\n let lemmas: Emitted[\"lemmas\"];\n if (later.length > 0) {\n for (const l of later) parts.push(`def s_${l.name} : Prop :=\\n ${l.statement}`);\n if (supplied && supplied.lemmas !== \"\") {\n const from = lineAfter();\n parts.push(supplied.lemmas);\n lemmas = { from, to: from + supplied.lemmas.split(\"\\n\").length - 1 };\n }\n const ownProofs: EmittedTheorem[] = [];\n for (const l of later) {\n const text = `theorem ${l.name} : s_${l.name} := by\\n unfold s_${l.name}\\n${indented(l.proof)}`;\n const from = lineAfter();\n parts.push(text);\n ownProofs.push({\n function: l.fn,\n property: l.property,\n name: l.name,\n from,\n to: from + text.split(\"\\n\").length - 1,\n supplied: true,\n });\n }\n // Each audit's line is recorded: only Lean's message at that line counts as the audit.\n for (const t of ownProofs) {\n // Its type, as Lean has it: a hypothesis the supplied text slipped in (a section variable) shows here.\n const typeLine = lineAfter();\n parts.push(`#check @${t.name}`);\n const axiomsLine = lineAfter();\n parts.push(`#print axioms ${t.name}`);\n theorems.push({ ...t, axiomsLine, typeLine });\n }\n }\n return { source: `${parts.join(\"\\n\\n\")}\\n`, theorems, skipped, ...(lemmas ? { lemmas } : {}) };\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 case \"list\":\n if (!Array.isArray(v)) fail(`${String(v)} is not an array`);\n return `([${v.map((x) => value(x, t.element, module)).join(\", \")}] : ${leanType(t)})`;\n case \"nothing\":\n return fail(\"a value of no type\");\n case \"nullable\":\n case \"union\":\n case \"null\":\n return fail(`a ${t.kind} type, which the Lean engine does not take yet`);\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/**\n * The Lean release the engine's contract corpus is checked against. On a\n * bump: run the corpus and the supplied-proof tests on the new release,\n * and read its release notes for a new command that runs code while a\n * file is checked (a `#` command is already refused; a new word goes into\n * `supplied.ts`'s refused list in the same change). CI caches the\n * toolchain by this file's hash.\n */\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. */\n/**\n * Lean's messages from `--json` output: one object per line, each with\n * its position. Lines that are not such an object (whatever a program\n * writes to the terminal) are not messages and are skipped, so nothing in\n * the checked file can pose as a message at a position it is not at.\n */\nexport function jsonDiagnostics(output: string): LeanDiagnostic[] {\n const out: LeanDiagnostic[] = [];\n for (const raw of output.split(\"\\n\")) {\n if (!raw.startsWith(\"{\")) continue;\n let m: { pos?: { line?: unknown; column?: unknown }; severity?: unknown; data?: unknown };\n try {\n m = JSON.parse(raw) as typeof m;\n } catch {\n continue;\n }\n const severity =\n m.severity === \"error\"\n ? \"error\"\n : m.severity === \"warning\"\n ? \"warning\"\n : m.severity === \"information\"\n ? \"info\"\n : undefined;\n if (severity === undefined || typeof m.pos?.line !== \"number\" || typeof m.data !== \"string\")\n continue;\n out.push({\n line: m.pos.line,\n column: typeof m.pos.column === \"number\" ? m.pos.column : 0,\n severity,\n message: m.data.trimEnd(),\n });\n }\n return out;\n}\n\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, \"--json\", \"Eutaxy.lean\"], {\n cwd: dir,\n timeoutMs: options.timeoutMs ?? 120_000,\n });\n return { run: result, diagnostics: jsonDiagnostics(`${result.stdout}\\n${result.stderr}`) };\n } finally {\n if (!options.keep) rmSync(dir, { recursive: true, force: true });\n }\n}\n","/**\n * Proofs supplied beside a spec file, for claims the engine's tactic\n * script does not close: `domain.props.lean` beside `domain.props.ts`.\n * Lemmas come first; then each `-- proof: <property>` line opens the\n * tactic proof of that property's statement, which Eutaxy emits and the\n * proof cannot change (it is fixed as a definition before any supplied\n * text). Lean's kernel checks the proof, and Eutaxy accepts it only when\n * it rests on Lean's standard axioms; what could switch checking off, add\n * an axiom or change how the statement reads is refused outright.\n */\n\nexport interface SuppliedProofs {\n /** The proof file's name, for verdicts. */\n readonly file: string;\n /** Everything before the first `-- proof:` line: lemmas the proofs use. */\n readonly lemmas: string;\n /** Each property's tactic proof, by property name (the names also when the file is refused). */\n readonly proofs: ReadonlyMap<string, string>;\n /** Why the file is refused, when it is; then none of its proofs is used, and its properties say why. */\n readonly refused?: string;\n}\n\n/** The axioms a supplied proof may rest on: Lean's standard ones. */\nexport const standardAxioms: ReadonlySet<string> = new Set([\n \"propext\",\n \"Classical.choice\",\n \"Quot.sound\",\n]);\n\n/**\n * Words a supplied proof may not use, anywhere in the file, comments and\n * strings included: what adds axioms or trusted code (`axiom`, `sorry`,\n * `unsafe`, `implemented_by`, `extern`, `opaque`, `native_decide`),\n * switches checks off (`set_option`), registers code Lean would run while\n * the file is checked (`attribute`, `initialize`, `simproc` and the like)\n * or changes how text reads (`macro`, `syntax`, `notation` and the like),\n * and `import`. The list narrows when a legitimate proof is refused and\n * grows only with a Lean bump that adds such a command (see\n * `leanToolchain`); never because of what a hostile file could do, which\n * the design answers.\n */\nconst refusedWords = [\n \"sorry\",\n \"admit\",\n \"axiom\",\n \"unsafe\",\n \"implemented_by\",\n \"extern\",\n \"opaque\",\n \"native_decide\",\n \"set_option\",\n \"macro\",\n \"macro_rules\",\n \"syntax\",\n \"notation\",\n \"infix\",\n \"infixl\",\n \"infixr\",\n \"prefix\",\n \"postfix\",\n \"elab\",\n \"elab_rules\",\n \"import\",\n \"attribute\",\n \"initialize\",\n \"simproc\",\n \"dsimproc\",\n \"simproc_decl\",\n \"dsimproc_decl\",\n // Section variables become hypotheses of the theorems after them: `variable (h : False)` would.\n \"section\",\n \"namespace\",\n \"variable\",\n \"include\",\n \"omit\",\n \"universe\",\n];\n\n/** Command families refused by how a word starts: `run_cmd`, `builtin_initialize`, `register_option`, `declare_syntax_cat`. */\nconst refusedStarts = [\"run_\", \"builtin_\", \"register_\", \"declare_\"];\n\n/**\n * Refused wherever they appear, inside a name too: every command run\n * while the file is checked starts with `#`, and every attribute (which\n * can hand Lean a tactic, an elaborator or a simplification procedure to\n * run) with `@[`.\n */\nconst refusedAnywhere = [\"#\", \"@[\"];\n\n/** Lean's ASCII identifier characters after the first. */\nconst identRest = /[A-Za-z0-9_'!?]/u;\n\n/**\n * Whether the text just before `at` continues a name, so that a word\n * starting there is part of that name rather than a token of its own.\n * Only a run of identifier characters that starts with an ASCII letter or\n * `_` counts: one that starts with a digit is a numeral, and Lean starts a\n * new token right after a numeral (`0xfsorry` is `0xf`, then `sorry`).\n * Anything else (`.`, `«`, Unicode) counts as a boundary, which refuses\n * more, never less.\n */\nfunction continuesName(text: string, at: number): boolean {\n let i = at;\n while (i > 0 && identRest.test(text[i - 1] as string)) i--;\n return i < at && /[A-Za-z_]/u.test(text[i] as string);\n}\n\n/** The first refused word or command the text holds, as a token of its own, or undefined. */\nexport function refusedIn(text: string): string | undefined {\n const anywhere = refusedAnywhere.find((w) => text.includes(w));\n if (anywhere !== undefined) return anywhere;\n for (const [words, whole] of [\n [refusedWords, true],\n [refusedStarts, false],\n ] as const) {\n for (const w of words) {\n for (let at = text.indexOf(w); at >= 0; at = text.indexOf(w, at + 1)) {\n if (continuesName(text, at)) continue;\n // A whole word followed by an identifier character is a longer name, which Lean reads as one.\n if (whole && identRest.test(text[at + w.length] ?? \"\")) continue;\n return w;\n }\n }\n }\n return undefined;\n}\n\n/** `-- proof: <property>`: any name the spec file can export, Unicode letters included. */\nconst marker = /^-- proof: (\\S+)\\s*$/u;\n\n/** Read a proof file: its lemmas, its proofs by property, or why it is refused. */\nexport function readSupplied(file: string, text: string): SuppliedProofs {\n const lemmas: string[] = [];\n const proofs = new Map<string, string[]>();\n let current: string[] = lemmas;\n let twice: string | undefined;\n for (const line of text.split(\"\\n\")) {\n const m = marker.exec(line);\n if (!m) {\n current.push(line);\n continue;\n }\n const name = m[1] as string;\n twice ??= proofs.has(name) ? name : undefined;\n current = [];\n proofs.set(name, current);\n }\n if (twice !== undefined) return refuse({ file, proofs }, `${file} proves ${twice} twice`);\n // Checked over the whole text, comments and strings too: telling them apart is lexing Lean, and a\n // lexer that slips (`\"/-\"` in a string read as a comment) would let a refused command through. A\n // refused word in a comment refuses the file as well, which costs a word, never soundness.\n const word = refusedIn(text);\n if (word !== undefined)\n return refuse(\n { file, proofs },\n `${file} uses ${word}, which a supplied proof may not (it could add an axiom, switch a check off, run code while the file is checked or change how the statement reads)`,\n );\n return {\n file,\n lemmas: lemmas.join(\"\\n\").trim(),\n proofs: new Map([...proofs].map(([k, v]) => [k, v.join(\"\\n\").replace(/\\s+$/, \"\")])),\n };\n}\n\n/** The file refused: none of its proofs is used, and every property it names says why. */\nexport function refuse(\n supplied: { readonly file: string; readonly proofs: ReadonlyMap<string, unknown> },\n reason: string,\n): SuppliedProofs {\n return {\n file: supplied.file,\n lemmas: \"\",\n proofs: new Map([...supplied.proofs.keys()].map((k) => [k, \"\"])),\n refused: reason,\n };\n}\n\n/** Lean's messages at one line: an audit is read only when Lean's own message is the only one there. */\nfunction onlyAt(\n messages: readonly {\n readonly line: number;\n readonly severity: string;\n readonly message: string;\n }[],\n line: number,\n): string | undefined {\n const at = messages.filter((m) => m.line === line);\n return at.length === 1 && at[0]?.severity === \"info\" ? at[0].message : undefined;\n}\n\n/**\n * The axioms Lean reports a theorem depends on: the message of the\n * `#print axioms` at `line`, Eutaxy's own audit command, and no other.\n * Undefined unless that message is the only one at the line: anything\n * else there (a forged copy, printed by code the file ran) makes the\n * audit unreadable rather than letting either message stand.\n */\nexport function axiomsOf(\n messages: readonly {\n readonly line: number;\n readonly severity: string;\n readonly message: string;\n }[],\n line: number,\n theorem: string,\n): string[] | undefined {\n const message = onlyAt(messages, line);\n if (message === undefined) return undefined;\n if (message === `'${theorem}' does not depend on any axioms`) return [];\n const prefix = `'${theorem}' depends on axioms: [`;\n if (message.startsWith(prefix) && message.endsWith(\"]\"))\n return message\n .slice(prefix.length, -1)\n .split(\",\")\n .map((x) => x.trim())\n .filter((x) => x.length > 0);\n return undefined;\n}\n\n/**\n * Whether Lean's message at the `#check` of a supplied theorem shows it\n * proves exactly its fixed statement `s_<name>`: no hypothesis added (a\n * section variable would show as `False → …`).\n */\nexport function provesExactly(\n messages: readonly {\n readonly line: number;\n readonly severity: string;\n readonly message: string;\n }[],\n line: number,\n theorem: string,\n): boolean {\n return onlyAt(messages, line) === `${theorem} : s_${theorem}`;\n}\n","/**\n * The engine: a module's functions through the subset reader, the emitter\n * and Lean, and each property's outcome back. One Lean run per module;\n * errors are mapped to theorems by line, so one failed proof does not hide\n * another. A proof that fails is `gave_up` (the engine is weak or the\n * claim is false; Lean does not say which), a function or property outside\n * the subset is `unsupported`, and no pinned toolchain is `unavailable`.\n * `total` is proved by Lean accepting the definition.\n */\n\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { basename } from \"node:path\";\nimport type {\n ModuleProofs,\n ProofOutcome,\n PropertyProof,\n Prover,\n ProveInput as ProverInput,\n} from \"@eutaxy/prover\";\nimport {\n builtinsAssumption,\n children,\n type Expr,\n listKinds,\n OutsideSubset,\n readSubset,\n restrictModule,\n type SubsetFunction,\n type SubsetModule,\n type SubsetType,\n} from \"@eutaxy/prover/reader\";\nimport type { FunctionSpec, Property, SpecError, SpecType } from \"@eutaxy/spec\";\nimport { dividesOutside, divisionOutside, type Emitted, emitModule } from \"./emit.ts\";\nimport { checkLean, findLean, type LeanDiagnostic, leanVersion } from \"./lean.ts\";\nimport {\n axiomsOf,\n provesExactly,\n readSupplied,\n type SuppliedProofs,\n standardAxioms,\n} from \"./supplied.ts\";\n\nexport const engineName = \"lean\";\n\n/** The types this engine translates: the integers, Bool, String and records of those. */\nexport const leanTakes = (t: SubsetType): boolean =>\n t.kind === \"int\" ||\n t.kind === \"bool\" ||\n t.kind === \"string\" ||\n t.kind === \"record\" ||\n (t.kind === \"list\" && leanTakes(t.element));\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 pure and total: the module's own, or generic or imported ones read at each call from their own files; nothing else is modelled\",\n builtinsAssumption,\n `the proof was checked by the Lean ${leanVersion} kernel on the emitted statement, not by Eutaxy`,\n];\n\n/** What a PROVEN over arrays rests on besides: the list model. */\nexport const listAssumption =\n \"an array is modelled as a Lean List, dense: a sparse array, whose holes JavaScript's array methods skip, is outside every array binder's domain\";\n\n/** What a PROVEN that unfolds a recursive function rests on besides: that the JavaScript returns. */\nexport const recursionAssumption =\n \"a recursive function is modelled as returning on every input: JavaScript's call stack is bounded, so on a long enough list the code throws (RangeError) where the model returns\";\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\n/** Every property of the functions, with one outcome. */\nfunction allWith(fns: readonly FunctionSpec[], outcome: ProofOutcome): PropertyProof[] {\n return fns.flatMap((fn) =>\n fn.properties.map((property) => ({ function: fn.name, property: property.name, outcome })),\n );\n}\n\n/** The emitted Lean for the module's functions in the subset, and the functions with specs outside it with why. */\nexport interface Prepared {\n readonly module: SubsetModule;\n /** The proofs supplied beside the spec file, when there is a proof file. */\n readonly supplied?: SuppliedProofs;\n readonly emitted: Emitted;\n /** The 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 /** Specs that did not read. */\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 ones with specs among them.\n */\nexport function prepare(input: ProveInput): Prepared {\n const specs = input.specs;\n const wanted = input.functions ? new Set(input.functions) : undefined;\n const fns = specs.functions.filter((f) => !wanted || wanted.has(f.name));\n // Nullable types and tagged unions are read, but this engine does not take them yet: the SMT engine does.\n // Division leaves the integers this engine models, except as Math.floor(x / c).\n const module = restrictModule(\n restrictModule(\n readSubset(\n input.source,\n fns.map((f) => f.name),\n input.modulePath === undefined ? {} : { path: input.modulePath },\n ),\n leanTakes,\n \"nullable types and tagged unions are not in the Lean engine's subset yet\",\n ),\n () => true,\n divisionOutside,\n new Set(),\n dividesOutside,\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 // A spec belongs to one declaration: the one the reader found at that offset. A nested function (in a\n // namespace, 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 ${fn.name} the spec names is not the module's top-level declaration of that name (line ${read.line})`,\n );\n }\n const properties: { function: string; property: Property }[] = fns\n .filter((fn) => !outside.has(fn.name))\n .flatMap((fn) =>\n fn.properties\n .filter((p) => p.kind === \"forall\")\n .map((property) => ({ function: fn.name, property })),\n );\n const specErrors = specs.errors;\n // Proofs supplied beside the spec file: `domain.props.lean` beside `domain.props.ts`.\n const proofFile = input.specPath?.replace(/\\.ts$/, \".lean\");\n const supplied =\n proofFile !== undefined && existsSync(proofFile)\n ? readSupplied(basename(proofFile), readFileSync(proofFile, \"utf8\"))\n : undefined;\n try {\n return {\n module,\n ...(supplied ? { supplied } : {}),\n emitted: emitModule(\n module,\n properties,\n input.extra,\n supplied && !supplied.refused ? supplied : undefined,\n ),\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/**\n * A supplied proof's outcome: given up on when its lemmas or its tactics\n * do not compile, or when it rests on an axiom beyond Lean's standard\n * ones (`sorry` is one); PROVEN otherwise, saying it was supplied.\n */\nfunction suppliedOutcome(\n file: string,\n error: LeanDiagnostic | undefined,\n axioms: readonly string[] | undefined,\n exact: boolean,\n assumptions: readonly string[],\n): ProofOutcome {\n if (error)\n return unknown(\n \"gave_up\",\n `the proof supplied in ${file} does not close: ${error.message.split(\"\\n\")[0]}`,\n );\n if (!exact)\n return unknown(\n \"gave_up\",\n `the proof supplied in ${file} proves more hypotheses than its statement has (a section variable?), or Lean did not report its type`,\n );\n if (axioms === undefined)\n return unknown(\"gave_up\", `Lean did not report the axioms of the proof supplied in ${file}`);\n const beyond = axioms.filter((a) => !standardAxioms.has(a));\n if (beyond.length > 0)\n return unknown(\n \"gave_up\",\n `the proof supplied in ${file} rests on ${beyond.join(\", \")}, beyond Lean's standard axioms`,\n );\n return {\n ...proven,\n assumptions: [\n ...assumptions,\n `the proof was supplied in ${file}, not found by the engine's tactic script; Lean's kernel checked it against the statement Eutaxy emitted, and it rests on no axioms beyond propext, Classical.choice and Quot.sound`,\n ],\n };\n}\n\n/** Prove a module's properties with the pinned Lean. */\nexport async function proveModule(input: ProveInput): Promise<LeanModuleProofs> {\n const { module, emitted, fns, outside, specErrors, supplied } = 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 f.properties.map((property) => ({\n function: f.name,\n property: property.name,\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 inLemmas = (d: LeanDiagnostic) =>\n emitted.lemmas !== undefined && d.line >= emitted.lemmas.from && d.line <= emitted.lemmas.to;\n const lemmaErrors = errors.filter(inLemmas);\n const elsewhere = errors.filter((d) => !inTheorem(d) && !inLemmas(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.properties) {\n if (property.kind === \"total\") {\n results.push({\n function: fn.name,\n property: property.name,\n outcome: {\n ...proven,\n assumptions: [\n ...engineAssumptions,\n ...modelAssumptions(property, fn.name, module),\n \"Lean accepted the definition, so it terminates on every input\",\n ],\n },\n });\n continue;\n }\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 if (supplied?.refused && supplied.proofs.has(property.name)) {\n results.push({\n function: fn.name,\n property: property.name,\n outcome: unknown(\"gave_up\", supplied.refused),\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 if (theorem?.supplied && supplied) {\n results.push({\n function: fn.name,\n property: property.name,\n outcome: suppliedOutcome(\n supplied.file,\n lemmaErrors[0] ?? failed[0],\n axiomsOf(checked.diagnostics, theorem.axiomsLine ?? 0, theorem.name),\n provesExactly(checked.diagnostics, theorem.typeLine ?? 0, theorem.name),\n [...engineAssumptions, ...modelAssumptions(property, fn.name, module)],\n ),\n });\n continue;\n }\n results.push({\n function: fn.name,\n property: property.name,\n outcome:\n failed.length === 0\n ? {\n ...proven,\n assumptions: [...engineAssumptions, ...modelAssumptions(property, fn.name, module)],\n }\n : unknown(\n \"gave_up\",\n `Lean could not close the proof: ${(failed[0] as LeanDiagnostic).message.split(\"\\n\")[0]}`,\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 list and recursion models a proof rests on, where its claim may meet them. */\nfunction modelAssumptions(property: Property, fn: string, module: SubsetModule): string[] {\n // The module functions this claim's own arrows name, by the spec file's names for them: named at\n // all, called or not, so `(sum)(xs)` counts; a disclosure may err only toward saying more.\n const arrows = [property.when?.body ?? \"\", property.ensures?.body ?? \"\"].join(\"\\n\");\n const called = property.imports.filter((i) =>\n new RegExp(`(^|[^\\\\w$])${i.local.replace(/\\$/g, \"\\\\$\")}($|[^\\\\w$])`).test(arrows),\n );\n const roots = [fn, ...called.map((i) => i.fn)];\n return [\n ...(usesLists(property, roots, module) ? [listAssumption] : []),\n ...(reached(roots, module).some((f) => f.structural !== undefined)\n ? [recursionAssumption]\n : []),\n ];\n}\n\n/**\n * The functions a property's claim may unfold: its function, the module\n * functions its arrows call, and, through their calls, everything they\n * reach.\n */\nfunction reached(roots: readonly string[], module: SubsetModule): SubsetFunction[] {\n const byName = new Map(module.functions.map((f) => [f.name, f]));\n const out = new Map<string, SubsetFunction>();\n const visit = (name: string) => {\n const f = byName.get(name);\n if (!f || out.has(name)) return;\n out.set(name, f);\n const walk = (e: Expr): void => {\n if (e.kind === \"call\") visit(e.callee);\n for (const c of children(e)) walk(c);\n };\n walk(f.body);\n };\n for (const r of roots) visit(r);\n return [...out.values()];\n}\n\n/**\n * Whether a list can be in play in a property: a binder whose type holds\n * an array at any depth, or a function the claim may unfold that holds a\n * list in its types (through records too) or builds one.\n */\nfunction usesLists(property: Property, roots: readonly string[], module: SubsetModule): boolean {\n const records = new Map(module.records.map((r) => [r.name, r]));\n const seen = new Set<string>();\n const hasList = (t: SubsetType): boolean => {\n if (t.kind === \"list\") return true;\n if (t.kind === \"nullable\") return hasList(t.inner);\n if (t.kind === \"record\" && !seen.has(t.name)) {\n seen.add(t.name);\n return records.get(t.name)?.fields.some((f) => hasList(f.type)) ?? false;\n }\n return false;\n };\n const hasArray = (t: SpecType): boolean => {\n if (t.kind === \"array\") return true;\n if (t.kind === \"union\") return t.members.some(hasArray);\n if (t.kind === \"record\") return t.fields.some((f) => hasArray(f.type));\n return false;\n };\n const builds = (e: Expr): boolean => listKinds.has(e.kind) || children(e).some(builds);\n // The arrows' own array literals and methods, read from their text: a disclosure may err only toward saying more.\n const arrowLists = [property.when, property.ensures].some(\n (a) => a !== undefined && /\\[|\\.(map|flatMap|every|some|reduce|slice|length)\\b/.test(a.body),\n );\n return (\n property.binders.some((b) => hasArray(b.type)) ||\n arrowLists ||\n reached(roots, module).some(\n (f) => hasList(f.returns) || f.params.some((p) => hasList(p.type)) || builds(f.body),\n )\n );\n}\n","/**\n * SMT-LIB 2 for a module in the subset and the properties on it, as Z3\n * reads it. `number` is the IEEE double (the floating-point theory, so\n * NaN, the infinities and -0 are in every binder's domain and `===` is\n * `fp.eq`, as in JavaScript), `string` a sequence of 16-bit code units,\n * `boolean` Bool, a record a datatype with one constructor, a tagged\n * union a datatype with one constructor per member holding that member's\n * record (so a record may be a member of several unions: a member is\n * wrapped where one of its unions is expected, and unwrapped where a test\n * of the tag narrows the union to it), a nullable type an\n * option datatype (`none`, `some`), with a name narrowed by a null check\n * bound to its value in the branch the check guards. Each property is one\n * script: the definitions, the binders as constants with what their\n * TypeScript types say beyond their sorts, the precondition asserted, the\n * claim's negation asserted, `check-sat`; an `unsat` is a proof, a model\n * is a candidate counterexample. Values in Z3's models are decoded back to\n * JavaScript values by this module too.\n */\n\nimport {\n type Expr,\n isListExpr,\n OutsideSubset,\n type RecordType,\n readArrowBody,\n renameVars,\n type SubsetFunction,\n type SubsetModule,\n type SubsetType,\n type TypeContext,\n typeOf,\n type UnionType,\n} from \"@eutaxy/prover/reader\";\nimport { type Arrow, describeType, type Property, type SpecType } from \"@eutaxy/spec\";\n\nexport const F64 = \"(_ FloatingPoint 11 53)\";\nexport const STR = \"(Seq (_ BitVec 16))\";\n\n/** A name as an SMT-LIB symbol: simple when it can be, quoted with | otherwise. */\nexport function symbol(name: string): string {\n // A quoted symbol may hold anything but `|` and `\\`: those are escaped as `%7c` and `%5c`, with `%`\n // itself as `%25` first, in every name, so two names never meet in one symbol (a quoted symbol and\n // a simple one spelled alike are the same symbol; a record is named as the compiler prints its\n // type, which may spell any of them).\n const escaped = name.replace(/%/g, \"%25\").replace(/\\\\/g, \"%5c\").replace(/\\|/g, \"%7c\");\n return /^[A-Za-z~!@$%^&*_+=<>.?/-][A-Za-z0-9~!@$%^&*_+=<>.?/-]*$/.test(escaped)\n ? escaped\n : `|${escaped}|`;\n}\n\n/** TypeScript names as SMT symbols that cannot clash with each other or with the theories' names. */\nexport const ident = {\n fn: (name: string) => symbol(`f_${name}`),\n /** The datatype of a record, or of a union. */\n record: (name: string) => symbol(`R_${name}`),\n constructor: (name: string) => symbol(`mk_${name}`),\n /** A union's constructor for one member, holding the member's record, and its selector. */\n inject: (union: string, member: string) => symbol(`in.${union}.${member}`),\n project: (union: string, member: string) => symbol(`out.${union}.${member}`),\n // A dot, which no TypeScript identifier holds, so selectors of different records never coincide.\n field: (record: string, field: string) => symbol(`fld.${record}.${field}`),\n variable: (name: string) => symbol(`v_${name}`),\n /** The option datatype over a sort, and its constructors and selector. */\n option: (base: string) => symbol(`Opt.${base}`),\n none: (base: string) => symbol(`none.${base}`),\n some: (base: string) => symbol(`some.${base}`),\n val: (base: string) => symbol(`val.${base}`),\n};\n\n/** The short name a sort has inside option names: `Opt.F64`, `Opt.R_X`. */\nexport function sortName(t: SubsetType, module: SubsetModule): string {\n if (t.kind === \"list\" || t.kind === \"nothing\") return fail(listsOutside);\n switch (t.kind) {\n case \"int\":\n return \"F64\";\n case \"bool\":\n return \"Bool\";\n case \"string\":\n return \"Str\";\n case \"record\":\n case \"union\":\n return ident.record(t.name);\n case \"nullable\":\n return ident.option(sortName(t.inner, module));\n case \"null\":\n return fail(\"null has no sort of its own\");\n }\n}\n\nexport function sort(t: SubsetType, module: SubsetModule): string {\n if (t.kind === \"list\" || t.kind === \"nothing\") return fail(listsOutside);\n switch (t.kind) {\n case \"int\":\n return F64;\n case \"bool\":\n return \"Bool\";\n case \"string\":\n return STR;\n case \"record\":\n case \"union\":\n case \"nullable\":\n return sortName(t, module);\n case \"null\":\n return fail(\"null has no sort of its own\");\n }\n}\n\n/** A constructor applied: a bare symbol when there are no arguments. */\nfunction construct(name: string, values: readonly string[]): string {\n return values.length === 0\n ? ident.constructor(name)\n : `(${ident.constructor(name)} ${values.join(\" \")})`;\n}\n\n/** A double as a floating-point literal. */\nexport function numberTerm(n: number): string {\n if (Number.isNaN(n)) return \"(_ NaN 11 53)\";\n if (n === Number.POSITIVE_INFINITY) return \"(_ +oo 11 53)\";\n if (n === Number.NEGATIVE_INFINITY) return \"(_ -oo 11 53)\";\n if (Object.is(n, -0)) return \"(_ -zero 11 53)\";\n if (n === 0) return \"(_ +zero 11 53)\";\n // Exact bits, so a value round-trips whatever its magnitude.\n const view = new DataView(new ArrayBuffer(8));\n view.setFloat64(0, n);\n const bits = view.getBigUint64(0);\n const sign = (bits >> 63n) & 1n;\n const exponent = (bits >> 52n) & 0x7ffn;\n const significand = bits & ((1n << 52n) - 1n);\n return `(fp #b${sign} #b${exponent.toString(2).padStart(11, \"0\")} #b${significand.toString(2).padStart(52, \"0\")})`;\n}\n\n/** A JavaScript string as a sequence of its UTF-16 code units. */\nexport function stringTerm(s: string): string {\n if (s.length === 0) return `(as seq.empty ${STR})`;\n const units: string[] = [];\n for (let i = 0; i < s.length; i++)\n units.push(`(seq.unit #x${s.charCodeAt(i).toString(16).padStart(4, \"0\")})`);\n return units.length === 1 ? (units[0] as string) : `(seq.++ ${units.join(\" \")})`;\n}\n\ninterface Env {\n readonly module: SubsetModule;\n readonly ctx: TypeContext;\n /** Each node's type per scope, computed once: emission asks for types at every level. */\n readonly types: WeakMap<Expr, Map<string, SubsetType>>;\n}\n\nfunction env(module: SubsetModule): Env {\n return {\n module,\n types: new WeakMap(),\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\n/** Why a list, or an operation on one, is refused here. */\nconst listsOutside = \"arrays are not in this engine's subset (the Lean engine takes them)\";\n\nconst fail: (message: string) => never = (message) => {\n throw new OutsideSubset(message, 0);\n};\n\n/** `Number.isInteger(x)`: finite and equal to its truncation. */\nfunction isIntegerTerm(x: string): string {\n return `(and (not (fp.isNaN ${x})) (not (fp.isInfinite ${x})) (fp.eq ${x} (fp.roundToIntegral RTZ ${x})))`;\n}\n\n/** The members of a union, as records, in declaration order. */\nfunction membersOf(union: string, env: Env): RecordType[] {\n const u = env.module.unions.find((x) => x.name === union) ?? fail(`no union ${union}`);\n return u.members.map((m) => env.ctx.records.get(m.record) ?? fail(`no record ${m.record}`));\n}\n\nconst tester = (constructorSymbol: string): string =>\n constructorSymbol.startsWith(\"|\")\n ? `|is-${constructorSymbol.slice(1)}`\n : `is-${constructorSymbol}`;\n\n/** `===` of two terms of a type, as JavaScript has it. */\nfunction sameAs(a: string, b: string, t: SubsetType, env: Env): string {\n if (t.kind === \"list\" || t.kind === \"nothing\") return fail(listsOutside);\n switch (t.kind) {\n case \"int\":\n return `(fp.eq ${a} ${b})`;\n case \"bool\":\n case \"string\":\n return `(= ${a} ${b})`;\n case \"nullable\": {\n const base = sortName(t.inner, env.module);\n return `(ite (and (${tester(ident.some(base))} ${a}) (${tester(ident.some(base))} ${b})) ${sameAs(`(${ident.val(base)} ${a})`, `(${ident.val(base)} ${b})`, t.inner, env)} (and (${tester(ident.none(base))} ${a}) (${tester(ident.none(base))} ${b})))`;\n }\n case \"record\":\n case \"union\":\n case \"null\":\n return fail(\"=== on records compares references in JavaScript; compare their fields instead\");\n }\n}\n\n/**\n * A term of type `actual` as a value of type `want`: a member record\n * wrapped in the union's constructor for it, a value wrapped in `some`\n * where a nullable is wanted, a nullable member mapped into the nullable\n * union. Anything else is already of the sort wanted.\n */\nfunction lift(inner: string, actual: SubsetType, want: SubsetType, module: SubsetModule): string {\n if (want.kind === \"union\" && actual.kind === \"record\")\n return `(${ident.inject(want.name, actual.name)} ${inner})`;\n if (want.kind !== \"nullable\") return inner;\n if (actual.kind === \"null\") return inner;\n if (actual.kind === \"nullable\") {\n if (want.inner.kind !== \"union\" || actual.inner.kind !== \"record\") return inner;\n const from = sortName(actual.inner, module);\n const to = sortName(want.inner, module);\n return `(ite (${tester(ident.none(from))} ${inner}) ${ident.none(to)} (${ident.some(to)} ${lift(`(${ident.val(from)} ${inner})`, actual.inner, want.inner, module)}))`;\n }\n return `(${ident.some(sortName(want.inner, module))} ${lift(inner, actual, want.inner, module)})`;\n}\n\n/**\n * A term of the expression's type, or of `expected` where one is given:\n * `null` and a non-null value become the option's constructors where a\n * nullable is expected, and a member record its union's where the union is.\n */\nexport function term(\n e: Expr,\n scope: ReadonlyMap<string, SubsetType>,\n env: Env,\n expected?: SubsetType,\n): string {\n const t = (x: Expr, want?: SubsetType) => term(x, scope, env, want);\n if (isListExpr(e)) return fail(listsOutside);\n // A node's type depends on the scope it is typed in (narrowing), so the memo is keyed by both.\n const typed = (x: Expr): SubsetType => {\n const key = JSON.stringify([...scope]);\n let byScope = env.types.get(x);\n if (!byScope) {\n byScope = new Map();\n env.types.set(x, byScope);\n }\n let found = byScope.get(key);\n if (!found) {\n found = typeOf(x, scope, env.ctx, fail);\n byScope.set(key, found);\n }\n return found;\n };\n // A value where `want` is expected: a conditional, a let or a narrowing produce the expected sort\n // themselves; anything else is lifted to it (`lift`).\n const coerceIn = (x: Expr, want: SubsetType, sc: ReadonlyMap<string, SubsetType>): string => {\n if (\n x.kind === \"cond\" ||\n x.kind === \"let\" ||\n x.kind === \"narrow\" ||\n x.kind === \"narrowTag\" ||\n x.kind === \"null\"\n )\n return term(x, sc, env, want);\n const actual = sc === scope ? typed(x) : typeOf(x, sc, env.ctx, fail);\n return lift(term(x, sc, env, want), actual, want, env.module);\n };\n const coerce = (x: Expr, want: SubsetType): string => coerceIn(x, want, scope);\n // A narrowed body is a value where the narrowing stands: coerced to what is expected there.\n const narrowed = (body: Expr, inner: ReadonlyMap<string, SubsetType>): string =>\n expected ? coerceIn(body, expected, inner) : term(body, inner, env);\n switch (e.kind) {\n case \"int\":\n return numberTerm(Number(e.value));\n case \"bool\":\n return e.value ? \"true\" : \"false\";\n case \"string\":\n return stringTerm(e.value);\n case \"null\":\n if (expected?.kind !== \"nullable\") fail(\"null where no nullable type is expected\");\n return ident.none(sortName(expected.inner, env.module));\n case \"var\":\n return ident.variable(e.name);\n case \"narrow\": {\n const nt = scope.get(e.name);\n if (nt?.kind !== \"nullable\") fail(`${e.name} is narrowed but is not a nullable`);\n const base = sortName(nt.inner, env.module);\n const inner = new Map(scope);\n inner.set(e.name, nt.inner);\n return `(let ((${ident.variable(e.name)} (${ident.val(base)} ${ident.variable(e.name)}))) ${narrowed(e.body, inner)})`;\n }\n case \"narrowTag\": {\n // The name is bound to the member's record inside the union's value (the guard the node sits\n // under makes the constructor the right one), typed as the member in the body.\n const nt = scope.get(e.name);\n if (nt?.kind !== \"union\") fail(`${e.name} is narrowed by a tag but is not a union`);\n const inner = new Map(scope);\n inner.set(e.name, { kind: \"record\", name: e.member });\n const v = ident.variable(e.name);\n return `(let ((${v} (${ident.project(nt.name, e.member)} ${v}))) ${narrowed(e.body, inner)})`;\n }\n case \"neg\":\n return `(fp.neg ${t(e.operand)})`;\n case \"not\":\n return `(not ${t(e.operand)})`;\n case \"isInteger\":\n return isIntegerTerm(t(e.operand));\n case \"floor\":\n // Math.floor: toward negative infinity, -0, NaN and the infinities kept, as IEEE 754 rounds.\n return `(fp.roundToIntegral RTN ${t(e.operand)})`;\n case \"binary\": {\n const lt = typed(e.left);\n const rt = typed(e.right);\n switch (e.op) {\n case \"+\":\n return lt.kind === \"string\"\n ? `(seq.++ ${t(e.left)} ${t(e.right)})`\n : `(fp.add RNE ${t(e.left)} ${t(e.right)})`;\n case \"-\":\n return `(fp.sub RNE ${t(e.left)} ${t(e.right)})`;\n case \"*\":\n return `(fp.mul RNE ${t(e.left)} ${t(e.right)})`;\n case \"/\":\n return `(fp.div RNE ${t(e.left)} ${t(e.right)})`;\n case \"<\":\n return `(fp.lt ${t(e.left)} ${t(e.right)})`;\n case \"<=\":\n return `(fp.leq ${t(e.left)} ${t(e.right)})`;\n case \">\":\n return `(fp.gt ${t(e.left)} ${t(e.right)})`;\n case \">=\":\n return `(fp.geq ${t(e.left)} ${t(e.right)})`;\n case \"===\":\n case \"!==\": {\n let eq: string;\n if (lt.kind === \"null\" || rt.kind === \"null\") {\n // Against null: whether the nullable side is none.\n const side = lt.kind === \"null\" ? e.right : e.left;\n const st = lt.kind === \"null\" ? rt : lt;\n if (st.kind !== \"nullable\")\n fail(\"a comparison with null of something that is not nullable\");\n eq = `(${tester(ident.none(sortName(st.inner, env.module)))} ${t(side)})`;\n } else if (lt.kind === \"nullable\" && rt.kind !== \"nullable\") {\n const base = sortName(lt.inner, env.module);\n eq = `(and (${tester(ident.some(base))} ${t(e.left)}) ${sameAs(`(${ident.val(base)} ${t(e.left)})`, t(e.right), lt.inner, env)})`;\n } else if (rt.kind === \"nullable\" && lt.kind !== \"nullable\") {\n const base = sortName(rt.inner, env.module);\n eq = `(and (${tester(ident.some(base))} ${t(e.right)}) ${sameAs(t(e.left), `(${ident.val(base)} ${t(e.right)})`, rt.inner, env)})`;\n } else eq = sameAs(t(e.left), t(e.right), lt, env);\n return e.op === \"===\" ? eq : `(not ${eq})`;\n }\n case \"&&\":\n return `(and ${t(e.left)} ${t(e.right)})`;\n case \"||\":\n return `(or ${t(e.left)} ${t(e.right)})`;\n }\n break;\n }\n case \"cond\": {\n // Both branches of one sort: the expected one, or what the branches share.\n const want = expected ?? typed(e);\n return `(ite ${t(e.test)} ${coerce(e.ifTrue, want)} ${coerce(e.ifFalse, want)})`;\n }\n case \"call\": {\n const sig = env.ctx.signatures.get(e.callee) ?? fail(`no signature for ${e.callee}`);\n const args = e.args.map((a, i) =>\n coerce(a, (sig.params[i] as (typeof sig.params)[number]).type),\n );\n return args.length === 0 ? ident.fn(e.callee) : `(${ident.fn(e.callee)} ${args.join(\" \")})`;\n }\n case \"field\": {\n const o = typed(e.object);\n const obj = t(e.object);\n if (o.kind === \"union\") {\n // The field every member has: read from whichever member the value is.\n const members = membersOf(o.name, env);\n return members.reduceRight<string | undefined>((rest, m) => {\n const read = `(${ident.field(m.name, e.field)} (${ident.project(o.name, m.name)} ${obj}))`;\n return rest === undefined\n ? read\n : `(ite (${tester(ident.inject(o.name, m.name))} ${obj}) ${read} ${rest})`;\n }, undefined) as string;\n }\n if (o.kind !== \"record\") fail(`field ${e.field} read from a ${o.kind}`);\n return `(${ident.field(o.name, e.field)} ${obj})`;\n }\n case \"record\": {\n const type = typed(e);\n if (type.kind !== \"record\") fail(\"a record literal of no record type\");\n const rec = env.ctx.records.get(type.name) ?? fail(`no record ${type.name}`);\n // Fields in the declaration's order, whatever order the literal wrote them in.\n const values = rec.fields.map((f) => {\n const given =\n e.fields.find((x) => x.name === f.name) ?? fail(`${type.name} literal without ${f.name}`);\n return coerce(given.value, f.type);\n });\n return construct(type.name, values);\n }\n case \"let\": {\n const inner = new Map(scope);\n const bound = e.type ?? typed(e.value);\n inner.set(e.name, bound);\n const value = e.type ? coerce(e.value, e.type) : t(e.value);\n // The body is the let's value: lifted to what is expected where the let stands.\n return `(let ((${ident.variable(e.name)} ${value})) ${narrowed(e.body, inner)})`;\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\n .map((p) => `(${ident.variable(p.name)} ${sort(p.type, module)})`)\n .join(\" \");\n // The body as a value of the declared return type (`coerce` is local to `term`; the rule is repeated).\n const body = (() => {\n const b = f.body;\n if (\n b.kind === \"cond\" ||\n b.kind === \"let\" ||\n b.kind === \"narrow\" ||\n b.kind === \"narrowTag\" ||\n b.kind === \"null\"\n )\n return term(b, scope, e, f.returns);\n return lift(term(b, scope, e, f.returns), typeOf(b, scope, e.ctx, fail), f.returns, module);\n })();\n return `(define-fun ${ident.fn(f.name)} (${params}) ${sort(f.returns, module)}\\n ${body})`;\n}\n\n/**\n * An option sort over every sort the module could mention: the primitives,\n * every record, every union. A body may join a\n * value with `null` in a `const` that no signature shows, so nothing is\n * left to discovery.\n */\nfunction optionSorts(module: SubsetModule): Map<string, SubsetType> {\n const out = new Map<string, SubsetType>();\n const bases: SubsetType[] = [\n { kind: \"int\" },\n { kind: \"bool\" },\n { kind: \"string\" },\n ...module.records.map((r): SubsetType => ({ kind: \"record\", name: r.name })),\n ...module.unions.map((u): SubsetType => ({ kind: \"union\", name: u.name })),\n ];\n for (const b of bases) out.set(sortName(b, module), b);\n return out;\n}\n\n/**\n * Every datatype in one declaration, so records, unions and options may\n * refer to one another in any order: a record is one constructor, a union\n * one per member holding its record, an option `none` and `some` over its\n * base sort.\n */\nexport function emitDatatypes(module: SubsetModule): string {\n const plain = module.records;\n const unions = module.unions;\n const options = optionSorts(module);\n const names = [\n ...plain.map((r) => ident.record(r.name)),\n ...unions.map((u) => ident.record(u.name)),\n ...[...options.keys()].map((base) => ident.option(base)),\n ];\n if (names.length === 0) return \"\";\n const constructorOf = (r: RecordType): string =>\n `(${ident.constructor(r.name)}${r.fields.map((f) => ` (${ident.field(r.name, f.name)} ${sort(f.type, module)})`).join(\"\")})`;\n const bodies = [\n ...plain.map((r) => `(${constructorOf(r)})`),\n ...unions.map(\n (u) =>\n `(${u.members.map((m) => `(${ident.inject(u.name, m.record)} (${ident.project(u.name, m.record)} ${ident.record(m.record)}))`).join(\" \")})`,\n ),\n ...[...options].map(\n ([base, inner]) =>\n `((${ident.none(base)}) (${ident.some(base)} (${ident.val(base)} ${sort(inner, module)})))`,\n ),\n ];\n return `(declare-datatypes (${names.map((n) => `(${n} 0)`).join(\" \")}) (${bodies.join(\" \")}))`;\n}\n\n/**\n * The subset type a binder ranges over, or `OutsideSubset`: `number` is\n * the double, a union of string literals is a string (constrained to the\n * literals in the script), a record is the module's datatype of that\n * name, `T | null` the option over `T`, a union of records the declared\n * union whose members match. Bigint and what the reader could not read\n * are outside.\n */\nexport function binderType(name: string, t: SpecType, module: SubsetModule): SubsetType {\n switch (t.kind) {\n case \"number\":\n return { kind: \"int\" };\n case \"boolean\":\n return { kind: \"bool\" };\n case \"string\":\n return { kind: \"string\" };\n case \"literal\":\n if (typeof t.value === \"string\") return { kind: \"string\" };\n if (typeof t.value === \"boolean\") return { kind: \"bool\" };\n return { kind: \"int\" };\n case \"bigint\":\n fail(`binder ${name} over bigint: the subset has no bigint`);\n break;\n case \"union\": {\n const nulls = t.members.filter((m) => m.kind === \"null\");\n if (t.members.some((m) => m.kind === \"undefined\"))\n fail(`binder ${name} over ${describeType(t)}: undefined is not in the subset (null is)`);\n const rest = t.members.filter((m) => m.kind !== \"null\");\n let inner: SubsetType;\n if (rest.every((m) => m.kind === \"literal\" && typeof m.value === \"string\"))\n inner = { kind: \"string\" };\n else if (rest.every((m) => m.kind === \"literal\" && typeof m.value === \"boolean\"))\n inner = { kind: \"bool\" };\n else if (rest.length === 1) inner = binderType(name, rest[0] as SpecType, module);\n else if (rest.every((m) => m.kind === \"record\")) {\n const union = findUnion(rest as readonly Extract<SpecType, { kind: \"record\" }>[], module);\n if (!union)\n fail(\n `binder ${name} over ${describeType(t)}: no one union the module declares has exactly these members`,\n );\n inner = { kind: \"union\", name: union.name };\n } else fail(`binder ${name} over ${describeType(t)}: a union the subset does not read`);\n return nulls.length > 0 ? { kind: \"nullable\", inner } : inner;\n }\n case \"record\":\n if (t.name !== undefined && module.records.some((r) => r.name === t.name))\n return { kind: \"record\", name: t.name };\n fail(\n `binder ${name} over ${describeType(t)}: ${t.name === undefined ? \"an inline record type\" : `record type ${t.name} is outside the subset`}`,\n );\n break;\n case \"null\":\n case \"undefined\":\n fail(`binder ${name} over ${t.kind}`);\n break;\n case \"array\":\n fail(`binder ${name} over ${describeType(t)}: arrays are not in the engine's subset yet`);\n break;\n case \"unknown\":\n fail(`binder ${name} over ${t.text}, which the reader could not read`);\n }\n}\n\n/**\n * The one declared union these member types are, compared field by field\n * and type by type: a field holding one literal is that literal in the\n * union's member, a union of literals is a field of no literal, and\n * everything else reads to the field's own type. A record may be a member\n * of several unions, so tags and field names alone could name the wrong\n * one; when more than one union fits, none is chosen.\n */\nfunction findUnion(\n members: readonly Extract<SpecType, { kind: \"record\" }>[],\n module: SubsetModule,\n): UnionType | undefined {\n const recordOf = (name: string) => module.records.find((r) => r.name === name);\n // A nested record is compared by its fields, not its name: the spec reader and the subset reader\n // may name one inline type differently (`Extract<U, …>` against `U.a`).\n const recordFits = (sm: Extract<SpecType, { kind: \"record\" }>, rec: RecordType): boolean =>\n sm.fields.length === rec.fields.length &&\n rec.fields.every((f) => {\n const sf = sm.fields.find((x) => x.name === f.name);\n return sf !== undefined && fieldFits(sf.type, f);\n });\n const typeFits = (sf: SpecType, t: SubsetType): boolean => {\n if (t.kind === \"record\") {\n const rec = recordOf(t.name);\n return sf.kind === \"record\" && rec !== undefined && recordFits(sf, rec);\n }\n if (t.kind === \"nullable\" && sf.kind === \"union\" && sf.members.some((m) => m.kind === \"null\")) {\n const rest = sf.members.filter((m) => m.kind !== \"null\");\n const inner: SpecType =\n rest.length === 1 ? (rest[0] as SpecType) : { kind: \"union\", members: rest };\n return typeFits(inner, t.inner);\n }\n if (t.kind === \"union\") {\n const u = module.unions.find((x) => x.name === t.name);\n if (!u || sf.kind !== \"union\" || sf.members.length !== u.members.length) return false;\n return u.members.every((m) => {\n const rec = recordOf(m.record);\n return (\n rec !== undefined && sf.members.some((sm) => sm.kind === \"record\" && recordFits(sm, rec))\n );\n });\n }\n try {\n return JSON.stringify(binderType(\"field\", sf, module)) === JSON.stringify(t);\n } catch (err) {\n if (err instanceof OutsideSubset) return false;\n throw err;\n }\n };\n function fieldFits(sf: SpecType, f: RecordType[\"fields\"][number]): boolean {\n if (f.literal !== undefined) return sf.kind === \"literal\" && sf.value === f.literal;\n if (sf.kind === \"literal\") return false;\n return typeFits(sf, f.type);\n }\n const fitting = module.unions.filter((u) => {\n if (u.members.length !== members.length) return false;\n return u.members.every((m) => {\n const rec = recordOf(m.record);\n return rec !== undefined && members.some((sm) => recordFits(sm, rec));\n });\n });\n return fitting.length === 1 ? fitting[0] : undefined;\n}\n\n/**\n * What a binder's subset type says that its sort does not: a union's\n * members carry their tags, and so on\n * into fields and under an option. Undefined when the sort says it all.\n */\nexport function wellFormed(\n target: string,\n t: SubsetType,\n module: SubsetModule,\n): string | undefined {\n switch (t.kind) {\n case \"int\":\n case \"bool\":\n case \"string\":\n case \"null\":\n return undefined;\n case \"nullable\": {\n const base = sortName(t.inner, module);\n const inner = wellFormed(`(${ident.val(base)} ${target})`, t.inner, module);\n return inner === undefined\n ? undefined\n : `(or (${tester(ident.none(base))} ${target}) ${inner})`;\n }\n case \"record\": {\n const rec = module.records.find((r) => r.name === t.name);\n if (!rec) return undefined;\n const parts: string[] = [];\n for (const f of rec.fields) {\n const read = `(${ident.field(rec.name, f.name)} ${target})`;\n if (f.literal !== undefined)\n parts.push(\n typeof f.literal === \"string\"\n ? `(= ${read} ${stringTerm(f.literal)})`\n : `(= ${read} ${f.literal ? \"true\" : \"false\"})`,\n );\n const inner = wellFormed(read, f.type, module);\n if (inner !== undefined) parts.push(inner);\n }\n return parts.length === 0\n ? undefined\n : parts.length === 1\n ? parts[0]\n : `(and ${parts.join(\" \")})`;\n }\n case \"union\": {\n const u = module.unions.find((x) => x.name === t.name);\n if (!u) return undefined;\n const cases = u.members.map((m) => {\n const is = `(${tester(ident.inject(u.name, m.record))} ${target})`;\n const inner = wellFormed(\n `(${ident.project(u.name, m.record)} ${target})`,\n { kind: \"record\", name: m.record },\n module,\n );\n return inner === undefined ? is : `(and ${is} ${inner})`;\n });\n return `(or ${cases.join(\" \")})`;\n }\n }\n}\n\n/**\n * What a binder's TypeScript type says beyond its sort: a literal, or a\n * union of literals (with or without null), admits only those values,\n * which the solver must be told, since the sort alone would let it pick\n * any string or number.\n */\nexport function domainConstraint(\n symbolName: string,\n t: SpecType,\n subset: SubsetType,\n module: SubsetModule,\n): string | undefined {\n const literal = (target: string, v: string | number | boolean): string =>\n typeof v === \"string\"\n ? `(= ${target} ${stringTerm(v)})`\n : typeof v === \"number\"\n ? `(fp.eq ${target} ${numberTerm(v)})`\n : `(= ${target} ${v ? \"true\" : \"false\"})`;\n const literals: (string | number | boolean)[] = [];\n let withNull = false;\n if (t.kind === \"literal\") literals.push(t.value);\n else if (t.kind === \"union\") {\n for (const m of t.members) {\n if (m.kind === \"literal\") literals.push(m.value);\n else if (m.kind === \"null\") withNull = true;\n else return undefined;\n }\n } else return undefined;\n if (literals.length === 0) return undefined;\n const over = (target: string) => {\n const alternatives = literals.map((v) => literal(target, v));\n return alternatives.length === 1\n ? (alternatives[0] as string)\n : `(or ${alternatives.join(\" \")})`;\n };\n if (subset.kind === \"nullable\") {\n const base = sortName(subset.inner, module);\n const some = `(and (${tester(ident.some(base))} ${symbolName}) ${over(`(${ident.val(base)} ${symbolName})`)})`;\n return withNull ? `(or (${tester(ident.none(base))} ${symbolName}) ${some})` : some;\n }\n return over(symbolName);\n}\n\n/** An arrow of the spec file as a Bool term over the binders, its own parameter names renamed to theirs. */\nfunction arrowTerm(\n arrow: Arrow,\n what: \"when\" | \"ensures\",\n property: Property,\n types: readonly SubsetType[],\n e: Env,\n): string {\n try {\n const binders = property.binders;\n const scope = new Map<string, SubsetType>();\n const names = new Map<string, string>();\n arrow.params.forEach((p, i) => {\n const binder = binders[i];\n const type = types[i];\n if (p === null) fail(`a destructured parameter in ${what}`);\n if (!binder || !type) fail(`${what} takes more parameters than the function has`);\n scope.set(p, type);\n names.set(p, binder.name);\n });\n const aliases = new Map(property.imports.map((i) => [i.local, i.fn]));\n const read = readArrowBody(arrow, scope, e.module, aliases);\n const t = typeOf(read, scope, e.ctx, fail);\n if (t.kind !== \"bool\")\n fail(`${what} is not boolean (a ${t.kind === \"record\" ? t.name : t.kind})`);\n const renamed = renameVars(read, names);\n const binderScope = new Map(binders.map((b, i) => [b.name, types[i] as SubsetType]));\n return term(renamed, binderScope, e);\n } catch (err) {\n if (!(err instanceof OutsideSubset)) throw err;\n throw new OutsideSubset(`${what} (spec file line ${arrow.line}): ${err.message}`, arrow.line);\n }\n}\n\n/** The definitions every script of the module starts with: datatypes, then functions, callees first. */\nexport function prelude(module: SubsetModule): string {\n const datatypes = emitDatatypes(module);\n return [\n \";; Generated by Eutaxy's first-party SMT engine from the module and its spec file.\",\n \"(set-option :produce-models true)\",\n ...(datatypes === \"\" ? [] : [datatypes]),\n ...module.functions.map((f) => emitFunction(f, module)),\n ].join(\"\\n\");\n}\n\nexport interface PropertyScript {\n readonly script: string;\n /** The binders' SMT names and types, in order, for reading a model back. */\n readonly binders: readonly {\n readonly name: string;\n readonly symbol: string;\n readonly type: SubsetType;\n }[];\n}\n\n/**\n * One property's script: the binders as constants, what their types say\n * beyond their sorts, the precondition asserted, the claim's negation\n * asserted. `unsat` proves the claim; `sat` comes with the binders' values.\n */\nexport function propertyScript(property: Property, module: SubsetModule): PropertyScript {\n if (property.kind !== \"forall\" || !property.ensures) fail(\"not a forall property\");\n const e = env(module);\n const types = property.binders.map((b) => binderType(b.name, b.type, module));\n const binders = property.binders.map((b, i) => ({\n name: b.name,\n symbol: ident.variable(b.name),\n type: types[i] as SubsetType,\n }));\n const lines = [\n prelude(module),\n ...binders.map((b) => `(declare-const ${b.symbol} ${sort(b.type, module)})`),\n // What a binder's subset type says that its sort does not: which member of a union, which tags.\n ...binders.flatMap((b) => {\n const c = wellFormed(b.symbol, b.type, module);\n return c === undefined ? [] : [`(assert ${c})`];\n }),\n ...property.binders.flatMap((b, i) => {\n const c = domainConstraint(\n (binders[i] as (typeof binders)[number]).symbol,\n b.type,\n types[i] as SubsetType,\n module,\n );\n return c === undefined ? [] : [`(assert ${c})`];\n }),\n ...(property.when ? [`(assert ${arrowTerm(property.when, \"when\", property, types, e)})`] : []),\n `(assert (not ${arrowTerm(property.ensures, \"ensures\", property, types, e)}))`,\n \"(check-sat)\",\n ...(binders.length > 0 ? [`(get-value (${binders.map((b) => b.symbol).join(\" \")}))`] : []),\n \"(get-info :reason-unknown)\",\n ];\n return { script: `${lines.join(\"\\n\")}\\n`, binders };\n}\n\n/** A TypeScript value of a subset type as a term, for translation checks. */\nexport function value(v: unknown, t: SubsetType, module: SubsetModule): string {\n if (t.kind === \"list\" || t.kind === \"nothing\") return fail(listsOutside);\n switch (t.kind) {\n case \"int\":\n if (typeof v !== \"number\") fail(`${String(v)} is not a number`);\n return numberTerm(v);\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 stringTerm(v);\n case \"nullable\": {\n const base = sortName(t.inner, module);\n return v === null ? ident.none(base) : `(${ident.some(base)} ${value(v, t.inner, module)})`;\n }\n case \"union\": {\n const u = module.unions.find((x) => x.name === t.name) ?? fail(`no union ${t.name}`);\n if (typeof v !== \"object\" || v === null) fail(`${String(v)} is not a ${t.name}`);\n const tag = (v as Record<string, unknown>)[u.tag];\n const member =\n u.members.find((m) => m.tag === tag) ?? fail(`${t.name} value with tag ${String(tag)}`);\n return `(${ident.inject(u.name, member.record)} ${value(v, { kind: \"record\", name: member.record }, module)})`;\n }\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 construct(\n t.name,\n rec.fields.map((f) => value(o[f.name], f.type, module)),\n );\n }\n case \"null\":\n return fail(\"a value of type null\");\n }\n}\n\n/** Equality of two terms of a type, as JavaScript would have it: `fp.eq` on numbers, field by field on records. */\nexport function equal(a: string, b: string, t: SubsetType, module: SubsetModule): string {\n if (t.kind === \"list\" || t.kind === \"nothing\") return fail(listsOutside);\n switch (t.kind) {\n case \"int\":\n return `(fp.eq ${a} ${b})`;\n case \"bool\":\n case \"string\":\n return `(= ${a} ${b})`;\n case \"nullable\": {\n const base = sortName(t.inner, module);\n return `(ite (and (${tester(ident.some(base))} ${a}) (${tester(ident.some(base))} ${b})) ${equal(`(${ident.val(base)} ${a})`, `(${ident.val(base)} ${b})`, t.inner, module)} (and (${tester(ident.none(base))} ${a}) (${tester(ident.none(base))} ${b})))`;\n }\n case \"union\": {\n const u = module.unions.find((x) => x.name === t.name) ?? fail(`no union ${t.name}`);\n const cases = u.members.map((m) => {\n const is = tester(ident.inject(u.name, m.record));\n const out = ident.project(u.name, m.record);\n return `(and (${is} ${a}) (${is} ${b}) ${equal(`(${out} ${a})`, `(${out} ${b})`, { kind: \"record\", name: m.record }, module)})`;\n });\n return `(or ${cases.join(\" \")})`;\n }\n case \"record\": {\n const rec = module.records.find((r) => r.name === t.name) ?? fail(`no record ${t.name}`);\n const fields = rec.fields.map((f) =>\n equal(\n `(${ident.field(t.name, f.name)} ${a})`,\n `(${ident.field(t.name, f.name)} ${b})`,\n f.type,\n module,\n ),\n );\n if (fields.length === 0) return \"true\";\n return fields.length === 1 ? (fields[0] as string) : `(and ${fields.join(\" \")})`;\n }\n case \"null\":\n return fail(\"equality at type null\");\n }\n}\n\n// ---------------------------------------------------------------------------\n// Reading Z3's answers.\n\nexport type SExpr = string | readonly SExpr[];\n\n/** Z3's output as S-expressions and atoms, in order. */\nexport function parseSExprs(text: string): SExpr[] {\n const out: SExpr[] = [];\n const stack: SExpr[][] = [];\n let i = 0;\n const push = (x: SExpr) => {\n const top = stack[stack.length - 1];\n if (top) top.push(x);\n else out.push(x);\n };\n while (i < text.length) {\n const c = text[i] as string;\n if (/\\s/.test(c)) {\n i++;\n continue;\n }\n if (c === \";\") {\n while (i < text.length && text[i] !== \"\\n\") i++;\n continue;\n }\n if (c === \"(\") {\n stack.push([]);\n i++;\n continue;\n }\n if (c === \")\") {\n const done = stack.pop();\n if (done) push(done);\n i++;\n continue;\n }\n if (c === '\"') {\n let j = i + 1;\n let s = \"\";\n while (j < text.length) {\n if (text[j] === '\"' && text[j + 1] === '\"') {\n s += '\"';\n j += 2;\n } else if (text[j] === '\"') break;\n else s += text[j++];\n }\n push(`\"${s}\"`);\n i = j + 1;\n continue;\n }\n if (c === \"|\") {\n const j = text.indexOf(\"|\", i + 1);\n push(text.slice(i, j < 0 ? text.length : j + 1));\n i = j < 0 ? text.length : j + 1;\n continue;\n }\n let j = i;\n while (j < text.length && !/[\\s()]/.test(text[j] as string)) j++;\n push(text.slice(i, j));\n i = j;\n }\n while (stack.length > 0) {\n const done = stack.pop();\n if (done) push(done);\n }\n return out;\n}\n\n/** Thrown when a model value is not of the shape the type calls for. */\nexport class UnreadableModel extends Error {}\n\nconst bitsOf = (atom: string): bigint =>\n atom.startsWith(\"#b\") ? BigInt(`0b${atom.slice(2)}`) : BigInt(`0x${atom.slice(2)}`);\n\n/** A model value of the type as a JavaScript value. */\nexport function decode(x: SExpr, t: SubsetType, module: SubsetModule): unknown {\n switch (t.kind) {\n case \"bool\":\n if (x === \"true\") return true;\n if (x === \"false\") return false;\n throw new UnreadableModel(`not a boolean: ${show(x)}`);\n case \"int\": {\n if (Array.isArray(x) && x[0] === \"_\") {\n const special = x[1];\n if (special === \"NaN\") return Number.NaN;\n if (special === \"+oo\") return Number.POSITIVE_INFINITY;\n if (special === \"-oo\") return Number.NEGATIVE_INFINITY;\n if (special === \"+zero\") return 0;\n if (special === \"-zero\") return -0;\n }\n if (Array.isArray(x) && x[0] === \"fp\" && x.length === 4) {\n const sign = bitsOf(x[1] as string);\n const exponent = bitsOf(x[2] as string);\n const significand = bitsOf(x[3] as string);\n const view = new DataView(new ArrayBuffer(8));\n view.setBigUint64(0, (sign << 63n) | (exponent << 52n) | significand);\n return view.getFloat64(0);\n }\n throw new UnreadableModel(`not a double: ${show(x)}`);\n }\n case \"string\":\n return decodeString(x);\n case \"nullable\": {\n const base = sortName(t.inner, module);\n if (x === ident.none(base)) return null;\n if (Array.isArray(x) && x[0] === ident.some(base) && x.length === 2)\n return decode(x[1] as SExpr, t.inner, module);\n throw new UnreadableModel(`not a ${describeSubset(t)}: ${show(x)}`);\n }\n case \"union\": {\n const u = module.unions.find((y) => y.name === t.name);\n if (!u) throw new UnreadableModel(`no union ${t.name}`);\n const head = Array.isArray(x) ? x[0] : x;\n const member = u.members.find((m) => ident.inject(u.name, m.record) === head);\n if (!member || !Array.isArray(x) || x.length !== 2)\n throw new UnreadableModel(`not a ${t.name}: ${show(x)}`);\n return decode(x[1] as SExpr, { kind: \"record\", name: member.record }, module);\n }\n case \"record\": {\n const rec = module.records.find((r) => r.name === t.name);\n if (!rec) throw new UnreadableModel(`no record ${t.name}`);\n if (rec.fields.length === 0 && x === ident.constructor(t.name)) return {};\n if (\n !Array.isArray(x) ||\n x[0] !== ident.constructor(t.name) ||\n x.length !== rec.fields.length + 1\n )\n throw new UnreadableModel(`not a ${t.name}: ${show(x)}`);\n const out: Record<string, unknown> = {};\n rec.fields.forEach((f, i) => {\n out[f.name] = decode(x[i + 1] as SExpr, f.type, module);\n });\n return out;\n }\n case \"null\":\n throw new UnreadableModel(\"a value of type null\");\n }\n}\n\nfunction describeSubset(t: SubsetType): string {\n return t.kind === \"nullable\"\n ? `${describeSubset(t.inner)} | null`\n : t.kind === \"record\" || t.kind === \"union\"\n ? t.name\n : t.kind;\n}\n\nfunction decodeString(x: SExpr): string {\n if (Array.isArray(x)) {\n if (x[0] === \"seq.unit\" && typeof x[1] === \"string\")\n return String.fromCharCode(Number(bitsOf(x[1])));\n if (x[0] === \"seq.++\") return x.slice(1).map(decodeString).join(\"\");\n if (x[0] === \"as\" && x[1] === \"seq.empty\") return \"\";\n if (x[0] === \"_\" && x[1] === \"seq.empty\") return \"\";\n }\n throw new UnreadableModel(`not a string: ${show(x)}`);\n}\n\nfunction show(x: SExpr): string {\n return typeof x === \"string\" ? x : `(${x.map(show).join(\" \")})`;\n}\n\nexport interface Answer {\n readonly result: \"sat\" | \"unsat\" | \"unknown\" | \"error\";\n /** The binders' values when `sat`, by SMT symbol. */\n readonly values: ReadonlyMap<string, SExpr>;\n readonly reason: string;\n /** Every `(error …)` Z3 printed, except the one for a model asked after `unsat`, which the script expects. */\n readonly errors: readonly string[];\n}\n\n/** What a property's script came back with. */\nexport function readAnswer(output: string): Answer {\n const parts = parseSExprs(output);\n const first = parts.find((p) => p === \"sat\" || p === \"unsat\" || p === \"unknown\");\n const errors = parts\n .filter((p): p is readonly SExpr[] => Array.isArray(p) && p[0] === \"error\")\n .map((e) => show(e))\n .filter((e) => !/model is not available/.test(e));\n const values = new Map<string, SExpr>();\n let reason = \"\";\n for (const p of parts) {\n if (!Array.isArray(p)) continue;\n if (p[0] === \":reason-unknown\" && typeof p[1] === \"string\") reason = p[1].replace(/^\"|\"$/g, \"\");\n if (p.every((x) => Array.isArray(x) && x.length === 2 && typeof x[0] === \"string\"))\n for (const pair of p as readonly (readonly [string, SExpr])[]) values.set(pair[0], pair[1]);\n }\n if (first === undefined)\n return { result: \"error\", values, reason: errors.join(\"; \") || output.trim(), errors };\n return { result: first as Answer[\"result\"], values, reason, errors };\n}\n","/**\n * Running Z3 over a process boundary. The engine is pinned to one Z3\n * release: a `z3` on the PATH (or in Homebrew's and the usual local\n * prefixes) must report that version. Nothing is downloaded during a\n * check; a missing solver is `unavailable`, with how to install it. Every\n * run carries a resource limit, Z3's own machine-independent budget, so\n * the same script gives the same outcome on every machine; a wall-clock\n * timeout is only the safety net.\n */\n\nimport { spawn } from \"node:child_process\";\nimport { mkdtempSync, rmSync, writeFileSync } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\n\n/** The Z3 release the engine's contract corpus is checked against. */\nexport const z3Version = \"5.3.2\";\n/** How to put the pinned solver on this machine. */\nexport const installHint = `install Z3 ${z3Version} (https://github.com/Z3Prover/z3/releases/tag/z3-${z3Version}; Homebrew: brew install z3) so that z3 is on the PATH`;\n/** The resource budget a check runs under (Z3's `rlimit`, in its own units), unless configured. */\nexport const defaultResourceLimit = 50_000_000;\n\nexport interface Z3Run {\n readonly code: number | null;\n readonly stdout: string;\n readonly stderr: string;\n readonly timedOut: boolean;\n}\n\nexport interface Z3Solver {\n readonly command: 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<Z3Run> {\n return new Promise((resolve) => {\n let child: ReturnType<typeof spawn>;\n try {\n child = spawn(command, args, { cwd: options.cwd, stdio: [\"ignore\", \"pipe\", \"pipe\"] });\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 child.kill(\"SIGKILL\");\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 `z3` executable: `EUTAXY_Z3`, the PATH, then the prefixes package managers install into. */\nexport function candidates(): string[] {\n const fromEnv = process.env[\"EUTAXY_Z3\"];\n return [\n ...(fromEnv ? [fromEnv] : []),\n \"z3\",\n \"/opt/homebrew/bin/z3\",\n \"/usr/local/bin/z3\",\n \"/usr/bin/z3\",\n ];\n}\n\n/**\n * The pinned solver if it is installed: a `z3` of exactly that version,\n * wherever among the candidates it is; another version is reported only\n * when no candidate is the pinned one.\n */\nexport async function findZ3(\n where: readonly string[] = candidates(),\n): Promise<Z3Solver | { readonly unavailable: string }> {\n let other: string | undefined;\n for (const z3 of where) {\n const v = await run(z3, [\"--version\"], { timeoutMs: 20_000 });\n if (v.code !== 0) continue;\n const m = /Z3 version (\\S+)/.exec(v.stdout);\n if (m?.[1] === z3Version) return { command: z3, version: z3Version };\n other ??= m?.[1] ?? \"of unknown version\";\n }\n if (other !== undefined)\n return {\n unavailable: `z3 ${other} found, but the engine is pinned to ${z3Version}; ${installHint}`,\n };\n return { unavailable: `no z3 found; ${installHint}` };\n}\n\nexport interface SolvedScript {\n readonly run: Z3Run;\n /** Whether Z3 reported the resource limit exceeded. */\n readonly resourceLimit: boolean;\n}\n\n/** Write the script to a scratch file and run Z3 on it under the resource limit. */\nexport async function solve(\n solver: Z3Solver,\n script: string,\n options: {\n readonly timeoutMs?: number;\n readonly resourceLimit?: number;\n readonly keep?: boolean;\n } = {},\n): Promise<SolvedScript> {\n const dir = mkdtempSync(join(tmpdir(), \"eutaxy-smt-\"));\n try {\n const file = join(dir, \"property.smt2\");\n writeFileSync(file, script);\n const result = await run(\n solver.command,\n [`rlimit=${options.resourceLimit ?? defaultResourceLimit}`, \"-smt2\", file],\n { cwd: dir, timeoutMs: options.timeoutMs ?? 120_000 },\n );\n return { run: result, resourceLimit: /resource limit/i.test(result.stdout) };\n } finally {\n if (!options.keep) rmSync(dir, { recursive: true, force: true });\n }\n}\n","/**\n * The engine: a module's functions through the subset reader, the emitter\n * and Z3, one script per property, and each property's outcome back. An\n * `unsat` is `PROVEN` under the engine's models of the language. A model\n * is a candidate counterexample, never a verdict: the engine runs the\n * spec file's own `when` and `ensures` on it, and only a claim that fails\n * on the real function is `REFUTED`, with the input shrunk as the TESTED\n * rung shrinks; a model the function does not confirm is a modelling gap,\n * `UNKNOWN` (`unsupported`) with the input. A resource limit reached is\n * `gave_up`; a function or property outside the subset is `unsupported`;\n * no pinned solver is `unavailable`.\n */\n\nimport { existsSync, readFileSync, rmSync, writeFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport {\n conforms,\n evaluate,\n type ModuleProofs,\n type ProofOutcome,\n type PropertyProof,\n type Prover,\n type ProveInput as ProverInput,\n render,\n shrinkRefutation,\n} from \"@eutaxy/prover\";\nimport {\n builtinsAssumption,\n listKinds,\n OutsideSubset,\n readSubset,\n restrictModule,\n type SubsetModule,\n} from \"@eutaxy/prover/reader\";\nimport { type Fn, type Forall, type FunctionSpec, isSpec, type Property } from \"@eutaxy/spec\";\nimport {\n decode,\n equal,\n type PropertyScript,\n prelude,\n propertyScript,\n readAnswer,\n UnreadableModel,\n} from \"./emit.ts\";\nimport { findZ3, solve, z3Version } from \"./z3.ts\";\n\nexport const engineName = \"smt\";\n\nexport interface ProveInput extends ProverInput {\n /** Extra Bool terms over the module's definitions that must hold (translation checks): each is checked unsatisfiable when negated. */\n readonly extra?: readonly string[];\n /** Z3's resource budget per property, in its own units. */\n readonly resourceLimit?: number;\n}\n\n/** This engine's report, with the definitions it ran. */\nexport interface SmtModuleProofs extends ModuleProofs {\n /** The prelude shared by every script, when any function was in the subset. */\n readonly smt?: string;\n}\n\n/** What every PROVEN verdict of this engine rests on. */\nexport const engineAssumptions: readonly string[] = [\n \"number is modelled as the IEEE double (the floating-point theory): NaN, the infinities and -0 are in every binder's domain, and === is fp.eq\",\n \"string is modelled as a sequence of 16-bit code units, as JavaScript holds it\",\n \"the function and its callees are pure and total: the module's own, or generic or imported ones read at each call from their own files; nothing else is modelled\",\n builtinsAssumption,\n `Z3 ${z3Version} found the claim's negation unsatisfiable under a resource limit; no proof object was checked by a kernel`,\n];\n\nconst proven: Extract<ProofOutcome, { kind: \"PROVEN\" }> = {\n kind: \"PROVEN\",\n engine: { name: engineName, version: z3Version },\n assumptions: engineAssumptions,\n};\n\nconst unknown = (\n cause: \"gave_up\" | \"unsupported\" | \"unavailable\",\n reason: string,\n): ProofOutcome => ({ kind: \"UNKNOWN\", cause, reason });\n\n/** The scripts for the module's functions in the subset, and the functions with specs outside it with why. */\nexport interface Prepared {\n readonly module: SubsetModule;\n readonly fns: readonly FunctionSpec[];\n readonly outside: ReadonlyMap<string, string>;\n /** One script per statable forall property. */\n readonly scripts: ReadonlyMap<string, PropertyScript>;\n /** Properties the emitter could not state, with why. */\n readonly skipped: ReadonlyMap<string, string>;\n readonly prelude: string;\n}\n\nconst key = (fn: string, property: string): string => `${fn}\\u0000${property}`;\n\n/** Read and emit: every function the subset takes, and a script per property of the ones with specs. */\nexport function prepare(input: ProveInput): Prepared {\n const wanted = input.functions ? new Set(input.functions) : undefined;\n const fns = input.specs.functions.filter((f) => !wanted || wanted.has(f.name));\n // Lists are read, but this engine does not take them: functions using one are outside here, so the\n // prelude never meets them and the module's other functions still go through.\n const module = restrictModule(\n readSubset(\n input.source,\n fns.map((f) => f.name),\n input.modulePath === undefined ? {} : { path: input.modulePath },\n ),\n (t) => t.kind !== \"list\" && t.kind !== \"nothing\",\n \"arrays are not in this engine's subset (the Lean engine takes them)\",\n listKinds,\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 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 ${fn.name} the spec names is not the module's top-level declaration of that name (line ${read.line})`,\n );\n }\n const scripts = new Map<string, PropertyScript>();\n const skipped = new Map<string, string>();\n let pre = \"\";\n try {\n pre = prelude(module);\n for (const fn of fns) {\n if (outside.has(fn.name)) continue;\n for (const property of fn.properties) {\n if (property.kind !== \"forall\") continue;\n try {\n scripts.set(key(fn.name, property.name), propertyScript(property, module));\n } catch (err) {\n if (!(err instanceof OutsideSubset)) throw err;\n skipped.set(key(fn.name, property.name), err.message);\n }\n }\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 scripts.clear();\n }\n return { module, fns, outside, scripts, skipped, prelude: pre };\n}\n\n/**\n * The spec file as a module. A relative import written without `.ts`\n * (`./domain`, `./domain.js`), which the simulator's loader resolves and\n * Node does not, is completed in a sibling copy that is imported and then\n * removed, so the copy's own relative imports still resolve.\n */\nasync function importSpecFile(specPath: string): Promise<Record<string, unknown>> {\n try {\n return (await import(pathToFileURL(specPath).href)) as Record<string, unknown>;\n } catch (err) {\n const code = (err as { code?: string }).code;\n if (code !== \"ERR_MODULE_NOT_FOUND\" && code !== \"ERR_UNSUPPORTED_DIR_IMPORT\") throw err;\n const source = readFileSync(specPath, \"utf8\");\n const dir = dirname(specPath);\n const rewritten = source.replace(\n /(from\\s*[\"'])(\\.{1,2}\\/[^\"']+?)(\\.js)?([\"'])/g,\n (whole, pre: string, rel: string, _js: string | undefined, post: string) =>\n existsSync(join(dir, `${rel}.ts`)) ? `${pre}${rel}.ts${post}` : whole,\n );\n if (rewritten === source) throw err;\n const copy = join(dir, `.eutaxy-replay-${process.pid}-${Date.now()}.props.ts`);\n writeFileSync(copy, rewritten);\n try {\n return (await import(pathToFileURL(copy).href)) as Record<string, unknown>;\n } finally {\n rmSync(copy, { force: true });\n }\n }\n}\n\n/** The spec file's export for a property, loaded for replay, or why it could not be. */\nasync function loadSpec(\n specPath: string | undefined,\n property: Property,\n fn: string,\n): Promise<Forall<Fn> | string> {\n if (specPath === undefined)\n return \"the engine was not given the spec file's path to replay the counterexample\";\n let ns: Record<string, unknown>;\n try {\n ns = await importSpecFile(specPath);\n } catch (err) {\n return `the spec file could not be loaded to replay the counterexample: ${String(err)}`;\n }\n const exported = Object.hasOwn(ns, property.name) ? ns[property.name] : undefined;\n if (!isSpec(exported) || exported.kind !== \"forall\")\n return `the spec file exports no forall named ${property.name} to replay the counterexample with`;\n if (typeof exported.fn !== \"function\" || exported.fn.name !== fn)\n return `the spec file's ${property.name} is not on ${fn}`;\n return exported;\n}\n\n/** Prove a module's properties with the pinned Z3. */\nexport async function proveModule(input: ProveInput): Promise<SmtModuleProofs> {\n const { fns, outside, scripts, skipped, module, prelude: smt } = prepare(input);\n const specErrors = input.specs.errors;\n const inSubset = fns.filter((f) => !outside.has(f.name));\n const results: PropertyProof[] = fns\n .filter((f) => outside.has(f.name))\n .flatMap((f) =>\n f.properties.map((property) => ({\n function: f.name,\n property: property.name,\n outcome: unknown(\"unsupported\", outside.get(f.name) as string),\n })),\n );\n if (inSubset.length === 0) return { results, specErrors };\n const allWith = (outcome: ProofOutcome): SmtModuleProofs => ({\n results: [\n ...results,\n ...inSubset.flatMap((fn) =>\n fn.properties.map((p) => ({ function: fn.name, property: p.name, outcome })),\n ),\n ],\n smt,\n specErrors,\n });\n const solver = await findZ3();\n if (\"unavailable\" in solver) return allWith(unknown(\"unavailable\", solver.unavailable));\n const options = {\n ...(input.timeoutMs === undefined ? {} : { timeoutMs: input.timeoutMs }),\n ...(input.resourceLimit === undefined ? {} : { resourceLimit: input.resourceLimit }),\n };\n // Translation checks first: a definition that does not compute what the TypeScript computes is an engine gap.\n if (input.extra && input.extra.length > 0) {\n const script = [\n smt,\n ...input.extra.flatMap((x) => [\"(push)\", `(assert (not ${x}))`, \"(check-sat)\", \"(pop)\"]),\n \"\",\n ].join(\"\\n\");\n const checked = await solve(solver, script, options);\n const answers = checked.run.stdout\n .split(\"\\n\")\n .map((l) => l.trim())\n .filter((l) => /^(sat|unsat|unknown)$/.test(l));\n if (checked.run.timedOut)\n return allWith(unknown(\"gave_up\", \"Z3 did not finish the translation checks in time\"));\n // The budget ran out on a check: nothing is known about the definitions, and nothing is claimed.\n if (answers.includes(\"unknown\"))\n return allWith(unknown(\"gave_up\", \"Z3 reached its resource limit on a translation check\"));\n const failed = answers.findIndex((a) => a !== \"unsat\");\n const errors = readAnswer(checked.run.stdout).errors;\n if (\n checked.run.code !== 0 ||\n errors.length > 0 ||\n answers.length !== input.extra.length ||\n failed >= 0\n )\n return allWith(\n unknown(\n \"unsupported\",\n `the emitted SMT failed a translation check${failed >= 0 ? ` (${input.extra[failed]})` : \"\"}: ${errors[0] ?? (checked.run.stderr || checked.run.stdout).trim().split(\"\\n\")[0] ?? \"\"}`,\n ),\n );\n }\n for (const fn of inSubset) {\n for (const property of fn.properties) {\n if (property.kind === \"total\") {\n results.push({\n function: fn.name,\n property: property.name,\n outcome: unknown(\n \"unsupported\",\n \"total is not decided by this engine (Lean proves it by acceptance)\",\n ),\n });\n continue;\n }\n const k = key(fn.name, property.name);\n const why = skipped.get(k);\n if (why !== undefined) {\n results.push({\n function: fn.name,\n property: property.name,\n outcome: unknown(\"unsupported\", why),\n });\n continue;\n }\n const script = scripts.get(k);\n if (!script) continue;\n const solved = await solve(solver, script.script, options);\n results.push({\n function: fn.name,\n property: property.name,\n outcome: await outcomeOf(solved, script, module, property, fn.name, input),\n });\n }\n }\n return { results, smt, specErrors };\n}\n\nasync function outcomeOf(\n solved: Awaited<ReturnType<typeof solve>>,\n script: PropertyScript,\n module: SubsetModule,\n property: Property,\n fn: string,\n input: ProveInput,\n): Promise<ProofOutcome> {\n if (solved.run.timedOut)\n return unknown(\"gave_up\", `Z3 did not finish within ${input.timeoutMs ?? 120_000} ms`);\n if (solved.run.code === null)\n return unknown(\"unavailable\", `Z3 could not be run: ${solved.run.stderr.trim()}`);\n const answer = readAnswer(solved.run.stdout);\n // An error Z3 printed means a command was dropped; whatever verdict line followed is not about the\n // claim. (The exit code says nothing here: Z3 exits non-zero for the model asked after `unsat` too.)\n if (answer.errors.length > 0)\n return unknown(\"unsupported\", `the emitted SMT did not run: ${answer.errors[0]}`);\n if (answer.result === \"unsat\") return proven;\n if (answer.result === \"unknown\")\n return unknown(\n \"gave_up\",\n solved.resourceLimit\n ? `Z3 reached its resource limit${answer.reason ? ` (${answer.reason})` : \"\"}`\n : `Z3 gave up: ${answer.reason || \"unknown\"}`,\n );\n if (answer.result === \"error\")\n return unknown(\"unsupported\", `the emitted SMT did not run: ${answer.reason}`);\n // sat: a candidate counterexample, replayed through the spec file's own claim.\n let values: unknown[];\n try {\n values = script.binders.map((b) => {\n const v = answer.values.get(b.symbol);\n if (v === undefined) throw new UnreadableModel(`no value for ${b.name} in the model`);\n return decode(v, b.type, module);\n });\n } catch (err) {\n if (!(err instanceof UnreadableModel)) throw err;\n return unknown(\"unsupported\", `Z3's model could not be read: ${err.message}`);\n }\n const rendered = property.binders.map((b, i) => `${b.name} = ${render(values[i])}`).join(\", \");\n // The solver saw the sorts; the claim quantifies over the TypeScript types, which may be narrower.\n if (!property.binders.every((b, i) => conforms(b.type, values[i])))\n return unknown(\n \"unsupported\",\n `Z3's model lies outside the parameter types (${rendered}): the engine's model of the types is wider than the types`,\n );\n const spec = await loadSpec(input.specPath, property, fn);\n if (typeof spec === \"string\") return unknown(\"unsupported\", `${spec} (the model: ${rendered})`);\n const evaluation = evaluate(spec, values);\n if (\"malformed\" in evaluation)\n return unknown(\n \"unsupported\",\n `the property could not be evaluated on the model (${rendered}): ${evaluation.malformed}`,\n );\n if (evaluation.outcome !== \"refuted\")\n return unknown(\n \"unsupported\",\n `the claim ${evaluation.outcome === \"held\" ? \"held\" : \"was outside its precondition\"} on the model Z3 gave (${rendered}): the engine's model of the language differs from the runtime here`,\n );\n const smallest = shrinkRefutation(spec, property.binders, values, evaluation);\n return {\n kind: \"REFUTED\",\n engine: { name: engineName, version: z3Version },\n counterexample: {\n binders: property.binders.map((b, i) => ({\n name: b.name,\n value: render(smallest.values[i]),\n })),\n ...(smallest.error === undefined ? {} : { error: smallest.error }),\n },\n assumptions: [\n \"found as a model of the claim's negation by Z3, confirmed by running the spec on it, then shrunk\",\n ],\n };\n}\n\n/** The engine as a `Prover`: available when the pinned solver is installed. */\nexport const smtProver: Prover = {\n name: engineName,\n async available() {\n const solver = await findZ3();\n return \"unavailable\" in solver ? solver : { version: solver.version };\n },\n prove: (input) => proveModule(input),\n};\n\nexport { equal };\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 { specEntries } 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, specEntries, ${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 files for `eutaxy check`: every `<module>.props.ts` next to the\n * scenario, read with its module into `SpecIR` on the Node side, and the\n * generated `specs.ts` that hands workerd each module's specs together\n * with a loader for its spec file. Which of them a run checks is the\n * scenario's `specs`, read where the scenario is loaded, inside the\n * generated test; a spec file loads only when its module is named.\n */\n\nimport { existsSync, readdirSync, readFileSync } from \"node:fs\";\nimport { basename, dirname, join, relative } from \"node:path\";\nimport { readSpecs } from \"@eutaxy/prover/reader\";\nimport type { ModuleSpecs } from \"@eutaxy/spec\";\nimport { specKey } from \"./keys.ts\";\n\nexport { specKey } from \"./keys.ts\";\n\n/** The suffix a spec file carries beside its module: `domain.ts` has `domain.props.ts`. */\nexport const specSuffix = \".props.ts\";\n\nexport interface SpecModule {\n /** The module's path relative to the scenario's directory, as a scenario names it: \"./domain.ts\". */\n readonly key: string;\n /** The module's absolute path. */\n readonly path: string;\n /** The spec file's absolute path. */\n readonly specPath: string;\n readonly specs: ModuleSpecs;\n}\n\nconst skipDirs = new Set([\"node_modules\", \".eutaxy\", \"dist\", \".git\"]);\n\n/** Read one module and its spec file; their imports resolve from where they are. */\nexport function readSpecModule(modulePath: string, specPath: string): ModuleSpecs {\n return readSpecs({\n module: readFileSync(modulePath, \"utf8\"),\n spec: readFileSync(specPath, \"utf8\"),\n modulePath,\n specPath,\n });\n}\n\n/** Spec files under `dir`, each with its module; a spec file without a module beside it is an error entry. */\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 if (!entry.name.endsWith(specSuffix)) continue;\n const modulePath = join(at, `${entry.name.slice(0, -specSuffix.length)}.ts`);\n const key = specKey(relative(dir, modulePath));\n if (!existsSync(modulePath)) {\n out.push({\n key,\n path: modulePath,\n specPath: path,\n specs: {\n functions: [],\n errors: [\n {\n line: 1,\n message: `${entry.name} has no module ${basename(modulePath)} beside it`,\n },\n ],\n },\n });\n continue;\n }\n out.push({ key, path: modulePath, specPath: path, specs: readSpecModule(modulePath, path) });\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/** 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/** A path as an import specifier from `.eutaxy/`: forward slashes, relative, `.ts` kept (Vite resolves it). */\nfunction importFrom(workDir: string, target: string): string {\n const rel = relative(workDir, target).split(\"\\\\\").join(\"/\");\n return rel.startsWith(\".\") ? rel : `./${rel}`;\n}\n\n/**\n * The generated `specs.ts`: each module's key mapped to its specs (plain\n * data read on the Node side) and a loader of its spec file. The loader is\n * lazy, so a spec file elsewhere that does not compile cannot stop a check\n * of a scenario that does not name its module.\n */\nexport function specFiles(modules: readonly SpecModule[], workDir: string): GeneratedFile[] {\n const header = \"// Generated by eutaxy check; deleted after the run.\";\n const lines = [\n header,\n \"// The `any`: this file runs in the user's Vitest, which does not type-check it; `SpecEntry` in workerd.ts is the shape.\",\n \"export const specEntries: Record<string, { specs: any; load: () => Promise<any> }> = {\",\n ...modules.map(\n (m) =>\n ` ${JSON.stringify(m.key)}: { specs: ${JSON.stringify(m.specs)}, load: () => import(${JSON.stringify(importFrom(workDir, m.specPath))}) },`,\n ),\n \"};\",\n ];\n return [{ name: \"specs.ts\", source: `${lines.join(\"\\n\")}\\n` }];\n}\n\n/** The directory a generated file's import is resolved from. */\nexport function specWorkDir(dir: string): string {\n return dirname(join(dir, \".eutaxy\", \"specs.ts\"));\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 { smtProver } from \"@eutaxy/prover-smt\";\nimport { renderSpecs, renderText } from \"@eutaxy/report\";\nimport { checkTestSource, metaKey, vitestConfigSource } from \"./generate.ts\";\nimport { cloudflareRegressionTest } from \"./regression.ts\";\nimport { findSpecModules, type SpecModule, 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, smt: smtProver };\n\n/** The engines named, or the error naming the first unknown one. */\nexport function enginesNamed(\n names: readonly string[],\n): { readonly engines: Prover[] } | { readonly error: string } {\n const engines: Prover[] = [];\n for (const name of names) {\n const engine = provers[name];\n if (!engine)\n return { error: `unknown prover ${name}; known: ${Object.keys(provers).join(\", \")}` };\n engines.push(engine);\n }\n return { engines };\n}\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 modules: readonly SpecModule[] = findSpecModules(dir),\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 found = modules.find((s) => s.key === key);\n const withSpecs = m.functions.filter((f) =>\n specs.some((v) => v.module === key && v.function === f),\n );\n if (!found || withSpecs.length === 0) continue;\n const source = readFileSync(found.path, \"utf8\");\n const reports: EngineReport[] = [];\n for (const engine of engines)\n reports.push({\n engine: engine.name,\n proofs: await engine.prove({\n source,\n specs: found.specs,\n functions: withSpecs,\n modulePath: found.path,\n specPath: found.specPath,\n }),\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 const specModules = findSpecModules(dir);\n for (const f of specFiles(specModules, workDir)) {\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 named = enginesNamed(o.provers);\n if (\"error\" in named) {\n o.stderr(`${named.error}\\n`);\n return exitCodes.error;\n }\n specs = await proveSpecs(dir, transport.observed ?? [], specs, named.engines, specModules);\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","/**\n * `eutaxy report [dir]`: every spec file under a directory through the\n * ladder, on the Node side. No scenario runs, so the ladder starts at\n * `TESTED` (inputs drawn from the parameter types); `--prover` adds the\n * `PROVEN` rung. Each module runs in a child process of its own, started\n * on this file: what the module prints goes to stderr, its state starts\n * fresh, and a property that never returns ends with the module's budget.\n * A process, not a worker thread: Node strips types with WebAssembly, and\n * V8 shares compiled wasm code between the threads of a process; V8 on\n * Node 24 can abort while one thread frees that code as another uses it\n * (seen as SIGSEGV, SIGBUS or SIGTRAP of the whole process).\n * A module that only loads inside workerd gets `UNKNOWN` until an engine\n * reads it.\n */\n\nimport { fork } from \"node:child_process\";\nimport { registerHooks } from \"node:module\";\nimport { resolve } from \"node:path\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\nimport type { SpecVerdict } from \"@eutaxy/core\";\nimport { checkSpecModule, type Prover } from \"@eutaxy/prover\";\nimport { renderSpecReport, renderSpecReportJson } from \"@eutaxy/report\";\nimport { enginesNamed, exitCodes, proveSpecs } from \"./check.ts\";\nimport { findSpecModules, type SpecModule } from \"./specs.ts\";\n\nexport interface ReportOptions {\n /** The directory to search for spec files, relative to `cwd`; default `cwd` itself. */\n readonly dir?: string;\n readonly cwd: string;\n /** The seed the `TESTED` rung draws from; default \"report\". */\n readonly seed?: string;\n /** Engines to run the `PROVEN` rung with, by name. */\n readonly provers?: readonly string[];\n /** How long one module's properties may take at `TESTED`; default 60 s. */\n readonly moduleBudgetMs?: number;\n readonly json: boolean;\n readonly stdout: (text: string) => void;\n readonly stderr: (text: string) => void;\n}\n\n/** The argument a module's process is started with, so this file knows to run it. */\nconst moduleFlag = \"--eutaxy-report-module\";\n\ninterface ModuleInput {\n readonly module: SpecModule;\n readonly seed: string;\n}\n\n/** What a module's process sends back; tagged, since the module itself may call `process.send`. */\ninterface ModuleOutput {\n readonly kind: \"eutaxy-report-verdicts\";\n readonly verdicts: SpecVerdict[];\n}\n\nfunction unknownAll(\n m: SpecModule,\n cause: \"gave_up\" | \"unavailable\",\n reason: string,\n): SpecVerdict[] {\n return m.specs.functions.flatMap((fn) =>\n fn.properties.map(\n (p): SpecVerdict => ({\n module: m.key,\n function: fn.name,\n property: p.name,\n text: p.text,\n kind: \"UNKNOWN\",\n cause,\n reason,\n assumptions: [],\n }),\n ),\n );\n}\n\n/**\n * Inside the module's process: a relative import from a `.ts` file that Node cannot\n * resolve is tried as TypeScript resolves it, so `./domain.js` and\n * `./domain` find `domain.ts` (or `domain/index.ts`), as `tsc` would.\n */\nfunction resolveAsTypeScript(): void {\n registerHooks({\n resolve(specifier, context, nextResolve) {\n try {\n return nextResolve(specifier, context);\n } catch (err) {\n const relative = specifier.startsWith(\"./\") || specifier.startsWith(\"../\");\n if (!relative || !context.parentURL?.endsWith(\".ts\")) throw err;\n const stem = specifier.endsWith(\".js\") ? specifier.slice(0, -3) : specifier;\n for (const candidate of [`${stem}.ts`, `${stem}/index.ts`]) {\n try {\n return nextResolve(candidate, context);\n } catch {}\n }\n throw err;\n }\n },\n });\n}\n\n/** Inside the module's process: load the module and its spec file, run the `TESTED` rung. */\nasync function testHere(m: SpecModule, seed: string): Promise<SpecVerdict[]> {\n resolveAsTypeScript();\n let namespace: Readonly<Record<string, unknown>>;\n let props: Readonly<Record<string, unknown>>;\n try {\n namespace = (await import(pathToFileURL(m.path).href)) as Record<string, unknown>;\n props = (await import(pathToFileURL(m.specPath).href)) as Record<string, unknown>;\n } catch (err) {\n return unknownAll(\n m,\n \"unavailable\",\n `the module or its spec file did not load in Node: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n return checkSpecModule(\n m.key,\n m.specs,\n props,\n namespace,\n { calls: [], unobservable: {} },\n { checked: false, tested: { seed } },\n );\n}\n\nconst send = process.send?.bind(process);\nif (process.argv[2] === moduleFlag && send) {\n process.once(\"disconnect\", () => process.exit(0));\n process.once(\"message\", async (input: ModuleInput) => {\n const verdicts = await testHere(input.module, input.seed);\n // Exit once the verdicts and everything the module wrote are out, whatever timers it left.\n send({ kind: \"eutaxy-report-verdicts\", verdicts } satisfies ModuleOutput, () =>\n process.stdout.write(\"\", () => process.stderr.write(\"\", () => process.exit(0))),\n );\n });\n}\n\n/**\n * One module's verdicts at the `TESTED` rung, from a child process. What\n * the module writes goes to `stderr`; a module that does not load, or does\n * not finish within the budget, leaves each property `UNKNOWN`.\n */\nexport function testModule(\n m: SpecModule,\n seed: string,\n budgetMs: number,\n stderr: (text: string) => void,\n): Promise<SpecVerdict[]> {\n return new Promise((done) => {\n const child = fork(fileURLToPath(import.meta.url), [moduleFlag], {\n stdio: [\"ignore\", \"pipe\", \"pipe\", \"ipc\"],\n serialization: \"advanced\",\n });\n child.stdout?.on(\"data\", (d: Buffer) => stderr(d.toString()));\n child.stderr?.on(\"data\", (d: Buffer) => stderr(d.toString()));\n // Settled on `close`, once the process has exited and all it wrote is read; `reported` holds\n // its verdicts if it sent them, and `ended` why it stopped otherwise.\n let reported: SpecVerdict[] | undefined;\n let ended: SpecVerdict[] | undefined;\n let settled = false;\n const settle = (verdicts: SpecVerdict[]) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n done(verdicts);\n };\n const timer = setTimeout(() => {\n ended = unknownAll(\n m,\n \"gave_up\",\n `the module's properties did not finish within ${budgetMs} ms on generated inputs (one may never return)`,\n );\n child.kill(\"SIGKILL\");\n // A process the module started may still hold the pipes open.\n child.stdout?.destroy();\n child.stderr?.destroy();\n }, budgetMs);\n child.on(\"message\", (message: Partial<ModuleOutput> | null) => {\n if (message?.kind === \"eutaxy-report-verdicts\" && Array.isArray(message.verdicts))\n reported ??= message.verdicts;\n });\n child.once(\"error\", (err) => {\n ended ??= unknownAll(m, \"unavailable\", `the module's process failed: ${err.message}`);\n // A process that never started (no pid) emits no `close`.\n if (child.pid === undefined) settle(ended);\n else child.kill(\"SIGKILL\");\n });\n child.once(\"close\", (code, signal) => {\n settle(\n reported ??\n ended ??\n unknownAll(\n m,\n \"unavailable\",\n `the module's process exited (${signal ?? code}) before reporting`,\n ),\n );\n });\n child.send({ module: m, seed } satisfies ModuleInput);\n });\n}\n\nexport async function runReport(o: ReportOptions): Promise<number> {\n const root = resolve(o.cwd, o.dir ?? \".\");\n let engines: Prover[] = [];\n if (o.provers && o.provers.length > 0) {\n const named = enginesNamed(o.provers);\n if (\"error\" in named) {\n o.stderr(`${named.error}\\n`);\n return exitCodes.error;\n }\n engines = named.engines;\n }\n let modules: SpecModule[];\n try {\n modules = findSpecModules(root);\n } catch (err) {\n o.stderr(`cannot read ${root}: ${err instanceof Error ? err.message : String(err)}\\n`);\n return exitCodes.error;\n }\n if (modules.length === 0) {\n o.stderr(`no spec files (*.props.ts) under ${root}\\n`);\n return exitCodes.error;\n }\n const errors = modules.flatMap((m) =>\n m.specs.errors.map((e) => `${m.key}${e.line > 0 ? `:${e.line}` : \"\"}: ${e.message}`),\n );\n if (errors.length > 0) {\n for (const e of errors) o.stderr(`${e}\\n`);\n return exitCodes.error;\n }\n let specs: readonly SpecVerdict[] = [];\n for (const m of modules)\n specs = [\n ...specs,\n ...(await testModule(m, o.seed ?? \"report\", o.moduleBudgetMs ?? 60_000, o.stderr)),\n ];\n if (engines.length > 0)\n specs = await proveSpecs(\n root,\n modules.map((m) => ({ module: m.key, functions: m.specs.functions.map((f) => f.name) })),\n specs,\n engines,\n modules,\n );\n o.stdout(`${o.json ? renderSpecReportJson(specs) : renderSpecReport(specs)}\\n`);\n // The codes check uses: 1 for a refuted or conflicting spec, 0 otherwise; UNKNOWN fails nothing.\n return specs.some((v) => v.kind === \"REFUTED\" || v.kind === \"CONFLICT\")\n ? exitCodes.VIOLATED\n : exitCodes.BOUNDED;\n}\n","import { parseArgs } from \"./args.ts\";\nimport { exitCodes, runCheck } from \"./check.ts\";\nimport { runReport } from \"./report.ts\";\n\nconst usage = `eutaxy — deterministic simulation checks and spec verdicts for Cloudflare Workers\n\nUsage:\n eutaxy check <scenario.sim.ts> [options]\n eutaxy report [dir] [--prover <names>] [--seed <seed>] [--json]\n\ncheck options:\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, smt)\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\nreport runs every spec file (*.props.ts) under dir (default: the current directory)\nthrough the TESTED rung, on inputs drawn from the parameter types with the seed\n(default: report), and the PROVEN rung with --prover. No scenario runs, so nothing\nis CHECKED.\n\nExit codes: 0 BOUNDED, 1 VIOLATED or a REFUTED or CONFLICT spec, 2 UNSUPPORTED, 3 error.\nreport: 0, or 1 for a REFUTED or CONFLICT spec, 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 // A value flag given without one would otherwise read as absent: `--prover` alone must not quietly\n // skip the PROVEN rung.\n for (const k of [\"wrangler\", \"seed\", \"max-runs\", \"budget-ms\", \"prover\", \"out\"])\n if (flags[k] === true) {\n io.stderr(`--${k} needs a value\\n`);\n return exitCodes.error;\n }\n const str = (k: string): string | undefined =>\n typeof flags[k] === \"string\" ? (flags[k] as string) : undefined;\n const provers = (str(\"prover\") ?? \"\")\n .split(\",\")\n .map((n) => n.trim())\n .filter((n) => n.length > 0);\n if (command === \"report\") {\n if (positionals.length > 2) {\n io.stderr(`report takes one directory\\n\\n${usage}`);\n return exitCodes.error;\n }\n const other = Object.keys(flags).find((k) => ![\"prover\", \"seed\", \"json\"].includes(k));\n if (other !== undefined) {\n io.stderr(`report does not take --${other}\\n`);\n return exitCodes.error;\n }\n const dir = positionals[1];\n return runReport({\n cwd: io.cwd,\n ...(dir === undefined ? {} : { dir }),\n ...(provers.length > 0 ? { provers } : {}),\n ...(str(\"seed\") ? { seed: str(\"seed\") as string } : {}),\n json: flags[\"json\"] === true,\n stdout: io.stdout,\n stderr: io.stderr,\n });\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 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 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 spec files beside them, 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 } from \"@eutaxy/prover\";\nimport { renderJson } from \"@eutaxy/report\";\nimport type { ModuleSpecs } from \"@eutaxy/spec\";\nimport { globKey, specKey } from \"./keys.ts\";\n\n/** What the generated test stores in its task meta. */\nexport interface CheckTransport {\n readonly report: unknown;\n /** Set instead of a report when a module the scenario's `specs` names has no usable spec file. */\n readonly specErrors?: readonly SpecError[];\n readonly worker: { readonly entry: string; readonly config: string };\n readonly setup: readonly { readonly kind: string; readonly [key: string]: unknown }[];\n /** The 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 entry: the module's specs, read on the Node side, and a loader of its spec file. */\nexport interface SpecEntry {\n readonly specs: ModuleSpecs;\n readonly load: () => Promise<object>;\n}\n\n/** Vite globs, keyed as `import.meta.glob` keys them from `.eutaxy/` (see `globKey`). */\nexport type ModuleGlob = Readonly<Record<string, () => Promise<unknown>>>;\n\n/** 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 /** The spec file's namespace: its exports are the specs. */\n readonly props: Readonly<Record<string, unknown>>;\n /** The functions observed: the ones with specs, and the decisions `refines` names that the module exports. */\n readonly names: readonly string[];\n}\n\n/**\n * The modules the scenario's `specs` name, loaded with their specs and\n * their spec files, and every reason the check cannot go ahead: a module\n * that is not there, a spec that does not read, a function name observed\n * in two modules (decisions are logged by name, so it would be ambiguous).\n * The spec files are loaded here, before anything is observed, so the\n * functions their specs hold are the modules' own.\n */\nexport async function selectSpecModules(\n scenario: ScenarioSpec,\n modules: ModuleGlob,\n specEntries: Readonly<Record<string, SpecEntry>>,\n): Promise<{\n readonly selected: readonly SelectedModule[];\n readonly specErrors: readonly SpecError[];\n}> {\n const decisions = scenario.invariants.flatMap((i) => (i.kind === \"refines\" ? [i.decision] : []));\n const specErrors: SpecError[] = [];\n const selected: SelectedModule[] = [];\n for (const path of scenario.specs ?? []) {\n const load = modules[globKey(path)];\n if (!load) {\n specErrors.push({ module: path, line: 0, message: \"no such module next to the scenario\" });\n continue;\n }\n const namespace = (await load()) as Record<string, unknown>;\n const key = specKey(path);\n const entry = Object.hasOwn(specEntries, key) ? specEntries[key] : undefined;\n const specs: ModuleSpecs = entry?.specs ?? { functions: [], errors: [] };\n for (const e of specs.errors)\n specErrors.push({\n module: e.inModule ? path : `${path.replace(/\\.ts$/, \"\")}.props.ts`,\n line: e.line,\n message: e.message,\n });\n const props = entry ? ((await entry.load()) as Record<string, unknown>) : {};\n const exported = decisions.filter((d) => typeof namespace[d] === \"function\");\n const names = [...new Set([...specs.functions.map((f) => f.name), ...exported])];\n selected.push({ path, key, namespace, specs, props, names });\n }\n const observedIn = new Map<string, string>();\n for (const m of selected)\n for (const n of m.names) {\n const other = observedIn.get(n);\n if (other === undefined) observedIn.set(n, m.path);\n else\n specErrors.push({\n module: m.path,\n line: 0,\n message: `${n} is observed in both ${other} and ${m.path}; decisions of one name must come from one module`,\n });\n }\n return { selected, specErrors };\n}\n\nexport interface WorkerdCheckInput {\n /** The scenario module's default export. */\n readonly scenario: ScenarioSpec;\n /** `env` from `cloudflare:workers`. */\n readonly env: object;\n /** The `cloudflare:test` module, for Durable Objects. */\n readonly durableObjects: DurableObjectTestHelpers;\n /** The raw text of the `.sql` files next to the scenario. */\n readonly sqlFiles: Readonly<Record<string, string>>;\n /** The TypeScript modules next to the scenario (the Worker and the spec modules among them). */\n readonly modules: ModuleGlob;\n /** The generated `specs.ts` entries, by module key. */\n readonly specEntries: Readonly<Record<string, SpecEntry>>;\n 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.specEntries,\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(\n m.key,\n m.specs,\n m.props,\n m.namespace as Record<string, unknown>,\n observers[i] as ReturnType<typeof observeCore>,\n { tested: { seed: input.seed } },\n ),\n );\n return {\n report: JSON.parse(renderJson(verdict, specs)) as unknown,\n ...transportBase,\n observed: selected.map((m) => ({ module: m.path, functions: m.names })),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;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,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