eutaxy 0.11.0 → 0.13.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.
@@ -1,20 +1,22 @@
1
- import { A as writeFaults, C as toJson, F as getPath, I as canonicalJson, O as decisionFaults, T as validateScenario, _ as withoutNetwork, a as explore, b as settleOn, c as runInvocation, d as findResponse, f as installScriptedFetch, g as toResponse, h as replyOf, i as proxiedSide, k as readFaults, l as CrashSignal, m as parseBody, n as DifferentialStuck, p as isRedirect, r as compareSides, t as observeCore, u as InjectedEffectError, v as patchGlobals, w as defaultBounds, x as virtualEpoch } from "./src-DGh7w877.mjs";
2
- import { a as redelivery, i as invocationOf, n as atLeastOncePerMessage$1 } from "./delivery-invariants-Br29H7Rg.mjs";
3
- import { _ as endpointNumber, a as renderText, b as describeVerdict, c as aggregate, f as shrinkRefutation, g as endpointBigInt, h as conforms, i as renderSpecs, l as checkSpecModule, m as evaluate, n as renderSpecReport, r as renderSpecReportJson, s as emitRegressionTest, t as renderJson, v as render, y as describeType } from "./src-CWVQEhTr.mjs";
1
+ import { I as canonicalJson } from "./src-DGh7w877.mjs";
2
+ import { _ as render, a as renderText, c as checkSpecModule, d as shrinkRefutation, g as endpointNumber, h as endpointBigInt, i as renderSpecs, m as conforms, n as renderSpecReport, p as evaluate, r as renderSpecReportJson, v as describeType } from "./src-5pKRvj02.mjs";
4
3
  import { n as isSpec } from "./combinators-CVjxodAJ.mjs";
4
+ import { t as aggregate } from "./provers-DS44OeEm.mjs";
5
+ import { H as cloudflareRegressionTest, n as specKey } from "./workerd-BMJ-GKx8.mjs";
5
6
  import { createRequire, registerHooks } from "node:module";
6
- import { fork, spawn } from "node:child_process";
7
+ import { Readable } from "node:stream";
8
+ import { createHash, randomBytes } from "node:crypto";
7
9
  import { chmodSync, closeSync, copyFileSync, createReadStream, existsSync, mkdirSync, mkdtempSync, openSync, readFileSync, readdirSync, renameSync, rmSync, symlinkSync, writeFileSync, writeSync } from "node:fs";
10
+ import { homedir, tmpdir } from "node:os";
8
11
  import { basename, dirname, join, relative, resolve, sep } from "node:path";
12
+ import { createZstdDecompress, inflateRawSync } from "node:zlib";
13
+ import { fork, spawn } from "node:child_process";
9
14
  import { InternalSymbolName, ModifierFlags, NodeFlags, SyntaxKind, forEachLeadingCommentRange, forEachTrailingCommentRange } from "typescript/ast";
10
15
  import { createFileSystemLayer } from "typescript/fs";
11
16
  import { API, DiagnosticCategory, SymbolFlags, TypeFlags, TypeFormatFlags } from "typescript/sync";
12
17
  import * as is from "typescript/ast/is";
13
- import { homedir, tmpdir } from "node:os";
14
18
  import { fileURLToPath, pathToFileURL } from "node:url";
15
- import { createHash, randomBytes } from "node:crypto";
16
- import { Readable } from "node:stream";
17
- import { createZstdDecompress, inflateRawSync } from "node:zlib";
19
+ import { createInterface } from "node:readline";
18
20
  // packages/cli/src/args.ts
19
21
  function parseArgs(argv, booleans = []) {
20
22
  const positionals = [];
@@ -4311,6 +4313,9 @@ async function checkLean(toolchain, source, options = {}) {
4311
4313
  }
4312
4314
  }
4313
4315
  // packages/prover-lean/src/supplied.ts
4316
+ /** The lines a goal file carries, and a proof file copied from one keeps, tying the proofs to the files they were written for. */
4317
+ const sourceHashMarker = "-- eutaxy-source-sha256: ";
4318
+ const specHashMarker = "-- eutaxy-spec-sha256: ";
4314
4319
  /** The axioms a supplied proof may rest on: Lean's standard ones. */
4315
4320
  const standardAxioms = /* @__PURE__ */ new Set([
4316
4321
  "propext",
@@ -4432,10 +4437,18 @@ function readSupplied(file, text) {
4432
4437
  file,
4433
4438
  proofs
4434
4439
  }, `${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)`);
4440
+ const hashLine = (marker) => {
4441
+ const hex = lemmas.find((l) => l.startsWith(marker))?.slice(marker.length).trim();
4442
+ return hex !== void 0 && /^[0-9a-f]{64}$/.test(hex) ? hex : void 0;
4443
+ };
4444
+ const sourceSha256 = hashLine(sourceHashMarker);
4445
+ const specSha256 = hashLine(specHashMarker);
4435
4446
  return {
4436
4447
  file,
4437
4448
  lemmas: lemmas.join("\n").trim(),
4438
- proofs: new Map([...proofs].map(([k, v]) => [k, v.join("\n").replace(/\s+$/, "")]))
4449
+ proofs: new Map([...proofs].map(([k, v]) => [k, v.join("\n").replace(/\s+$/, "")])),
4450
+ ...sourceSha256 === void 0 ? {} : { sourceSha256 },
4451
+ ...specSha256 === void 0 ? {} : { specSha256 }
4439
4452
  };
4440
4453
  }
4441
4454
  /** The file refused: none of its proofs is used, and every property it names says why. */
@@ -4474,6 +4487,54 @@ function axiomsOf(messages, line, theorem) {
4474
4487
  function provesExactly(messages, line, theorem) {
4475
4488
  return onlyAt(messages, line) === `${theorem} : s_${theorem}`;
4476
4489
  }
4490
+ // packages/prover-lean/src/goals.ts
4491
+ /** The proof file's name beside a spec file: `domain.props.lean` for `domain.props.ts`. */
4492
+ function proofFileFor(specFile) {
4493
+ return specFile.replace(/\.ts$/, ".lean");
4494
+ }
4495
+ /** The goal file's name beside a spec file: `domain.props.goals.lean` for `domain.props.ts`. */
4496
+ function goalFileFor(specFile) {
4497
+ return specFile.replace(/\.ts$/, ".goals.lean");
4498
+ }
4499
+ /** A line of generated commentary: one a proof file may hold, or a note that it was left out. */
4500
+ const commentLine = (text) => refusedIn(text) === void 0 ? text : "-- (a line left out: it held a word a proof file may not use)";
4501
+ const comment = (text) => text.split("\n").map((l) => commentLine(l.length > 0 ? `-- ${l}` : "--")).join("\n");
4502
+ /**
4503
+ * Render the goal file: the header with the hashes, each goal described
4504
+ * in comments (the proof file's lemma area, where comments cost nothing),
4505
+ * then one open `-- proof:` part per goal at the end, since everything
4506
+ * after a `-- proof:` line belongs to that proof. The text avoids every
4507
+ * word a supplied proof may not use, so the file copied as is reads as a
4508
+ * proof file with open proofs: every generated line is checked, and one
4509
+ * that would refuse the file (a reason Lean gave, a file or function name
4510
+ * that is itself a refused word) is left out, with a note in its place.
4511
+ * The function is named by its Lean identifier, as the statement names it.
4512
+ */
4513
+ function renderGoals(input) {
4514
+ const header = [
4515
+ `-- Open proof goals for ${input.specFile}, written by Eutaxy's Lean engine (Lean ${leanVersion}).`,
4516
+ "-- Each goal below is a property the tactic script could not close, with the statement Eutaxy",
4517
+ "-- emits for it. To supply proofs, copy this file to",
4518
+ `-- ${proofFileFor(input.specFile)} beside the spec file, put lemmas above the \`-- proof:\` lines and`,
4519
+ "-- tactics under each, and run the engine again (eutaxy report --prover lean). The hashes tie the",
4520
+ "-- proofs to these versions of the module and the spec: once either changes, the proofs are stale",
4521
+ "-- until the goals are written again.",
4522
+ `${sourceHashMarker}${input.sourceSha256}`,
4523
+ `${specHashMarker}${input.specSha256}`
4524
+ ];
4525
+ const described = input.goals.map((g) => [
4526
+ commentLine(`-- goal: ${g.property}, a property of ${ident$1.fn(g.function)}`),
4527
+ commentLine(`-- Lean said: ${g.reason}`),
4528
+ "-- statement:",
4529
+ comment(g.statement.replace(/^/gm, " "))
4530
+ ].join("\n"));
4531
+ const open = input.goals.map((g) => `-- proof: ${g.property}\n -- tactics here`);
4532
+ return `${[
4533
+ header.map(commentLine).join("\n"),
4534
+ ...described,
4535
+ ...open
4536
+ ].join("\n\n")}\n`;
4537
+ }
4477
4538
  // packages/prover-lean/src/prove.ts
4478
4539
  /**
4479
4540
  * The engine: a module's functions through the subset reader, the emitter
@@ -4541,7 +4602,11 @@ function prepare$1(input) {
4541
4602
  })));
4542
4603
  const specErrors = specs.errors;
4543
4604
  const proofFile = input.specPath?.replace(/\.ts$/, ".lean");
4544
- const supplied = proofFile !== void 0 && existsSync(proofFile) ? readSupplied(basename(proofFile), readFileSync(proofFile, "utf8")) : void 0;
4605
+ let supplied = proofFile !== void 0 && existsSync(proofFile) ? readSupplied(basename(proofFile), readFileSync(proofFile, "utf8")) : void 0;
4606
+ if (supplied && !supplied.refused) {
4607
+ const stale = staleness(supplied, input);
4608
+ if (stale !== void 0) supplied = refuse(supplied, stale);
4609
+ }
4545
4610
  try {
4546
4611
  return {
4547
4612
  module,
@@ -4567,6 +4632,17 @@ function prepare$1(input) {
4567
4632
  };
4568
4633
  }
4569
4634
  }
4635
+ const sha256 = (text) => createHash("sha256").update(text).digest("hex");
4636
+ /** Why a proof file is stale, when it names the hashes of the files it was written for and either moved. */
4637
+ function staleness(supplied, input) {
4638
+ const moved = [];
4639
+ if (supplied.sourceSha256 !== void 0 && supplied.sourceSha256 !== sha256(input.source)) moved.push("the module");
4640
+ if (supplied.specSha256 !== void 0 && input.specPath !== void 0 && existsSync(input.specPath)) {
4641
+ if (supplied.specSha256 !== sha256(readFileSync(input.specPath, "utf8"))) moved.push("the spec file");
4642
+ }
4643
+ if (moved.length === 0) return void 0;
4644
+ return `${supplied.file} is stale: ${moved.join(" and ")} changed since its proofs were written (the hashes it names no longer match); write the goals again and bring the proofs over`;
4645
+ }
4570
4646
  /**
4571
4647
  * A supplied proof's outcome: given up on when its lemmas or its tactics
4572
4648
  * do not compile, or when it rests on an axiom beyond Lean's standard
@@ -4670,10 +4746,23 @@ async function proveModule$1(input) {
4670
4746
  } : unknown$1("gave_up", `Lean could not close the proof: ${failed[0].message.split("\n")[0]}`)
4671
4747
  });
4672
4748
  }
4749
+ const goals = [];
4750
+ for (const fn of inSubset) for (const property of fn.properties) {
4751
+ if (property.kind !== "forall") continue;
4752
+ const r = results.find((x) => x.function === fn.name && x.property === property.name);
4753
+ if (r?.outcome.kind !== "UNKNOWN" || r.outcome.cause !== "gave_up") continue;
4754
+ goals.push({
4755
+ function: fn.name,
4756
+ property: property.name,
4757
+ statement: stated(property, module).text,
4758
+ reason: r.outcome.reason
4759
+ });
4760
+ }
4673
4761
  return {
4674
4762
  results,
4675
4763
  lean,
4676
- specErrors
4764
+ specErrors,
4765
+ goals
4677
4766
  };
4678
4767
  }
4679
4768
  /** The engine as a `Prover`: available when the pinned toolchain is installed. */
@@ -5935,45 +6024,6 @@ export default defineConfig({
5935
6024
  });
5936
6025
  `;
5937
6026
  }
5938
- // packages/cli/src/regression.ts
5939
- /** A Vitest regression test for a Cloudflare scenario, to run under the Cloudflare Vitest plugin. */
5940
- function cloudflareRegressionTest(verdict, options) {
5941
- const bindings = Object.keys(options.schemaPaths).sort();
5942
- const withExports = options.exports === true || options.workflows === true;
5943
- const imports = [
5944
- "import { createCloudflarePlatform } from \"eutaxy/cloudflare\";",
5945
- "import { env } from \"cloudflare:workers\";",
5946
- ...options.durableObjects ? ["import * as cloudflareTest from \"cloudflare:test\";"] : [],
5947
- `import scenario from ${JSON.stringify(options.scenarioPath)};`,
5948
- ...bindings.map((b) => `import schema_${b} from ${JSON.stringify(`${options.schemaPaths[b]}?raw`)};`),
5949
- withExports ? `import * as worker from ${JSON.stringify(options.workerPath)};` : `import handler from ${JSON.stringify(options.workerPath)};`,
5950
- ...(options.specModules ?? []).map((m, i) => `import * as core_${i} from ${JSON.stringify(m.path)};`)
5951
- ];
5952
- const schemas = `{ ${bindings.map((b) => `${b}: schema_${b}`).join(", ")} }`;
5953
- const retries = options.maxRetries === void 0 ? "" : `, maxRetries: ${options.maxRetries}`;
5954
- const objects = options.durableObjects ? ", durableObjects: cloudflareTest" : "";
5955
- return emitRegressionTest(verdict, {
5956
- imports,
5957
- platform: `createCloudflarePlatform({ env, ${withExports ? "handler: worker.default" : "handler"}, schemas: ${schemas}${retries}${objects}${withExports ? ", exports: worker" : ""} })`,
5958
- scenario: options.budgetMs === void 0 ? "scenario" : `{ ...scenario, bounds: { ...scenario.bounds, budgetMs: ${options.budgetMs} } }`,
5959
- ...options.expect ? { expect: options.expect } : {},
5960
- ...options.engineModule ? { engineModule: options.engineModule } : {},
5961
- ...options.specModules && options.specModules.length > 0 ? { observe: options.specModules.map((m, i) => ({
5962
- namespace: `core_${i}`,
5963
- functions: m.functions
5964
- })) } : {}
5965
- });
5966
- }
5967
- // packages/cli/src/keys.ts
5968
- /** How the two halves of `eutaxy check` name a module next to the scenario. Imports nothing, so workerd can load it. */
5969
- /** Normalize a module path from a scenario's `specs` to a key: "./domain.ts". */
5970
- function specKey(path) {
5971
- return `./${path.split("\\").join("/").replace(/^(\.\/)+/, "")}`;
5972
- }
5973
- /** The key Vite's `import.meta.glob` gives a path next to the scenario, seen from `.eutaxy/`. */
5974
- function globKey(path) {
5975
- return `.${specKey(path)}`;
5976
- }
5977
6027
  const skipDirs = /* @__PURE__ */ new Set([
5978
6028
  "node_modules",
5979
6029
  ".eutaxy",
@@ -6083,7 +6133,7 @@ function enginesNamed(names) {
6083
6133
  * module's source, the outcomes folded into the simulator's verdicts.
6084
6134
  * An engine that is not installed proves nothing and says so.
6085
6135
  */
6086
- async function proveSpecs(dir, observed, specs, engines, modules = findSpecModules(dir)) {
6136
+ async function proveSpecs(dir, observed, specs, engines, modules = findSpecModules(dir), onReport) {
6087
6137
  let out = specs;
6088
6138
  for (const m of observed) {
6089
6139
  const key = specKey(m.module);
@@ -6092,16 +6142,20 @@ async function proveSpecs(dir, observed, specs, engines, modules = findSpecModul
6092
6142
  if (!found || withSpecs.length === 0) continue;
6093
6143
  const source = readFileSync(found.path, "utf8");
6094
6144
  const reports = [];
6095
- for (const engine of engines) reports.push({
6096
- engine: engine.name,
6097
- proofs: await engine.prove({
6098
- source,
6099
- specs: found.specs,
6100
- functions: withSpecs,
6101
- modulePath: found.path,
6102
- specPath: found.specPath
6103
- })
6104
- });
6145
+ for (const engine of engines) {
6146
+ const report = {
6147
+ engine: engine.name,
6148
+ proofs: await engine.prove({
6149
+ source,
6150
+ specs: found.specs,
6151
+ functions: withSpecs,
6152
+ modulePath: found.path,
6153
+ specPath: found.specPath
6154
+ })
6155
+ };
6156
+ reports.push(report);
6157
+ onReport?.(found, report);
6158
+ }
6105
6159
  out = aggregate(key, out, reports);
6106
6160
  }
6107
6161
  return out;
@@ -6182,9 +6236,10 @@ async function runCheck(o) {
6182
6236
  o.stderr(`no wrangler config found next to the scenario; pass --wrangler <path>\n`);
6183
6237
  return exitCodes.error;
6184
6238
  }
6239
+ const stamp = `${process.pid}-${randomBytes(3).toString("hex")}`;
6185
6240
  const workDir = join(dir, ".eutaxy");
6186
- const testPath = join(workDir, `${name}.check.test.ts`);
6187
- const configPath = join(workDir, "vitest.config.mts");
6241
+ const testPath = join(workDir, `${name}.${stamp}.check.test.ts`);
6242
+ const configPath = join(workDir, `vitest.config.${stamp}.mts`);
6188
6243
  mkdirSync(workDir, { recursive: true });
6189
6244
  try {
6190
6245
  writeFileSync(testPath, checkTestSource({
@@ -6199,7 +6254,7 @@ async function runCheck(o) {
6199
6254
  mkdirSync(dirname(join(workDir, f.name)), { recursive: true });
6200
6255
  writeFileSync(join(workDir, f.name), f.source);
6201
6256
  }
6202
- const reportPath = join(workDir, "vitest-report.json");
6257
+ const reportPath = join(workDir, `vitest-report.${stamp}.json`);
6203
6258
  rmSync(reportPath, { force: true });
6204
6259
  writeFileSync(configPath, vitestConfigSource(wrangler, testPath, reportPath));
6205
6260
  const { code, output } = await runVitest(vitestBin(dir), configPath, dir);
@@ -6223,14 +6278,16 @@ async function runCheck(o) {
6223
6278
  }
6224
6279
  specs = await proveSpecs(dir, transport.observed ?? [], specs, named.engines, specModules);
6225
6280
  }
6226
- const printed = o.provers && o.provers.length > 0 ? {
6281
+ const regressionPath = verdict.kind === "VIOLATED" && !o.noRegression ? o.out ? resolve(o.cwd, o.out) : join(dir, `${name}.regression.test.ts`) : void 0;
6282
+ const printed = {
6227
6283
  ...transport.report,
6228
- specs
6229
- } : transport.report;
6284
+ ...o.provers && o.provers.length > 0 ? { specs } : {},
6285
+ ...regressionPath === void 0 ? {} : { regressionTest: toPosix(relative(o.cwd, regressionPath) || regressionPath) }
6286
+ };
6230
6287
  if (o.json) o.stdout(`${canonicalJson(printed)}\n`);
6231
6288
  else o.stdout(`${renderText(verdict)}\n${specs.length > 0 ? `\n${renderSpecs(specs)}\n` : ""}`);
6232
- if (verdict.kind === "VIOLATED" && !o.noRegression) {
6233
- const outPath = o.out ? resolve(o.cwd, o.out) : join(dir, `${name}.regression.test.ts`);
6289
+ if (regressionPath !== void 0) {
6290
+ const outPath = regressionPath;
6234
6291
  const outDir = dirname(outPath);
6235
6292
  const schemaPaths = {};
6236
6293
  for (const step of transport.setup) if (step.kind === "d1") schemaPaths[String(step["binding"])] = toPosix(relative(outDir, resolve(dir, String(step["schemaFile"]))));
@@ -6254,12 +6311,22 @@ async function runCheck(o) {
6254
6311
  if (verdict.kind !== "VIOLATED" && specs.some((v) => v.kind === "REFUTED" || v.kind === "CONFLICT")) return exitCodes.VIOLATED;
6255
6312
  return exitCodes[verdict.kind];
6256
6313
  } finally {
6257
- if (!o.keep) rmSync(workDir, {
6258
- recursive: true,
6259
- force: true
6260
- });
6314
+ if (!o.keep) cleanUp(workDir, stamp);
6261
6315
  }
6262
6316
  }
6317
+ /**
6318
+ * Remove this run's files; the shared ones and the directory go only when
6319
+ * no other run's files are left there (another check may still be using
6320
+ * them).
6321
+ */
6322
+ function cleanUp(workDir, stamp) {
6323
+ if (!existsSync(workDir)) return;
6324
+ for (const f of readdirSync(workDir)) if (f.includes(`.${stamp}.`)) rmSync(join(workDir, f), { force: true });
6325
+ if (!readdirSync(workDir).some((f) => /\.check\.test\.ts$|^vitest\.config\..*\.mts$|^vitest-report\./.test(f))) rmSync(workDir, {
6326
+ recursive: true,
6327
+ force: true
6328
+ });
6329
+ }
6263
6330
  // packages/cli/src/archive.ts
6264
6331
  /**
6265
6332
  * Reading the two archive formats the prover releases come in, with Node's
@@ -6896,6 +6963,31 @@ function testModule(m, seed, budgetMs, stderr) {
6896
6963
  });
6897
6964
  });
6898
6965
  }
6966
+ /**
6967
+ * Write a module's open Lean goals beside its spec file as
6968
+ * `<spec>.goals.lean`, a proof file with every proof open, and list them.
6969
+ * No open goal removes a goal file left from an earlier run.
6970
+ */
6971
+ function writeGoals(m, goals, cwd) {
6972
+ const path = goalFileFor(m.specPath);
6973
+ if (goals.length === 0) {
6974
+ rmSync(path, { force: true });
6975
+ return [];
6976
+ }
6977
+ const sha = (text) => createHash("sha256").update(text).digest("hex");
6978
+ writeFileSync(path, renderGoals({
6979
+ specFile: basename(m.specPath),
6980
+ sourceSha256: sha(readFileSync(m.path, "utf8")),
6981
+ specSha256: sha(readFileSync(m.specPath, "utf8")),
6982
+ goals
6983
+ }));
6984
+ const file = relative(cwd, path).split("\\").join("/");
6985
+ return goals.map((g) => ({
6986
+ module: m.key,
6987
+ file,
6988
+ ...g
6989
+ }));
6990
+ }
6899
6991
  async function runReport(o) {
6900
6992
  const root = resolve(o.cwd, o.dir ?? ".");
6901
6993
  let engines = [];
@@ -6914,10 +7006,22 @@ async function runReport(o) {
6914
7006
  o.stderr(`cannot read ${root}: ${err instanceof Error ? err.message : String(err)}\n`);
6915
7007
  return exitCodes.error;
6916
7008
  }
7009
+ if (o.only !== void 0) {
7010
+ const spec = resolve(o.cwd, o.only);
7011
+ modules = modules.filter((m) => m.specPath === spec);
7012
+ if (modules.length === 0) {
7013
+ o.stderr(`no spec file ${spec} under ${root}\n`);
7014
+ return exitCodes.error;
7015
+ }
7016
+ }
6917
7017
  if (modules.length === 0) {
6918
7018
  o.stderr(`no spec files (*.props.ts) under ${root}\n`);
6919
7019
  return exitCodes.error;
6920
7020
  }
7021
+ if (o.goals && !engines.some((e) => e.name === leanProver.name)) {
7022
+ o.stderr("--goals needs the lean engine among --prover\n");
7023
+ return exitCodes.error;
7024
+ }
6921
7025
  const errors = modules.flatMap((m) => m.specs.errors.map((e) => `${m.key}${e.line > 0 ? `:${e.line}` : ""}: ${e.message}`));
6922
7026
  if (errors.length > 0) {
6923
7027
  for (const e of errors) o.stderr(`${e}\n`);
@@ -6925,13 +7029,501 @@ async function runReport(o) {
6925
7029
  }
6926
7030
  let specs = [];
6927
7031
  for (const m of modules) specs = [...specs, ...await testModule(m, o.seed ?? "report", o.moduleBudgetMs ?? 6e4, o.stderr)];
7032
+ const goals = [];
6928
7033
  if (engines.length > 0) specs = await proveSpecs(root, modules.map((m) => ({
6929
7034
  module: m.key,
6930
7035
  functions: m.specs.functions.map((f) => f.name)
6931
- })), specs, engines, modules);
6932
- o.stdout(`${o.json ? renderSpecReportJson(specs) : renderSpecReport(specs)}\n`);
7036
+ })), specs, engines, modules, o.goals ? (m, report) => {
7037
+ if (report.engine !== leanProver.name) return;
7038
+ if (report.proofs.goals === void 0) return;
7039
+ goals.push(...writeGoals(m, report.proofs.goals, o.cwd));
7040
+ } : void 0);
7041
+ if (o.json) {
7042
+ const json = JSON.parse(renderSpecReportJson(specs));
7043
+ o.stdout(`${canonicalJson({
7044
+ ...json,
7045
+ ...o.goals ? { goals } : {}
7046
+ })}\n`);
7047
+ } else {
7048
+ o.stdout(`${renderSpecReport(specs)}\n`);
7049
+ if (o.goals) o.stdout(goals.length === 0 ? "\nNo open Lean goals.\n" : `\n${goals.length} open Lean goal${goals.length === 1 ? "" : "s"} written to ${[...new Set(goals.map((g) => g.file))].join(", ")}\n`);
7050
+ }
6933
7051
  return specs.some((v) => v.kind === "REFUTED" || v.kind === "CONFLICT") ? exitCodes.VIOLATED : exitCodes.BOUNDED;
6934
7052
  }
7053
+ // packages/cli/src/version.ts
7054
+ /** The published package's version, as the MCP server reports it; the release tooling keeps it in step. */
7055
+ const eutaxyVersion = "0.13.0";
7056
+ // packages/cli/src/mcp.ts
7057
+ /**
7058
+ * `eutaxy mcp`: a Model Context Protocol server over stdio, so a coding
7059
+ * agent runs the loop "check, read the report, fix or prove, check again"
7060
+ * through one tool. One JSON-RPC message per line on stdin and stdout,
7061
+ * logs on stderr, exit when stdin closes; written with the standard
7062
+ * library alone. It speaks both eras of the protocol: the stateless
7063
+ * `2026-07-28` revision, every request carrying its version and client
7064
+ * capabilities in `_meta` and `server/discover` answering what is
7065
+ * supported; and the `2025-11-25` revision (and its predecessors) with the
7066
+ * `initialize` handshake today's clients open with. The tools are pure
7067
+ * functions of the repository's files that return the JSON report, as
7068
+ * structured content beside its text; a verdict is a result whatever it
7069
+ * says, and only a command that could not run is a tool error. Eutaxy
7070
+ * never calls a model: every verdict depends only on files.
7071
+ */
7072
+ /** The protocol revisions served: the stateless one by `_meta`, the handshake ones by `initialize`. */
7073
+ const modernVersions = ["2026-07-28"];
7074
+ const legacyVersions = [
7075
+ "2025-11-25",
7076
+ "2025-06-18",
7077
+ "2025-03-26",
7078
+ "2024-11-05"
7079
+ ];
7080
+ const protocolVersionKey = "io.modelcontextprotocol/protocolVersion";
7081
+ const clientCapabilitiesKey = "io.modelcontextprotocol/clientCapabilities";
7082
+ const serverInfoKey = "io.modelcontextprotocol/serverInfo";
7083
+ const serverInfo = {
7084
+ name: "eutaxy",
7085
+ version: eutaxyVersion
7086
+ };
7087
+ const instructions = [
7088
+ "Eutaxy checks Cloudflare Workers by deterministic simulation and proves properties of their pure TypeScript core.",
7089
+ "`check` runs a scenario file (*.sim.ts) and returns the verdict: BOUNDED (no violation within the bounds), VIOLATED (with the shrunk schedule, and a regression test written beside the scenario that replays it), or UNSUPPORTED.",
7090
+ "`report` runs every spec file (*.props.ts) under a directory through the TESTED rung and, with engines named, the PROVEN rung.",
7091
+ "`goals` lists the properties the Lean engine could not prove and writes each module's open goals beside its spec file as <spec>.goals.lean, a proof file with every proof open: copy it to <spec>.lean, add lemmas and tactics, then call `prove` on the spec file. A proof whose source or spec changed since the goals were written is stale, never PROVEN.",
7092
+ "`prover_status` says which proof engines are installed; `eutaxy prover install lean` or `smt` installs one.",
7093
+ "Verdicts depend only on files in the repository; nothing here calls a model."
7094
+ ].join("\n");
7095
+ const realRunners = {
7096
+ check: runCheck,
7097
+ report: runReport,
7098
+ status: async () => {
7099
+ const engines = [];
7100
+ for (const [name, engine] of Object.entries(provers)) {
7101
+ const a = await engine.available();
7102
+ engines.push({
7103
+ name,
7104
+ ..."unavailable" in a ? {
7105
+ installed: false,
7106
+ reason: a.unavailable
7107
+ } : {
7108
+ installed: true,
7109
+ version: a.version
7110
+ }
7111
+ });
7112
+ }
7113
+ return { engines };
7114
+ }
7115
+ };
7116
+ var ToolError = class extends Error {};
7117
+ /** A command's exit code and what it printed. */
7118
+ async function capture(run) {
7119
+ let stdout = "";
7120
+ let stderr = "";
7121
+ return {
7122
+ code: await run((t) => {
7123
+ stdout += t;
7124
+ }, (t) => {
7125
+ stderr += t;
7126
+ }),
7127
+ stdout,
7128
+ stderr
7129
+ };
7130
+ }
7131
+ /** The report a command printed as JSON, or a tool error with what it said instead. */
7132
+ function reported(what, r) {
7133
+ if (r.code === exitCodes.error) throw new ToolError(`${what} could not run (exit 3): ${r.stderr.trim() || r.stdout.trim()}`);
7134
+ try {
7135
+ return JSON.parse(r.stdout);
7136
+ } catch {
7137
+ throw new ToolError(`${what} printed no JSON report: ${(r.stdout + r.stderr).trim()}`);
7138
+ }
7139
+ }
7140
+ const str = (args, key, required = false) => {
7141
+ const v = args[key];
7142
+ if (v === void 0) {
7143
+ if (required) throw new ToolError(`${key} is required`);
7144
+ return;
7145
+ }
7146
+ if (typeof v !== "string" || v.length === 0) throw new ToolError(`${key} must be a non-empty string`);
7147
+ return v;
7148
+ };
7149
+ const bool = (args, key) => {
7150
+ const v = args[key];
7151
+ if (v === void 0) return void 0;
7152
+ if (typeof v !== "boolean") throw new ToolError(`${key} must be a boolean`);
7153
+ return v;
7154
+ };
7155
+ const positiveInt = (args, key) => {
7156
+ const v = args[key];
7157
+ if (v === void 0) return void 0;
7158
+ if (typeof v !== "number" || !Number.isInteger(v) || v <= 0) throw new ToolError(`${key} must be a positive integer`);
7159
+ return v;
7160
+ };
7161
+ const strings = (args, key) => {
7162
+ const v = args[key];
7163
+ if (v === void 0) return void 0;
7164
+ if (!Array.isArray(v) || !v.every((x) => typeof x === "string" && x.length > 0)) throw new ToolError(`${key} must be an array of non-empty strings`);
7165
+ return v;
7166
+ };
7167
+ const only = (args, allowed) => {
7168
+ const extra = Object.keys(args).find((k) => !allowed.includes(k));
7169
+ if (extra !== void 0) throw new ToolError(`unknown argument ${extra}; the arguments are ${allowed.join(", ")}`);
7170
+ };
7171
+ const engineNames = Object.keys(provers);
7172
+ const proversSchema = {
7173
+ type: "array",
7174
+ items: {
7175
+ type: "string",
7176
+ enum: engineNames
7177
+ },
7178
+ description: `Proof engines for the PROVEN rung: ${engineNames.join(", ")}`
7179
+ };
7180
+ const asResult = (structured, isError = false) => ({
7181
+ structured,
7182
+ text: JSON.stringify(structured, null, 2),
7183
+ ...isError ? { isError: true } : {}
7184
+ });
7185
+ const tools = [
7186
+ {
7187
+ name: "check",
7188
+ title: "Check a scenario",
7189
+ description: "Run a scenario file (*.sim.ts) in the simulator and return the JSON report: the verdict (BOUNDED, VIOLATED with the shrunk schedule, or UNSUPPORTED), the spec verdicts, and on a violation the path of the regression test written beside the scenario (regressionTest). Exit code 1 is a violation or a refuted spec, not an error.",
7190
+ inputSchema: {
7191
+ type: "object",
7192
+ properties: {
7193
+ scenario: {
7194
+ type: "string",
7195
+ description: "Path of the scenario file, relative to the working directory"
7196
+ },
7197
+ wrangler: {
7198
+ type: "string",
7199
+ description: "Wrangler config path; default: the one beside the scenario"
7200
+ },
7201
+ seed: {
7202
+ type: "string",
7203
+ description: "Exploration seed; default: the scenario file name"
7204
+ },
7205
+ maxRuns: {
7206
+ type: "integer",
7207
+ minimum: 1,
7208
+ description: "Cap on exploration runs"
7209
+ },
7210
+ budgetMs: {
7211
+ type: "integer",
7212
+ minimum: 1,
7213
+ description: "Time budget in milliseconds, replacing the scenario's"
7214
+ },
7215
+ exhaustive: {
7216
+ type: "boolean",
7217
+ description: "Run every schedule within the bounds once"
7218
+ },
7219
+ provers: proversSchema,
7220
+ regression: {
7221
+ type: "boolean",
7222
+ description: "Write the regression test on a violation; default true"
7223
+ },
7224
+ out: {
7225
+ type: "string",
7226
+ description: "Where to write the regression test"
7227
+ }
7228
+ },
7229
+ required: ["scenario"],
7230
+ additionalProperties: false
7231
+ },
7232
+ async run(args, ctx, runners) {
7233
+ only(args, [
7234
+ "scenario",
7235
+ "wrangler",
7236
+ "seed",
7237
+ "maxRuns",
7238
+ "budgetMs",
7239
+ "exhaustive",
7240
+ "provers",
7241
+ "regression",
7242
+ "out"
7243
+ ]);
7244
+ const scenario = str(args, "scenario", true);
7245
+ const wrangler = str(args, "wrangler");
7246
+ const seed = str(args, "seed");
7247
+ const maxRuns = positiveInt(args, "maxRuns");
7248
+ const budgetMs = positiveInt(args, "budgetMs");
7249
+ const engines = strings(args, "provers");
7250
+ const out = str(args, "out");
7251
+ const r = await capture((stdout, stderr) => runners.check({
7252
+ scenario,
7253
+ cwd: ctx.cwd,
7254
+ ...wrangler === void 0 ? {} : { wrangler },
7255
+ ...seed === void 0 ? {} : { seed },
7256
+ ...maxRuns === void 0 ? {} : { maxRuns },
7257
+ ...budgetMs === void 0 ? {} : { budgetMs },
7258
+ exhaustive: bool(args, "exhaustive") === true,
7259
+ ...engines === void 0 ? {} : { provers: engines },
7260
+ json: true,
7261
+ ...out === void 0 ? {} : { out },
7262
+ noRegression: bool(args, "regression") === false,
7263
+ expectViolation: false,
7264
+ keep: false,
7265
+ stdout,
7266
+ stderr
7267
+ }));
7268
+ return asResult({
7269
+ exitCode: r.code,
7270
+ report: reported("check", r)
7271
+ });
7272
+ }
7273
+ },
7274
+ {
7275
+ name: "report",
7276
+ title: "Report on the spec files",
7277
+ description: "Run every spec file (*.props.ts) under a directory through the TESTED rung and, with engines named, the PROVEN rung; return the JSON report of spec verdicts. Exit code 1 is a refuted or conflicting spec, not an error.",
7278
+ inputSchema: {
7279
+ type: "object",
7280
+ properties: {
7281
+ dir: {
7282
+ type: "string",
7283
+ description: "Directory to search; default: the working directory"
7284
+ },
7285
+ provers: proversSchema,
7286
+ seed: {
7287
+ type: "string",
7288
+ description: "Seed for the TESTED rung; default report"
7289
+ }
7290
+ },
7291
+ additionalProperties: false
7292
+ },
7293
+ async run(args, ctx, runners) {
7294
+ only(args, [
7295
+ "dir",
7296
+ "provers",
7297
+ "seed"
7298
+ ]);
7299
+ const dir = str(args, "dir");
7300
+ const engines = strings(args, "provers");
7301
+ const seed = str(args, "seed");
7302
+ const r = await capture((stdout, stderr) => runners.report({
7303
+ cwd: ctx.cwd,
7304
+ ...dir === void 0 ? {} : { dir },
7305
+ ...engines === void 0 ? {} : { provers: engines },
7306
+ ...seed === void 0 ? {} : { seed },
7307
+ json: true,
7308
+ stdout,
7309
+ stderr
7310
+ }));
7311
+ return asResult({
7312
+ exitCode: r.code,
7313
+ report: reported("report", r)
7314
+ });
7315
+ }
7316
+ },
7317
+ {
7318
+ name: "goals",
7319
+ title: "List the open proof goals",
7320
+ description: "Run the Lean engine on every spec file under a directory and list the properties it could not prove, each with the statement it tried; write each module's open goals beside its spec file as <spec>.goals.lean, a proof file with every proof open (copy it to <spec>.lean, add lemmas and tactics, then call prove). Needs the lean engine installed.",
7321
+ inputSchema: {
7322
+ type: "object",
7323
+ properties: { dir: {
7324
+ type: "string",
7325
+ description: "Directory to search; default: the working directory"
7326
+ } },
7327
+ additionalProperties: false
7328
+ },
7329
+ async run(args, ctx, runners) {
7330
+ only(args, ["dir"]);
7331
+ const dir = str(args, "dir");
7332
+ const r = await capture((stdout, stderr) => runners.report({
7333
+ cwd: ctx.cwd,
7334
+ ...dir === void 0 ? {} : { dir },
7335
+ provers: ["lean"],
7336
+ goals: true,
7337
+ json: true,
7338
+ stdout,
7339
+ stderr
7340
+ }));
7341
+ return asResult({
7342
+ exitCode: r.code,
7343
+ report: reported("goals", r)
7344
+ });
7345
+ }
7346
+ },
7347
+ {
7348
+ name: "prove",
7349
+ title: "Check the proofs supplied for a spec file",
7350
+ description: "Run the Lean engine on one module, the one whose spec file (*.props.ts) is given, with the proofs supplied beside it in <spec>.lean, and return its spec verdicts: PROVEN where a proof closes (Lean's kernel checked it against the statement Eutaxy emitted), UNKNOWN with the reason where it does not, or where the proof file is stale (written for another version of the module or the spec).",
7351
+ inputSchema: {
7352
+ type: "object",
7353
+ properties: { spec: {
7354
+ type: "string",
7355
+ description: "Path of the spec file, relative to the working directory"
7356
+ } },
7357
+ required: ["spec"],
7358
+ additionalProperties: false
7359
+ },
7360
+ async run(args, ctx, runners) {
7361
+ only(args, ["spec"]);
7362
+ const spec = str(args, "spec", true);
7363
+ const r = await capture((stdout, stderr) => runners.report({
7364
+ cwd: ctx.cwd,
7365
+ dir: dirname(spec),
7366
+ only: spec,
7367
+ provers: ["lean"],
7368
+ json: true,
7369
+ stdout,
7370
+ stderr
7371
+ }));
7372
+ return asResult({
7373
+ exitCode: r.code,
7374
+ report: reported("prove", r)
7375
+ });
7376
+ }
7377
+ },
7378
+ {
7379
+ name: "prover_status",
7380
+ title: "Which proof engines are installed",
7381
+ description: "For each proof engine (lean, smt): whether its pinned toolchain is installed and its version, or why not and how to install it (eutaxy prover install <name>).",
7382
+ inputSchema: {
7383
+ type: "object",
7384
+ additionalProperties: false
7385
+ },
7386
+ async run(args, _ctx, runners) {
7387
+ only(args, []);
7388
+ return asResult(await runners.status());
7389
+ }
7390
+ }
7391
+ ];
7392
+ const errorResponse = (id, code, message, data) => ({
7393
+ jsonrpc: "2.0",
7394
+ id,
7395
+ error: {
7396
+ code,
7397
+ message,
7398
+ ...data === void 0 ? {} : { data }
7399
+ }
7400
+ });
7401
+ /** A result in the requester's era: the stateless one carries `resultType` and the server's identity. */
7402
+ const resultResponse = (req, result) => ({
7403
+ jsonrpc: "2.0",
7404
+ id: req.id,
7405
+ result: req.modern ? {
7406
+ resultType: "complete",
7407
+ ...result,
7408
+ _meta: { [serverInfoKey]: serverInfo }
7409
+ } : result
7410
+ });
7411
+ const toolListing = () => tools.map((t) => ({
7412
+ name: t.name,
7413
+ title: t.title,
7414
+ description: t.description,
7415
+ inputSchema: t.inputSchema
7416
+ }));
7417
+ async function callTool(req, ctx) {
7418
+ const name = req.params["name"];
7419
+ const tool = tools.find((t) => t.name === name);
7420
+ if (typeof name !== "string" || !tool) return errorResponse(req.id, -32602, `Unknown tool: ${String(name)}`);
7421
+ const args = req.params["arguments"] ?? {};
7422
+ if (typeof args !== "object" || args === null || Array.isArray(args)) return errorResponse(req.id, -32602, "arguments must be an object");
7423
+ const runners = {
7424
+ ...realRunners,
7425
+ ...ctx.runners
7426
+ };
7427
+ let result;
7428
+ try {
7429
+ result = await tool.run(args, ctx, runners);
7430
+ } catch (err) {
7431
+ const message = err instanceof Error ? err.message : String(err);
7432
+ result = {
7433
+ structured: { error: message },
7434
+ text: message,
7435
+ isError: true
7436
+ };
7437
+ }
7438
+ return resultResponse(req, {
7439
+ content: [{
7440
+ type: "text",
7441
+ text: result.text
7442
+ }],
7443
+ structuredContent: result.structured,
7444
+ isError: result.isError === true
7445
+ });
7446
+ }
7447
+ /**
7448
+ * One line in, at most one line out: the response to a request, nothing
7449
+ * for a notification. A request of the stateless era whose version is not
7450
+ * served gets the `UnsupportedProtocolVersion` error with what is.
7451
+ */
7452
+ async function handleLine(line, ctx) {
7453
+ let message;
7454
+ try {
7455
+ message = JSON.parse(line);
7456
+ } catch {
7457
+ return JSON.stringify(errorResponse(null, -32700, "Parse error"));
7458
+ }
7459
+ if (Array.isArray(message)) return JSON.stringify(errorResponse(null, -32600, "Invalid Request: batches are not supported"));
7460
+ if (typeof message !== "object" || message === null) return JSON.stringify(errorResponse(null, -32600, "Invalid Request"));
7461
+ const m = message;
7462
+ const id = m["id"];
7463
+ const idOk = typeof id === "string" || typeof id === "number";
7464
+ if (m["jsonrpc"] !== "2.0" || typeof m["method"] !== "string") return JSON.stringify(errorResponse(idOk ? id : null, -32600, "Invalid Request"));
7465
+ if (id === void 0) return void 0;
7466
+ if (!idOk) return JSON.stringify(errorResponse(null, -32600, "Invalid Request: id must be a string or a number"));
7467
+ const params = typeof m["params"] === "object" && m["params"] !== null ? m["params"] : {};
7468
+ const meta = typeof params["_meta"] === "object" && params["_meta"] !== null ? params["_meta"] : {};
7469
+ const requested = meta[protocolVersionKey];
7470
+ const req = {
7471
+ id,
7472
+ method: m["method"],
7473
+ params,
7474
+ modern: typeof requested === "string"
7475
+ };
7476
+ if (req.modern) {
7477
+ if (!modernVersions.includes(requested)) return JSON.stringify(errorResponse(req.id, -32022, "Unsupported protocol version", {
7478
+ supported: [...modernVersions],
7479
+ requested
7480
+ }));
7481
+ if (typeof meta[clientCapabilitiesKey] !== "object" || meta[clientCapabilitiesKey] === null) return JSON.stringify(errorResponse(req.id, -32602, `Invalid params: _meta.${clientCapabilitiesKey} is required`));
7482
+ }
7483
+ let response;
7484
+ try {
7485
+ response = await dispatch(req, ctx);
7486
+ } catch (err) {
7487
+ response = errorResponse(req.id, -32603, `Internal error: ${err instanceof Error ? err.message : String(err)}`);
7488
+ }
7489
+ return JSON.stringify(response);
7490
+ }
7491
+ async function dispatch(req, ctx) {
7492
+ switch (req.method) {
7493
+ case "initialize": {
7494
+ const asked = req.params["protocolVersion"];
7495
+ const version = typeof asked === "string" && legacyVersions.includes(asked) ? asked : legacyVersions[0];
7496
+ return resultResponse(req, {
7497
+ protocolVersion: version,
7498
+ capabilities: { tools: {} },
7499
+ serverInfo,
7500
+ instructions
7501
+ });
7502
+ }
7503
+ case "ping": return resultResponse(req, {});
7504
+ case "server/discover": return resultResponse(req, {
7505
+ supportedVersions: [...modernVersions],
7506
+ capabilities: { tools: {} },
7507
+ instructions
7508
+ });
7509
+ case "tools/list": return resultResponse(req, { tools: toolListing() });
7510
+ case "tools/call": return callTool(req, ctx);
7511
+ default: return errorResponse(req.id, -32601, `Method not found: ${req.method}`);
7512
+ }
7513
+ }
7514
+ /** Serve on the process's standard streams until stdin closes. Requests are answered one at a time, in order. */
7515
+ async function serveStdio(ctx) {
7516
+ const lines = createInterface({
7517
+ input: process.stdin,
7518
+ crlfDelay: Number.POSITIVE_INFINITY
7519
+ });
7520
+ for await (const line of lines) {
7521
+ if (line.trim().length === 0) continue;
7522
+ const out = await handleLine(line, ctx);
7523
+ if (out !== void 0) process.stdout.write(`${out}\n`);
7524
+ }
7525
+ return exitCodes.BOUNDED;
7526
+ }
6935
7527
  // packages/cli/src/main.ts
6936
7528
  const usage = `eutaxy — deterministic simulation checks and spec verdicts for Cloudflare Workers
6937
7529
 
@@ -6939,6 +7531,7 @@ Usage:
6939
7531
  eutaxy check <scenario.sim.ts> [options]
6940
7532
  eutaxy report [dir] [--prover <names>] [--seed <seed>] [--json]
6941
7533
  eutaxy prover install <lean|smt> [--from <url or directory>] [--json]
7534
+ eutaxy mcp
6942
7535
 
6943
7536
  check options:
6944
7537
  --wrangler <path> wrangler config (default: wrangler.jsonc/json/toml beside the scenario)
@@ -6965,6 +7558,13 @@ downloaded from the upstream GitHub release, or from a mirror or offline directo
6965
7558
  holding the same file (--from), and checked against the engine's SHA-256 before it is
6966
7559
  unpacked. Nothing is downloaded at any other time.
6967
7560
 
7561
+ report options: --goals writes each module's open Lean goals beside its spec file as
7562
+ <spec>.goals.lean (a proof file with every proof open) and lists them; needs --prover lean.
7563
+
7564
+ mcp serves the Model Context Protocol over stdio (one JSON-RPC message per line, logs on
7565
+ stderr) for a coding agent: tools check, report, goals, prove and prover_status, each
7566
+ returning the JSON report. Point the agent's MCP configuration at "eutaxy mcp".
7567
+
6968
7568
  Exit codes: 0 BOUNDED, 1 VIOLATED or a REFUTED or CONFLICT spec, 2 UNSUPPORTED, 3 error.
6969
7569
  report: 0, or 1 for a REFUTED or CONFLICT spec, 3 error. prover install: 0, or 3.
6970
7570
  `;
@@ -6975,7 +7575,8 @@ async function main(argv, io) {
6975
7575
  "expect-violation",
6976
7576
  "keep",
6977
7577
  "help",
6978
- "exhaustive"
7578
+ "exhaustive",
7579
+ "goals"
6979
7580
  ]);
6980
7581
  const command = positionals[0];
6981
7582
  if (!command || command === "help" || flags["help"] === true) {
@@ -6996,6 +7597,16 @@ async function main(argv, io) {
6996
7597
  }
6997
7598
  const str = (k) => typeof flags[k] === "string" ? flags[k] : void 0;
6998
7599
  const provers = (str("prover") ?? "").split(",").map((n) => n.trim()).filter((n) => n.length > 0);
7600
+ if (command === "mcp") {
7601
+ if (positionals.length !== 1 || Object.keys(flags).length > 0) {
7602
+ io.stderr(`mcp takes no arguments\n\n${usage}`);
7603
+ return exitCodes.error;
7604
+ }
7605
+ return serveStdio({
7606
+ cwd: io.cwd,
7607
+ log: io.stderr
7608
+ });
7609
+ }
6999
7610
  if (command === "prover") {
7000
7611
  const names = Object.keys(toolchains).join("|");
7001
7612
  if (positionals[1] !== "install" || positionals.length !== 3) {
@@ -7028,7 +7639,8 @@ async function main(argv, io) {
7028
7639
  const other = Object.keys(flags).find((k) => ![
7029
7640
  "prover",
7030
7641
  "seed",
7031
- "json"
7642
+ "json",
7643
+ "goals"
7032
7644
  ].includes(k));
7033
7645
  if (other !== void 0) {
7034
7646
  io.stderr(`report does not take --${other}\n`);
@@ -7040,6 +7652,7 @@ async function main(argv, io) {
7040
7652
  ...dir === void 0 ? {} : { dir },
7041
7653
  ...provers.length > 0 ? { provers } : {},
7042
7654
  ...str("seed") ? { seed: str("seed") } : {},
7655
+ ...flags["goals"] === true ? { goals: true } : {},
7043
7656
  json: flags["json"] === true,
7044
7657
  stdout: io.stdout,
7045
7658
  stderr: io.stderr
@@ -7084,3972 +7697,6 @@ async function main(argv, io) {
7084
7697
  stderr: io.stderr
7085
7698
  });
7086
7699
  }
7087
- // packages/cloudflare/src/check.ts
7088
- /** Explore a scenario on a platform and return its verdict. */
7089
- function check(spec, platform, options = { seed: spec.name }) {
7090
- return explore(spec, platform, options);
7091
- }
7092
- /** For use from a test: passes only when the scenario is BOUNDED. */
7093
- async function expectHolds(spec, platform, options) {
7094
- const verdict = await check(spec, platform, options);
7095
- if (verdict.kind !== "BOUNDED") throw new Error(describeVerdict(verdict));
7096
- }
7097
- // packages/cloudflare/src/d1.ts
7098
- /**
7099
- * The D1 binding proxy. Every statement execution is an effect point: the
7100
- * engine decides the fault, the real Miniflare-backed D1 performs the query,
7101
- * and the log records call, result and fault in the documented shape.
7102
- */
7103
- /** Whether a binding is a D1 database (what the proxies and the differential wrap). */
7104
- function isD1(value) {
7105
- return typeof value === "object" && value !== null && typeof value.prepare === "function" && typeof value.batch === "function";
7106
- }
7107
- function point(ctx, target, op, args, allowed) {
7108
- return {
7109
- invocation: ctx.currentInvocation(),
7110
- target,
7111
- op,
7112
- args,
7113
- allowed
7114
- };
7115
- }
7116
- function metaOf(result) {
7117
- return {
7118
- changes: result.meta.changes ?? 0,
7119
- lastRowId: result.meta.last_row_id ?? null
7120
- };
7121
- }
7122
- var StatementProxy = class StatementProxy {
7123
- real;
7124
- target;
7125
- ctx;
7126
- sql;
7127
- params;
7128
- constructor(real, target, ctx, sql, params) {
7129
- this.real = real;
7130
- this.target = target;
7131
- this.ctx = ctx;
7132
- this.sql = sql;
7133
- this.params = params;
7134
- }
7135
- /** The real statement, for `batch()`. */
7136
- get statement() {
7137
- return this.real;
7138
- }
7139
- args() {
7140
- return {
7141
- sql: this.sql,
7142
- params: toJson(this.params)
7143
- };
7144
- }
7145
- bind(...values) {
7146
- return new StatementProxy(this.real.bind(...values), this.target, this.ctx, this.sql, values);
7147
- }
7148
- run() {
7149
- return this.ctx.hooks.effect(point(this.ctx, this.target, "run", this.args(), writeFaults), () => this.real.run(), (r) => metaOf(r));
7150
- }
7151
- all() {
7152
- return this.ctx.hooks.effect(point(this.ctx, this.target, "all", this.args(), readFaults), () => this.real.all(), (r) => ({
7153
- rows: r.results.length,
7154
- changes: r.meta.changes ?? 0
7155
- }));
7156
- }
7157
- first(colName) {
7158
- return this.ctx.hooks.effect(point(this.ctx, this.target, "first", {
7159
- ...this.args(),
7160
- column: colName ?? null
7161
- }, readFaults), () => colName === void 0 ? this.real.first() : this.real.first(colName), (r) => ({ row: toJson(r) }));
7162
- }
7163
- raw(options) {
7164
- return this.ctx.hooks.effect(point(this.ctx, this.target, "raw", this.args(), readFaults), () => options ? this.real.raw(options) : this.real.raw(), (r) => ({ rows: r.length }));
7165
- }
7166
- };
7167
- /** Wrap a D1 binding. Methods not modelled fall through to the real binding and mark the run unsupported. */
7168
- function proxyD1(real, binding, ctx) {
7169
- const target = `D1:${binding}`;
7170
- const modelled = {
7171
- prepare(sql) {
7172
- return new StatementProxy(real.prepare(sql), target, ctx, sql, []);
7173
- },
7174
- batch(statements) {
7175
- const unwrapped = statements.map((s) => s instanceof StatementProxy ? s.statement : s);
7176
- const args = { statements: statements.map((s) => s instanceof StatementProxy ? {
7177
- sql: s.sql,
7178
- params: toJson(s.params)
7179
- } : "<unproxied statement>") };
7180
- return ctx.hooks.effect(point(ctx, target, "batch", args, writeFaults), () => real.batch(unwrapped), (rs) => ({
7181
- changes: rs.reduce((n, r) => n + (r.meta.changes ?? 0), 0),
7182
- statements: rs.length
7183
- }));
7184
- },
7185
- exec(sql) {
7186
- return ctx.hooks.effect(point(ctx, target, "exec", { sql }, writeFaults), () => real.exec(sql), (r) => ({
7187
- count: r.count,
7188
- duration: 0
7189
- }));
7190
- }
7191
- };
7192
- return new Proxy(real, { get(obj, prop, receiver) {
7193
- if (prop in modelled) return modelled[prop];
7194
- const value = Reflect.get(obj, prop, receiver);
7195
- if (typeof value === "function") {
7196
- ctx.hooks.unsupported(`D1 ${binding}.${String(prop)} is not modelled`);
7197
- return value.bind(obj);
7198
- }
7199
- return value;
7200
- } });
7201
- }
7202
- /**
7203
- * Statements in a schema file. Splits on semicolons outside string literals,
7204
- * quoted identifiers and comments, and keeps CREATE TRIGGER bodies (and CASE
7205
- * expressions) whole by tracking BEGIN/CASE ... END nesting.
7206
- */
7207
- function splitSql(sql) {
7208
- const out = [];
7209
- let cur = "";
7210
- let depth = 0;
7211
- let i = 0;
7212
- const isWordChar = (c) => c !== void 0 && /[A-Za-z0-9_]/.test(c);
7213
- while (i < sql.length) {
7214
- const c = sql[i];
7215
- const next = sql[i + 1];
7216
- if (c === "-" && next === "-") {
7217
- while (i < sql.length && sql[i] !== "\n") i++;
7218
- continue;
7219
- }
7220
- if (c === "/" && next === "*") {
7221
- const end = sql.indexOf("*/", i + 2);
7222
- i = end === -1 ? sql.length : end + 2;
7223
- continue;
7224
- }
7225
- if (c === "'" || c === "\"" || c === "`" || c === "[") {
7226
- const close = c === "[" ? "]" : c;
7227
- let j = i + 1;
7228
- for (;;) {
7229
- const k = sql.indexOf(close, j);
7230
- if (k === -1) {
7231
- j = sql.length;
7232
- break;
7233
- }
7234
- if (close !== "]" && sql[k + 1] === close) {
7235
- j = k + 2;
7236
- continue;
7237
- }
7238
- j = k + 1;
7239
- break;
7240
- }
7241
- cur += sql.slice(i, j);
7242
- i = j;
7243
- continue;
7244
- }
7245
- if (isWordChar(c) && !isWordChar(sql[i - 1])) {
7246
- let j = i;
7247
- while (isWordChar(sql[j])) j++;
7248
- const word = sql.slice(i, j);
7249
- const upper = word.toUpperCase();
7250
- if (upper === "BEGIN" || upper === "CASE") depth++;
7251
- else if (upper === "END" && depth > 0) depth--;
7252
- cur += word;
7253
- i = j;
7254
- continue;
7255
- }
7256
- if (c === ";" && depth === 0) {
7257
- const statement = cur.trim();
7258
- if (statement.length > 0) out.push(statement);
7259
- cur = "";
7260
- i++;
7261
- continue;
7262
- }
7263
- cur += c;
7264
- i++;
7265
- }
7266
- const last = cur.trim();
7267
- if (last.length > 0) out.push(last);
7268
- return out;
7269
- }
7270
- /** Drop every user table and re-apply the schema, using the real binding (not an effect). */
7271
- async function resetD1(real, schema) {
7272
- const tables = await real.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' AND name NOT LIKE '\\_cf\\_%' ESCAPE '\\'").all();
7273
- for (const { name } of tables.results) await real.prepare(`DROP TABLE IF EXISTS "${name.replace(/"/g, "\"\"")}"`).run();
7274
- for (const statement of splitSql(schema)) await real.prepare(statement).run();
7275
- }
7276
- /** Every user table's rows, sorted canonically, read through the real binding (not an effect). */
7277
- async function snapshotD1(real) {
7278
- const tables = await real.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' AND name NOT LIKE '\\_cf\\_%' ESCAPE '\\' ORDER BY name").all();
7279
- const out = {};
7280
- for (const { name } of tables.results) out[name] = (await real.prepare(`SELECT * FROM "${name.replace(/"/g, "\"\"")}"`).all()).results.map((r) => toJson(r)).map((j) => [canonicalJson(j), j]).sort((a, b) => a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0).map(([, j]) => j);
7281
- return out;
7282
- }
7283
- // packages/cloudflare/src/background.ts
7284
- const CUT_OFF = ["cut_off"];
7285
- /**
7286
- * The `ExecutionContext` handed to a handler; `waitUntil` work is collected to
7287
- * run after it returns. A rejection is kept in `failures` when given: a
7288
- * scheduled invocation's status is that of its first failed `waitUntil`
7289
- * (Cloudflare, Scheduled handler); a queue or HTTP delivery's is not.
7290
- */
7291
- function executionContext(background, failures) {
7292
- return {
7293
- waitUntil: (promise) => {
7294
- background.push(promise.then(() => void 0, (error) => {
7295
- failures?.push(error);
7296
- }));
7297
- },
7298
- passThroughOnException: () => {},
7299
- props: {}
7300
- };
7301
- }
7302
- /**
7303
- * Background work extends the invocation but never changes the acknowledgement or the response.
7304
- * A cut-off here is the isolate dying after them: work not yet started is lost.
7305
- */
7306
- async function drainBackground(hooks, inv, invocation, target, background) {
7307
- if (background.length === 0 || inv.isCrashed()) return false;
7308
- try {
7309
- hooks.effectSync({
7310
- invocation,
7311
- target,
7312
- op: "background",
7313
- args: { pending: background.length },
7314
- allowed: CUT_OFF
7315
- }, () => null, () => null);
7316
- await Promise.race([hooks.settle(Promise.all(background), invocation), inv.crashed]);
7317
- return false;
7318
- } catch (err) {
7319
- if (!(err instanceof CrashSignal)) throw err;
7320
- return true;
7321
- }
7322
- }
7323
- // packages/cloudflare/src/alarms.ts
7324
- /**
7325
- * Durable Object alarms in virtual time. Eutaxy takes over each object's
7326
- * alarm methods (on its storage and inside transactions), so the runtime
7327
- * never schedules an alarm on the real clock, whose time is far ahead of
7328
- * the virtual one. A set alarm is kept per object, so it survives eviction
7329
- * as a real one does, and becomes an event due at its virtual time; when
7330
- * the run reaches it, the object's `alarm()` handler runs as one effect.
7331
- *
7332
- * Semantics, as Cloudflare documents them (developers.cloudflare.com/
7333
- * durable-objects/api/base/#alarm): an object has one alarm, a later
7334
- * `setAlarm` replaces it, execution is at least once, and a handler that
7335
- * throws is retried with exponential backoff starting at two seconds, up to
7336
- * six retries, with `{ retryCount, isRetry }`. `setAlarm` inside a
7337
- * transaction takes effect only if the transaction commits.
7338
- */
7339
- /** `EventRef.source` of an alarm event. */
7340
- const alarmSource = "durable_object_alarm";
7341
- /** Cloudflare retries a failed alarm handler up to six times, after 2 s, 4 s, 8 s, ... */
7342
- const maxRetries = 6;
7343
- const firstRetryMs = 2e3;
7344
- /** The alarms of one namespace's objects; the platform clears it before each run. */
7345
- var AlarmBook = class {
7346
- entries = /* @__PURE__ */ new Map();
7347
- clear() {
7348
- this.entries.clear();
7349
- }
7350
- entry(id) {
7351
- let e = this.entries.get(id);
7352
- if (!e) {
7353
- e = {
7354
- time: null,
7355
- seq: 0,
7356
- gen: 0,
7357
- firings: 0
7358
- };
7359
- this.entries.set(id, e);
7360
- }
7361
- return e;
7362
- }
7363
- };
7364
- /** One alarm control per object: setting schedules an event at the alarm's virtual time. */
7365
- function alarmControl(book, binding, id, object, hooks) {
7366
- const entry = book.entry(id);
7367
- return {
7368
- get: () => entry.time,
7369
- set: (time) => {
7370
- entry.time = time;
7371
- entry.seq++;
7372
- entry.gen = entry.seq;
7373
- const data = {
7374
- binding,
7375
- gen: entry.gen,
7376
- id,
7377
- object,
7378
- time,
7379
- retryCount: 0
7380
- };
7381
- const now = Date.now();
7382
- hooks().enqueue({
7383
- id: `alarm:${binding}:${object}:${entry.seq}`,
7384
- attempt: 1,
7385
- source: alarmSource,
7386
- data,
7387
- ...time > now ? { at: time } : {}
7388
- });
7389
- },
7390
- delete: () => {
7391
- entry.time = null;
7392
- entry.seq++;
7393
- entry.gen = entry.seq;
7394
- },
7395
- unsupported: (reason) => hooks().unsupported(`Durable Object ${binding} ${object}: ${reason}`)
7396
- };
7397
- }
7398
- /** Storage objects whose alarm methods Eutaxy has taken over (one per live instance). */
7399
- const takenOver = /* @__PURE__ */ new WeakSet();
7400
- const timeOf = (time) => typeof time === "number" ? time : time.getTime();
7401
- /** Storage objects whose alarm was read before Eutaxy took them over (in a constructor). */
7402
- const readBeforeTakeover = /* @__PURE__ */ new WeakSet();
7403
- /** Storage prototypes whose getAlarm records such reads. */
7404
- const watched = /* @__PURE__ */ new WeakSet();
7405
- /**
7406
- * Record reads of the native alarm on storage not yet taken over: a rebuilt
7407
- * object's constructor reads native storage, where Eutaxy's pending alarm is
7408
- * not. The wrapper only records; it returns what the native method returns.
7409
- */
7410
- function watchReads(storage) {
7411
- const proto = Object.getPrototypeOf(storage);
7412
- if (!proto || watched.has(proto) || typeof proto.getAlarm !== "function") return;
7413
- watched.add(proto);
7414
- const native = proto.getAlarm;
7415
- proto.getAlarm = function(...args) {
7416
- if (!takenOver.has(this)) readBeforeTakeover.add(this);
7417
- return native.apply(this, args);
7418
- };
7419
- }
7420
- /**
7421
- * Replace an object's alarm methods so no real alarm is ever scheduled. An
7422
- * alarm the object set before the takeover (in its constructor) is moved
7423
- * over: deleted from the runtime and set on the control, unless an alarm is
7424
- * still pending, which the constructor could not see in native storage
7425
- * (Eutaxy keeps it): then the pending one stays and the run is UNSUPPORTED.
7426
- */
7427
- async function takeOverAlarms(storage, alarm) {
7428
- if (takenOver.has(storage)) return;
7429
- watchReads(storage);
7430
- takenOver.add(storage);
7431
- if (readBeforeTakeover.has(storage) && alarm.get() !== null) alarm.unsupported("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");
7432
- const existing = await storage.getAlarm();
7433
- if (existing !== null) {
7434
- await storage.deleteAlarm();
7435
- if (alarm.get() === null) alarm.set(existing);
7436
- else alarm.unsupported("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");
7437
- }
7438
- const s = storage;
7439
- let inSync = false;
7440
- const outsideSync = (op) => {
7441
- if (inSync) alarm.unsupported(`${op} inside transactionSync() is not modelled`);
7442
- };
7443
- Object.assign(s, {
7444
- setAlarm: async (time) => {
7445
- outsideSync("setAlarm");
7446
- alarm.set(timeOf(time));
7447
- },
7448
- getAlarm: async () => alarm.get(),
7449
- deleteAlarm: async () => {
7450
- outsideSync("deleteAlarm");
7451
- alarm.delete();
7452
- }
7453
- });
7454
- if (typeof s["transactionSync"] === "function") {
7455
- const transactionSync = s["transactionSync"].bind(storage);
7456
- s["transactionSync"] = (callback) => {
7457
- inSync = true;
7458
- try {
7459
- return transactionSync(callback);
7460
- } finally {
7461
- inSync = false;
7462
- }
7463
- };
7464
- }
7465
- const transaction = s["transaction"].bind(storage);
7466
- s["transaction"] = async (callback) => {
7467
- let pending;
7468
- let rolledBack = false;
7469
- const held = {
7470
- setAlarm: async (time) => {
7471
- pending = { time: timeOf(time) };
7472
- },
7473
- getAlarm: async () => pending ? pending.time : alarm.get(),
7474
- deleteAlarm: async () => {
7475
- pending = { time: null };
7476
- }
7477
- };
7478
- const result = await transaction((txn) => {
7479
- pending = void 0;
7480
- rolledBack = false;
7481
- return callback(new Proxy(txn, { get(target, prop) {
7482
- if (typeof prop === "string" && prop in held) return held[prop];
7483
- const value = target[prop];
7484
- if (prop === "rollback" && typeof value === "function") return (...args) => {
7485
- rolledBack = true;
7486
- return value.apply(target, args);
7487
- };
7488
- return typeof value === "function" ? value.bind(target) : value;
7489
- } }));
7490
- });
7491
- if (pending && !rolledBack) {
7492
- if (pending.time === null) alarm.delete();
7493
- else alarm.set(pending.time);
7494
- }
7495
- return result;
7496
- };
7497
- }
7498
- /**
7499
- * Fire an alarm event: skip it when the object's alarm has since moved or
7500
- * been deleted, run `alarm()` as one effect otherwise, and schedule a retry
7501
- * with backoff when the handler fails, crashes, or a fault says it did.
7502
- */
7503
- async function deliverAlarm(event, hooks, maxRedeliveries, d) {
7504
- const a = event.data;
7505
- const entry = d.book.entry(a.id);
7506
- if (entry.gen !== a.gen) return {
7507
- status: "completed",
7508
- followUps: []
7509
- };
7510
- if (a.retryCount === 0) {
7511
- if (entry.time !== a.time) return {
7512
- status: "completed",
7513
- followUps: []
7514
- };
7515
- if (entry.firings >= d.limit) {
7516
- entry.time = null;
7517
- d.bookkeep("alarm_not_fired", {
7518
- object: a.object,
7519
- firings: entry.firings
7520
- });
7521
- return {
7522
- status: "completed",
7523
- followUps: []
7524
- };
7525
- }
7526
- entry.firings++;
7527
- }
7528
- const invocation = invocationOf(event);
7529
- const inv = hooks.startInvocation(invocation);
7530
- const info = {
7531
- retryCount: a.retryCount,
7532
- isRetry: a.retryCount > 0
7533
- };
7534
- const { status } = await runInvocation(hooks, inv, () => hooks.effect({
7535
- invocation,
7536
- target: `DO:${d.binding}`,
7537
- op: "alarm",
7538
- args: {
7539
- object: a.object,
7540
- retryCount: a.retryCount
7541
- },
7542
- allowed: readFaults,
7543
- hostsEffects: true
7544
- }, async () => {
7545
- await d.runAlarm(a.id, a.object, info, a.gen);
7546
- return null;
7547
- }, () => null, {
7548
- onAbandon: () => d.abort(a.id),
7549
- mayPark: () => d.mayPark(a.id)
7550
- }));
7551
- if (status === "crashed") await d.evict(a.id);
7552
- if (status !== "completed") {
7553
- const next = redelivery(event, maxRetries, { maxRedeliveries });
7554
- if (next) {
7555
- const retryAt = Date.now() + firstRetryMs * 2 ** a.retryCount;
7556
- const data = {
7557
- ...a,
7558
- retryCount: a.retryCount + 1
7559
- };
7560
- if (entry.gen === a.gen) entry.time = retryAt;
7561
- hooks.enqueue({
7562
- ...next,
7563
- data,
7564
- at: retryAt
7565
- });
7566
- } else {
7567
- if (entry.gen === a.gen) entry.time = null;
7568
- d.bookkeep("alarm_gave_up", {
7569
- object: a.object,
7570
- retries: a.retryCount
7571
- });
7572
- }
7573
- }
7574
- return {
7575
- status,
7576
- followUps: []
7577
- };
7578
- }
7579
- // packages/cloudflare/src/durable-objects.ts
7580
- /**
7581
- * The Durable Object namespace proxy. The objects are the real ones workerd
7582
- * runs: storage, transactions and the input and output gates are the
7583
- * runtime's own. Eutaxy proxies the boundary a Worker crosses to reach them:
7584
- * every call on a stub is an effect point, so a call can fail before it
7585
- * reaches the object (`crash_before`, `error`), or reach it, commit, and
7586
- * lose its answer (`ambiguous`) or its caller (`crash_after`).
7587
- *
7588
- * Between runs every object is cleared, seeded from the scenario's setup
7589
- * and evicted, so it starts from storage alone; after a run its storage is
7590
- * snapshotted for state invariants. Both go through the Cloudflare Vitest
7591
- * plugin's test helpers. Alarms are taken over on each object's storage and
7592
- * fire in virtual time (see alarms.ts).
7593
- */
7594
- const typed = (helpers) => helpers;
7595
- function isDurableObjectNamespace(value) {
7596
- return typeof value === "object" && value !== null && typeof value.idFromName === "function" && typeof value.get === "function";
7597
- }
7598
- /** How deep each object state is inside blockConcurrencyWhile, while it is. */
7599
- const gateDepth = /* @__PURE__ */ new WeakMap();
7600
- /** Object-state prototypes whose blockConcurrencyWhile records that depth. */
7601
- const gateWatched = /* @__PURE__ */ new WeakSet();
7602
- /**
7603
- * Record when an object holds its input gate with blockConcurrencyWhile,
7604
- * on the state prototype so constructors are covered too; the wrapper only
7605
- * records and calls the native method.
7606
- */
7607
- function watchGate(state) {
7608
- const proto = Object.getPrototypeOf(state);
7609
- if (!proto || gateWatched.has(proto) || typeof proto.blockConcurrencyWhile !== "function") return;
7610
- gateWatched.add(proto);
7611
- const native = proto.blockConcurrencyWhile;
7612
- proto.blockConcurrencyWhile = function(callback) {
7613
- return native.call(this, async () => {
7614
- gateDepth.set(this, (gateDepth.get(this) ?? 0) + 1);
7615
- try {
7616
- return await callback();
7617
- } finally {
7618
- gateDepth.set(this, (gateDepth.get(this) ?? 1) - 1);
7619
- }
7620
- });
7621
- };
7622
- }
7623
- /** Whether the object is inside blockConcurrencyWhile now. */
7624
- function gateHeld(state) {
7625
- return state !== void 0 && (gateDepth.get(state) ?? 0) > 0;
7626
- }
7627
- /** What Eutaxy keeps about one namespace during a run; the platform clears it before each run. */
7628
- var BindingState = class {
7629
- /** Names learned this run (seeded ones come back with the setup), so traces never depend on earlier runs. */
7630
- names = /* @__PURE__ */ new Map();
7631
- /** Ids of the objects a call or an alarm reached this run. */
7632
- touched = /* @__PURE__ */ new Set();
7633
- /** The objects' alarms in virtual time. */
7634
- alarms = new AlarmBook();
7635
- /** Each reached object's live state, so an invocation that crashes inside it can reset it. */
7636
- states = /* @__PURE__ */ new Map();
7637
- /** Whether the object's own effects may wait for a turn: not while it holds its input gate. */
7638
- mayPark(id) {
7639
- return !gateHeld(this.states.get(id));
7640
- }
7641
- clear() {
7642
- this.names.clear();
7643
- this.touched.clear();
7644
- this.alarms.clear();
7645
- this.states.clear();
7646
- }
7647
- /**
7648
- * Reset an object the way a crash does, with `ctx.abort()`, which
7649
- * application code cannot catch: the runtime ends the requests inside it.
7650
- * Called where an injected crash happens inside the object's own work,
7651
- * which is the one place abort() works (from outside, workerd refuses).
7652
- */
7653
- abort(id) {
7654
- const state = this.states.get(id);
7655
- this.states.delete(id);
7656
- try {
7657
- state?.abort("Eutaxy: the invocation crashed inside this object");
7658
- } catch {}
7659
- }
7660
- };
7661
- /** The storage's own alarm deletion, even after Eutaxy replaced the method on it. */
7662
- async function deleteRealAlarm(storage) {
7663
- const proto = Object.getPrototypeOf(storage);
7664
- await (Object.hasOwn(storage, "deleteAlarm") ? proto.deleteAlarm : storage.deleteAlarm)?.call(storage);
7665
- }
7666
- /** An RPC argument as effect-log data; a Request becomes its method and URL. */
7667
- function argument(value) {
7668
- if (value instanceof Request) return {
7669
- method: value.method,
7670
- url: value.url
7671
- };
7672
- return toJson(value);
7673
- }
7674
- /**
7675
- * Whether a result is data the caller holds by value. Anything else (an RPC
7676
- * capability, an object with methods) would let later calls bypass the
7677
- * proxy, so it makes the run UNSUPPORTED.
7678
- */
7679
- function isPlainData(value, depth = 0) {
7680
- if (value === null || value === void 0) return true;
7681
- if (typeof value === "function") return false;
7682
- if (typeof value !== "object") return true;
7683
- if (depth > 8) return false;
7684
- if (value instanceof Response || value instanceof Date) return true;
7685
- if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer) return true;
7686
- const proto = Object.getPrototypeOf(value);
7687
- if (Array.isArray(value)) return value.every((v) => isPlainData(v, depth + 1));
7688
- if (proto !== Object.prototype && proto !== null) return false;
7689
- return Object.values(value).every((v) => isPlainData(v, depth + 1));
7690
- }
7691
- /** An RPC result as effect-log data; a Response becomes its status. */
7692
- function summarize(result) {
7693
- if (result instanceof Response) return {
7694
- status: result.status,
7695
- ok: result.ok
7696
- };
7697
- return toJson(result);
7698
- }
7699
- function proxyNamespace(real, binding, ctx, state, helpers, isReset) {
7700
- const target = `DO:${binding}`;
7701
- const { names, touched, alarms: book } = state;
7702
- const nameOf = (id) => names.get(id.toString()) ?? id.toString();
7703
- function stubFor(stub, id, object) {
7704
- /** Make sure the call may reach the object, and take over its alarms first. */
7705
- async function reach(real) {
7706
- if (!helpers) ctx.hooks.unsupported(`Durable Object binding ${binding} needs the Cloudflare test helpers (pass durableObjects to createCloudflarePlatform)`);
7707
- else if (!isReset()) ctx.hooks.unsupported(`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`);
7708
- else {
7709
- touched.add(id);
7710
- await typed(helpers).runInDurableObject(real, (_instance, live) => {
7711
- watchGate(live);
7712
- state.states.set(id, live);
7713
- return takeOverAlarms(live.storage, alarmControl(book, binding, id, object, () => ctx.hooks));
7714
- });
7715
- }
7716
- }
7717
- /** A result passed back to the Worker; one that is not plain data cannot be followed. */
7718
- function plain(result) {
7719
- if (!isPlainData(result)) ctx.hooks.unsupported(`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`);
7720
- return result;
7721
- }
7722
- /**
7723
- * The promise a call returns. On a real stub it is an RPC promise that
7724
- * pipelines property reads (`stub.getData().value`); this one is not, so
7725
- * a read on it makes the run UNSUPPORTED instead of yielding undefined.
7726
- */
7727
- function pipelineGuard(promise) {
7728
- return new Proxy(promise, { get(target, prop) {
7729
- if (typeof prop === "symbol" || prop === "then" || prop === "catch" || prop === "finally") {
7730
- const value = Reflect.get(target, prop, target);
7731
- return typeof value === "function" ? value.bind(target) : value;
7732
- }
7733
- ctx.hooks.unsupported(`Durable Object ${binding} ${object}: RPC promise pipelining (reading .${prop} on a call's promise) is not supported; await the call first`);
7734
- } });
7735
- }
7736
- /** One effect on the object: a method call, or awaiting an RPC property. */
7737
- function onObject(op, args, perform) {
7738
- return ctx.hooks.effect({
7739
- invocation: ctx.currentInvocation(),
7740
- target,
7741
- op,
7742
- args,
7743
- allowed: writeFaults,
7744
- hostsEffects: true
7745
- }, perform, summarize, {
7746
- onAbandon: () => state.abort(id),
7747
- mayPark: () => state.mayPark(id)
7748
- });
7749
- }
7750
- return new Proxy(stub, { get(real, prop, receiver) {
7751
- if (prop === "then") return void 0;
7752
- if (typeof prop !== "string" || prop === "id" || prop === "name") return Reflect.get(real, prop, receiver);
7753
- const call = (...args) => pipelineGuard(onObject(prop, {
7754
- object,
7755
- args: args.map(argument)
7756
- }, async () => {
7757
- await reach(real);
7758
- const method = real[prop];
7759
- if (typeof method !== "function") throw new TypeError(`${binding} stub has no ${prop}`);
7760
- return plain(await Reflect.apply(method, real, args));
7761
- }));
7762
- const read = () => onObject(prop, {
7763
- object,
7764
- property: true
7765
- }, async () => {
7766
- await reach(real);
7767
- return plain(await real[prop]);
7768
- });
7769
- const awaitable = (onFulfilled, onRejected) => read().then(onFulfilled, onRejected);
7770
- return new Proxy(call, { get(target, key) {
7771
- if (key === "then") return awaitable;
7772
- if (typeof key === "symbol") return Reflect.get(target, key);
7773
- ctx.hooks.unsupported(`Durable Object ${binding} ${object}: RPC promise pipelining (reading .${prop}.${key}) is not supported; await .${prop} first`);
7774
- } });
7775
- } });
7776
- }
7777
- function idFromName(name) {
7778
- const id = real.idFromName(name);
7779
- names.set(id.toString(), name);
7780
- return id;
7781
- }
7782
- return new Proxy(real, { get(target, prop, receiver) {
7783
- switch (prop) {
7784
- case "idFromName": return idFromName;
7785
- case "idFromString": return (hex) => target.idFromString(hex);
7786
- case "newUniqueId": return (options) => {
7787
- ctx.hooks.unsupported(`${binding}.newUniqueId() is random and differs on replay; use idFromName`);
7788
- return target.newUniqueId(options);
7789
- };
7790
- case "get": return (id, options) => stubFor(target.get(id, options), id.toString(), nameOf(id));
7791
- case "getByName": return (name) => {
7792
- const id = idFromName(name);
7793
- return stubFor(target.get(id), id.toString(), name);
7794
- };
7795
- case "jurisdiction": return (jurisdiction) => {
7796
- ctx.hooks.unsupported(`${binding}.jurisdiction() namespaces are not proxied or reset; use the namespace itself`);
7797
- return target.jurisdiction(jurisdiction);
7798
- };
7799
- default: {
7800
- const value = Reflect.get(target, prop, receiver);
7801
- return typeof value === "function" ? value.bind(target) : value;
7802
- }
7803
- }
7804
- } });
7805
- }
7806
- /** Drop an object's instance from outside it; one that is not running has nothing to drop. */
7807
- async function evictObject(real, helpers, id) {
7808
- if (!helpers) return;
7809
- await typed(helpers).evictDurableObject(real.get(real.idFromString(id))).catch(() => {});
7810
- }
7811
- /**
7812
- * Run an object's `alarm()` handler inside it, after taking over its alarms
7813
- * (the instance may be new since the alarm was set).
7814
- */
7815
- function alarmRunner(real, binding, ctx, helpers, state) {
7816
- return async (id, object, info, gen) => {
7817
- if (!helpers) {
7818
- ctx.hooks.unsupported(`Durable Object binding ${binding} needs the Cloudflare test helpers`);
7819
- return;
7820
- }
7821
- state.touched.add(id);
7822
- await typed(helpers).runInDurableObject(real.get(real.idFromString(id)), async (instance, live) => {
7823
- watchGate(live);
7824
- state.states.set(id, live);
7825
- await takeOverAlarms(live.storage, alarmControl(state.alarms, binding, id, object, () => ctx.hooks));
7826
- const entry = state.alarms.entry(id);
7827
- if (entry.gen !== gen) return;
7828
- entry.time = null;
7829
- const handler = instance.alarm;
7830
- if (typeof handler !== "function") {
7831
- ctx.hooks.unsupported(`Durable Object ${binding} ${object} set an alarm but has no alarm() handler`);
7832
- return;
7833
- }
7834
- await handler.call(instance, info);
7835
- });
7836
- };
7837
- }
7838
- /** The objects to reset: every id the namespace has created, plus the setup's named ones. */
7839
- async function objectIds(real, helpers, names, seeded) {
7840
- const ids = /* @__PURE__ */ new Map();
7841
- for (const id of await typed(helpers).listDurableObjectIds(real)) ids.set(id.toString(), id);
7842
- for (const name of seeded) {
7843
- const id = real.idFromName(name);
7844
- names.set(id.toString(), name);
7845
- ids.set(id.toString(), id);
7846
- }
7847
- return [...ids.values()].sort((a, b) => a.toString() < b.toString() ? -1 : 1);
7848
- }
7849
- /**
7850
- * Clear every object of the namespace, write the seeded entries, and evict
7851
- * them all, so each run's first call constructs the object from storage.
7852
- */
7853
- async function resetNamespace(real, helpers, names, objects) {
7854
- const { requested } = await withoutNetwork(() => clearAndSeed(real, helpers, names, objects));
7855
- if (requested) throw new Error("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");
7856
- }
7857
- async function clearAndSeed(real, helpers, names, objects) {
7858
- const ids = await objectIds(real, helpers, names, Object.keys(objects));
7859
- for (const id of ids) {
7860
- const stub = real.get(id);
7861
- const name = names.get(id.toString());
7862
- const entries = name !== void 0 && Object.hasOwn(objects, name) ? objects[name] : void 0;
7863
- await typed(helpers).runInDurableObject(stub, async (_instance, state) => {
7864
- watchGate(state);
7865
- await state.storage.deleteAll();
7866
- await deleteRealAlarm(state.storage);
7867
- if (entries && Object.keys(entries).length > 0) await state.storage.put(entries);
7868
- });
7869
- await typed(helpers).evictDurableObject(stub);
7870
- }
7871
- }
7872
- /**
7873
- * Each object's storage as rows `{ key, value }`, sorted by key, one table
7874
- * per object name. An object no call reached this run still holds exactly
7875
- * its seed (reset left it evicted), so its rows come from the seed and it is
7876
- * not constructed: its constructor would run outside the simulation. Such an
7877
- * object that is running anyway was reached some other way (through another
7878
- * object's own binding): `onIndirect` is told, and the seed is not its state.
7879
- * The tables are the seeded objects and those a call reached, never objects
7880
- * only earlier runs created, so a snapshot depends on this run alone.
7881
- */
7882
- async function snapshotNamespace(real, helpers, names, touched, objects, onIndirect, onUnsupported) {
7883
- const { value, requested } = await withoutNetwork(() => readTables(real, helpers, names, touched, objects, onIndirect, onUnsupported));
7884
- if (requested) onUnsupported("a Durable Object made a request while its storage was being snapshotted");
7885
- return value;
7886
- }
7887
- async function readTables(real, helpers, names, touched, objects, onIndirect, onUnsupported) {
7888
- const out = {};
7889
- for (const id of await objectIds(real, helpers, names, Object.keys(objects))) {
7890
- const name = names.get(id.toString()) ?? id.toString();
7891
- if (!touched.has(id.toString())) {
7892
- if (await typed(helpers).evictDurableObject(real.get(id)).then(() => true, () => false)) onIndirect(name);
7893
- if (!Object.hasOwn(objects, name)) continue;
7894
- }
7895
- const entries = touched.has(id.toString()) ? [...await typed(helpers).runInDurableObject(real.get(id), (_instance, state) => {
7896
- if (!takenOver.has(state.storage)) onUnsupported(`Durable Object ${name} was reset during the run and reconstructed for the snapshot; its constructor ran outside the simulation`);
7897
- return state.storage.list();
7898
- })] : Object.entries(Object.hasOwn(objects, name) ? objects[name] ?? {} : {});
7899
- Object.defineProperty(out, name, {
7900
- value: entries.sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, value]) => ({
7901
- key,
7902
- value: toJson(value)
7903
- })),
7904
- enumerable: true,
7905
- writable: true,
7906
- configurable: true
7907
- });
7908
- }
7909
- return out;
7910
- }
7911
- // packages/cloudflare/src/r2.ts
7912
- /**
7913
- * The R2 binding proxy. Every `put`, `delete`, `get`, `head` and `list` is
7914
- * an effect point against the real Miniflare-backed bucket. A body is read
7915
- * inside its `get`'s effect and handed back in an object with the same
7916
- * fields and body methods: reading it later would be I/O the run cannot
7917
- * see. An object's random `version` and wall-clock `uploaded` are replaced
7918
- * by stand-ins (see `VersionBook`), so traces stay byte-identical.
7919
- */
7920
- /** Whether a binding is an R2 bucket (Miniflare's `R2Bucket`). */
7921
- function isR2(value) {
7922
- if (typeof value !== "object" || value === null) return false;
7923
- const v = value;
7924
- return [
7925
- "head",
7926
- "get",
7927
- "put",
7928
- "delete",
7929
- "list",
7930
- "createMultipartUpload"
7931
- ].every((m) => typeof v[m] === "function");
7932
- }
7933
- /**
7934
- * Stand-ins for the version and upload time of each object version the run
7935
- * sees, in the order it first sees them: versions count up, and the time is
7936
- * the virtual time it was first seen.
7937
- */
7938
- var VersionBook = class {
7939
- seen = /* @__PURE__ */ new Map();
7940
- clear() {
7941
- this.seen.clear();
7942
- }
7943
- standIn(realVersion, at) {
7944
- let s = this.seen.get(realVersion);
7945
- if (!s) {
7946
- s = {
7947
- version: (this.seen.size + 1).toString(16).padStart(32, "0"),
7948
- uploaded: new Date(at)
7949
- };
7950
- this.seen.set(realVersion, s);
7951
- }
7952
- return {
7953
- version: s.version,
7954
- uploaded: new Date(s.uploaded.getTime())
7955
- };
7956
- }
7957
- };
7958
- /** An object's metadata, with stand-ins for its version and upload time. */
7959
- function metadata(real, book, at) {
7960
- const { version, uploaded } = book.standIn(real.version, at);
7961
- return {
7962
- key: real.key,
7963
- version,
7964
- size: real.size,
7965
- etag: real.etag,
7966
- httpEtag: real.httpEtag,
7967
- uploaded,
7968
- httpMetadata: real.httpMetadata,
7969
- customMetadata: real.customMetadata,
7970
- range: real.range,
7971
- checksums: real.checksums,
7972
- storageClass: real.storageClass,
7973
- ssecKeyMd5: real.ssecKeyMd5,
7974
- writeHttpMetadata: (headers) => real.writeHttpMetadata(headers)
7975
- };
7976
- }
7977
- /**
7978
- * The bytes behind each body stream the proxy hands out. The stream itself
7979
- * has no known length, which the runtime's put requires, so a put given one
7980
- * (copying an object) is given its bytes instead.
7981
- */
7982
- const buffered = /* @__PURE__ */ new WeakMap();
7983
- /**
7984
- * An object with its body, already read: the stream and the body methods
7985
- * share one consumption, as a real body's do. A method fails once the
7986
- * stream is read, cancelled or locked by a reader; the stream ends empty
7987
- * once a method has read the body.
7988
- */
7989
- function withBody(meta, bytes) {
7990
- let used = false;
7991
- let stream;
7992
- const take = () => {
7993
- if (used || stream?.locked) throw new TypeError("Body has already been used");
7994
- used = true;
7995
- return bytes.slice();
7996
- };
7997
- return Object.defineProperties(meta, {
7998
- body: {
7999
- enumerable: true,
8000
- get: () => {
8001
- stream ??= new ReadableStream({
8002
- pull(controller) {
8003
- if (!used) controller.enqueue(bytes.slice());
8004
- used = true;
8005
- controller.close();
8006
- },
8007
- cancel() {
8008
- used = true;
8009
- }
8010
- }, { highWaterMark: 0 });
8011
- buffered.set(stream, take);
8012
- return stream;
8013
- }
8014
- },
8015
- bodyUsed: {
8016
- enumerable: true,
8017
- get: () => used
8018
- },
8019
- arrayBuffer: { value: async () => take().buffer },
8020
- bytes: { value: async () => take() },
8021
- text: { value: async () => new TextDecoder().decode(take()) },
8022
- json: { value: async () => JSON.parse(new TextDecoder().decode(take())) },
8023
- blob: { value: async () => new Blob([take()]) }
8024
- });
8025
- }
8026
- /** Conditions as the trace keeps them: a `Headers` object by its entries. */
8027
- function conditions(onlyIf) {
8028
- if (onlyIf === void 0) return {};
8029
- return { onlyIf: onlyIf instanceof Headers ? Object.fromEntries(onlyIf.entries()) : onlyIf };
8030
- }
8031
- /** What the trace keeps of a get's options: the conditions and range, never an encryption key. */
8032
- function getArgs(key, options) {
8033
- return toJson({
8034
- key,
8035
- ...conditions(options?.onlyIf),
8036
- ...options?.range === void 0 ? {} : { range: options.range }
8037
- });
8038
- }
8039
- /** What the trace keeps of a put's options: the conditions and metadata, not checksums or keys. */
8040
- function putArgs(options) {
8041
- if (!options) return {};
8042
- return toJson({
8043
- ...conditions(options.onlyIf),
8044
- ...options.customMetadata === void 0 ? {} : { customMetadata: options.customMetadata },
8045
- ...options.httpMetadata === void 0 ? {} : { httpMetadata: options.httpMetadata }
8046
- });
8047
- }
8048
- function proxyR2(real, binding, ctx, book) {
8049
- const target = `R2:${binding}`;
8050
- const point = (op, args, allowed) => ({
8051
- invocation: ctx.currentInvocation(),
8052
- target,
8053
- op,
8054
- args,
8055
- allowed
8056
- });
8057
- const notModelled = (what) => {
8058
- const reason = `R2 ${binding}: ${what} is not modelled`;
8059
- ctx.hooks.unsupported(reason);
8060
- throw new Error(`eutaxy: ${reason}`);
8061
- };
8062
- /** Date conditions compare the store's real upload time, not the stand-in the Worker saw. */
8063
- const checkConditions = (onlyIf) => {
8064
- if (onlyIf instanceof Headers ? ["if-modified-since", "if-unmodified-since"].some((h) => onlyIf.has(h)) : typeof onlyIf === "object" && onlyIf !== null && ("uploadedBefore" in onlyIf || "uploadedAfter" in onlyIf)) ctx.hooks.unsupported(`R2 ${binding}: conditions on the upload time are not modelled`);
8065
- };
8066
- const described = (o) => o === null ? { found: false } : {
8067
- found: true,
8068
- key: o.key,
8069
- size: o.size,
8070
- etag: o.etag
8071
- };
8072
- return {
8073
- put: (key, value, options) => ctx.hooks.effect(point("put", {
8074
- key,
8075
- ...putArgs(options)
8076
- }, writeFaults), async () => {
8077
- checkConditions(options?.onlyIf);
8078
- const read = value instanceof ReadableStream ? buffered.get(value) : void 0;
8079
- const stored = await real.put(key, read ? read() : value, options);
8080
- return stored === null ? null : metadata(stored, book, Date.now());
8081
- }, (o) => o === null ? { stored: false } : {
8082
- stored: true,
8083
- size: o.size,
8084
- etag: o.etag
8085
- }),
8086
- delete: (keys) => ctx.hooks.effect(point("delete", { keys: typeof keys === "string" ? [keys] : [...keys] }, writeFaults), () => real.delete(keys), () => null),
8087
- get: (key, options) => ctx.hooks.effect(point("get", getArgs(key, options), readFaults), async () => {
8088
- checkConditions(options?.onlyIf);
8089
- const o = await real.get(key, options);
8090
- if (o === null) return null;
8091
- const meta = metadata(o, book, Date.now());
8092
- if (!("body" in o)) return meta;
8093
- return withBody(meta, new Uint8Array(await o.arrayBuffer()));
8094
- }, (o) => ({
8095
- ...described(o),
8096
- ...o !== null ? { body: "body" in o } : {}
8097
- })),
8098
- head: (key) => ctx.hooks.effect(point("head", { key }, readFaults), async () => {
8099
- const o = await real.head(key);
8100
- return o === null ? null : metadata(o, book, Date.now());
8101
- }, described),
8102
- list: (options) => ctx.hooks.effect(point("list", toJson(options ?? {}), readFaults), async () => {
8103
- const listed = await real.list(options);
8104
- const at = Date.now();
8105
- return {
8106
- ...listed,
8107
- objects: listed.objects.map((o) => metadata(o, book, at))
8108
- };
8109
- }, (l) => ({
8110
- keys: l.objects.map((o) => o.key),
8111
- truncated: l.truncated,
8112
- delimitedPrefixes: l.delimitedPrefixes
8113
- })),
8114
- createMultipartUpload: () => notModelled("createMultipartUpload()"),
8115
- resumeMultipartUpload: () => notModelled("resumeMultipartUpload()")
8116
- };
8117
- }
8118
- /** Every object of the bucket, through all pages of a listing. */
8119
- async function allObjects(real) {
8120
- const out = [];
8121
- let cursor;
8122
- for (;;) {
8123
- const page = await real.list({
8124
- include: ["customMetadata", "httpMetadata"],
8125
- ...cursor === void 0 ? {} : { cursor }
8126
- });
8127
- out.push(...page.objects);
8128
- if (!page.truncated) return out;
8129
- cursor = page.cursor;
8130
- }
8131
- }
8132
- /** Empty the bucket and put its seeds, before a run. */
8133
- async function resetR2(real, seeds) {
8134
- const keys = (await allObjects(real)).map((o) => o.key);
8135
- for (let i = 0; i < keys.length; i += 1e3) await real.delete(keys.slice(i, i + 1e3));
8136
- for (const [key, seed] of Object.entries(seeds)) if (typeof seed === "string") await real.put(key, seed);
8137
- else await real.put(key, seed.value, {
8138
- ...seed.customMetadata ? { customMetadata: { ...seed.customMetadata } } : {},
8139
- ...seed.httpMetadata ? { httpMetadata: { ...seed.httpMetadata } } : {}
8140
- });
8141
- }
8142
- /** Largest object whose text the snapshot keeps. */
8143
- const snapshotTextLimit = 4096;
8144
- /**
8145
- * The bucket's objects as rows `{ key, size, etag, customMetadata,
8146
- * httpMetadata, text? }` by key, `text` for an object of up to 4 KiB that is
8147
- * valid UTF-8. Versions and upload times are left out: they are the store's,
8148
- * not the Worker's.
8149
- */
8150
- async function snapshotR2(real) {
8151
- const rows = [];
8152
- const objects = (await allObjects(real)).sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
8153
- for (const o of objects) {
8154
- let text;
8155
- if (o.size <= snapshotTextLimit) {
8156
- const body = await real.get(o.key);
8157
- if (body && "body" in body) try {
8158
- text = new TextDecoder("utf-8", {
8159
- fatal: true,
8160
- ignoreBOM: false
8161
- }).decode(await body.arrayBuffer());
8162
- } catch {}
8163
- }
8164
- rows.push(toJson({
8165
- key: o.key,
8166
- size: o.size,
8167
- etag: o.etag,
8168
- customMetadata: o.customMetadata ?? {},
8169
- httpMetadata: o.httpMetadata ?? {},
8170
- ...text === void 0 ? {} : { text }
8171
- }));
8172
- }
8173
- return rows;
8174
- }
8175
- // packages/cloudflare/src/cron.ts
8176
- const fields = [
8177
- {
8178
- name: "minute",
8179
- min: 0,
8180
- max: 59
8181
- },
8182
- {
8183
- name: "hour",
8184
- min: 0,
8185
- max: 23
8186
- },
8187
- {
8188
- name: "day of month",
8189
- min: 1,
8190
- max: 31
8191
- },
8192
- {
8193
- name: "month",
8194
- min: 1,
8195
- max: 12,
8196
- names: [
8197
- "jan",
8198
- "feb",
8199
- "mar",
8200
- "apr",
8201
- "may",
8202
- "jun",
8203
- "jul",
8204
- "aug",
8205
- "sep",
8206
- "oct",
8207
- "nov",
8208
- "dec"
8209
- ],
8210
- firstName: 1
8211
- },
8212
- {
8213
- name: "weekday",
8214
- min: 1,
8215
- max: 7,
8216
- names: [
8217
- "sun",
8218
- "mon",
8219
- "tue",
8220
- "wed",
8221
- "thu",
8222
- "fri",
8223
- "sat"
8224
- ],
8225
- firstName: 1
8226
- }
8227
- ];
8228
- function value(token, field) {
8229
- const lower = token.toLowerCase();
8230
- if (field.names) {
8231
- const i = field.names.indexOf(lower);
8232
- if (i >= 0) return (field.firstName ?? 0) + i;
8233
- }
8234
- if (!/^\d+$/.test(token)) throw new Error(`${field.name}: ${JSON.stringify(token)} is not a value`);
8235
- const n = Number(token);
8236
- if (n < field.min || n > field.max) throw new Error(`${field.name}: ${n} is outside ${field.min}-${field.max}`);
8237
- return n;
8238
- }
8239
- function parseField(text, field) {
8240
- if (/[LW#]/i.test(text) && !field.names?.some((n) => text.toLowerCase().includes(n))) throw new Error(`${field.name}: L, W and # are not modelled`);
8241
- const out = /* @__PURE__ */ new Set();
8242
- for (const part of text.split(",")) {
8243
- const pieces = part.split("/");
8244
- if (pieces.length > 2 || part === "") throw new Error(`${field.name}: ${JSON.stringify(part)} is not a value, range or step`);
8245
- const [rangeText, stepText] = pieces;
8246
- let step = 1;
8247
- if (stepText !== void 0) {
8248
- if (!/^\d+$/.test(stepText) || Number(stepText) < 1) throw new Error(`${field.name}: step ${JSON.stringify(stepText)} is not a positive number`);
8249
- step = Number(stepText);
8250
- }
8251
- let from;
8252
- let to;
8253
- if (rangeText === "*") {
8254
- from = field.min;
8255
- to = field.max;
8256
- } else if (rangeText.includes("-")) {
8257
- const ends = rangeText.split("-");
8258
- if (ends.length !== 2) throw new Error(`${field.name}: ${JSON.stringify(rangeText)} is not a range`);
8259
- const [a, b] = ends;
8260
- from = value(a, field);
8261
- to = value(b, field);
8262
- if (from > to) throw new Error(`${field.name}: range ${rangeText} runs backwards`);
8263
- } else {
8264
- from = value(rangeText, field);
8265
- to = stepText === void 0 ? from : field.max;
8266
- }
8267
- for (let v = from; v <= to; v += step) out.add(v);
8268
- }
8269
- return out;
8270
- }
8271
- /** Parse an expression; throws with the field and the problem when it is not one Cloudflare accepts. */
8272
- function parseCron(expression) {
8273
- const parts = expression.trim().split(/\s+/);
8274
- if (parts.length !== 5) throw new Error(`a cron expression has five fields, got ${parts.length}: ${JSON.stringify(expression)}`);
8275
- const [minute, hour, dom, month, weekday] = parts;
8276
- return {
8277
- minutes: parseField(minute, fields[0]),
8278
- hours: parseField(hour, fields[1]),
8279
- daysOfMonth: parseField(dom, fields[2]),
8280
- months: parseField(month, fields[3]),
8281
- weekdays: parseField(weekday, fields[4]),
8282
- anyDayOfMonth: dom === "*",
8283
- anyWeekday: weekday === "*"
8284
- };
8285
- }
8286
- /** Whether the minute starting at `time` (ms since the epoch, UTC) matches. */
8287
- function cronMatches(schedule, time) {
8288
- const d = new Date(time);
8289
- if (!schedule.minutes.has(d.getUTCMinutes()) || !schedule.hours.has(d.getUTCHours())) return false;
8290
- if (!schedule.months.has(d.getUTCMonth() + 1)) return false;
8291
- const dayOk = schedule.daysOfMonth.has(d.getUTCDate());
8292
- const weekdayOk = schedule.weekdays.has(d.getUTCDay() + 1);
8293
- if (!schedule.anyDayOfMonth && !schedule.anyWeekday) return dayOk || weekdayOk;
8294
- return dayOk && weekdayOk;
8295
- }
8296
- const minuteMs = 6e4;
8297
- /**
8298
- * Between two matches of any expression Cloudflare accepts lie at most eight
8299
- * years (the 29th of February across a century's missing leap year); an
8300
- * expression with no match in that span never fires.
8301
- */
8302
- const longestGapMs = 4743360 * minuteMs;
8303
- /** The first `count` tick times at or after `from`, each the start of a matching minute. */
8304
- function cronTicks(expression, from, count) {
8305
- const schedule = parseCron(expression);
8306
- const out = [];
8307
- let t = Math.ceil(from / minuteMs) * minuteMs;
8308
- let horizon = t + longestGapMs;
8309
- while (out.length < count) {
8310
- if (t > horizon) throw new Error(`${JSON.stringify(expression)} never fires`);
8311
- if (cronMatches(schedule, t)) {
8312
- out.push(t);
8313
- horizon = t + longestGapMs;
8314
- }
8315
- t += minuteMs;
8316
- }
8317
- return out;
8318
- }
8319
- // packages/cloudflare/src/scenario.ts
8320
- /**
8321
- * Typed construction of scenario specs for Cloudflare Workers. Everything here
8322
- * produces the plain-data `ScenarioSpec` from core; this module only knows the
8323
- * Cloudflare shapes (queues, D1 bindings) and the effect conventions the
8324
- * proxies follow.
8325
- */
8326
- function http(requests, options = {}) {
8327
- return {
8328
- kind: "http",
8329
- requests: requests.map((r, i) => ({
8330
- id: r.id ?? `req-${i + 1}`,
8331
- method: (r.method ?? (r.body === void 0 ? "GET" : "POST")).toUpperCase(),
8332
- path: r.path,
8333
- headers: r.headers ?? {},
8334
- ...r.body === void 0 ? {} : { body: r.body }
8335
- })),
8336
- retries: options.retries ?? 3,
8337
- retryOn: options.retryOn ?? "non-2xx",
8338
- ...options.delaysMs === void 0 ? {} : { delaysMs: [...options.delaysMs] },
8339
- ...options.deadlineMs === void 0 ? {} : { deadlineMs: options.deadlineMs }
8340
- };
8341
- }
8342
- function rpc(calls, options = {}) {
8343
- return {
8344
- kind: "rpc",
8345
- ...options.entrypoint === void 0 ? {} : { entrypoint: options.entrypoint },
8346
- calls: calls.map((c, i) => ({
8347
- id: c.id ?? `call-${i + 1}`,
8348
- method: c.method,
8349
- args: [...c.args ?? []]
8350
- })),
8351
- retries: options.retries ?? 0,
8352
- ...options.delaysMs === void 0 ? {} : { delaysMs: [...options.delaysMs] },
8353
- ...options.deadlineMs === void 0 ? {} : { deadlineMs: options.deadlineMs }
8354
- };
8355
- }
8356
- /** The target of a call's effects: the method, under the entrypoint's name when the drive names one. */
8357
- function rpcTarget(drive, method) {
8358
- return `Rpc:${drive.entrypoint === void 0 ? method : `${drive.entrypoint}.${method}`}`;
8359
- }
8360
- function cron(expression, options = {}) {
8361
- const count = options.ticks ?? 1;
8362
- return {
8363
- kind: "cron",
8364
- cron: expression,
8365
- ticks: (Number.isInteger(count) && count >= 1 ? cronTicks(expression, virtualEpoch, count) : []).map((at, i) => ({
8366
- id: `tick-${i + 1}`,
8367
- at
8368
- })),
8369
- retries: options.retries ?? 0
8370
- };
8371
- }
8372
- /** The drive's events as they are first delivered: one per message, request or call, attempt 1. */
8373
- function driveEvents(drive) {
8374
- switch (drive.kind) {
8375
- case "queue": return drive.messages.map((m) => ({
8376
- id: m.id,
8377
- attempt: 1,
8378
- data: m.body
8379
- }));
8380
- case "http": return drive.requests.map((r) => ({
8381
- id: r.id,
8382
- attempt: 1,
8383
- data: r
8384
- }));
8385
- case "rpc": return drive.calls.map((c) => ({
8386
- id: c.id,
8387
- attempt: 1,
8388
- data: c
8389
- }));
8390
- case "cron": return drive.ticks.map((t) => ({
8391
- id: t.id,
8392
- attempt: 1,
8393
- data: {
8394
- cron: drive.cron,
8395
- scheduledTime: t.at
8396
- },
8397
- at: t.at
8398
- }));
8399
- }
8400
- }
8401
- /** The drive with only the named events kept, for shrinking. */
8402
- function restrictDrive(drive, keepIds) {
8403
- const keep = (id) => keepIds.includes(id);
8404
- switch (drive.kind) {
8405
- case "queue": return {
8406
- ...drive,
8407
- messages: drive.messages.filter((m) => keep(m.id))
8408
- };
8409
- case "http": return {
8410
- ...drive,
8411
- requests: drive.requests.filter((r) => keep(r.id))
8412
- };
8413
- case "rpc": return {
8414
- ...drive,
8415
- calls: drive.calls.filter((c) => keep(c.id))
8416
- };
8417
- case "cron": return {
8418
- ...drive,
8419
- ticks: drive.ticks.filter((t) => keep(t.id))
8420
- };
8421
- }
8422
- }
8423
- function durableObject(binding, objects = {}, options = {}) {
8424
- return {
8425
- kind: "durable_object",
8426
- binding,
8427
- objects,
8428
- ...options.alarmsPerObject === void 0 ? {} : { alarmsPerObject: options.alarmsPerObject }
8429
- };
8430
- }
8431
- function r2Bucket(binding, objects = {}) {
8432
- return {
8433
- kind: "r2",
8434
- binding,
8435
- objects
8436
- };
8437
- }
8438
- /**
8439
- * Selects an R2 bucket's operations that completed, a `put` by default; a
8440
- * put whose `onlyIf` failed stored nothing and is not selected, as a D1
8441
- * write that changed no row is not.
8442
- */
8443
- function r2Op(binding, op = "put") {
8444
- const target = `R2:${binding}`;
8445
- return op === "put" ? {
8446
- target,
8447
- op,
8448
- kind: "result",
8449
- where: { "result.stored": true }
8450
- } : {
8451
- target,
8452
- op,
8453
- kind: "result"
8454
- };
8455
- }
8456
- /** A bucket's objects at the end of the run as rows `{ key, size, etag, customMetadata, httpMetadata, text? }`. */
8457
- function r2Rows(binding, where) {
8458
- const target = `R2:${binding}`;
8459
- return where ? {
8460
- target,
8461
- table: "objects",
8462
- where
8463
- } : {
8464
- target,
8465
- table: "objects"
8466
- };
8467
- }
8468
- /**
8469
- * Every row the query returns is named by some row of `in` (its `column`
8470
- * equals the row's value at `path`), as with a foreign key.
8471
- */
8472
- function references(name, query, path, inQuery, column) {
8473
- return {
8474
- kind: "references",
8475
- name,
8476
- query,
8477
- path,
8478
- in: inQuery,
8479
- column
8480
- };
8481
- }
8482
- function workflow(binding, className, options = {}) {
8483
- return {
8484
- kind: "workflow",
8485
- binding,
8486
- className,
8487
- ...options.name === void 0 ? {} : { name: options.name }
8488
- };
8489
- }
8490
- function service(binding, options = {}) {
8491
- return {
8492
- kind: "service",
8493
- binding,
8494
- ...options.methods === void 0 ? {} : { methods: options.methods },
8495
- ...options.fetch === void 0 ? {} : { fetch: [...options.fetch] }
8496
- };
8497
- }
8498
- /** Selects the calls through a service binding that completed, one method's or all. */
8499
- function serviceCall(binding, method) {
8500
- return {
8501
- target: `Service:${binding}`,
8502
- ...method === void 0 ? {} : { op: method },
8503
- kind: "result"
8504
- };
8505
- }
8506
- /** Selects a Workflow's step attempts, optionally of one step; a failed attempt's result carries its error. */
8507
- function workflowStep(binding, step) {
8508
- return {
8509
- target: `Workflow:${binding}`,
8510
- op: "step_result",
8511
- kind: "result",
8512
- ...step === void 0 ? {} : { where: { "args.step": step } }
8513
- };
8514
- }
8515
- /** A Workflow's instances at the end of the run as rows `{ id, status, params, output?, error? }`. */
8516
- function workflowRows(binding, where) {
8517
- const target = `Workflow:${binding}`;
8518
- return where ? {
8519
- target,
8520
- table: "instances",
8521
- where
8522
- } : {
8523
- target,
8524
- table: "instances"
8525
- };
8526
- }
8527
- /**
8528
- * The storage of one object (by the name its id was made from) as rows
8529
- * `{ key, value }`, for state invariants.
8530
- */
8531
- function durableObjectRows(binding, object, where) {
8532
- const target = `DO:${binding}`;
8533
- return where ? {
8534
- target,
8535
- table: object,
8536
- where
8537
- } : {
8538
- target,
8539
- table: object
8540
- };
8541
- }
8542
- function queue(name, messages) {
8543
- return {
8544
- kind: "queue",
8545
- queue: name,
8546
- messages: messages.map((m, i) => ({
8547
- id: m.id ?? `msg-${i + 1}`,
8548
- body: m.body
8549
- }))
8550
- };
8551
- }
8552
- function d1Schema(binding, schemaFile) {
8553
- return {
8554
- kind: "d1",
8555
- binding,
8556
- schemaFile
8557
- };
8558
- }
8559
- /**
8560
- * Effect conventions for D1 (what the proxies record):
8561
- * call payload { args: { sql, params } }
8562
- * result payload { args: { sql, params }, result: { changes, lastRowId } }
8563
- * A committed write is a `result` whose `result.changes` is at least 1.
8564
- */
8565
- function d1Write(binding, op = "run") {
8566
- return {
8567
- target: `D1:${binding}`,
8568
- op,
8569
- kind: "result",
8570
- atLeast: { "result.changes": 1 }
8571
- };
8572
- }
8573
- /** Reads of a D1 binding: `first` (result payload `{ row }`), `all` or `raw`. */
8574
- function d1Read(binding, op = "first") {
8575
- return {
8576
- target: `D1:${binding}`,
8577
- op,
8578
- kind: "result"
8579
- };
8580
- }
8581
- /** Dot path to the Nth bound parameter of a D1 statement, in an effect payload. */
8582
- function d1Param(index) {
8583
- return `args.params.${index}`;
8584
- }
8585
- /**
8586
- * The shell follows the core function `decision` (see the `refines`
8587
- * invariant): every selected effect carries out the latest decision of its
8588
- * invocation, agrees with it on `follows`, and, with `state`, was not made
8589
- * stale by another invocation's write between the read it rests on and the
8590
- * effect. The core function's module must be listed in the scenario's
8591
- * `specs`, which is what records its calls.
8592
- */
8593
- function refines(name, decision, effect, options = {}) {
8594
- return {
8595
- kind: "refines",
8596
- name,
8597
- decision,
8598
- effect,
8599
- ...options
8600
- };
8601
- }
8602
- /**
8603
- * Every message's (or request's, or call's) `bodyKey` value must appear at
8604
- * least once as `key` in a selected effect: nothing the drive delivered may
8605
- * be lost. For an RPC drive `bodyKey` is a path into the call's arguments
8606
- * (`"0.orderId"`).
8607
- */
8608
- function atLeastOncePerMessage(name, drive, effect, key, bodyKey) {
8609
- if (drive.kind === "queue") return atLeastOncePerMessage$1(name, drive.messages, effect, key, bodyKey);
8610
- if (drive.kind === "cron") {
8611
- const ticks = drive.ticks.map((t) => ({
8612
- id: t.id,
8613
- body: {
8614
- cron: drive.cron,
8615
- scheduledTime: t.at
8616
- }
8617
- }));
8618
- return atLeastOncePerMessage$1(name, ticks, effect, key, bodyKey);
8619
- }
8620
- if (drive.kind === "rpc") {
8621
- const calls = drive.calls.map((c) => ({
8622
- id: c.id,
8623
- body: c.args
8624
- }));
8625
- return {
8626
- ...atLeastOncePerMessage$1(name, calls, effect, key, bodyKey),
8627
- perMessage: { bodyKey: bodyKey === "" ? "args" : `args.${bodyKey}` }
8628
- };
8629
- }
8630
- const requests = drive.requests.map((r) => ({
8631
- id: r.id,
8632
- body: r.body ?? null
8633
- }));
8634
- return {
8635
- ...atLeastOncePerMessage$1(name, requests, effect, key, bodyKey),
8636
- perMessage: { bodyKey: bodyKey === "" ? "body" : `body.${bodyKey}` }
8637
- };
8638
- }
8639
- /**
8640
- * Selects the responses the Worker returned for a path (`ok` narrows to 2xx
8641
- * or to everything else). One `result` per attempt: a crash before the
8642
- * response leaves none, a thrown error records status 500.
8643
- */
8644
- function httpResponse(path, options = {}) {
8645
- return {
8646
- target: `Http:${path}`,
8647
- op: "response",
8648
- kind: "result",
8649
- ...options.ok === void 0 ? {} : { where: { "result.ok": options.ok } }
8650
- };
8651
- }
8652
- /**
8653
- * Selects the answers an RPC method gave (`ok` narrows to values returned
8654
- * or to errors thrown). One `result` per attempt: a crash before the
8655
- * response leaves none.
8656
- */
8657
- function rpcResponse(method, options = {}) {
8658
- return {
8659
- target: rpcTarget(options, method),
8660
- op: "response",
8661
- kind: "result",
8662
- ...options.ok === void 0 ? {} : { where: { "result.ok": options.ok } }
8663
- };
8664
- }
8665
- /** Rows of a D1 table in the end-of-run snapshot, optionally filtered. */
8666
- function d1Rows(binding, table, where) {
8667
- return where ? {
8668
- target: `D1:${binding}`,
8669
- table,
8670
- where
8671
- } : {
8672
- target: `D1:${binding}`,
8673
- table
8674
- };
8675
- }
8676
- /** Every row the query selects satisfies all conditions. */
8677
- function everyRow(name, query, holds) {
8678
- return {
8679
- kind: "everyRow",
8680
- name,
8681
- query,
8682
- holds
8683
- };
8684
- }
8685
- /** No two rows the query selects share the value at `path` (a column, or a dot path into the row). */
8686
- function unique(name, query, path) {
8687
- return {
8688
- kind: "unique",
8689
- name,
8690
- query,
8691
- path
8692
- };
8693
- }
8694
- /** Every selected effect has a row whose column equals the effect's key. */
8695
- function implies(name, when, key, state, column) {
8696
- return {
8697
- kind: "implies",
8698
- name,
8699
- when,
8700
- key,
8701
- state,
8702
- column
8703
- };
8704
- }
8705
- /** Selects the acknowledgement that took effect for each message (explicit or implicit; not one ignored after a retry). */
8706
- function queueAck(queueName) {
8707
- return {
8708
- target: `Queue:${queueName}`,
8709
- op: "ack",
8710
- kind: "result",
8711
- where: { "result.effective": true }
8712
- };
8713
- }
8714
- /**
8715
- * Declare an external service: requests to `host` are answered from
8716
- * `responses` (every request gets 200 and an empty body when omitted), and
8717
- * `dedupeBy` names the header whose value makes repeated requests
8718
- * idempotent at that service.
8719
- */
8720
- function external(name, host, options = {}) {
8721
- return {
8722
- name,
8723
- host,
8724
- guarantees: options.dedupeBy ? { dedupeBy: options.dedupeBy } : {},
8725
- ...options.responses ? { responses: options.responses } : {}
8726
- };
8727
- }
8728
- /**
8729
- * Selects the requests to an external that took effect: a request replayed
8730
- * under a dedupe key the external had already seen is not counted.
8731
- */
8732
- function fetchCall(externalName, method) {
8733
- return {
8734
- target: `Fetch:${externalName}`,
8735
- ...method ? { op: method.toUpperCase() } : {},
8736
- kind: "result",
8737
- where: { "result.effective": true }
8738
- };
8739
- }
8740
- function validateHttpDrive(drive) {
8741
- const errors = [];
8742
- if (drive.requests.length === 0) errors.push("http drive needs at least one request");
8743
- const ids = /* @__PURE__ */ new Set();
8744
- drive.requests.forEach((r, i) => {
8745
- if (!r.path.startsWith("/")) errors.push(`requests[${i}].path must start with "/"`);
8746
- if (!r.method) errors.push(`requests[${i}].method must not be empty`);
8747
- if (ids.has(r.id)) errors.push(`duplicate request id ${JSON.stringify(r.id)}`);
8748
- ids.add(r.id);
8749
- if ((r.method === "GET" || r.method === "HEAD") && r.body !== void 0) errors.push(`requests[${i}] is a ${r.method} and cannot carry a body`);
8750
- });
8751
- errors.push(...validateCaller("http", drive));
8752
- return errors;
8753
- }
8754
- /** The caller's policy, as both drives a caller resends declare it. */
8755
- function validateCaller(kind, drive) {
8756
- const errors = [];
8757
- if (!(Number.isInteger(drive.retries) && drive.retries >= 0)) errors.push(`${kind} drive retries must be a non-negative integer`);
8758
- (drive.delaysMs ?? []).forEach((d, i) => {
8759
- if (!(Number.isInteger(d) && d >= 0)) errors.push(`${kind} drive delaysMs[${i}] must be a non-negative integer`);
8760
- });
8761
- if (drive.deadlineMs !== void 0 && !(Number.isInteger(drive.deadlineMs) && drive.deadlineMs > 0)) errors.push(`${kind} drive deadlineMs must be a positive integer`);
8762
- return errors;
8763
- }
8764
- function validateCronDrive(drive) {
8765
- const errors = [];
8766
- try {
8767
- parseCron(drive.cron);
8768
- } catch (err) {
8769
- errors.push(`cron drive: ${err.message}`);
8770
- }
8771
- if (drive.ticks.length === 0) errors.push("cron drive ticks must be a positive integer");
8772
- const ids = /* @__PURE__ */ new Set();
8773
- drive.ticks.forEach((t, i) => {
8774
- if (ids.has(t.id)) errors.push(`duplicate tick id ${JSON.stringify(t.id)}`);
8775
- ids.add(t.id);
8776
- const previous = drive.ticks[i - 1];
8777
- if (previous && !(t.at > previous.at)) errors.push(`ticks[${i}] does not come after ticks[${i - 1}]`);
8778
- });
8779
- if (!(Number.isInteger(drive.retries) && drive.retries >= 0)) errors.push("cron drive retries must be a non-negative integer");
8780
- return errors;
8781
- }
8782
- /** A method name the entrypoint can have: an identifier that is not the constructor. */
8783
- const methodName = /^[A-Za-z_$][\w$]*$/;
8784
- function validateRpcDrive(drive) {
8785
- const errors = [];
8786
- if (drive.entrypoint !== void 0 && !methodName.test(drive.entrypoint)) errors.push("rpc drive entrypoint must be an exported class name");
8787
- const ids = /* @__PURE__ */ new Set();
8788
- drive.calls.forEach((c, i) => {
8789
- if (!methodName.test(c.method) || c.method === "constructor") errors.push(`calls[${i}].method must be a method name`);
8790
- if (!Array.isArray(c.args)) errors.push(`calls[${i}].args must be an array`);
8791
- if (ids.has(c.id)) errors.push(`duplicate call id ${JSON.stringify(c.id)}`);
8792
- ids.add(c.id);
8793
- });
8794
- errors.push(...validateCaller("rpc", drive));
8795
- return errors;
8796
- }
8797
- /** Build and validate a scenario spec; throws with every problem listed. */
8798
- function defineScenario(input) {
8799
- const drive = input.drive.kind === "queue" ? queue(input.drive.queue, input.drive.messages) : input.drive;
8800
- const spec = {
8801
- version: 1,
8802
- name: input.name,
8803
- platform: "cloudflare",
8804
- worker: input.worker,
8805
- drive,
8806
- setup: input.setup ?? [],
8807
- externals: input.externals ?? [],
8808
- invariants: input.invariants,
8809
- bounds: {
8810
- ...defaultBounds,
8811
- ...input.bounds
8812
- },
8813
- ...input.specs ? { specs: input.specs } : {}
8814
- };
8815
- const errors = [
8816
- ...validateScenario(spec),
8817
- ...drive.kind === "http" ? validateHttpDrive(drive) : [],
8818
- ...drive.kind === "rpc" ? validateRpcDrive(drive) : [],
8819
- ...drive.kind === "cron" ? validateCronDrive(drive) : []
8820
- ];
8821
- if (errors.length > 0) throw new Error(`invalid scenario ${JSON.stringify(input.name)}:\n- ${errors.join("\n- ")}`);
8822
- return spec;
8823
- }
8824
- // packages/cloudflare/src/services.ts
8825
- /**
8826
- * Service bindings with the callee scripted. A Worker reaches a peer through
8827
- * `env.BINDING`, by RPC method or by `fetch()`; Cloudflare routes the call on
8828
- * the same thread and retries nothing (Workers, service bindings). The real
8829
- * binding is never called here: the scenario's `service()` setup scripts the
8830
- * replies, and each call is one effect with the faults of a Durable Object
8831
- * stub call, where `crash_before` and `error` mean the call never reached
8832
- * the callee, `ambiguous` that it acted and the answer was lost, and
8833
- * `crash_after` that the caller died after it.
8834
- */
8835
- /** Marks of the other kinds of binding, which a service binding's duck type must not carry. */
8836
- const otherKinds = [
8837
- "prepare",
8838
- "idFromName",
8839
- "head",
8840
- "createBatch"
8841
- ];
8842
- /**
8843
- * Whether an env value is a service binding (the runtime's `Fetcher`). In
8844
- * workerd it is an RPC stub whose every property read yields a callable, so
8845
- * duck typing alone would take it for any other kind: the runtime's class is
8846
- * checked first, and the duck type (fetch and connect, none of the other
8847
- * kinds' marks) serves test doubles.
8848
- */
8849
- function isServiceBinding(value) {
8850
- if (typeof value !== "object" || value === null) return false;
8851
- const fetcher = globalThis.Fetcher;
8852
- if (typeof fetcher === "function" && value instanceof fetcher) return true;
8853
- if ((Object.getPrototypeOf(value)?.constructor)?.name === "Fetcher") return true;
8854
- const v = value;
8855
- return typeof v["fetch"] === "function" && typeof v["connect"] === "function" && otherKinds.every((k) => typeof v[k] !== "function");
8856
- }
8857
- /** The built-in error classes RPC carries across as themselves (workerd keeps the type). */
8858
- const builtInErrors = {
8859
- Error,
8860
- EvalError,
8861
- RangeError,
8862
- ReferenceError,
8863
- SyntaxError,
8864
- TypeError,
8865
- URIError
8866
- };
8867
- /**
8868
- * The error the caller sees for a `throws` reply, `"<Name>: <message>"`: a
8869
- * built-in error class is that class, so `instanceof` holds as it does over
8870
- * RPC; any other name is an `Error` carrying the name.
8871
- */
8872
- function scriptedError(spec) {
8873
- const at = spec.indexOf(": ");
8874
- if (at < 0) return new Error(spec);
8875
- const name = spec.slice(0, at);
8876
- const message = spec.slice(at + 2);
8877
- const builtIn = builtInErrors[name];
8878
- if (builtIn) return new builtIn(message);
8879
- const error = new Error(message);
8880
- error.name = name;
8881
- return error;
8882
- }
8883
- /** The scripted stub a Worker sees under a service binding's name. */
8884
- function proxyService(binding, ctx, script) {
8885
- const target = `Service:${binding}`;
8886
- const point = (op, args) => ({
8887
- invocation: ctx.currentInvocation(),
8888
- target,
8889
- op,
8890
- args,
8891
- allowed: writeFaults
8892
- });
8893
- const unsupported = (what) => {
8894
- const reason = `service binding ${binding}: ${what}`;
8895
- ctx.hooks.unsupported(reason);
8896
- throw new Error(`eutaxy: ${reason}`);
8897
- };
8898
- /** The scripted reply to a method, by name; a method the script lacks cannot be answered. */
8899
- const replyTo = (method) => {
8900
- if (script.methods === void 0) return { returns: null };
8901
- if (!Object.hasOwn(script.methods, method)) return unsupported(`no scripted reply for method ${method}; add it to the service(${JSON.stringify(binding)}) setup's methods`);
8902
- return script.methods[method];
8903
- };
8904
- const answer = (method) => {
8905
- const reply = replyTo(method);
8906
- if ("throws" in reply) throw scriptedError(reply.throws);
8907
- return structuredClone(reply.returns);
8908
- };
8909
- const fetchThrough = async (input, init) => {
8910
- const request = new Request(input, init);
8911
- const url = new URL(request.url);
8912
- const method = request.method.toUpperCase();
8913
- const headers = {};
8914
- request.headers.forEach((value, name) => {
8915
- headers[name.toLowerCase()] = value;
8916
- });
8917
- const body = parseBody(await request.text());
8918
- const reply = await ctx.hooks.effect(point(method, {
8919
- url: request.url,
8920
- method,
8921
- headers,
8922
- body
8923
- }), async () => {
8924
- const found = findResponse({
8925
- name: binding,
8926
- host: url.host,
8927
- guarantees: {},
8928
- ...script.fetch === void 0 ? {} : { responses: script.fetch }
8929
- }, method, url.pathname);
8930
- if (found === void 0) return unsupported(`no scripted reply for fetch ${method} ${url.pathname}; add it to the service(${JSON.stringify(binding)}) setup's fetch`);
8931
- const reply = replyOf(found);
8932
- if (isRedirect(reply.status) && request.redirect !== "manual") return unsupported(`the scripted reply to ${method} ${url.pathname} is a ${reply.status} redirect, which the runtime would follow; script the final reply or fetch with redirect: "manual"`);
8933
- return reply;
8934
- }, (r) => ({ status: r.status }));
8935
- return toResponse(reply);
8936
- };
8937
- /**
8938
- * The promise a call returns. On the real stub it is an RPC promise that
8939
- * pipelines property reads (`stub.charge().id`); this one is not, so a read
8940
- * on it makes the run UNSUPPORTED instead of yielding undefined.
8941
- */
8942
- const pipelineGuard = (promise, method) => new Proxy(promise, { get(target, prop) {
8943
- if (typeof prop === "symbol" || prop === "then" || prop === "catch" || prop === "finally") {
8944
- const value = Reflect.get(target, prop, target);
8945
- return typeof value === "function" ? value.bind(target) : value;
8946
- }
8947
- ctx.hooks.unsupported(`service binding ${binding}: RPC promise pipelining (reading .${prop} on ${method}()'s promise) is not supported; await the call first`);
8948
- } });
8949
- /** One call: `stub.method(...)`, or `await stub.property` (an RPC getter). */
8950
- const call = (method) => {
8951
- const invoke = (...args) => pipelineGuard(ctx.hooks.effect(point(method, { args: args.map((a) => toJson(a)) }), async () => answer(method), (value) => ({ value: toJson(value) })), method);
8952
- const read = () => ctx.hooks.effect(point(method, { property: true }), async () => answer(method), (value) => ({ value: toJson(value) }));
8953
- const awaitable = (onFulfilled, onRejected) => read().then(onFulfilled, onRejected);
8954
- return new Proxy(invoke, { get(fn, key) {
8955
- if (key === "then") return awaitable;
8956
- if (typeof key === "symbol") return Reflect.get(fn, key);
8957
- ctx.hooks.unsupported(`service binding ${binding}: RPC promise pipelining (reading .${method}.${key}) is not supported; await .${method} first`);
8958
- } });
8959
- };
8960
- return new Proxy({}, { get(_stub, prop) {
8961
- if (prop === "then" || typeof prop === "symbol") return void 0;
8962
- if (prop === "fetch") return fetchThrough;
8963
- if (prop === "connect") return () => unsupported("connect() (a raw TCP socket) is not modelled");
8964
- return call(prop);
8965
- } });
8966
- }
8967
- // packages/cloudflare/src/entrypoint.ts
8968
- /**
8969
- * Constructing an entrypoint class (`WorkerEntrypoint`, `WorkflowEntrypoint`)
8970
- * outside the runtime, for the one `new` per call or instance run that the
8971
- * models make themselves.
8972
- */
8973
- /** Sets `ctx` and `env` as the runtime's base classes do, for the one `new` workerd would refuse. */
8974
- var StandInEntrypoint = class {
8975
- ctx;
8976
- env;
8977
- constructor(ctx, env) {
8978
- this.ctx = ctx;
8979
- this.env = env;
8980
- }
8981
- };
8982
- /**
8983
- * Construct a subclass of the entrypoint base class named `base`. workerd's
8984
- * base constructors accept only a native ExecutionContext, so for this one
8985
- * synchronous `new` the class that extends the base directly extends a
8986
- * stand-in instead; its own constructor and field initialisers run as
8987
- * written, and the base is put back before anything else can run.
8988
- */
8989
- function constructEntrypoint(cls, base, ctx, env) {
8990
- if (typeof cls !== "function") throw new TypeError("not a class");
8991
- let direct = cls;
8992
- for (;;) {
8993
- const parent = Object.getPrototypeOf(direct);
8994
- if (typeof parent !== "function" || parent === Function.prototype) throw new TypeError(`${cls.name} does not extend ${base}`);
8995
- if (parent.name === base) break;
8996
- direct = parent;
8997
- }
8998
- const original = Object.getPrototypeOf(direct);
8999
- Object.setPrototypeOf(direct, StandInEntrypoint);
9000
- try {
9001
- return Reflect.construct(cls, [ctx, env]);
9002
- } finally {
9003
- Object.setPrototypeOf(direct, original);
9004
- }
9005
- }
9006
- // packages/cloudflare/src/workflows.ts
9007
- /**
9008
- * Workflows, modelled: the binding's `create`/`get`, and each instance run
9009
- * as invocations of its class's `run(event, step)` against a model of the
9010
- * engine (persisted step results, retries in virtual time, restarts that
9011
- * re-run `run` from the start). The real local engine is never called: it
9012
- * runs on its own real-time clock and retry loop, which Eutaxy can neither
9013
- * fault nor schedule. See docs/design.md, "Workflows".
9014
- */
9015
- /** The `EventRef.source` of a Workflow instance's run. */
9016
- const workflowSource = "workflow";
9017
- /** Before a step's callback: the engine restarts before the step runs. */
9018
- const STEP_START = ["crash_before"];
9019
- /**
9020
- * After it: the engine restarts after the step ran but before its result
9021
- * was persisted (`crash_after`), or the attempt ran and counted as failed,
9022
- * as a timeout does (`ambiguous`).
9023
- */
9024
- const STEP_RESULT = ["crash_after", "ambiguous"];
9025
- /**
9026
- * Cloudflare's defaults for a step without a config (Workflows, Sleeping
9027
- * and retrying). A partial config is merged with them field by field, as
9028
- * the engine does. Miniflare's local engine waits 1 s by default; the
9029
- * model keeps the documented 10 s.
9030
- */
9031
- const defaultRetries = {
9032
- limit: 5,
9033
- delay: 1e4,
9034
- backoff: "exponential"
9035
- };
9036
- /** Keep a thrown value as the engine keeps it, with an Error's name, which the clone would lose. */
9037
- function failure(thrown) {
9038
- let kept;
9039
- try {
9040
- kept = structuredClone(thrown);
9041
- } catch {
9042
- kept = new Error(String(thrown));
9043
- }
9044
- return thrown instanceof Error ? {
9045
- ok: false,
9046
- error: kept,
9047
- errorName: thrown.name
9048
- } : {
9049
- ok: false,
9050
- error: kept
9051
- };
9052
- }
9053
- /** One binding's instances in the current run. */
9054
- var WorkflowRegistry = class {
9055
- instances = /* @__PURE__ */ new Map();
9056
- clear() {
9057
- this.instances.clear();
9058
- }
9059
- /** The instances as rows for the end-of-run snapshot, by id. */
9060
- rows() {
9061
- return [...this.instances.values()].sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0).map((i) => ({
9062
- id: i.id,
9063
- status: i.status,
9064
- params: toJson(i.params),
9065
- ...i.output === void 0 ? {} : { output: toJson(i.output) },
9066
- ...i.error === void 0 ? {} : { error: `${i.error.name}: ${i.error.message}` }
9067
- }));
9068
- }
9069
- };
9070
- /** A Workflow binding as the env shows it (Miniflare's `WorkflowImpl`). */
9071
- function isWorkflowBinding(value) {
9072
- if (typeof value !== "object" || value === null) return false;
9073
- const v = value;
9074
- return typeof v["create"] === "function" && typeof v["createBatch"] === "function" && typeof v["get"] === "function";
9075
- }
9076
- /** The binding's proxy: instances live in the registry and run as events, never in the real engine. */
9077
- function proxyWorkflow(binding, ctx, registry) {
9078
- const target = `Workflow:${binding}`;
9079
- const unsupported = (what) => {
9080
- const reason = `Workflow ${binding}: ${what} is not modelled`;
9081
- ctx.hooks.unsupported(reason);
9082
- throw new Error(`eutaxy: ${reason}`);
9083
- };
9084
- const handle = (id) => ({
9085
- id,
9086
- status: () => ctx.hooks.effect({
9087
- invocation: ctx.currentInvocation(),
9088
- target,
9089
- op: "status",
9090
- args: { id },
9091
- allowed: []
9092
- }, async () => {
9093
- const i = registry.instances.get(id);
9094
- if (!i) throw new Error("instance.not_found");
9095
- return {
9096
- status: i.status,
9097
- output: i.output === void 0 ? null : structuredClone(i.output),
9098
- ...i.error === void 0 ? {} : { error: { ...i.error } }
9099
- };
9100
- }, (s) => toJson(s)),
9101
- pause: () => unsupported("pause()"),
9102
- resume: () => unsupported("resume()"),
9103
- terminate: () => unsupported("terminate()"),
9104
- restart: () => unsupported("restart()"),
9105
- sendEvent: (args = {}) => ctx.hooks.effect({
9106
- invocation: ctx.currentInvocation(),
9107
- target,
9108
- op: "send_event",
9109
- args: {
9110
- id,
9111
- type: toJson(args.type),
9112
- payload: toJson(args.payload)
9113
- },
9114
- allowed: writeFaults
9115
- }, async () => {
9116
- const type = validEventType(args.type);
9117
- const i = registry.instances.get(id);
9118
- if (!i) throw new Error("instance.not_found");
9119
- if (i.status === "complete" || i.status === "errored") throw new Error(`(instance.not_running) Workflow instance with id "${id}" is ${i.status} and takes no events`);
9120
- const event = {
9121
- type,
9122
- payload: structuredClone(args.payload),
9123
- timestamp: /* @__PURE__ */ new Date()
9124
- };
9125
- const queue = i.events.get(type) ?? [];
9126
- queue.push(event);
9127
- i.events.set(type, queue);
9128
- if (i.status === "waiting" && i.waiting?.type === type && !i.waiting.woken) {
9129
- i.waiting.woken = true;
9130
- ctx.hooks.enqueue({
9131
- id: `workflow:${binding}:${id}:event-${i.waiting.gen}`,
9132
- attempt: 1,
9133
- source: workflowSource,
9134
- data: {
9135
- binding,
9136
- id,
9137
- wake: i.waiting.gen
9138
- }
9139
- });
9140
- }
9141
- return null;
9142
- }, () => null),
9143
- delete: () => unsupported("delete()"),
9144
- subscribe: () => unsupported("subscribe()")
9145
- });
9146
- return {
9147
- async create(options = {}) {
9148
- const id = options.id ?? crypto.randomUUID();
9149
- const params = structuredClone(options.params === void 0 ? {} : options.params);
9150
- return ctx.hooks.effect({
9151
- invocation: ctx.currentInvocation(),
9152
- target,
9153
- op: "create",
9154
- args: {
9155
- id,
9156
- params: toJson(params)
9157
- },
9158
- allowed: writeFaults
9159
- }, async () => {
9160
- if (!validInstanceId(id)) throw new Error("Workflow instance has invalid id");
9161
- if (registry.instances.has(id)) throw new Error(`(instance.already_exists) Workflow instance with id "${id}" already exists`);
9162
- registry.instances.set(id, {
9163
- id,
9164
- params,
9165
- createdAt: Date.now(),
9166
- status: "queued",
9167
- events: /* @__PURE__ */ new Map(),
9168
- waiting: void 0,
9169
- waitGen: 0,
9170
- persisted: /* @__PURE__ */ new Map(),
9171
- attempts: /* @__PURE__ */ new Map(),
9172
- configs: /* @__PURE__ */ new Map(),
9173
- deadlines: /* @__PURE__ */ new Map()
9174
- });
9175
- ctx.hooks.enqueue({
9176
- id: `workflow:${binding}:${id}`,
9177
- attempt: 1,
9178
- source: workflowSource,
9179
- data: {
9180
- binding,
9181
- id
9182
- }
9183
- });
9184
- return handle(id);
9185
- }, () => ({ id }));
9186
- },
9187
- async get(id) {
9188
- return ctx.hooks.effect({
9189
- invocation: ctx.currentInvocation(),
9190
- target,
9191
- op: "get",
9192
- args: { id },
9193
- allowed: []
9194
- }, async () => {
9195
- if (!registry.instances.has(id)) throw new Error("instance.not_found");
9196
- return handle(id);
9197
- }, () => ({ id }));
9198
- },
9199
- createBatch: () => unsupported("createBatch()"),
9200
- deleteBatch: () => unsupported("deleteBatch()")
9201
- };
9202
- }
9203
- /** The binding's rule for an instance id (Miniflare): up to 100 of these characters. */
9204
- function validInstanceId(id) {
9205
- return typeof id === "string" && id.length <= 100 && /^[a-zA-Z0-9_][a-zA-Z0-9-_]*$/.test(id);
9206
- }
9207
- /** An event type as Workflows accept it (Events and parameters): up to 100 of these characters, else `workflow.invalid_event_type`. */
9208
- function validEventType(type) {
9209
- if (typeof type === "string" && type.length <= 100 && /^[a-zA-Z0-9_][a-zA-Z0-9-_]*$/.test(type)) return type;
9210
- throw new Error(`(workflow.invalid_event_type) event type must be up to 100 letters, digits, - or _, got ${JSON.stringify(type)}`);
9211
- }
9212
- /** Thrown through `run()` to suspend an instance waiting for an event; never meant to be caught. */
9213
- var Suspension = class {
9214
- gen;
9215
- constructor(gen) {
9216
- this.gen = gen;
9217
- }
9218
- };
9219
- /**
9220
- * Whether a run event wakes the instance: not a wake at all, the restart of a
9221
- * run a wake began (its first delivery resumed the instance), or the wake of
9222
- * the wait still pending.
9223
- */
9224
- function wakes(instance, event) {
9225
- const wake = event.data.wake;
9226
- if (wake === void 0 || event.attempt > 1) return true;
9227
- return instance.status === "waiting" && instance.waiting?.gen === wake;
9228
- }
9229
- /** Construct a `WorkflowEntrypoint` subclass outside the runtime, for the one `new` per instance run. */
9230
- function constructWorkflow(cls, ctx, env) {
9231
- return constructEntrypoint(cls, "WorkflowEntrypoint", ctx, env);
9232
- }
9233
- /** The engine's conversion (itty-time): a year is 365.25 days, a month 30; an unknown unit counts 1. */
9234
- const units = {
9235
- year: 315576e5,
9236
- month: 2592e6,
9237
- week: 6048e5,
9238
- day: 864e5,
9239
- hour: 36e5,
9240
- minute: 6e4,
9241
- second: 1e3,
9242
- m: 1
9243
- };
9244
- /** The engine's reading of a duration, NaN where it reads none. */
9245
- function engineDuration(d) {
9246
- if (!Number.isNaN(Number(d)) && typeof d !== "object") return Number(d);
9247
- if (typeof d !== "string") return NaN;
9248
- const m = /^([^ ]+) +(\w\w*?)s?$/.exec(d);
9249
- if (!m) return NaN;
9250
- return Number(m[1]) * (units[m[2]] ?? 1);
9251
- }
9252
- /** A Workflows duration in milliseconds, read as the engine reads it. */
9253
- function durationMs(d) {
9254
- const ms = engineDuration(d);
9255
- if (Number.isNaN(ms) || ms < 0) throw new TypeError(`not a Workflows duration: ${String(d)}`);
9256
- return ms;
9257
- }
9258
- /** Miniflare's `isValidStepConfig`, exactly: its schema is strict, and a timeout `== 0` is refused. */
9259
- function validStepConfig(config) {
9260
- const only = (o, keys) => Object.keys(o).every((k) => keys.includes(k));
9261
- const durationOk = (v) => !Number.isNaN(engineDuration(v));
9262
- if (typeof config !== "object" || config === null || !only(config, [
9263
- "retries",
9264
- "timeout",
9265
- "sensitive"
9266
- ])) return false;
9267
- const c = config;
9268
- const r = c["retries"];
9269
- if (r !== void 0) {
9270
- if (typeof r !== "object" || r === null || !only(r, [
9271
- "delay",
9272
- "limit",
9273
- "backoff"
9274
- ])) return false;
9275
- const delay = r["delay"];
9276
- if (!(typeof delay === "function" || typeof delay === "string" || typeof delay === "number" && delay >= 0)) return false;
9277
- if (typeof r["limit"] !== "number" || r["limit"] < 0) return false;
9278
- if (r["backoff"] !== void 0 && ![
9279
- "constant",
9280
- "linear",
9281
- "exponential"
9282
- ].includes(r["backoff"])) return false;
9283
- if (typeof delay !== "function" && !durationOk(delay)) return false;
9284
- }
9285
- const t = c["timeout"];
9286
- if (t !== void 0) {
9287
- if (!(typeof t === "string" || typeof t === "number" && t >= 0)) return false;
9288
- if (t == 0 || !durationOk(t)) return false;
9289
- }
9290
- if (c["sensitive"] !== void 0 && c["sensitive"] !== "output") return false;
9291
- return true;
9292
- }
9293
- const utf8 = new TextEncoder();
9294
- /** About how many bytes a value takes stored, walking it as structured cloning does. */
9295
- function approximateBytes(value, seen = /* @__PURE__ */ new Set()) {
9296
- if (value === null || value === void 0) return 1;
9297
- switch (typeof value) {
9298
- case "string": return utf8.encode(value).length;
9299
- case "number":
9300
- case "bigint": return 8;
9301
- case "boolean": return 1;
9302
- case "object": break;
9303
- default: return 0;
9304
- }
9305
- const o = value;
9306
- if (seen.has(o)) return 0;
9307
- seen.add(o);
9308
- if (o instanceof ArrayBuffer || ArrayBuffer.isView(o)) return o.byteLength;
9309
- if (o instanceof Date) return 8;
9310
- let total = 0;
9311
- if (o instanceof Map) for (const [k, v] of o) total += approximateBytes(k, seen) + approximateBytes(v, seen);
9312
- else if (o instanceof Set) for (const v of o) total += approximateBytes(v, seen);
9313
- else for (const [k, v] of Object.entries(o)) total += utf8.encode(k).length + approximateBytes(v, seen);
9314
- return total;
9315
- }
9316
- function sleep(ms) {
9317
- return new Promise((resolve) => setTimeout(resolve, ms));
9318
- }
9319
- /**
9320
- * One engine attempt of an instance: construct its class and call `run`.
9321
- * Steps whose results were persisted return them without running; a crash
9322
- * restarts the instance (a new attempt, from the start of `run`).
9323
- */
9324
- async function deliverWorkflow(event, hooks, d) {
9325
- const invocation = invocationOf(event);
9326
- const inv = hooks.startInvocation(invocation);
9327
- const target = `Workflow:${d.binding}`;
9328
- const instance = d.instance;
9329
- if (!wakes(instance, event)) return {
9330
- status: "completed",
9331
- followUps: []
9332
- };
9333
- instance.status = "running";
9334
- instance.waiting = void 0;
9335
- const background = [];
9336
- const counts = /* @__PURE__ */ new Map();
9337
- const key = (kind, name) => {
9338
- const count = (counts.get(`${kind}:${name}`) ?? 0) + 1;
9339
- counts.set(`${kind}:${name}`, count);
9340
- return `${kind}:${name}#${count}`;
9341
- };
9342
- const replay = (o) => {
9343
- if (o.ok) return structuredClone(o.value);
9344
- const error = structuredClone(o.error);
9345
- if (o.errorName !== void 0 && error instanceof Error) error.name = o.errorName;
9346
- throw error;
9347
- };
9348
- const step = {
9349
- do: async (name, a, b, c) => {
9350
- const [config, fn, options] = typeof a === "function" ? [
9351
- {},
9352
- a,
9353
- b
9354
- ] : [
9355
- a ?? {},
9356
- b,
9357
- c
9358
- ];
9359
- if (suspending !== void 0) continuedAfterSuspension("step.do");
9360
- if (options?.rollback !== void 0) {
9361
- hooks.unsupported(`Workflow ${d.binding}: rollback handlers are not modelled`);
9362
- throw new Error("eutaxy: rollback handlers are not modelled");
9363
- }
9364
- const fatal = (message) => {
9365
- hooks.unsupported(`Workflow ${d.binding}: ${message}`);
9366
- const err = new Error(message);
9367
- err.name = "WorkflowFatalError";
9368
- throw err;
9369
- };
9370
- if (name.length > 256 || [...name].some((c) => c.charCodeAt(0) < 32)) fatal(`Step name "${name}" exceeds max length (256 chars) or invalid characters found`);
9371
- if (!validStepConfig(config)) fatal(`Step config for "${name}" is in a invalid format. See https://developers.cloudflare.com/workflows/build/sleeping-and-retrying/`);
9372
- const k = key("do", name);
9373
- const count = counts.get(`do:${name}`);
9374
- const done = instance.persisted.get(k);
9375
- if (done) return replay(done);
9376
- const live = {
9377
- ...defaultRetries,
9378
- ...config.retries
9379
- };
9380
- const first = instance.configs.get(k);
9381
- if (!first) instance.configs.set(k, {
9382
- retries: live,
9383
- timeout: config.timeout ?? "10 minutes",
9384
- ...config.sensitive === void 0 ? {} : { sensitive: config.sensitive }
9385
- });
9386
- const sensitive = first ? first.sensitive : config.sensitive;
9387
- const stored = first?.retries;
9388
- const retries = stored && typeof stored.delay === "function" ? {
9389
- ...stored,
9390
- delay: typeof live.delay === "function" ? live.delay : defaultRetries.delay
9391
- } : stored ?? live;
9392
- const limit = Math.min(retries.limit, d.maxRedeliveries);
9393
- const { delay, ...shown } = retries;
9394
- const resolved = {
9395
- retries: typeof delay === "function" ? shown : retries,
9396
- timeout: first ? first.timeout : config.timeout ?? "10 minutes",
9397
- ...sensitive === void 0 ? {} : { sensitive }
9398
- };
9399
- for (let attempt = (instance.attempts.get(k) ?? 0) + 1;; attempt++) {
9400
- const due = instance.deadlines.get(`retry:${k}`);
9401
- if (due !== void 0) {
9402
- await sleep(Math.max(0, due - Date.now()));
9403
- instance.deadlines.delete(`retry:${k}`);
9404
- }
9405
- const stepContext = {
9406
- step: {
9407
- name,
9408
- count
9409
- },
9410
- attempt,
9411
- config: {
9412
- ...resolved,
9413
- retries: { ...resolved.retries }
9414
- }
9415
- };
9416
- const args = {
9417
- instance: instance.id,
9418
- step: name,
9419
- count,
9420
- attempt
9421
- };
9422
- await hooks.effect({
9423
- invocation,
9424
- target,
9425
- op: "step",
9426
- args,
9427
- allowed: STEP_START
9428
- }, async () => null, () => null);
9429
- instance.attempts.set(k, attempt);
9430
- let failed = false;
9431
- let thrown;
9432
- let value;
9433
- let returned;
9434
- try {
9435
- returned = { value: await fn(stepContext) };
9436
- } catch (err) {
9437
- if (err instanceof CrashSignal || inv.isCrashed()) throw err;
9438
- failed = true;
9439
- thrown = err;
9440
- try {
9441
- hooks.effectSync({
9442
- invocation,
9443
- target,
9444
- op: "step_result",
9445
- args,
9446
- allowed: []
9447
- }, () => {
9448
- throw err;
9449
- }, () => null);
9450
- } catch {}
9451
- }
9452
- if (returned !== void 0) {
9453
- const notModelled = (reason) => {
9454
- hooks.unsupported(`Workflow ${d.binding}: step "${name}" ${reason}`);
9455
- throw new Error(`eutaxy: step "${name}" ${reason}`);
9456
- };
9457
- try {
9458
- value = structuredClone(returned.value);
9459
- } catch {
9460
- notModelled("returned a value that is not structured-cloneable (a ReadableStream is not modelled)");
9461
- }
9462
- if (approximateBytes(value) > 1048576) notModelled("returned more than about 1 MiB, which the engine refuses (\"output is too large\"); Eutaxy cannot measure the stored size exactly");
9463
- }
9464
- if (!failed) try {
9465
- await hooks.effect({
9466
- invocation,
9467
- target,
9468
- op: "step_result",
9469
- args,
9470
- allowed: STEP_RESULT
9471
- }, async () => value, (v) => ({ output: sensitive === "output" ? "[REDACTED]" : toJson(v) }));
9472
- instance.persisted.set(k, {
9473
- ok: true,
9474
- value
9475
- });
9476
- return structuredClone(value);
9477
- } catch (err) {
9478
- if (err instanceof CrashSignal || !(err instanceof InjectedEffectError)) throw err;
9479
- thrown = Object.assign(/* @__PURE__ */ new Error(`Execution timed out after ${durationMs(resolved.timeout)}ms`), { name: "WorkflowTimeoutError" });
9480
- }
9481
- if (thrown instanceof Error && (thrown.name === "NonRetryableError" || thrown.message.startsWith("NonRetryableError"))) throw thrown;
9482
- if (attempt > limit) {
9483
- instance.persisted.set(k, failure(thrown));
9484
- throw thrown;
9485
- }
9486
- let wait;
9487
- try {
9488
- const delayContext = {
9489
- step: {
9490
- name,
9491
- count
9492
- },
9493
- attempt,
9494
- config: {
9495
- ...resolved,
9496
- retries: { ...resolved.retries }
9497
- }
9498
- };
9499
- wait = await retryDelayMs$1(retries, attempt, delayContext, thrown);
9500
- } catch (err) {
9501
- hooks.unsupported(`Workflow ${d.binding}: step "${name}"'s retry delay function threw (${String(err)})`);
9502
- throw err;
9503
- }
9504
- instance.deadlines.set(`retry:${k}`, Date.now() + wait);
9505
- await sleep(wait);
9506
- instance.deadlines.delete(`retry:${k}`);
9507
- }
9508
- },
9509
- sleep: async (name, duration) => {
9510
- const ms = durationMs(duration);
9511
- await sleepStep(key("sleep", `${name}\u0000${ms}`), name, ms);
9512
- },
9513
- sleepUntil: async (name, timestamp) => {
9514
- const at = timestamp instanceof Date ? timestamp.getTime() : Number(timestamp);
9515
- const k = key("sleepUntil", `${name}\u0000${at}`);
9516
- if (instance.persisted.has(k)) {
9517
- if (at < Date.now()) hooks.unsupported(`Workflow ${d.binding}: step.sleepUntil "${name}" replayed after its time, where Miniflare's engine throws`);
9518
- return;
9519
- }
9520
- if (at < Date.now() && !instance.deadlines.has(k)) throw new Error("You can't sleep until a time in the past, time-traveler");
9521
- await sleepStep(k, name, Math.max(0, at - Date.now()), at);
9522
- },
9523
- waitForEvent: async (name, options = {}) => {
9524
- if (suspending !== void 0) continuedAfterSuspension("step.waitForEvent");
9525
- const type = validEventType(options.type);
9526
- const timeoutMs = durationMs(options.timeout ?? "24 hours");
9527
- if (!(timeoutMs >= 1e3 && timeoutMs <= 31536e6)) {
9528
- hooks.unsupported(`Workflow ${d.binding}: waitForEvent "${name}" timeout must be between 1 second and 365 days`);
9529
- const err = /* @__PURE__ */ new Error(`Invalid timeout for waitForEvent "${name}"`);
9530
- err.name = "WorkflowFatalError";
9531
- throw err;
9532
- }
9533
- const k = key("waitForEvent", name);
9534
- const done = instance.persisted.get(k);
9535
- if (done) return replay(done);
9536
- const args = {
9537
- instance: instance.id,
9538
- step: name,
9539
- type
9540
- };
9541
- const existing = instance.deadlines.get(k);
9542
- const queue = instance.events.get(type) ?? [];
9543
- const inTime = queue.findIndex((e) => existing === void 0 || e.timestamp.getTime() < existing);
9544
- const received = inTime < 0 ? void 0 : queue.splice(inTime, 1)[0];
9545
- if (received) {
9546
- hooks.effectSync({
9547
- invocation,
9548
- target,
9549
- op: "event",
9550
- args: {
9551
- ...args,
9552
- timestamp: received.timestamp.getTime()
9553
- },
9554
- allowed: []
9555
- }, () => received, (e) => ({ payload: toJson(e.payload) }));
9556
- instance.persisted.set(k, {
9557
- ok: true,
9558
- value: received
9559
- });
9560
- return structuredClone(received);
9561
- }
9562
- if (existing !== void 0 && Date.now() >= existing) {
9563
- const error = Object.assign(/* @__PURE__ */ new Error(`Execution timed out after ${timeoutMs}ms`), { name: "WorkflowTimeoutError" });
9564
- hooks.effectSync({
9565
- invocation,
9566
- target,
9567
- op: "wait_timeout",
9568
- args,
9569
- allowed: []
9570
- }, () => null, () => null);
9571
- instance.persisted.set(k, failure(error));
9572
- throw error;
9573
- }
9574
- const deadline = existing ?? Date.now() + timeoutMs;
9575
- if (existing === void 0) {
9576
- instance.deadlines.set(k, deadline);
9577
- hooks.effectSync({
9578
- invocation,
9579
- target,
9580
- op: "wait",
9581
- args: {
9582
- ...args,
9583
- timeoutMs
9584
- },
9585
- allowed: []
9586
- }, () => null, () => null);
9587
- }
9588
- const gen = ++instance.waitGen;
9589
- instance.waiting = {
9590
- type,
9591
- gen,
9592
- woken: false
9593
- };
9594
- suspending = {
9595
- gen,
9596
- deadline
9597
- };
9598
- throw new Suspension(gen);
9599
- }
9600
- };
9601
- /** Set once a wait suspended this run: anything the code does after it caught the suspension is not modelled. */
9602
- let suspending;
9603
- const continuedAfterSuspension = (what) => {
9604
- const reason = `Workflow ${d.binding}: ${what} after step.waitForEvent suspended the instance; the code caught the suspension (catch only the wait's WorkflowTimeoutError)`;
9605
- hooks.unsupported(reason);
9606
- throw new Error(`eutaxy: ${reason}`);
9607
- };
9608
- async function sleepStep(k, name, ms, until) {
9609
- if (suspending !== void 0) continuedAfterSuspension("step.sleep");
9610
- if (instance.persisted.has(k)) return;
9611
- const pending = instance.deadlines.get(k);
9612
- if (pending !== void 0) {
9613
- await sleep(Math.max(0, pending - Date.now()));
9614
- instance.persisted.set(k, {
9615
- ok: true,
9616
- value: null
9617
- });
9618
- return;
9619
- }
9620
- instance.deadlines.set(k, Date.now() + ms);
9621
- hooks.effectSync({
9622
- invocation,
9623
- target,
9624
- op: "sleep",
9625
- args: {
9626
- instance: instance.id,
9627
- step: name,
9628
- ms,
9629
- ...until === void 0 ? {} : { until }
9630
- },
9631
- allowed: []
9632
- }, () => null, () => null);
9633
- await sleep(ms);
9634
- instance.persisted.set(k, {
9635
- ok: true,
9636
- value: null
9637
- });
9638
- }
9639
- const ran = await runInvocation(hooks, inv, () => {
9640
- const flow = constructWorkflow(d.cls, executionContext(background), d.env);
9641
- const workflowEvent = {
9642
- payload: structuredClone(instance.params),
9643
- timestamp: new Date(instance.createdAt),
9644
- instanceId: instance.id
9645
- };
9646
- if (d.name !== void 0) workflowEvent["workflowName"] = d.name;
9647
- else Object.defineProperty(workflowEvent, "workflowName", {
9648
- enumerable: true,
9649
- get: () => {
9650
- hooks.unsupported(`Workflow ${d.binding}: event.workflowName needs the Workflow's name, workflow(binding, className, { name })`);
9651
- }
9652
- });
9653
- return flow.run(workflowEvent, step);
9654
- });
9655
- const serialised = (value) => {
9656
- try {
9657
- return {
9658
- status: "completed",
9659
- value: structuredClone(value)
9660
- };
9661
- } catch {
9662
- hooks.unsupported(`Workflow ${d.binding}: run() returned a value that is not structured-cloneable`);
9663
- return {
9664
- status: "errored",
9665
- error: /* @__PURE__ */ new Error("run() returned a value that is not structured-cloneable")
9666
- };
9667
- }
9668
- };
9669
- let result = ran.status === "completed" ? serialised(ran.value) : ran;
9670
- if (suspending !== void 0) {
9671
- if (!(ran.status === "errored" && ran.error instanceof Suspension) && ran.status !== "crashed") hooks.unsupported(`Workflow ${d.binding}: run() ${ran.status === "completed" ? "returned" : "threw"} after step.waitForEvent suspended the instance; the code caught the suspension (catch only the wait's WorkflowTimeoutError)`);
9672
- if (ran.status !== "crashed") result = {
9673
- status: "completed",
9674
- value: void 0
9675
- };
9676
- }
9677
- let status = result.status;
9678
- if (suspending !== void 0 && result.status === "completed") {
9679
- instance.status = "waiting";
9680
- const suspended = suspending;
9681
- if (await drainBackground(hooks, inv, invocation, target, background)) status = "crashed";
9682
- if (status === "crashed") {
9683
- instance.status = "running";
9684
- instance.waiting = void 0;
9685
- }
9686
- const followUps = status === "crashed" ? instance.status === "running" && event.attempt <= d.maxFaultsPerRun ? [{
9687
- ...event,
9688
- attempt: event.attempt + 1
9689
- }] : [] : [{
9690
- id: `workflow:${d.binding}:${instance.id}:timeout-${suspended.gen}`,
9691
- attempt: 1,
9692
- source: workflowSource,
9693
- data: {
9694
- binding: d.binding,
9695
- id: instance.id,
9696
- wake: suspended.gen
9697
- },
9698
- at: suspended.deadline
9699
- }];
9700
- return {
9701
- status,
9702
- followUps
9703
- };
9704
- }
9705
- if (result.status === "completed") {
9706
- instance.status = "complete";
9707
- instance.output = result.value;
9708
- hooks.effectSync({
9709
- invocation,
9710
- target,
9711
- op: "complete",
9712
- args: {
9713
- instance: instance.id,
9714
- output: toJson(instance.output)
9715
- },
9716
- allowed: []
9717
- }, () => null, () => null);
9718
- } else if (result.status === "errored") {
9719
- instance.status = "errored";
9720
- const e = result.error;
9721
- instance.error = e instanceof Error ? {
9722
- name: e.name,
9723
- message: e.message
9724
- } : {
9725
- name: "Error",
9726
- message: String(e)
9727
- };
9728
- hooks.effectSync({
9729
- invocation,
9730
- target,
9731
- op: "errored",
9732
- args: {
9733
- instance: instance.id,
9734
- error: `${instance.error.name}: ${instance.error.message}`
9735
- },
9736
- allowed: []
9737
- }, () => null, () => null);
9738
- }
9739
- if (await drainBackground(hooks, inv, invocation, target, background)) status = "crashed";
9740
- const followUps = status === "crashed" && instance.status === "running" && event.attempt <= d.maxFaultsPerRun ? [{
9741
- ...event,
9742
- attempt: event.attempt + 1
9743
- }] : [];
9744
- return {
9745
- status,
9746
- followUps
9747
- };
9748
- }
9749
- /** The delay before the next attempt (Workflows, Sleeping and retrying; a delay function is called). */
9750
- async function retryDelayMs$1(retries, attempt, ctx, error) {
9751
- const base = durationMs(typeof retries.delay === "function" ? await retries.delay({
9752
- ctx,
9753
- error
9754
- }) : retries.delay);
9755
- switch (retries.backoff) {
9756
- case "linear": return base * attempt;
9757
- case "exponential": return base * 2 ** (attempt - 1);
9758
- default: return base;
9759
- }
9760
- }
9761
- // packages/cloudflare/src/bindings.ts
9762
- /** A D1 database: Miniflare's SQLite, reset to the scenario's schema and read back whole. */
9763
- function d1Binding(schemas) {
9764
- const proxies = /* @__PURE__ */ new Map();
9765
- return {
9766
- kind: "d1",
9767
- target: "D1",
9768
- is: isD1,
9769
- proxy(name, real, ctx) {
9770
- let p = proxies.get(name);
9771
- if (!p) {
9772
- p = proxyD1(real, name, ctx);
9773
- proxies.set(name, p);
9774
- }
9775
- return p;
9776
- },
9777
- clear() {},
9778
- async reset(step, real) {
9779
- const schema = schemas[step.binding];
9780
- if (schema === void 0) throw new Error(`no schema provided for D1 binding ${step.binding}`);
9781
- if (!isD1(real)) throw new Error(`env.${step.binding} is not a D1 binding`);
9782
- await resetD1(real, schema);
9783
- },
9784
- async snapshot(_step, real) {
9785
- return isD1(real) ? snapshotD1(real) : null;
9786
- }
9787
- };
9788
- }
9789
- /** An R2 bucket: Miniflare's real one, emptied and seeded before each run. */
9790
- function r2Binding() {
9791
- /** The buckets the current scenario sets up. */
9792
- let setUp = /* @__PURE__ */ new Set();
9793
- const proxies = /* @__PURE__ */ new Map();
9794
- /** One book for every bucket: the stand-ins count up across them. */
9795
- const versions = new VersionBook();
9796
- return {
9797
- kind: "r2",
9798
- target: "R2",
9799
- is: isR2,
9800
- proxy(name, real, ctx) {
9801
- if (!setUp.has(name)) ctx.hooks.unsupported(`R2 binding ${name} needs an r2Bucket() setup step, which empties it before each run`);
9802
- let p = proxies.get(name);
9803
- if (!p) {
9804
- p = proxyR2(real, name, ctx, versions);
9805
- proxies.set(name, p);
9806
- }
9807
- return p;
9808
- },
9809
- clear() {
9810
- setUp = /* @__PURE__ */ new Set();
9811
- versions.clear();
9812
- },
9813
- async reset(step, real) {
9814
- if (!isR2(real)) throw new Error(`env.${step.binding} is not an R2 bucket`);
9815
- setUp.add(step.binding);
9816
- await resetR2(real, step.objects);
9817
- },
9818
- async snapshot(_step, real) {
9819
- return isR2(real) ? { objects: await snapshotR2(real) } : null;
9820
- }
9821
- };
9822
- }
9823
- /**
9824
- * A Durable Object namespace: the real objects workerd runs, cleared, seeded
9825
- * and evicted before each run, their storage snapshotted after it, and their
9826
- * alarms taken over and fired as events of the run.
9827
- */
9828
- function durableObjectBinding(deps) {
9829
- const { ctx, helpers } = deps;
9830
- const proxies = /* @__PURE__ */ new Map();
9831
- /** The bindings the current scenario's setup resets before each run. */
9832
- let setUp = /* @__PURE__ */ new Set();
9833
- /** Per binding, alarm firings allowed per object in the current run. */
9834
- let alarmLimits = /* @__PURE__ */ new Map();
9835
- /** Per binding, what the current run knows about its objects. */
9836
- const states = /* @__PURE__ */ new Map();
9837
- const stateFor = (binding) => {
9838
- let state = states.get(binding);
9839
- if (!state) {
9840
- state = new BindingState();
9841
- states.set(binding, state);
9842
- }
9843
- return state;
9844
- };
9845
- const namespace = (name, real = deps.real(name)) => {
9846
- if (!isDurableObjectNamespace(real)) throw new Error(`env.${name} is not a Durable Object namespace`);
9847
- return real;
9848
- };
9849
- const required = () => {
9850
- if (!helpers) throw new Error("Durable Object setup needs the Cloudflare test helpers: createCloudflarePlatform({ ..., durableObjects: await import(\"cloudflare:test\") })");
9851
- return helpers;
9852
- };
9853
- return {
9854
- kind: "durable_object",
9855
- target: "DO",
9856
- is: isDurableObjectNamespace,
9857
- proxy(name, real, ctx) {
9858
- let p = proxies.get(name);
9859
- if (!p) {
9860
- p = proxyNamespace(real, name, ctx, stateFor(name), helpers, () => setUp.has(name));
9861
- proxies.set(name, p);
9862
- }
9863
- return p;
9864
- },
9865
- clear() {
9866
- setUp = /* @__PURE__ */ new Set();
9867
- alarmLimits = /* @__PURE__ */ new Map();
9868
- for (const state of states.values()) state.clear();
9869
- },
9870
- async reset(step, real) {
9871
- setUp.add(step.binding);
9872
- alarmLimits.set(step.binding, step.alarmsPerObject ?? 3);
9873
- await resetNamespace(namespace(step.binding, real), required(), stateFor(step.binding).names, step.objects);
9874
- },
9875
- async snapshot(step, real, unsupported) {
9876
- const binding = step.binding;
9877
- return snapshotNamespace(namespace(binding, real), required(), stateFor(binding).names, stateFor(binding).touched, step.objects, (object) => unsupported(`Durable Object ${binding} ${object} was reached without a call Eutaxy saw (through another object's binding); calls between objects are not proxied yet`), unsupported);
9878
- },
9879
- source: alarmSource,
9880
- async deliver(event, hooks, spec) {
9881
- const binding = String(event.data.binding ?? "");
9882
- return deliverAlarm(event, hooks, spec.bounds.maxRedeliveries, {
9883
- binding,
9884
- book: stateFor(binding).alarms,
9885
- limit: alarmLimits.get(binding) ?? 3,
9886
- runAlarm: alarmRunner(namespace(binding), binding, ctx, helpers, stateFor(binding)),
9887
- abort: (id) => stateFor(binding).abort(id),
9888
- mayPark: (id) => stateFor(binding).mayPark(id),
9889
- evict: (id) => evictObject(namespace(binding), helpers, id),
9890
- bookkeep: (op, args) => hooks.effectSync({
9891
- invocation: hooks.bookkeeping(),
9892
- target: `DO:${binding}`,
9893
- op,
9894
- args,
9895
- allowed: []
9896
- }, () => null, () => null)
9897
- });
9898
- }
9899
- };
9900
- }
9901
- /**
9902
- * A Workflow binding: a model of the engine running the scenario's own
9903
- * class, never the real binding; instances live in a registry and run as
9904
- * events of the run.
9905
- */
9906
- function workflowBinding(deps) {
9907
- /** The bindings the current scenario sets up, with the class each runs. */
9908
- let classes = /* @__PURE__ */ new Map();
9909
- const registries = /* @__PURE__ */ new Map();
9910
- const registryFor = (binding) => {
9911
- let r = registries.get(binding);
9912
- if (!r) {
9913
- r = new WorkflowRegistry();
9914
- registries.set(binding, r);
9915
- }
9916
- return r;
9917
- };
9918
- const proxies = /* @__PURE__ */ new Map();
9919
- return {
9920
- kind: "workflow",
9921
- target: "Workflow",
9922
- is: isWorkflowBinding,
9923
- proxy(name, _real, ctx) {
9924
- if (!classes.has(name)) {
9925
- ctx.hooks.unsupported(`Workflow binding ${name} needs a workflow() setup step naming its class`);
9926
- return proxyWorkflow(name, ctx, new WorkflowRegistry());
9927
- }
9928
- let p = proxies.get(name);
9929
- if (!p) {
9930
- p = proxyWorkflow(name, ctx, registryFor(name));
9931
- proxies.set(name, p);
9932
- }
9933
- return p;
9934
- },
9935
- clear() {
9936
- classes = /* @__PURE__ */ new Map();
9937
- for (const registry of registries.values()) registry.clear();
9938
- },
9939
- async reset(step) {
9940
- classes.set(step.binding, step);
9941
- },
9942
- async snapshot(step) {
9943
- return { instances: registryFor(step.binding).rows() };
9944
- },
9945
- source: workflowSource,
9946
- async deliver(event, hooks, spec) {
9947
- const { binding, id } = event.data;
9948
- const setup = classes.get(binding);
9949
- if (!setup) return {
9950
- status: "errored",
9951
- followUps: []
9952
- };
9953
- const className = setup.className;
9954
- const cls = deps.exports?.[className];
9955
- const instance = registryFor(binding).instances.get(id);
9956
- if (typeof cls !== "function" || !instance) {
9957
- hooks.unsupported(`Workflow ${binding}: class ${className} is not among the Worker module's exports; pass them as createCloudflarePlatform({ ..., exports })`);
9958
- return {
9959
- status: "errored",
9960
- followUps: []
9961
- };
9962
- }
9963
- return deliverWorkflow(event, hooks, {
9964
- binding,
9965
- ...setup.name === void 0 ? {} : { name: setup.name },
9966
- instance,
9967
- cls,
9968
- env: deps.env(),
9969
- maxFaultsPerRun: spec.bounds.maxFaultsPerRun,
9970
- maxRedeliveries: spec.bounds.maxRedeliveries
9971
- });
9972
- }
9973
- };
9974
- }
9975
- /**
9976
- * A service binding: never the real binding, a stub answering from the
9977
- * scenario's `service` setup; each call one effect. Nothing to reset or
9978
- * snapshot, the callee is scripted.
9979
- */
9980
- function serviceBinding() {
9981
- /** The bindings the current scenario scripts. */
9982
- let scripts = /* @__PURE__ */ new Map();
9983
- /** Per binding, the stub for the current run's script. */
9984
- const proxies = /* @__PURE__ */ new Map();
9985
- return {
9986
- kind: "service",
9987
- target: "Service",
9988
- is: isServiceBinding,
9989
- proxy(name, _real, ctx) {
9990
- const script = scripts.get(name);
9991
- if (!script) {
9992
- ctx.hooks.unsupported(`service binding ${name} needs a service() setup step scripting the Worker it reaches`);
9993
- return proxyService(name, ctx, {
9994
- kind: "service",
9995
- binding: name,
9996
- methods: {}
9997
- });
9998
- }
9999
- let p = proxies.get(name);
10000
- if (!p) {
10001
- p = proxyService(name, ctx, script);
10002
- proxies.set(name, p);
10003
- }
10004
- return p;
10005
- },
10006
- clear() {
10007
- scripts = /* @__PURE__ */ new Map();
10008
- proxies.clear();
10009
- },
10010
- async reset(step) {
10011
- scripts.set(step.binding, step);
10012
- },
10013
- async snapshot() {
10014
- return null;
10015
- }
10016
- };
10017
- }
10018
- /**
10019
- * The setup steps these records own, each with its record, in setup order:
10020
- * what the platform resets and snapshots, and the differential runner
10021
- * compares. A step no record owns is left to the scenario's validation.
10022
- */
10023
- function ownedSetups(setup, bindings) {
10024
- const out = [];
10025
- for (const step of setup) {
10026
- const binding = bindings.find((b) => b.kind === step.kind);
10027
- if (binding) out.push([binding, step]);
10028
- }
10029
- return out;
10030
- }
10031
- // packages/cloudflare/src/caller.ts
10032
- /**
10033
- * The caller of an inbound request or RPC call. Cloudflare retries neither,
10034
- * so resends follow the policy the drive declares for the caller: how many
10035
- * times it resends, the virtual delay before each resend, and how long it
10036
- * waits for an answer. The decision is the caller's and is made once per
10037
- * attempt: at the response point, or at its deadline if the handler has
10038
- * not answered by then.
10039
- */
10040
- /** The response point: a crash before it is a response the caller never saw. */
10041
- const RESPOND = ["crash_before"];
10042
- /**
10043
- * With a caller deadline the answer can also arrive too late: `ambiguous`
10044
- * here means it was sent, the caller counted it as failed, and the handler
10045
- * carried on.
10046
- */
10047
- const RESPOND_WITH_DEADLINE = ["crash_before", "ambiguous"];
10048
- /** The virtual delay before resend number `resend` (1 for the first), per the policy. */
10049
- function retryDelayMs(policy, resend) {
10050
- const delays = policy.delaysMs ?? [];
10051
- return delays[Math.min(resend, delays.length) - 1] ?? 0;
10052
- }
10053
- /**
10054
- * Start waiting for the attempt's answer. With a deadline, a virtual timer
10055
- * makes the caller give up at it whatever the handler is doing, so a resend
10056
- * can start while the first attempt still runs. `gaveUp` is what the
10057
- * `gave_up` effect records when the retries are spent.
10058
- */
10059
- function startCaller(event, hooks, spec, policy, target, gaveUp) {
10060
- const started = Date.now();
10061
- const deadline = policy.deadlineMs;
10062
- const lateAt = deadline === void 0 ? void 0 : started + deadline;
10063
- /** The caller decides once: it accepts the answer, or gives up at `at` and resends or stops. */
10064
- let decided = false;
10065
- const giveUp = (at) => {
10066
- if (decided) return;
10067
- decided = true;
10068
- const next = redelivery(event, policy.retries, spec.bounds);
10069
- if (next) {
10070
- const resendAt = Math.max(at + retryDelayMs(policy, event.attempt), Date.now());
10071
- hooks.enqueue({
10072
- ...next,
10073
- ...resendAt > Date.now() ? { at: resendAt } : {}
10074
- });
10075
- } else hooks.effectSync({
10076
- invocation: hooks.bookkeeping(),
10077
- target,
10078
- op: "gave_up",
10079
- args: gaveUp,
10080
- allowed: []
10081
- }, () => null, () => null);
10082
- };
10083
- const deadlineTimer = lateAt === void 0 ? void 0 : setTimeout(() => giveUp(lateAt), deadline);
10084
- return {
10085
- responseFaults: deadline === void 0 ? RESPOND : RESPOND_WITH_DEADLINE,
10086
- isLate: () => lateAt !== void 0 && Date.now() > lateAt,
10087
- settle(accepted, late) {
10088
- if (deadlineTimer !== void 0) clearTimeout(deadlineTimer);
10089
- if (accepted) decided = true;
10090
- else giveUp(late && lateAt !== void 0 ? lateAt : Date.now());
10091
- }
10092
- };
10093
- }
10094
- // packages/cloudflare/src/http.ts
10095
- /** The URL inbound requests are addressed to; handlers read only the path. */
10096
- const requestOrigin = "https://worker.test";
10097
- /** Build the `Request` a drive entry describes. */
10098
- function requestFor(r) {
10099
- const headers = new Headers(r.headers);
10100
- let body = null;
10101
- if (r.body !== void 0) {
10102
- if (typeof r.body === "string") body = r.body;
10103
- else {
10104
- body = JSON.stringify(r.body);
10105
- if (!headers.has("content-type")) headers.set("content-type", "application/json");
10106
- }
10107
- }
10108
- return new Request(`${requestOrigin}${r.path}`, {
10109
- method: r.method,
10110
- headers,
10111
- body
10112
- });
10113
- }
10114
- /** A compact record of a response for the effect log: status, ok, and a bounded body. */
10115
- async function summarizeResponse(response) {
10116
- const text = await response.clone().text();
10117
- let body = text.length > 1e3 ? `${text.slice(0, 1e3)}…` : text;
10118
- if (text && (response.headers.get("content-type") ?? "").includes("json")) try {
10119
- body = JSON.parse(text);
10120
- } catch {}
10121
- return {
10122
- status: response.status,
10123
- ok: response.ok,
10124
- body
10125
- };
10126
- }
10127
- /** One attempt of an inbound request, under the caller's retry policy and deadline. */
10128
- async function deliverRequest(event, hooks, spec, drive, invocation, worker) {
10129
- const req = event.data;
10130
- const target = `Http:${req.path}`;
10131
- const inv = hooks.startInvocation(invocation);
10132
- const background = [];
10133
- const handler = worker.handler.fetch;
10134
- if (!handler) throw new Error("the Worker has no fetch() handler");
10135
- const args = {
10136
- requestId: event.id,
10137
- method: req.method,
10138
- path: req.path
10139
- };
10140
- const caller = startCaller(event, hooks, spec, drive, target, {
10141
- requestId: event.id,
10142
- attempts: event.attempt
10143
- });
10144
- const handled = await runInvocation(hooks, inv, () => handler.call(worker.handler, requestFor(req), worker.env, executionContext(background)));
10145
- const response = handled.status === "completed" ? handled.value : void 0;
10146
- let status = handled.status;
10147
- let summary = null;
10148
- let read = "errored";
10149
- if (status === "completed" && response) {
10150
- const body = await runInvocation(hooks, inv, () => summarizeResponse(response));
10151
- read = body.status === "completed" ? body.value : body.status;
10152
- if (read === "crashed" || read === "errored") status = read;
10153
- }
10154
- let late = caller.isLate();
10155
- const allowed = caller.responseFaults;
10156
- if (status === "completed" && typeof read === "object") {
10157
- const s = read;
10158
- try {
10159
- hooks.effectSync({
10160
- invocation,
10161
- target,
10162
- op: "response",
10163
- args,
10164
- allowed
10165
- }, () => s, (v) => v);
10166
- summary = s;
10167
- } catch (err) {
10168
- if (err instanceof CrashSignal) status = "crashed";
10169
- else if (err instanceof InjectedEffectError) {
10170
- summary = s;
10171
- late = true;
10172
- } else throw err;
10173
- }
10174
- } else if (status === "errored") {
10175
- const s = {
10176
- status: 500,
10177
- ok: false,
10178
- body: ""
10179
- };
10180
- hooks.effectSync({
10181
- invocation,
10182
- target,
10183
- op: "response",
10184
- args,
10185
- allowed: []
10186
- }, () => s, (v) => v);
10187
- summary = s;
10188
- }
10189
- const accepted = summary !== null && !late && (drive.retryOn === "5xx" ? summary.status < 500 : summary.ok);
10190
- caller.settle(accepted, late);
10191
- if (await drainBackground(hooks, inv, invocation, target, background)) status = "crashed";
10192
- return {
10193
- status,
10194
- followUps: []
10195
- };
10196
- }
10197
- // packages/cloudflare/src/queues.ts
10198
- /** Queue delivery: one invocation per delivery of a message, redelivered until acked or dead-lettered. */
10199
- /** Deep-copy JSON data so a handler that mutates its message cannot leak into other runs. */
10200
- function cloneJson(value) {
10201
- return JSON.parse(JSON.stringify(value));
10202
- }
10203
- /** One delivery of a queue message, with Queues' at-least-once semantics. */
10204
- async function deliverMessage(event, hooks, spec, drive, invocation, worker, maxRetries) {
10205
- const queueTarget = `Queue:${drive.queue}`;
10206
- const inv = hooks.startInvocation(invocation);
10207
- /** Cloudflare honours the first ack or retry decision per message; later ones are ignored. */
10208
- const state = { decision: null };
10209
- const background = [];
10210
- /** Records the call; the result says whether it took effect (the first decision wins). */
10211
- const decide = (op, args) => {
10212
- hooks.effectSync({
10213
- invocation,
10214
- target: queueTarget,
10215
- op,
10216
- args,
10217
- allowed: decisionFaults
10218
- }, () => {
10219
- if (state.decision !== null) return false;
10220
- state.decision = op;
10221
- return true;
10222
- }, (effective) => ({ effective }));
10223
- };
10224
- const message = {
10225
- id: event.id,
10226
- timestamp: /* @__PURE__ */ new Date(),
10227
- body: cloneJson(event.data),
10228
- attempts: event.attempt,
10229
- ack: () => decide("ack", {
10230
- messageId: event.id,
10231
- implicit: false,
10232
- body: event.data
10233
- }),
10234
- retry: () => decide("retry", {
10235
- messageId: event.id,
10236
- body: event.data
10237
- })
10238
- };
10239
- const batch = {
10240
- queue: drive.queue,
10241
- messages: [message],
10242
- metadata: { metrics: {
10243
- backlogCount: 0,
10244
- backlogBytes: 0
10245
- } },
10246
- ackAll: () => message.ack(),
10247
- retryAll: () => message.retry()
10248
- };
10249
- const execution = executionContext(background);
10250
- const handler = worker.handler.queue;
10251
- if (!handler) throw new Error("the Worker has no queue() handler");
10252
- let status = (await runInvocation(hooks, inv, () => handler.call(worker.handler, batch, worker.env, execution))).status;
10253
- if (status === "completed" && state.decision === null) try {
10254
- decide("ack", {
10255
- messageId: event.id,
10256
- implicit: true,
10257
- body: event.data
10258
- });
10259
- } catch (err) {
10260
- if (err instanceof CrashSignal) status = "crashed";
10261
- else throw err;
10262
- }
10263
- if (await drainBackground(hooks, inv, invocation, queueTarget, background)) status = "crashed";
10264
- const followUps = [];
10265
- if (state.decision !== "ack") {
10266
- const next = redelivery(event, maxRetries, spec.bounds);
10267
- if (next) followUps.push(next);
10268
- else hooks.effectSync({
10269
- invocation: hooks.bookkeeping(),
10270
- target: queueTarget,
10271
- op: "dead_letter",
10272
- args: {
10273
- messageId: event.id,
10274
- attempts: event.attempt
10275
- },
10276
- allowed: []
10277
- }, () => null, () => null);
10278
- }
10279
- return {
10280
- status,
10281
- followUps
10282
- };
10283
- }
10284
- // packages/cloudflare/src/rpc.ts
10285
- /**
10286
- * Inbound RPC delivery: one invocation per attempt of a `WorkerEntrypoint`
10287
- * method call the drive's caller makes. The entrypoint is constructed anew
10288
- * for each call, as the runtime does (Cloudflare, Workers RPC: a new
10289
- * instance of the class for every call), and its return value or the error
10290
- * it threw is the response the caller sees.
10291
- */
10292
- /**
10293
- * An error as the caller sees it over RPC: a new error object with the
10294
- * name and message (Cloudflare, RPC error handling), nothing of its class.
10295
- */
10296
- function describeError(error) {
10297
- if (error instanceof Error) return `${error.name}: ${error.message}`;
10298
- return typeof error === "string" ? error : JSON.stringify(toJson(error));
10299
- }
10300
- /** One attempt of a call, under the caller's retry policy and deadline. */
10301
- async function deliverCall(event, hooks, spec, drive, invocation, cls, env) {
10302
- const call = event.data;
10303
- const target = rpcTarget(drive, call.method);
10304
- const inv = hooks.startInvocation(invocation);
10305
- const background = [];
10306
- const args = {
10307
- callId: event.id,
10308
- method: call.method,
10309
- args: call.args
10310
- };
10311
- const caller = startCaller(event, hooks, spec, drive, target, {
10312
- callId: event.id,
10313
- attempts: event.attempt
10314
- });
10315
- const ran = await runInvocation(hooks, inv, () => callMethod(cls, call, executionContext(background), env));
10316
- let status = ran.status;
10317
- let late = caller.isLate();
10318
- let answer = null;
10319
- if (ran.status === "completed") {
10320
- if (!isPlainData(ran.value)) hooks.unsupported(`Rpc ${call.method}: the result is not plain data (a stub, a function or a stream); RPC capabilities are not modelled`);
10321
- const s = {
10322
- ok: true,
10323
- value: toJson(ran.value)
10324
- };
10325
- try {
10326
- hooks.effectSync({
10327
- invocation,
10328
- target,
10329
- op: "response",
10330
- args,
10331
- allowed: caller.responseFaults
10332
- }, () => s, (v) => v);
10333
- answer = s;
10334
- } catch (err) {
10335
- if (err instanceof CrashSignal) status = "crashed";
10336
- else if (err instanceof InjectedEffectError) {
10337
- answer = s;
10338
- late = true;
10339
- } else throw err;
10340
- }
10341
- } else if (ran.status === "errored") {
10342
- const s = {
10343
- ok: false,
10344
- error: describeError(ran.error)
10345
- };
10346
- hooks.effectSync({
10347
- invocation,
10348
- target,
10349
- op: "response",
10350
- args,
10351
- allowed: []
10352
- }, () => s, (v) => v);
10353
- answer = s;
10354
- }
10355
- caller.settle(answer !== null && !late && answer.ok, late);
10356
- if (await drainBackground(hooks, inv, invocation, target, background)) status = "crashed";
10357
- return {
10358
- status,
10359
- followUps: []
10360
- };
10361
- }
10362
- /**
10363
- * The class an RPC drive calls: the named export, or the Worker's default
10364
- * export (the class passed as the handler, or `exports.default`). Not
10365
- * necessarily a class: the platform reports what it found instead.
10366
- */
10367
- function entrypointClass(handler, exports, entrypoint) {
10368
- if (entrypoint !== void 0) return exports?.[entrypoint];
10369
- return typeof handler === "function" ? handler : exports?.["default"];
10370
- }
10371
- /**
10372
- * The method RPC exposes under a name: one the class or a superclass defines
10373
- * on its prototype. An instance property, even a function, and Object's own
10374
- * methods are not callable (workerd: "The RPC receiver does not implement the
10375
- * method").
10376
- */
10377
- function rpcMethod(instance, name) {
10378
- for (let proto = Object.getPrototypeOf(instance); proto !== null && proto !== Object.prototype; proto = Object.getPrototypeOf(proto)) {
10379
- const own = Object.getOwnPropertyDescriptor(proto, name);
10380
- if (!own) continue;
10381
- return typeof own.value === "function" && name !== "constructor" ? own.value : void 0;
10382
- }
10383
- }
10384
- /**
10385
- * Construct the entrypoint for one call and invoke the method, as the
10386
- * runtime does per call. The arguments are copied, as RPC copies them: a
10387
- * method that mutates one changes neither the scenario nor a later attempt.
10388
- */
10389
- function callMethod(cls, call, ctx, env) {
10390
- const instance = constructEntrypoint(cls, "WorkerEntrypoint", ctx, env);
10391
- const method = rpcMethod(instance, call.method);
10392
- if (!method) throw new TypeError(`The RPC receiver does not implement the method "${call.method}".`);
10393
- return method.apply(instance, structuredClone(call.args));
10394
- }
10395
- // packages/cloudflare/src/scheduled.ts
10396
- /**
10397
- * Cron Trigger delivery: one invocation of the Worker's `scheduled()` handler
10398
- * per tick attempt, with `scheduledTime` the tick's virtual time and `cron`
10399
- * the expression (Workers, Scheduled handler). Cloudflare documents
10400
- * `noRetry()` but no retry count, so the drive declares how many times a
10401
- * tick whose handler failed is re-run; `noRetry()` stops them.
10402
- */
10403
- /** One attempt of a tick: the handler runs, and a failure is re-run as the drive declares unless it said noRetry(). */
10404
- async function deliverTick(event, hooks, spec, drive, invocation, worker) {
10405
- const tick = event.data;
10406
- const target = `Cron:${drive.cron}`;
10407
- const inv = hooks.startInvocation(invocation);
10408
- const background = [];
10409
- /** Rejections of waitUntil work: the first one is the invocation's status (Cloudflare, Scheduled handler). */
10410
- const failures = [];
10411
- const handler = worker.handler.scheduled;
10412
- if (!handler) throw new Error("the Worker has no scheduled() handler");
10413
- let noRetry = false;
10414
- const controller = {
10415
- scheduledTime: tick.scheduledTime,
10416
- cron: tick.cron,
10417
- noRetry: () => {
10418
- hooks.effectSync({
10419
- invocation,
10420
- target,
10421
- op: "no_retry",
10422
- args: { tick: event.id },
10423
- allowed: decisionFaults
10424
- }, () => {
10425
- noRetry = true;
10426
- return null;
10427
- }, () => null);
10428
- }
10429
- };
10430
- let status = (await runInvocation(hooks, inv, () => handler.call(worker.handler, controller, worker.env, executionContext(background, failures)))).status;
10431
- if (await drainBackground(hooks, inv, invocation, target, background)) status = "crashed";
10432
- if (status === "completed" && failures.length > 0) status = "errored";
10433
- const followUps = [];
10434
- if (status !== "completed" && !noRetry) {
10435
- const next = redelivery(event, drive.retries, spec.bounds);
10436
- if (next) followUps.push(next);
10437
- else hooks.effectSync({
10438
- invocation: hooks.bookkeeping(),
10439
- target,
10440
- op: "gave_up",
10441
- args: {
10442
- tick: event.id,
10443
- attempts: event.attempt
10444
- },
10445
- allowed: []
10446
- }, () => null, () => null);
10447
- }
10448
- return {
10449
- status,
10450
- followUps
10451
- };
10452
- }
10453
- // packages/cloudflare/src/platform.ts
10454
- /**
10455
- * The Cloudflare platform: delivers queue messages to the Worker's `queue()`
10456
- * handler and inbound requests to its `fetch()` handler, with proxied
10457
- * bindings, and applies Queues' at-least-once semantics (explicit and
10458
- * implicit ack, retry, redelivery up to max_retries, dead-lettering) as
10459
- * documented by Cloudflare, and for requests the caller's retry policy
10460
- * declared in the drive.
10461
- */
10462
- function isBindingLike(value) {
10463
- if (typeof value === "function") return true;
10464
- if (typeof value !== "object" || value === null) return false;
10465
- const proto = Object.getPrototypeOf(value);
10466
- return [...Object.getOwnPropertyNames(value), ...Object.getOwnPropertyNames(proto ?? {})].some((k) => k !== "constructor" && typeof value[k] === "function");
10467
- }
10468
- const assumptions = [
10469
- "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",
10470
- "D1 statements run against Miniflare's SQLite; each run/first/all/raw/batch/exec is one effect",
10471
- "message.timestamp is the virtual clock's time at delivery",
10472
- "only D1, Durable Object, R2, Workflow and scripted service bindings are proxied; touching any other binding makes the run UNSUPPORTED",
10473
- "service bindings are scripted callees: the Worker behind a binding is never called; each RPC method call or fetch() through it is one effect answered from the scenario's service() setup, where crash_before and error mean the call never reached the callee, ambiguous that it acted and the answer was lost, and crash_after that the caller died after it (developers.cloudflare.com/workers/runtime-apis/bindings/service-bindings/); Cloudflare does not retry such a call",
10474
- "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",
10475
- "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/)",
10476
- "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)",
10477
- "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/)",
10478
- "state invariants read a snapshot of every D1 binding named in setup, taken after the last event",
10479
- "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",
10480
- "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/)",
10481
- "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",
10482
- "cron triggers: each tick of the drive's expression is one invocation of scheduled(), with scheduledTime the tick's virtual time (UTC, the expression's matches from the virtual epoch on, in Cloudflare's dialect where weekdays run 1 = Sunday to 7 = Saturday; L, W and # are not modelled) and cron the expression (developers.cloudflare.com/workers/runtime-apis/handlers/scheduled/, /workers/configuration/cron-triggers/); Cloudflare documents noRetry() but no retry count, so the drive declares how many times a tick whose handler failed is re-run, and none after noRetry()",
10483
- "inbound RPC: one invocation per call attempt, the entrypoint constructed anew for each with a fresh ExecutionContext (developers.cloudflare.com/workers/runtime-apis/bindings/service-bindings/rpc/); the return value is the response effect, and an exception reaches the caller as a new error with its name and message (developers.cloudflare.com/workers/runtime-apis/rpc/error-handling/); Cloudflare does not retry a call, so the drive's caller resends a call that threw or got no answer as the http drive's caller does; a result that is not plain data (a stub, a function, a stream) makes the run UNSUPPORTED"
10484
- ];
10485
- function createCloudflarePlatform(options) {
10486
- const env = options.env;
10487
- const maxRetries = options.maxRetries ?? 3;
10488
- let hooksRef = null;
10489
- const ctx = {
10490
- get hooks() {
10491
- if (!hooksRef) throw new Error("no run in progress");
10492
- return hooksRef;
10493
- },
10494
- currentInvocation: () => ctx.hooks.running()
10495
- };
10496
- /**
10497
- * The kinds of binding modelled, in the order an env value is tried against
10498
- * them: a service binding first, since in workerd it answers every duck
10499
- * type (its property reads are RPC stubs).
10500
- */
10501
- const bindings = [
10502
- serviceBinding(),
10503
- d1Binding(options.schemas),
10504
- durableObjectBinding({
10505
- ctx,
10506
- helpers: options.durableObjects,
10507
- real: (name) => env[name]
10508
- }),
10509
- r2Binding(),
10510
- workflowBinding({
10511
- exports: options.exports,
10512
- env: () => proxiedEnv
10513
- })
10514
- ];
10515
- const proxiedEnv = new Proxy(env, { get(target, prop, receiver) {
10516
- const value = Reflect.get(target, prop, receiver);
10517
- if (typeof prop !== "string") return value;
10518
- for (const binding of bindings) if (binding.is(value)) return binding.proxy(prop, value, ctx);
10519
- if (isBindingLike(value)) ctx.hooks.unsupported(`binding ${prop} is not proxied`);
10520
- return value;
10521
- } });
10522
- const worker = {
10523
- handler: typeof options.handler === "function" ? {} : options.handler,
10524
- env: proxiedEnv
10525
- };
10526
- return {
10527
- name: "cloudflare",
10528
- assumptions,
10529
- concurrent: true,
10530
- async reset(spec) {
10531
- for (const binding of bindings) binding.clear();
10532
- for (const [binding, setup] of ownedSetups(spec.setup, bindings)) await binding.reset(setup, env[setup.binding]);
10533
- },
10534
- restrictEvents(spec, keepIds) {
10535
- return {
10536
- ...spec,
10537
- drive: restrictDrive(spec.drive, keepIds)
10538
- };
10539
- },
10540
- async finish(spec, hooks) {
10541
- for (const [binding, setup] of ownedSetups(spec.setup, bindings)) {
10542
- const tables = await binding.snapshot(setup, env[setup.binding], (reason) => hooks.unsupported(reason));
10543
- if (tables) hooks.snapshot(hooks.bookkeeping(), `${binding.target}:${setup.binding}`, { tables });
10544
- }
10545
- },
10546
- initialEvents(spec) {
10547
- return driveEvents(spec.drive);
10548
- },
10549
- async deliver(event, hooks, spec) {
10550
- const drive = spec.drive;
10551
- const invocation = invocationOf(event);
10552
- hooksRef = hooks;
10553
- const owner = event.source === void 0 ? void 0 : bindings.find((b) => b.source === event.source);
10554
- if (owner?.deliver) return owner.deliver(event, hooks, spec);
10555
- switch (drive.kind) {
10556
- case "http": return deliverRequest(event, hooks, spec, drive, invocation, worker);
10557
- case "cron": return deliverTick(event, hooks, spec, drive, invocation, worker);
10558
- case "rpc": {
10559
- const cls = entrypointClass(options.handler, options.exports, drive.entrypoint);
10560
- if (typeof cls !== "function") {
10561
- hooks.unsupported(`Rpc: ${drive.entrypoint === void 0 ? "the Worker's default export" : `export ${drive.entrypoint}`} is not a WorkerEntrypoint class; pass the Worker module's exports as createCloudflarePlatform({ ..., exports })`);
10562
- return {
10563
- status: "errored",
10564
- followUps: []
10565
- };
10566
- }
10567
- return deliverCall(event, hooks, spec, drive, invocation, cls, proxiedEnv);
10568
- }
10569
- default: return deliverMessage(event, hooks, spec, drive, invocation, worker, maxRetries);
10570
- }
10571
- }
10572
- };
10573
- }
10574
- // packages/cloudflare/src/differential.ts
10575
- /**
10576
- * Differential check: the same fault-free scenario run once through Eutaxy's
10577
- * proxies and once against the raw bindings, with the queue model (or the
10578
- * HTTP caller's retry policy) applied on the raw side itself. Any difference in the per-attempt decisions or in
10579
- * the final D1 and R2 state is a bug in the proxies or the platform model, not in
10580
- * the Worker. The raw side shares Eutaxy's *reading* of Cloudflare's queue
10581
- * semantics (core's redelivery rule among it); what it does not share is any proxy code.
10582
- */
10583
- /**
10584
- * The raw side's only wrapper: counts D1 calls in flight (so the settle loop
10585
- * knows real I/O is pending) and advances the clock as the proxies do. It
10586
- * records nothing and injects nothing.
10587
- */
10588
- function countingD1(real, io, clock) {
10589
- const realOf = /* @__PURE__ */ new WeakMap();
10590
- const track = async (p) => {
10591
- io.n++;
10592
- try {
10593
- return await p;
10594
- } finally {
10595
- io.n--;
10596
- clock.advance(1);
10597
- }
10598
- };
10599
- const wrapStatement = (s) => {
10600
- const proxy = new Proxy(s, { get(t, prop, r) {
10601
- const v = Reflect.get(t, prop, r);
10602
- if (prop === "bind") return (...a) => wrapStatement(t.bind(...a));
10603
- if (prop === "run" || prop === "all" || prop === "first" || prop === "raw") return (...a) => track(v.apply(t, a));
10604
- return typeof v === "function" ? v.bind(t) : v;
10605
- } });
10606
- realOf.set(proxy, s);
10607
- return proxy;
10608
- };
10609
- return new Proxy(real, { get(t, prop, r) {
10610
- const v = Reflect.get(t, prop, r);
10611
- if (prop === "prepare") return (sql) => wrapStatement(t.prepare(sql));
10612
- if (prop === "batch") return (stmts) => track(t.batch(stmts.map((s) => realOf.get(s) ?? s)));
10613
- if (prop === "exec") return (sql) => track(t.exec(sql));
10614
- return typeof v === "function" ? v.bind(t) : v;
10615
- } });
10616
- }
10617
- /**
10618
- * The same for an R2 bucket: each call advances the clock as its proxied
10619
- * effect does, and reading a body it gave counts as I/O in flight but does
10620
- * not advance the clock (the proxy reads it inside the get). Reads through
10621
- * the body's own stream are not counted: wrapping it would lose the known
10622
- * length a copy's put needs, and Miniflare answers them within the settle
10623
- * loop's real tick (checked with an 8 MB body).
10624
- */
10625
- function countingR2(real, io, clock) {
10626
- const track = async (p, advance) => {
10627
- io.n++;
10628
- try {
10629
- return await p;
10630
- } finally {
10631
- io.n--;
10632
- if (advance) clock.advance(1);
10633
- }
10634
- };
10635
- const reads = [
10636
- "arrayBuffer",
10637
- "bytes",
10638
- "text",
10639
- "json",
10640
- "blob"
10641
- ];
10642
- const counted = (o) => {
10643
- if (o === null || typeof o !== "object" || !("body" in o)) return o;
10644
- return new Proxy(o, { get(t, prop) {
10645
- const v = Reflect.get(t, prop);
10646
- if (typeof prop === "string" && reads.includes(prop) && typeof v === "function") return (...a) => track(v.apply(t, a), false);
10647
- return typeof v === "function" ? v.bind(t) : v;
10648
- } });
10649
- };
10650
- return new Proxy(real, { get(t, prop, r) {
10651
- const v = Reflect.get(t, prop, r);
10652
- if (prop === "put" || prop === "delete" || prop === "get" || prop === "head" || prop === "list") return async (...a) => counted(await track(v.apply(t, a), true));
10653
- return typeof v === "function" ? v.bind(t) : v;
10654
- } });
10655
- }
10656
- /**
10657
- * The bindings whose state the two sides compare: those a store holds and
10658
- * the real binding resets and reads back (D1, R2). Durable Objects and
10659
- * Workflows have no raw side.
10660
- */
10661
- function storedBindings(options) {
10662
- return [d1Binding(options.schemas), r2Binding()];
10663
- }
10664
- async function snapshotAll(spec, options) {
10665
- const env = options.env;
10666
- const out = {};
10667
- for (const [binding, setup] of ownedSetups(spec.setup, storedBindings(options))) {
10668
- const tables = await binding.snapshot(setup, env[setup.binding], (reason) => {
10669
- throw new Error(`snapshot of ${setup.binding}: ${reason}`);
10670
- });
10671
- if (tables) out[setup.binding] = tables;
10672
- }
10673
- return out;
10674
- }
10675
- /** The Eutaxy side, keeping each delivery's status and the decision it made. */
10676
- async function eutaxySide(spec, options) {
10677
- const { attempts, unsupported } = await proxiedSide(spec, createCloudflarePlatform(options), (event, result, entries) => {
10678
- const invocation = invocationOf(event);
10679
- const mine = entries.filter((e) => e.invocation === invocation);
10680
- const decision = mine.some((e) => e.kind === "result" && e.op === "no_retry") ? "no_retry" : mine.find((e) => e.kind === "result" && (e.op === "ack" || e.op === "retry") && getPath(e.payload, "result.effective") === true)?.op;
10681
- const response = mine.find((e) => e.kind === "result" && e.op === "response");
10682
- const answer = () => {
10683
- if (!response) return {};
10684
- if (spec.drive.kind === "rpc") return { result: getPath(response.payload, "result") ?? null };
10685
- return { response: getPath(response.payload, "result.status") };
10686
- };
10687
- return {
10688
- event: event.id,
10689
- attempt: event.attempt,
10690
- status: result.status === "completed" ? "completed" : "errored",
10691
- decision: decision ?? null,
10692
- ...answer()
10693
- };
10694
- });
10695
- return {
10696
- attempts,
10697
- state: await snapshotAll(spec, options),
10698
- unsupported
10699
- };
10700
- }
10701
- /** Each binding's tables under `<binding>.<table>`, as the comparison names them. */
10702
- function flatten(state) {
10703
- const out = {};
10704
- for (const [binding, tables] of Object.entries(state)) for (const [table, rows] of Object.entries(tables)) out[`${binding}.${table}`] = rows;
10705
- return out;
10706
- }
10707
- /** The next event as the engine picks it: the earliest due, the first inserted among equals. */
10708
- function takeEarliest(pending) {
10709
- let best = 0;
10710
- for (let i = 1; i < pending.length; i++) if ((pending[i]?.at ?? 0) < (pending[best]?.at ?? 0)) best = i;
10711
- return pending.splice(best, 1)[0];
10712
- }
10713
- /** The raw side: the handler called directly with the real bindings and plain message or Request objects. */
10714
- async function rawSide(spec, options) {
10715
- const env = options.env;
10716
- const drive = spec.drive;
10717
- const maxRetries = options.maxRetries ?? 3;
10718
- for (const [binding, setup] of ownedSetups(spec.setup, storedBindings(options))) await binding.reset(setup, env[setup.binding]);
10719
- const attempts = [];
10720
- const pending = [...driveEvents(drive)];
10721
- const patched = patchGlobals(0);
10722
- const unsupported = [];
10723
- const restoreFetch = installScriptedFetch(spec.externals, null, (r) => unsupported.push(r), () => patched.clock.advance(1));
10724
- const io = { n: 0 };
10725
- const counting = /* @__PURE__ */ new Map();
10726
- const countedEnv = new Proxy(env, { get(target, prop, receiver) {
10727
- const value = Reflect.get(target, prop, receiver);
10728
- if (typeof prop !== "string" || !(isD1(value) || isR2(value))) return value;
10729
- let c = counting.get(prop);
10730
- if (!c) {
10731
- c = isD1(value) ? countingD1(value, io, patched.clock) : countingR2(value, io, patched.clock);
10732
- counting.set(prop, c);
10733
- }
10734
- return c;
10735
- } });
10736
- const settle = (p) => settleOn(p, {
10737
- clock: patched.clock,
10738
- inFlight: () => io.n,
10739
- crashed: () => false,
10740
- stuck: () => {
10741
- throw new DifferentialStuck();
10742
- }
10743
- });
10744
- try {
10745
- const handlers = typeof options.handler === "function" ? {} : options.handler;
10746
- if (drive.kind === "rpc") {
10747
- const cls = entrypointClass(options.handler, options.exports, drive.entrypoint);
10748
- if (typeof cls !== "function") throw new Error("the Worker has no WorkerEntrypoint class");
10749
- while (pending.length > 0) {
10750
- const event = takeEarliest(pending);
10751
- const call = event.data;
10752
- const background = [];
10753
- let status;
10754
- let result;
10755
- try {
10756
- const value = await settle(Promise.resolve().then(() => callMethod(cls, call, executionContext(background), countedEnv)));
10757
- result = {
10758
- ok: true,
10759
- value: toJson(value)
10760
- };
10761
- status = "completed";
10762
- } catch (err) {
10763
- if (err instanceof CrashSignal || err instanceof DifferentialStuck) throw err;
10764
- result = {
10765
- ok: false,
10766
- error: describeError(err)
10767
- };
10768
- status = "errored";
10769
- }
10770
- await settle(Promise.all(background));
10771
- attempts.push({
10772
- event: event.id,
10773
- attempt: event.attempt,
10774
- status,
10775
- decision: null,
10776
- result
10777
- });
10778
- const next = status === "completed" ? null : redelivery(event, drive.retries, spec.bounds);
10779
- if (next) pending.push(next);
10780
- }
10781
- } else if (drive.kind === "cron") {
10782
- const handler = handlers.scheduled;
10783
- if (!handler) throw new Error("the Worker has no scheduled() handler");
10784
- while (pending.length > 0) {
10785
- const event = takeEarliest(pending);
10786
- const tick = event.data;
10787
- if (event.at !== void 0 && event.at > patched.clock.now()) patched.clock.advance(event.at - patched.clock.now());
10788
- const background = [];
10789
- const failures = [];
10790
- let noRetry = false;
10791
- const controller = {
10792
- scheduledTime: tick.scheduledTime,
10793
- cron: tick.cron,
10794
- noRetry: () => {
10795
- noRetry = true;
10796
- }
10797
- };
10798
- let status;
10799
- try {
10800
- await settle(Promise.resolve().then(() => handler.call(handlers, controller, countedEnv, executionContext(background, failures))));
10801
- status = "completed";
10802
- } catch (err) {
10803
- if (err instanceof CrashSignal || err instanceof DifferentialStuck) throw err;
10804
- status = "errored";
10805
- }
10806
- await settle(Promise.all(background));
10807
- if (status === "completed" && failures.length > 0) status = "errored";
10808
- attempts.push({
10809
- event: event.id,
10810
- attempt: event.attempt,
10811
- status,
10812
- decision: noRetry ? "no_retry" : null
10813
- });
10814
- const next = status === "completed" || noRetry ? null : redelivery(event, drive.retries, spec.bounds);
10815
- if (next) pending.push(next);
10816
- }
10817
- } else if (drive.kind === "http") {
10818
- const handler = handlers.fetch;
10819
- if (!handler) throw new Error("the Worker has no fetch() handler");
10820
- while (pending.length > 0) {
10821
- const event = takeEarliest(pending);
10822
- const req = event.data;
10823
- const background = [];
10824
- let status;
10825
- let response = 500;
10826
- try {
10827
- const r = await settle(Promise.resolve().then(() => handler.call(handlers, requestFor(req), countedEnv, executionContext(background))));
10828
- await settle(r.clone().text());
10829
- response = r.status;
10830
- status = "completed";
10831
- } catch (err) {
10832
- if (err instanceof CrashSignal || err instanceof DifferentialStuck) throw err;
10833
- status = "errored";
10834
- }
10835
- await settle(Promise.all(background));
10836
- attempts.push({
10837
- event: event.id,
10838
- attempt: event.attempt,
10839
- status,
10840
- decision: null,
10841
- response
10842
- });
10843
- const next = (drive.retryOn === "5xx" ? response < 500 : response >= 200 && response < 300) ? null : redelivery(event, drive.retries, spec.bounds);
10844
- if (next) pending.push(next);
10845
- }
10846
- } else {
10847
- const handler = handlers.queue;
10848
- if (!handler) throw new Error("the Worker has no queue() handler");
10849
- while (pending.length > 0) {
10850
- const event = takeEarliest(pending);
10851
- let decision = null;
10852
- const background = [];
10853
- const message = {
10854
- id: event.id,
10855
- timestamp: /* @__PURE__ */ new Date(),
10856
- body: JSON.parse(JSON.stringify(event.data)),
10857
- attempts: event.attempt,
10858
- ack: () => {
10859
- decision ??= "ack";
10860
- },
10861
- retry: () => {
10862
- decision ??= "retry";
10863
- }
10864
- };
10865
- const batch = {
10866
- queue: drive.queue,
10867
- messages: [message],
10868
- metadata: { metrics: {
10869
- backlogCount: 0,
10870
- backlogBytes: 0
10871
- } },
10872
- ackAll: () => message.ack(),
10873
- retryAll: () => message.retry()
10874
- };
10875
- const ctx = executionContext(background);
10876
- let status;
10877
- try {
10878
- await settle(Promise.resolve().then(() => handler.call(handlers, batch, countedEnv, ctx)));
10879
- status = "completed";
10880
- } catch (err) {
10881
- if (err instanceof CrashSignal || err instanceof DifferentialStuck) throw err;
10882
- status = "errored";
10883
- }
10884
- if (status === "completed") decision ??= "ack";
10885
- await settle(Promise.all(background));
10886
- attempts.push({
10887
- event: event.id,
10888
- attempt: event.attempt,
10889
- status,
10890
- decision
10891
- });
10892
- const next = decision === "ack" ? null : redelivery(event, maxRetries, spec.bounds);
10893
- if (next) pending.push(next);
10894
- }
10895
- }
10896
- } finally {
10897
- restoreFetch();
10898
- patched.restore();
10899
- }
10900
- if (unsupported.length > 0) throw new DifferentialStuck(`raw side: ${unsupported.join("; ")}`);
10901
- return {
10902
- attempts,
10903
- state: await snapshotAll(spec, options)
10904
- };
10905
- }
10906
- /** Run both sides and compare. The Eutaxy side runs first; both start from the schema. */
10907
- async function runDifferential(spec, options) {
10908
- if ((spec.drive.kind === "http" || spec.drive.kind === "rpc") && ("delaysMs" in spec.drive || "deadlineMs" in spec.drive)) throw new Error("runDifferential does not model the caller's delaysMs or deadlineMs yet");
10909
- const { unsupported, ...eutaxy } = await eutaxySide(spec, options);
10910
- const raw = await rawSide(spec, options);
10911
- const differences = compareSides({
10912
- attempts: eutaxy.attempts,
10913
- state: flatten(eutaxy.state)
10914
- }, {
10915
- attempts: raw.attempts,
10916
- state: flatten(raw.state)
10917
- }, unsupported);
10918
- return {
10919
- equal: differences.length === 0,
10920
- eutaxy,
10921
- raw,
10922
- differences,
10923
- unsupported
10924
- };
10925
- }
10926
- // packages/cli/src/workerd.ts
10927
- /**
10928
- * The half of `eutaxy check` that runs inside workerd: the generated test
10929
- * passes its module globs here and stores what this returns in its task
10930
- * meta, which the CLI reads back. It imports nothing that needs Node, so
10931
- * the Cloudflare Vitest plugin can load it.
10932
- */
10933
- /** Each D1 binding's schema, read from the `.sql` files next to the scenario. */
10934
- function schemasFor(scenario, sqlFiles) {
10935
- const schemas = {};
10936
- for (const step of scenario.setup) {
10937
- if (step.kind !== "d1") continue;
10938
- const file = String(step["schemaFile"]);
10939
- const sql = sqlFiles[globKey(file)];
10940
- if (sql === void 0) throw new Error(`schema file ${file} not found next to the scenario`);
10941
- schemas[String(step["binding"])] = sql;
10942
- }
10943
- return schemas;
10944
- }
10945
- /**
10946
- * The modules the scenario's `specs` name, loaded with their specs and
10947
- * their spec files, and every reason the check cannot go ahead: a module
10948
- * that is not there, a spec that does not read, a function name observed
10949
- * in two modules (decisions are logged by name, so it would be ambiguous).
10950
- * The spec files are loaded here, before anything is observed, so the
10951
- * functions their specs hold are the modules' own.
10952
- */
10953
- async function selectSpecModules(scenario, modules, specEntries) {
10954
- const decisions = scenario.invariants.flatMap((i) => i.kind === "refines" ? [i.decision] : []);
10955
- const specErrors = [];
10956
- const selected = [];
10957
- for (const path of scenario.specs ?? []) {
10958
- const load = modules[globKey(path)];
10959
- if (!load) {
10960
- specErrors.push({
10961
- module: path,
10962
- line: 0,
10963
- message: "no such module next to the scenario"
10964
- });
10965
- continue;
10966
- }
10967
- const namespace = await load();
10968
- const key = specKey(path);
10969
- const entry = Object.hasOwn(specEntries, key) ? specEntries[key] : void 0;
10970
- const specs = entry?.specs ?? {
10971
- functions: [],
10972
- errors: []
10973
- };
10974
- for (const e of specs.errors) specErrors.push({
10975
- module: e.inModule ? path : `${path.replace(/\.ts$/, "")}.props.ts`,
10976
- line: e.line,
10977
- message: e.message
10978
- });
10979
- const props = entry ? await entry.load() : {};
10980
- const exported = decisions.filter((d) => typeof namespace[d] === "function");
10981
- const names = [.../* @__PURE__ */ new Set([...specs.functions.map((f) => f.name), ...exported])];
10982
- selected.push({
10983
- path,
10984
- key,
10985
- namespace,
10986
- specs,
10987
- props,
10988
- names
10989
- });
10990
- }
10991
- const observedIn = /* @__PURE__ */ new Map();
10992
- for (const m of selected) for (const n of m.names) {
10993
- const other = observedIn.get(n);
10994
- if (other === void 0) observedIn.set(n, m.path);
10995
- else specErrors.push({
10996
- module: m.path,
10997
- line: 0,
10998
- message: `${n} is observed in both ${other} and ${m.path}; decisions of one name must come from one module`
10999
- });
11000
- }
11001
- return {
11002
- selected,
11003
- specErrors
11004
- };
11005
- }
11006
- /** Run the scenario's check, with its specs observed, and return what the CLI reads back. */
11007
- async function checkInWorkerd(input) {
11008
- const { scenario } = input;
11009
- const schemas = schemasFor(scenario, input.sqlFiles);
11010
- const load = input.modules[globKey(scenario.worker.entry)];
11011
- if (!load) throw new Error(`worker entry ${scenario.worker.entry} not found next to the scenario`);
11012
- const worker = await load();
11013
- const platform = createCloudflarePlatform({
11014
- env: input.env,
11015
- handler: worker.default,
11016
- schemas,
11017
- durableObjects: input.durableObjects,
11018
- exports: worker
11019
- });
11020
- const { selected, specErrors } = await selectSpecModules(scenario, input.modules, input.specEntries);
11021
- const transportBase = {
11022
- worker: scenario.worker,
11023
- setup: scenario.setup,
11024
- drive: scenario.drive
11025
- };
11026
- if (specErrors.length > 0) return {
11027
- report: null,
11028
- specErrors,
11029
- ...transportBase
11030
- };
11031
- const observers = selected.map((m) => observeCore(m.namespace, m.names));
11032
- let verdict;
11033
- try {
11034
- verdict = await check(scenario, platform, {
11035
- seed: input.seed,
11036
- ...input.maxRuns === void 0 ? {} : { maxRuns: input.maxRuns },
11037
- ...input.budgetMs === void 0 ? {} : { budgetMs: input.budgetMs },
11038
- ...input.exhaustive ? { exhaustive: true } : {}
11039
- });
11040
- } finally {
11041
- for (const o of observers) o.restore();
11042
- }
11043
- const specs = selected.flatMap((m, i) => checkSpecModule(m.key, m.specs, m.props, m.namespace, observers[i], { tested: { seed: input.seed } }));
11044
- return {
11045
- report: JSON.parse(renderJson(verdict, specs)),
11046
- ...transportBase,
11047
- observed: selected.map((m) => ({
11048
- module: m.path,
11049
- functions: m.names
11050
- }))
11051
- };
11052
- }
11053
- export { serviceCall as A, r2Op as C, rpc as D, refines as E, snapshotD1 as F, check as I, expectHolds as L, workflow as M, workflowRows as N, rpcResponse as O, workflowStep as P, main as R, r2Bucket as S, references as T, http as _, cron as a, queue as b, d1Rows as c, defineScenario as d, durableObject as f, fetchCall as g, external as h, atLeastOncePerMessage as i, unique as j, service as k, d1Schema as l, everyRow as m, runDifferential as n, d1Param as o, durableObjectRows as p, createCloudflarePlatform as r, d1Read as s, checkInWorkerd as t, d1Write as u, httpResponse as v, r2Rows as w, queueAck as x, implies as y, cloudflareRegressionTest as z };
7700
+ export { main as t };
11054
7701
 
11055
- //# sourceMappingURL=src-BYm3aLWV.mjs.map
7702
+ //# sourceMappingURL=cli-D3SPblWw.mjs.map