eutaxy 0.13.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/README.md +10 -6
  2. package/dist/aws.d.mts +28 -2
  3. package/dist/aws.d.mts.map +1 -1
  4. package/dist/aws.mjs +13 -2
  5. package/dist/aws.mjs.map +1 -1
  6. package/dist/bin.mjs +1 -1
  7. package/dist/{cli-D3SPblWw.mjs → cli-CzGCMudc.mjs} +1269 -117
  8. package/dist/cli-CzGCMudc.mjs.map +1 -0
  9. package/dist/cli.d.mts.map +1 -1
  10. package/dist/cli.mjs +1 -1
  11. package/dist/cloudflare.d.mts +180 -15
  12. package/dist/cloudflare.d.mts.map +1 -1
  13. package/dist/cloudflare.mjs +3 -3
  14. package/dist/{combinators-Bsd9HKtw.d.mts → combinators-BecOKcmi.d.mts} +7 -1
  15. package/dist/combinators-BecOKcmi.d.mts.map +1 -0
  16. package/dist/{combinators-CVjxodAJ.mjs → combinators-CLfsPfhT.mjs} +6 -1
  17. package/dist/combinators-CLfsPfhT.mjs.map +1 -0
  18. package/dist/{delivery-invariants-Br29H7Rg.mjs → delivery-invariants-BCtvzAfW.mjs} +7 -2
  19. package/dist/delivery-invariants-BCtvzAfW.mjs.map +1 -0
  20. package/dist/delivery-invariants-DzMy3iPs.d.mts +10 -0
  21. package/dist/delivery-invariants-DzMy3iPs.d.mts.map +1 -0
  22. package/dist/{explore-B7aR_5Hy.d.mts → explore-B52m-wmk.d.mts} +13 -2
  23. package/dist/explore-B52m-wmk.d.mts.map +1 -0
  24. package/dist/index.d.mts +25 -3
  25. package/dist/index.d.mts.map +1 -1
  26. package/dist/index.mjs +2 -2
  27. package/dist/index.mjs.map +1 -1
  28. package/dist/{platform-CCz48WF9.d.mts → platform-Ba1Kvdza.d.mts} +18 -1
  29. package/dist/platform-Ba1Kvdza.d.mts.map +1 -0
  30. package/dist/provers-DS44OeEm.mjs.map +1 -1
  31. package/dist/spec.d.mts +1 -1
  32. package/dist/spec.mjs +1 -1
  33. package/dist/{src-5pKRvj02.mjs → src-nwQA9Xwr.mjs} +9 -3
  34. package/dist/src-nwQA9Xwr.mjs.map +1 -0
  35. package/dist/{src-DGh7w877.mjs → src-ud5wEfnx.mjs} +111 -16
  36. package/dist/src-ud5wEfnx.mjs.map +1 -0
  37. package/dist/{workerd-BMJ-GKx8.mjs → workerd-Be43_PZo.mjs} +2050 -1503
  38. package/dist/workerd-Be43_PZo.mjs.map +1 -0
  39. package/package.json +1 -1
  40. package/dist/cli-D3SPblWw.mjs.map +0 -1
  41. package/dist/combinators-Bsd9HKtw.d.mts.map +0 -1
  42. package/dist/combinators-CVjxodAJ.mjs.map +0 -1
  43. package/dist/delivery-invariants-Br29H7Rg.mjs.map +0 -1
  44. package/dist/delivery-invariants-DZOBkCMR.d.mts +0 -5
  45. package/dist/delivery-invariants-DZOBkCMR.d.mts.map +0 -1
  46. package/dist/explore-B7aR_5Hy.d.mts.map +0 -1
  47. package/dist/platform-CCz48WF9.d.mts.map +0 -1
  48. package/dist/src-5pKRvj02.mjs.map +0 -1
  49. package/dist/src-DGh7w877.mjs.map +0 -1
  50. package/dist/workerd-BMJ-GKx8.mjs.map +0 -1
@@ -1,14 +1,14 @@
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";
3
- import { n as isSpec } from "./combinators-CVjxodAJ.mjs";
1
+ import { L as canonicalJson } from "./src-ud5wEfnx.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-nwQA9Xwr.mjs";
3
+ import { n as isSpec } from "./combinators-CLfsPfhT.mjs";
4
4
  import { t as aggregate } from "./provers-DS44OeEm.mjs";
5
- import { H as cloudflareRegressionTest, n as specKey } from "./workerd-BMJ-GKx8.mjs";
5
+ import { G as cloudflareRegressionTest, n as globKey, r as specKey } from "./workerd-Be43_PZo.mjs";
6
6
  import { createRequire, registerHooks } from "node:module";
7
7
  import { Readable } from "node:stream";
8
8
  import { createHash, randomBytes } from "node:crypto";
9
9
  import { chmodSync, closeSync, copyFileSync, createReadStream, existsSync, mkdirSync, mkdtempSync, openSync, readFileSync, readdirSync, renameSync, rmSync, symlinkSync, writeFileSync, writeSync } from "node:fs";
10
10
  import { homedir, tmpdir } from "node:os";
11
- import { basename, dirname, join, relative, resolve, sep } from "node:path";
11
+ import { basename, dirname, extname, join, relative, resolve, sep } from "node:path";
12
12
  import { createZstdDecompress, inflateRawSync } from "node:zlib";
13
13
  import { fork, spawn } from "node:child_process";
14
14
  import { InternalSymbolName, ModifierFlags, NodeFlags, SyntaxKind, forEachLeadingCommentRange, forEachTrailingCommentRange } from "typescript/ast";
@@ -1202,15 +1202,14 @@ function narrowsOf(test, holds) {
1202
1202
  if (test.kind === "binary" && test.op === "||" && !holds) return [...narrowsOf(test.left, false), ...narrowsOf(test.right, false)];
1203
1203
  return [];
1204
1204
  }
1205
- /** The field that tells a union's members apart: literal-typed in every member, with a different literal in each. */
1205
+ /**
1206
+ * The field that tells a union's members apart, as the union names it: the
1207
+ * one the types read chose (`UnionType.tag`), which the engines encode by.
1208
+ * Re-deriving it from the member records could pick another field where two
1209
+ * discriminate, and the reader would then refuse the test the engines take.
1210
+ */
1206
1211
  function tagOf(union, ctx) {
1207
- const members = membersIn(union, ctx);
1208
- const first = members[0];
1209
- if (!first) return void 0;
1210
- return first.fields.filter((f) => f.literal !== void 0).map((f) => f.name).find((name) => {
1211
- const values = members.map((m) => m.fields.find((f) => f.name === name)?.literal);
1212
- return values.every((v) => v !== void 0) && new Set(values.map((v) => JSON.stringify(v))).size === values.length;
1213
- });
1212
+ return ctx.unions.find((u) => u.name === union)?.tag;
1214
1213
  }
1215
1214
  /**
1216
1215
  * The names a test, holding or failing, shows to be one member of their
@@ -1925,11 +1924,12 @@ function callees(e, out = /* @__PURE__ */ new Set()) {
1925
1924
  /** The path a module read from text alone is compiled under: an import of another file does not resolve from it. */
1926
1925
  const virtualModulePath = "/eutaxy/reader/module.ts";
1927
1926
  /** What typing a module's expressions needs, shared by every function read. */
1928
- function moduleContext(records) {
1927
+ function moduleContext(records, unions) {
1929
1928
  const signatures = /* @__PURE__ */ new Map();
1930
1929
  return {
1931
1930
  ctx: {
1932
1931
  records,
1932
+ unions,
1933
1933
  signatures
1934
1934
  },
1935
1935
  signatures
@@ -2081,7 +2081,7 @@ function directiveIn(sf, start, end) {
2081
2081
  const check = (pos, commentEnd) => {
2082
2082
  if (found || pos < start || commentEnd > end) return;
2083
2083
  const comment = text.slice(pos, commentEnd);
2084
- const m = comment.startsWith("//") ? singleLine.exec(comment) : lastLine.exec(comment.slice(comment.lastIndexOf("\n") + 1));
2084
+ const m = comment.startsWith("//") ? singleLine.exec(comment) : lastLine.exec(comment.slice(comment.lastIndexOf("\n") + 1).trimStart());
2085
2085
  if (m) found = {
2086
2086
  text: `@ts-${m[1]}`,
2087
2087
  pos
@@ -2645,7 +2645,7 @@ function readSubset(source, functions, options = {}) {
2645
2645
  if (err !== skip) throw err;
2646
2646
  }
2647
2647
  }
2648
- const { ctx, signatures } = moduleContext(types.records);
2648
+ const { ctx, signatures } = moduleContext(types.records, types.unions);
2649
2649
  const names = {
2650
2650
  callable: (n) => declared.has(n) && !generic.has(n),
2651
2651
  target: (n) => n,
@@ -2806,6 +2806,7 @@ function arrowReader(sf, module, aliases) {
2806
2806
  }]));
2807
2807
  return new ExprReader(sf, names, typeSource, {
2808
2808
  records,
2809
+ unions: module.unions,
2809
2810
  signatures
2810
2811
  }, () => 0);
2811
2812
  }
@@ -3594,7 +3595,7 @@ function readSpecs(input) {
3594
3595
  * no names of these shapes, so a function called `decide` or a parameter
3595
3596
  * called `max` stays what the author meant.
3596
3597
  */
3597
- const ident$1 = {
3598
+ const ident$2 = {
3598
3599
  fn: (name) => quote(`f_${name}`),
3599
3600
  record: (name) => quote(`R_${name}`),
3600
3601
  variable: (name) => quote(`v_${name}`),
@@ -3611,7 +3612,7 @@ function leanType(t) {
3611
3612
  case "int": return "Int";
3612
3613
  case "bool": return "Bool";
3613
3614
  case "string": return "String";
3614
- case "record": return ident$1.record(t.name);
3615
+ case "record": return ident$2.record(t.name);
3615
3616
  case "list": return `(List ${leanType(t.element)})`;
3616
3617
  case "nothing": return fail$1("the element type of an empty array, which nothing gives");
3617
3618
  case "nullable":
@@ -3621,8 +3622,8 @@ function leanType(t) {
3621
3622
  }
3622
3623
  function emitRecord(r) {
3623
3624
  return [
3624
- `structure ${ident$1.record(r.name)} where`,
3625
- ...r.fields.map((f) => ` ${ident$1.field(f.name)} : ${leanType(f.type)}`),
3625
+ `structure ${ident$2.record(r.name)} where`,
3626
+ ...r.fields.map((f) => ` ${ident$2.field(f.name)} : ${leanType(f.type)}`),
3626
3627
  " deriving Repr, DecidableEq"
3627
3628
  ].join("\n");
3628
3629
  }
@@ -3631,6 +3632,7 @@ function env$1(module) {
3631
3632
  module,
3632
3633
  ctx: {
3633
3634
  records: new Map(module.records.map((r) => [r.name, r])),
3635
+ unions: module.unions,
3634
3636
  signatures: new Map(module.functions.map((f) => [f.name, {
3635
3637
  params: f.params,
3636
3638
  returns: f.returns
@@ -3675,7 +3677,7 @@ function term$1(e, scope, env) {
3675
3677
  case "string": return leanString(e.value);
3676
3678
  case "var":
3677
3679
  if (env.cons?.list === e.name) return `(${env.cons.head} :: ${env.cons.tail})`;
3678
- return ident$1.variable(e.name);
3680
+ return ident$2.variable(e.name);
3679
3681
  case "null":
3680
3682
  case "narrow": return fail$1("null, which the Lean engine does not take yet");
3681
3683
  case "narrowTag": return fail$1("a union, which the Lean engine does not take yet");
@@ -3714,21 +3716,21 @@ function term$1(e, scope, env) {
3714
3716
  }
3715
3717
  break;
3716
3718
  case "cond": return `(if ${t(e.test)} = true then ${t(e.ifTrue)} else ${t(e.ifFalse)})`;
3717
- case "call": return `(${ident$1.fn(e.callee)}${e.args.map((a) => ` ${t(a)}`).join("")})`;
3719
+ case "call": return `(${ident$2.fn(e.callee)}${e.args.map((a) => ` ${t(a)}`).join("")})`;
3718
3720
  case "field":
3719
3721
  if (typeOf(e.object, scope, env.ctx, fail$1).kind === "list") return `(Int.ofNat (List.length ${t(e.object)}))`;
3720
- return `${t(e.object)}.${ident$1.field(e.field)}`;
3722
+ return `${t(e.object)}.${ident$2.field(e.field)}`;
3721
3723
  case "record": {
3722
3724
  const type = typeOf(e, scope, env.ctx, fail$1);
3723
- const name = type.kind === "record" ? ident$1.record(type.name) : fail$1("a record literal of no record type");
3724
- return `({ ${e.fields.map((f) => `${ident$1.field(f.name)} := ${t(f.value)}`).join(", ")} } : ${name})`;
3725
+ const name = type.kind === "record" ? ident$2.record(type.name) : fail$1("a record literal of no record type");
3726
+ return `({ ${e.fields.map((f) => `${ident$2.field(f.name)} := ${t(f.value)}`).join(", ")} } : ${name})`;
3725
3727
  }
3726
3728
  case "let": {
3727
3729
  const inner = new Map(scope);
3728
3730
  const bound = e.type ?? typeOf(e.value, scope, env.ctx, fail$1);
3729
3731
  inner.set(e.name, bound);
3730
3732
  const annotated = e.type ? ` : ${leanType(e.type)}` : "";
3731
- return `(let ${ident$1.variable(e.name)}${annotated} := ${t(e.value)}; ${term$1(e.body, inner, env)})`;
3733
+ return `(let ${ident$2.variable(e.name)}${annotated} := ${t(e.value)}; ${term$1(e.body, inner, env)})`;
3732
3734
  }
3733
3735
  case "list":
3734
3736
  if (e.items.length === 0 && !e.rest) return "[]";
@@ -3748,7 +3750,7 @@ function term$1(e, scope, env) {
3748
3750
  if (e.index !== void 0) inner.set(e.index, { kind: "int" });
3749
3751
  const body = term$1(e.body, inner, env);
3750
3752
  const nat = e.index === void 0 ? "" : quote(`nv_${e.index}`);
3751
- const fn = e.index === void 0 ? `(fun ${ident$1.variable(e.item)} => ${body})` : `(fun (${ident$1.variable(e.item)}, ${nat}) => let ${ident$1.variable(e.index)} := Int.ofNat ${nat}; ${body})`;
3753
+ const fn = e.index === void 0 ? `(fun ${ident$2.variable(e.item)} => ${body})` : `(fun (${ident$2.variable(e.item)}, ${nat}) => let ${ident$2.variable(e.index)} := Int.ofNat ${nat}; ${body})`;
3752
3754
  const list = e.index === void 0 ? t(e.list) : `(List.zipIdx ${t(e.list)})`;
3753
3755
  if (e.op === "map") return `(List.map ${fn} ${list})`;
3754
3756
  if (e.op === "flatMap") return `(List.flatMap ${fn} ${list})`;
@@ -3760,15 +3762,15 @@ function term$1(e, scope, env) {
3760
3762
  const inner = new Map(scope);
3761
3763
  inner.set(e.acc, typeOf(e, scope, env.ctx, fail$1));
3762
3764
  inner.set(e.item, listType.element);
3763
- return `(List.foldl (fun ${ident$1.variable(e.acc)} ${ident$1.variable(e.item)} => ${term$1(e.body, inner, env)}) ${t(e.init)} ${t(e.list)})`;
3765
+ return `(List.foldl (fun ${ident$2.variable(e.acc)} ${ident$2.variable(e.item)} => ${term$1(e.body, inner, env)}) ${t(e.init)} ${t(e.list)})`;
3764
3766
  }
3765
3767
  }
3766
3768
  }
3767
3769
  function emitFunction$1(f, module) {
3768
3770
  const e = env$1(module);
3769
3771
  const scope = new Map(f.params.map((p) => [p.name, p.type]));
3770
- const params = f.params.map((p) => `(${ident$1.variable(p.name)} : ${leanType(p.type)})`).join(" ");
3771
- const head = `def ${ident$1.fn(f.name)} ${params} : ${leanType(f.returns)} :=`;
3772
+ const params = f.params.map((p) => `(${ident$2.variable(p.name)} : ${leanType(p.type)})`).join(" ");
3773
+ const head = `def ${ident$2.fn(f.name)} ${params} : ${leanType(f.returns)} :=`;
3772
3774
  if (f.structural === void 0 || f.body.kind !== "cond") return `${head}\n ${term$1(f.body, scope, e)}`;
3773
3775
  const list = f.params[f.structural].name;
3774
3776
  const cons = {
@@ -3778,7 +3780,7 @@ function emitFunction$1(f, module) {
3778
3780
  };
3779
3781
  return [
3780
3782
  head,
3781
- ` match ${ident$1.variable(list)} with`,
3783
+ ` match ${ident$2.variable(list)} with`,
3782
3784
  ` | [] => ${term$1(f.body.ifTrue, scope, e)}`,
3783
3785
  ` | ${cons.head} :: ${cons.tail} => ${term$1(f.body.ifFalse, scope, {
3784
3786
  ...e,
@@ -3861,7 +3863,7 @@ function stated(property, module) {
3861
3863
  if (property.kind !== "forall" || !property.ensures) fail$1("not a forall property");
3862
3864
  const e = env$1(module);
3863
3865
  const types = property.binders.map((b) => binderType$1(b.name, b.type, module));
3864
- const binders = property.binders.map((b, i) => `(${ident$1.variable(b.name)} : ${leanType(types[i])})`).join(" ");
3866
+ const binders = property.binders.map((b, i) => `(${ident$2.variable(b.name)} : ${leanType(types[i])})`).join(" ");
3865
3867
  const hyps = property.when ? [`(${arrowTerm$1(property.when, "when", property, types, e)} = true)`] : [];
3866
3868
  const claim = `(${arrowTerm$1(property.ensures, "ensures", property, types, e)} = true)`;
3867
3869
  const body = [...hyps, claim].join(" →\n ");
@@ -3881,10 +3883,10 @@ function stated(property, module) {
3881
3883
  * the statement.
3882
3884
  */
3883
3885
  function tactics(module, property, hypotheses) {
3884
- const defs = module.functions.map((f) => ident$1.fn(f.name)).join(", ");
3885
- const names = property.binders.map((b) => ident$1.variable(b.name));
3886
+ const defs = module.functions.map((f) => ident$2.fn(f.name)).join(", ");
3887
+ const names = property.binders.map((b) => ident$2.variable(b.name));
3886
3888
  const hyps = Array.from({ length: hypotheses }, (_, i) => `h${i}_`);
3887
- const bools = property.binders.filter((b) => b.type.kind === "boolean" || b.type.kind === "literal" && typeof b.type.value === "boolean").map((b) => ident$1.variable(b.name));
3889
+ const bools = property.binders.filter((b) => b.type.kind === "boolean" || b.type.kind === "literal" && typeof b.type.value === "boolean").map((b) => ident$2.variable(b.name));
3888
3890
  const introduced = [...names, ...hyps];
3889
3891
  return [
3890
3892
  ...introduced.length > 0 ? [` intro ${introduced.join(" ")}`] : [],
@@ -4523,7 +4525,7 @@ function renderGoals(input) {
4523
4525
  `${specHashMarker}${input.specSha256}`
4524
4526
  ];
4525
4527
  const described = input.goals.map((g) => [
4526
- commentLine(`-- goal: ${g.property}, a property of ${ident$1.fn(g.function)}`),
4528
+ commentLine(`-- goal: ${g.property}, a property of ${ident$2.fn(g.function)}`),
4527
4529
  commentLine(`-- Lean said: ${g.reason}`),
4528
4530
  "-- statement:",
4529
4531
  comment(g.statement.replace(/^/gm, " "))
@@ -4855,7 +4857,7 @@ function symbol(name) {
4855
4857
  return /^[A-Za-z~!@$%^&*_+=<>.?/-][A-Za-z0-9~!@$%^&*_+=<>.?/-]*$/.test(escaped) ? escaped : `|${escaped}|`;
4856
4858
  }
4857
4859
  /** TypeScript names as SMT symbols that cannot clash with each other or with the theories' names. */
4858
- const ident = {
4860
+ const ident$1 = {
4859
4861
  fn: (name) => symbol(`f_${name}`),
4860
4862
  /** The datatype of a record, or of a union. */
4861
4863
  record: (name) => symbol(`R_${name}`),
@@ -4879,8 +4881,8 @@ function sortName(t, module) {
4879
4881
  case "bool": return "Bool";
4880
4882
  case "string": return "Str";
4881
4883
  case "record":
4882
- case "union": return ident.record(t.name);
4883
- case "nullable": return ident.option(sortName(t.inner, module));
4884
+ case "union": return ident$1.record(t.name);
4885
+ case "nullable": return ident$1.option(sortName(t.inner, module));
4884
4886
  case "null": return fail("null has no sort of its own");
4885
4887
  }
4886
4888
  }
@@ -4898,7 +4900,7 @@ function sort(t, module) {
4898
4900
  }
4899
4901
  /** A constructor applied: a bare symbol when there are no arguments. */
4900
4902
  function construct(name, values) {
4901
- return values.length === 0 ? ident.constructor(name) : `(${ident.constructor(name)} ${values.join(" ")})`;
4903
+ return values.length === 0 ? ident$1.constructor(name) : `(${ident$1.constructor(name)} ${values.join(" ")})`;
4902
4904
  }
4903
4905
  /** A double as a floating-point literal. */
4904
4906
  function numberTerm(n) {
@@ -4928,6 +4930,7 @@ function env(module) {
4928
4930
  types: /* @__PURE__ */ new WeakMap(),
4929
4931
  ctx: {
4930
4932
  records: new Map(module.records.map((r) => [r.name, r])),
4933
+ unions: module.unions,
4931
4934
  signatures: new Map(module.functions.map((f) => [f.name, {
4932
4935
  params: f.params,
4933
4936
  returns: f.returns
@@ -4958,7 +4961,7 @@ function sameAs(a, b, t, env) {
4958
4961
  case "string": return `(= ${a} ${b})`;
4959
4962
  case "nullable": {
4960
4963
  const base = sortName(t.inner, env.module);
4961
- return `(ite (and (${tester(ident.some(base))} ${a}) (${tester(ident.some(base))} ${b})) ${sameAs(`(${ident.val(base)} ${a})`, `(${ident.val(base)} ${b})`, t.inner, env)} (and (${tester(ident.none(base))} ${a}) (${tester(ident.none(base))} ${b})))`;
4964
+ return `(ite (and (${tester(ident$1.some(base))} ${a}) (${tester(ident$1.some(base))} ${b})) ${sameAs(`(${ident$1.val(base)} ${a})`, `(${ident$1.val(base)} ${b})`, t.inner, env)} (and (${tester(ident$1.none(base))} ${a}) (${tester(ident$1.none(base))} ${b})))`;
4962
4965
  }
4963
4966
  case "record":
4964
4967
  case "union":
@@ -4972,16 +4975,16 @@ function sameAs(a, b, t, env) {
4972
4975
  * union. Anything else is already of the sort wanted.
4973
4976
  */
4974
4977
  function lift(inner, actual, want, module) {
4975
- if (want.kind === "union" && actual.kind === "record") return `(${ident.inject(want.name, actual.name)} ${inner})`;
4978
+ if (want.kind === "union" && actual.kind === "record") return `(${ident$1.inject(want.name, actual.name)} ${inner})`;
4976
4979
  if (want.kind !== "nullable") return inner;
4977
4980
  if (actual.kind === "null") return inner;
4978
4981
  if (actual.kind === "nullable") {
4979
4982
  if (want.inner.kind !== "union" || actual.inner.kind !== "record") return inner;
4980
4983
  const from = sortName(actual.inner, module);
4981
4984
  const to = sortName(want.inner, module);
4982
- return `(ite (${tester(ident.none(from))} ${inner}) ${ident.none(to)} (${ident.some(to)} ${lift(`(${ident.val(from)} ${inner})`, actual.inner, want.inner, module)}))`;
4985
+ return `(ite (${tester(ident$1.none(from))} ${inner}) ${ident$1.none(to)} (${ident$1.some(to)} ${lift(`(${ident$1.val(from)} ${inner})`, actual.inner, want.inner, module)}))`;
4983
4986
  }
4984
- return `(${ident.some(sortName(want.inner, module))} ${lift(inner, actual, want.inner, module)})`;
4987
+ return `(${ident$1.some(sortName(want.inner, module))} ${lift(inner, actual, want.inner, module)})`;
4985
4988
  }
4986
4989
  /**
4987
4990
  * A term of the expression's type, or of `expected` where one is given:
@@ -5018,15 +5021,15 @@ function term(e, scope, env, expected) {
5018
5021
  case "string": return stringTerm(e.value);
5019
5022
  case "null":
5020
5023
  if (expected?.kind !== "nullable") fail("null where no nullable type is expected");
5021
- return ident.none(sortName(expected.inner, env.module));
5022
- case "var": return ident.variable(e.name);
5024
+ return ident$1.none(sortName(expected.inner, env.module));
5025
+ case "var": return ident$1.variable(e.name);
5023
5026
  case "narrow": {
5024
5027
  const nt = scope.get(e.name);
5025
5028
  if (nt?.kind !== "nullable") fail(`${e.name} is narrowed but is not a nullable`);
5026
5029
  const base = sortName(nt.inner, env.module);
5027
5030
  const inner = new Map(scope);
5028
5031
  inner.set(e.name, nt.inner);
5029
- return `(let ((${ident.variable(e.name)} (${ident.val(base)} ${ident.variable(e.name)}))) ${narrowed(e.body, inner)})`;
5032
+ return `(let ((${ident$1.variable(e.name)} (${ident$1.val(base)} ${ident$1.variable(e.name)}))) ${narrowed(e.body, inner)})`;
5030
5033
  }
5031
5034
  case "narrowTag": {
5032
5035
  const nt = scope.get(e.name);
@@ -5036,8 +5039,8 @@ function term(e, scope, env, expected) {
5036
5039
  kind: "record",
5037
5040
  name: e.member
5038
5041
  });
5039
- const v = ident.variable(e.name);
5040
- return `(let ((${v} (${ident.project(nt.name, e.member)} ${v}))) ${narrowed(e.body, inner)})`;
5042
+ const v = ident$1.variable(e.name);
5043
+ return `(let ((${v} (${ident$1.project(nt.name, e.member)} ${v}))) ${narrowed(e.body, inner)})`;
5041
5044
  }
5042
5045
  case "neg": return `(fp.neg ${t(e.operand)})`;
5043
5046
  case "not": return `(not ${t(e.operand)})`;
@@ -5062,13 +5065,13 @@ function term(e, scope, env, expected) {
5062
5065
  const side = lt.kind === "null" ? e.right : e.left;
5063
5066
  const st = lt.kind === "null" ? rt : lt;
5064
5067
  if (st.kind !== "nullable") fail("a comparison with null of something that is not nullable");
5065
- eq = `(${tester(ident.none(sortName(st.inner, env.module)))} ${t(side)})`;
5068
+ eq = `(${tester(ident$1.none(sortName(st.inner, env.module)))} ${t(side)})`;
5066
5069
  } else if (lt.kind === "nullable" && rt.kind !== "nullable") {
5067
5070
  const base = sortName(lt.inner, env.module);
5068
- eq = `(and (${tester(ident.some(base))} ${t(e.left)}) ${sameAs(`(${ident.val(base)} ${t(e.left)})`, t(e.right), lt.inner, env)})`;
5071
+ eq = `(and (${tester(ident$1.some(base))} ${t(e.left)}) ${sameAs(`(${ident$1.val(base)} ${t(e.left)})`, t(e.right), lt.inner, env)})`;
5069
5072
  } else if (rt.kind === "nullable" && lt.kind !== "nullable") {
5070
5073
  const base = sortName(rt.inner, env.module);
5071
- eq = `(and (${tester(ident.some(base))} ${t(e.right)}) ${sameAs(t(e.left), `(${ident.val(base)} ${t(e.right)})`, rt.inner, env)})`;
5074
+ eq = `(and (${tester(ident$1.some(base))} ${t(e.right)}) ${sameAs(t(e.left), `(${ident$1.val(base)} ${t(e.right)})`, rt.inner, env)})`;
5072
5075
  } else eq = sameAs(t(e.left), t(e.right), lt, env);
5073
5076
  return e.op === "===" ? eq : `(not ${eq})`;
5074
5077
  }
@@ -5084,17 +5087,17 @@ function term(e, scope, env, expected) {
5084
5087
  case "call": {
5085
5088
  const sig = env.ctx.signatures.get(e.callee) ?? fail(`no signature for ${e.callee}`);
5086
5089
  const args = e.args.map((a, i) => coerce(a, sig.params[i].type));
5087
- return args.length === 0 ? ident.fn(e.callee) : `(${ident.fn(e.callee)} ${args.join(" ")})`;
5090
+ return args.length === 0 ? ident$1.fn(e.callee) : `(${ident$1.fn(e.callee)} ${args.join(" ")})`;
5088
5091
  }
5089
5092
  case "field": {
5090
5093
  const o = typed(e.object);
5091
5094
  const obj = t(e.object);
5092
5095
  if (o.kind === "union") return membersOf(o.name, env).reduceRight((rest, m) => {
5093
- const read = `(${ident.field(m.name, e.field)} (${ident.project(o.name, m.name)} ${obj}))`;
5094
- return rest === void 0 ? read : `(ite (${tester(ident.inject(o.name, m.name))} ${obj}) ${read} ${rest})`;
5096
+ const read = `(${ident$1.field(m.name, e.field)} (${ident$1.project(o.name, m.name)} ${obj}))`;
5097
+ return rest === void 0 ? read : `(ite (${tester(ident$1.inject(o.name, m.name))} ${obj}) ${read} ${rest})`;
5095
5098
  }, void 0);
5096
5099
  if (o.kind !== "record") fail(`field ${e.field} read from a ${o.kind}`);
5097
- return `(${ident.field(o.name, e.field)} ${obj})`;
5100
+ return `(${ident$1.field(o.name, e.field)} ${obj})`;
5098
5101
  }
5099
5102
  case "record": {
5100
5103
  const type = typed(e);
@@ -5110,20 +5113,20 @@ function term(e, scope, env, expected) {
5110
5113
  const bound = e.type ?? typed(e.value);
5111
5114
  inner.set(e.name, bound);
5112
5115
  const value = e.type ? coerce(e.value, e.type) : t(e.value);
5113
- return `(let ((${ident.variable(e.name)} ${value})) ${narrowed(e.body, inner)})`;
5116
+ return `(let ((${ident$1.variable(e.name)} ${value})) ${narrowed(e.body, inner)})`;
5114
5117
  }
5115
5118
  }
5116
5119
  }
5117
5120
  function emitFunction(f, module) {
5118
5121
  const e = env(module);
5119
5122
  const scope = new Map(f.params.map((p) => [p.name, p.type]));
5120
- const params = f.params.map((p) => `(${ident.variable(p.name)} ${sort(p.type, module)})`).join(" ");
5123
+ const params = f.params.map((p) => `(${ident$1.variable(p.name)} ${sort(p.type, module)})`).join(" ");
5121
5124
  const body = (() => {
5122
5125
  const b = f.body;
5123
5126
  if (b.kind === "cond" || b.kind === "let" || b.kind === "narrow" || b.kind === "narrowTag" || b.kind === "null") return term(b, scope, e, f.returns);
5124
5127
  return lift(term(b, scope, e, f.returns), typeOf(b, scope, e.ctx, fail), f.returns, module);
5125
5128
  })();
5126
- return `(define-fun ${ident.fn(f.name)} (${params}) ${sort(f.returns, module)}\n ${body})`;
5129
+ return `(define-fun ${ident$1.fn(f.name)} (${params}) ${sort(f.returns, module)}\n ${body})`;
5127
5130
  }
5128
5131
  /**
5129
5132
  * An option sort over every sort the module could mention: the primitives,
@@ -5160,16 +5163,16 @@ function emitDatatypes(module) {
5160
5163
  const unions = module.unions;
5161
5164
  const options = optionSorts(module);
5162
5165
  const names = [
5163
- ...plain.map((r) => ident.record(r.name)),
5164
- ...unions.map((u) => ident.record(u.name)),
5165
- ...[...options.keys()].map((base) => ident.option(base))
5166
+ ...plain.map((r) => ident$1.record(r.name)),
5167
+ ...unions.map((u) => ident$1.record(u.name)),
5168
+ ...[...options.keys()].map((base) => ident$1.option(base))
5166
5169
  ];
5167
5170
  if (names.length === 0) return "";
5168
- const constructorOf = (r) => `(${ident.constructor(r.name)}${r.fields.map((f) => ` (${ident.field(r.name, f.name)} ${sort(f.type, module)})`).join("")})`;
5171
+ const constructorOf = (r) => `(${ident$1.constructor(r.name)}${r.fields.map((f) => ` (${ident$1.field(r.name, f.name)} ${sort(f.type, module)})`).join("")})`;
5169
5172
  const bodies = [
5170
5173
  ...plain.map((r) => `(${constructorOf(r)})`),
5171
- ...unions.map((u) => `(${u.members.map((m) => `(${ident.inject(u.name, m.record)} (${ident.project(u.name, m.record)} ${ident.record(m.record)}))`).join(" ")})`),
5172
- ...[...options].map(([base, inner]) => `((${ident.none(base)}) (${ident.some(base)} (${ident.val(base)} ${sort(inner, module)})))`)
5174
+ ...unions.map((u) => `(${u.members.map((m) => `(${ident$1.inject(u.name, m.record)} (${ident$1.project(u.name, m.record)} ${ident$1.record(m.record)}))`).join(" ")})`),
5175
+ ...[...options].map(([base, inner]) => `((${ident$1.none(base)}) (${ident$1.some(base)} (${ident$1.val(base)} ${sort(inner, module)})))`)
5173
5176
  ];
5174
5177
  return `(declare-datatypes (${names.map((n) => `(${n} 0)`).join(" ")}) (${bodies.join(" ")}))`;
5175
5178
  }
@@ -5300,15 +5303,15 @@ function wellFormed(target, t, module) {
5300
5303
  case "null": return;
5301
5304
  case "nullable": {
5302
5305
  const base = sortName(t.inner, module);
5303
- const inner = wellFormed(`(${ident.val(base)} ${target})`, t.inner, module);
5304
- return inner === void 0 ? void 0 : `(or (${tester(ident.none(base))} ${target}) ${inner})`;
5306
+ const inner = wellFormed(`(${ident$1.val(base)} ${target})`, t.inner, module);
5307
+ return inner === void 0 ? void 0 : `(or (${tester(ident$1.none(base))} ${target}) ${inner})`;
5305
5308
  }
5306
5309
  case "record": {
5307
5310
  const rec = module.records.find((r) => r.name === t.name);
5308
5311
  if (!rec) return void 0;
5309
5312
  const parts = [];
5310
5313
  for (const f of rec.fields) {
5311
- const read = `(${ident.field(rec.name, f.name)} ${target})`;
5314
+ const read = `(${ident$1.field(rec.name, f.name)} ${target})`;
5312
5315
  if (f.literal !== void 0) parts.push(typeof f.literal === "string" ? `(= ${read} ${stringTerm(f.literal)})` : `(= ${read} ${f.literal ? "true" : "false"})`);
5313
5316
  const inner = wellFormed(read, f.type, module);
5314
5317
  if (inner !== void 0) parts.push(inner);
@@ -5319,8 +5322,8 @@ function wellFormed(target, t, module) {
5319
5322
  const u = module.unions.find((x) => x.name === t.name);
5320
5323
  if (!u) return void 0;
5321
5324
  return `(or ${u.members.map((m) => {
5322
- const is = `(${tester(ident.inject(u.name, m.record))} ${target})`;
5323
- const inner = wellFormed(`(${ident.project(u.name, m.record)} ${target})`, {
5325
+ const is = `(${tester(ident$1.inject(u.name, m.record))} ${target})`;
5326
+ const inner = wellFormed(`(${ident$1.project(u.name, m.record)} ${target})`, {
5324
5327
  kind: "record",
5325
5328
  name: m.record
5326
5329
  }, module);
@@ -5351,8 +5354,8 @@ function domainConstraint(symbolName, t, subset, module) {
5351
5354
  };
5352
5355
  if (subset.kind === "nullable") {
5353
5356
  const base = sortName(subset.inner, module);
5354
- const some = `(and (${tester(ident.some(base))} ${symbolName}) ${over(`(${ident.val(base)} ${symbolName})`)})`;
5355
- return withNull ? `(or (${tester(ident.none(base))} ${symbolName}) ${some})` : some;
5357
+ const some = `(and (${tester(ident$1.some(base))} ${symbolName}) ${over(`(${ident$1.val(base)} ${symbolName})`)})`;
5358
+ return withNull ? `(or (${tester(ident$1.none(base))} ${symbolName}) ${some})` : some;
5356
5359
  }
5357
5360
  return over(symbolName);
5358
5361
  }
@@ -5401,7 +5404,7 @@ function propertyScript(property, module) {
5401
5404
  const types = property.binders.map((b) => binderType(b.name, b.type, module));
5402
5405
  const binders = property.binders.map((b, i) => ({
5403
5406
  name: b.name,
5404
- symbol: ident.variable(b.name),
5407
+ symbol: ident$1.variable(b.name),
5405
5408
  type: types[i]
5406
5409
  }));
5407
5410
  return {
@@ -5516,15 +5519,15 @@ function decode(x, t, module) {
5516
5519
  case "string": return decodeString(x);
5517
5520
  case "nullable": {
5518
5521
  const base = sortName(t.inner, module);
5519
- if (x === ident.none(base)) return null;
5520
- if (Array.isArray(x) && x[0] === ident.some(base) && x.length === 2) return decode(x[1], t.inner, module);
5522
+ if (x === ident$1.none(base)) return null;
5523
+ if (Array.isArray(x) && x[0] === ident$1.some(base) && x.length === 2) return decode(x[1], t.inner, module);
5521
5524
  throw new UnreadableModel(`not a ${describeSubset(t)}: ${show(x)}`);
5522
5525
  }
5523
5526
  case "union": {
5524
5527
  const u = module.unions.find((y) => y.name === t.name);
5525
5528
  if (!u) throw new UnreadableModel(`no union ${t.name}`);
5526
5529
  const head = Array.isArray(x) ? x[0] : x;
5527
- const member = u.members.find((m) => ident.inject(u.name, m.record) === head);
5530
+ const member = u.members.find((m) => ident$1.inject(u.name, m.record) === head);
5528
5531
  if (!member || !Array.isArray(x) || x.length !== 2) throw new UnreadableModel(`not a ${t.name}: ${show(x)}`);
5529
5532
  return decode(x[1], {
5530
5533
  kind: "record",
@@ -5534,8 +5537,8 @@ function decode(x, t, module) {
5534
5537
  case "record": {
5535
5538
  const rec = module.records.find((r) => r.name === t.name);
5536
5539
  if (!rec) throw new UnreadableModel(`no record ${t.name}`);
5537
- if (rec.fields.length === 0 && x === ident.constructor(t.name)) return {};
5538
- if (!Array.isArray(x) || x[0] !== ident.constructor(t.name) || x.length !== rec.fields.length + 1) throw new UnreadableModel(`not a ${t.name}: ${show(x)}`);
5540
+ if (rec.fields.length === 0 && x === ident$1.constructor(t.name)) return {};
5541
+ if (!Array.isArray(x) || x[0] !== ident$1.constructor(t.name) || x.length !== rec.fields.length + 1) throw new UnreadableModel(`not a ${t.name}: ${show(x)}`);
5539
5542
  const out = {};
5540
5543
  rec.fields.forEach((f, i) => {
5541
5544
  out[f.name] = decode(x[i + 1], f.type, module);
@@ -5976,12 +5979,537 @@ const smtProver = {
5976
5979
  },
5977
5980
  prove: (input) => proveModule(input)
5978
5981
  };
5982
+ // packages/cli/src/resolve.ts
5983
+ /**
5984
+ * Relative imports from a `.ts` file that Node cannot resolve are tried as
5985
+ * TypeScript resolves them, so `./domain.js` and `./domain` find `domain.ts`
5986
+ * (or `domain/index.ts`), as `tsc` and Vite would. Used where the command
5987
+ * imports a user's module in Node: `eutaxy report` for spec modules, `eutaxy
5988
+ * check` for a scenario that names callees.
5989
+ */
5990
+ let registered = false;
5991
+ /** Register the hook once per process. */
5992
+ function resolveAsTypeScript() {
5993
+ if (registered) return;
5994
+ registered = true;
5995
+ registerHooks({ resolve(specifier, context, nextResolve) {
5996
+ try {
5997
+ return nextResolve(specifier, context);
5998
+ } catch (err) {
5999
+ if (!(specifier.startsWith("./") || specifier.startsWith("../")) || !context.parentURL?.endsWith(".ts")) throw err;
6000
+ const stem = specifier.endsWith(".js") ? specifier.slice(0, -3) : specifier;
6001
+ for (const candidate of [`${stem}.ts`, `${stem}/index.ts`]) try {
6002
+ return nextResolve(candidate, context);
6003
+ } catch {}
6004
+ throw err;
6005
+ }
6006
+ } });
6007
+ }
6008
+ // packages/cli/src/callees.ts
6009
+ /**
6010
+ * The callees a scenario names (`callee()` steps), read on the Node side for
6011
+ * `eutaxy check`. Each callee's wrangler config gives its Worker's name and
6012
+ * its bindings; the command adds them to the test's isolate under qualified
6013
+ * names (`<name>/<binding>`): the main module it generates re-exports the
6014
+ * caller's exports as they are and the callees' Durable Object and Workflow
6015
+ * classes under qualified aliases, and the Vitest config's miniflare options
6016
+ * add the callees' resources. Probed inside workerd (2026-11): the plugin
6017
+ * takes a `main` beside the caller's `wrangler.configPath`, miniflare options
6018
+ * add to and override the wrangler config's bindings, and wrangler, miniflare
6019
+ * and workerd accept a slash in a binding name.
6020
+ */
6021
+ /** The `callee` steps of a setup, as the scenario wrote them. */
6022
+ function calleeSteps(setup) {
6023
+ return setup.filter((s) => s.kind === "callee").map((s) => ({
6024
+ binding: String(s["binding"]),
6025
+ entry: String(s["entry"]),
6026
+ config: String(s["config"]),
6027
+ ...s["entrypoint"] === void 0 ? {} : { entrypoint: String(s["entrypoint"]) }
6028
+ }));
6029
+ }
6030
+ /**
6031
+ * Whether the scenario's source names a callee at all: the command imports
6032
+ * the scenario module in Node only then, since reading its steps needs it.
6033
+ */
6034
+ function mentionsCallee(scenarioSource) {
6035
+ return /\bcallee\s*\(/.test(scenarioSource);
6036
+ }
6037
+ /** The argument that makes a process started on this module load one scenario and report it. */
6038
+ const scenarioFlag = "--eutaxy-load-scenario";
6039
+ /** Inside the child: import the scenario and keep what the command reads. */
6040
+ async function loadHere(scenarioPath) {
6041
+ resolveAsTypeScript();
6042
+ const spec = (await import(pathToFileURL(scenarioPath).href)).default;
6043
+ if (!spec || !Array.isArray(spec.setup) || typeof spec.worker?.entry !== "string") throw new Error("the scenario module's default export is not a scenario");
6044
+ return {
6045
+ setup: spec.setup,
6046
+ worker: spec.worker
6047
+ };
6048
+ }
6049
+ const send$1 = process.send?.bind(process);
6050
+ if (process.argv[2] === scenarioFlag && send$1) {
6051
+ process.once("disconnect", () => process.exit(0));
6052
+ process.once("message", async (scenarioPath) => {
6053
+ let output;
6054
+ try {
6055
+ output = {
6056
+ kind: "eutaxy-scenario",
6057
+ scenario: await loadHere(scenarioPath)
6058
+ };
6059
+ } catch (err) {
6060
+ output = {
6061
+ kind: "eutaxy-scenario-error",
6062
+ message: String(err)
6063
+ };
6064
+ }
6065
+ send$1(output, () => process.exit(0));
6066
+ });
6067
+ }
6068
+ /** How long a scenario module may take to load before the command gives up on it. */
6069
+ const loadBudgetMs = 6e4;
6070
+ /**
6071
+ * Import the scenario module in Node and return its setup and Worker, in a
6072
+ * child process started on this module (as `eutaxy report` loads modules):
6073
+ * a long-lived process (the MCP server) would otherwise get Node's cached
6074
+ * module after the scenario or what it imports changed. Relative imports
6075
+ * are resolved as TypeScript resolves them (`./setup.js` and `./setup` find
6076
+ * `setup.ts`). Rejects with what the import threw.
6077
+ */
6078
+ function loadScenario(scenarioPath) {
6079
+ return new Promise((resolveLoad, reject) => {
6080
+ const child = fork(fileURLToPath(import.meta.url), [scenarioFlag], {
6081
+ stdio: [
6082
+ "ignore",
6083
+ "ignore",
6084
+ "pipe",
6085
+ "ipc"
6086
+ ],
6087
+ serialization: "advanced"
6088
+ });
6089
+ let errors = "";
6090
+ child.stderr?.on("data", (d) => {
6091
+ errors += d.toString();
6092
+ });
6093
+ let settled = false;
6094
+ const settle = (outcome) => {
6095
+ if (settled) return;
6096
+ settled = true;
6097
+ clearTimeout(timer);
6098
+ outcome();
6099
+ };
6100
+ const timer = setTimeout(() => {
6101
+ child.kill("SIGKILL");
6102
+ settle(() => reject(/* @__PURE__ */ new Error(`the scenario module did not load within ${loadBudgetMs} ms`)));
6103
+ }, loadBudgetMs);
6104
+ child.on("message", (output) => {
6105
+ settle(() => {
6106
+ if (output.kind === "eutaxy-scenario") resolveLoad(output.scenario);
6107
+ else reject(new Error(output.message));
6108
+ });
6109
+ });
6110
+ child.once("error", (err) => settle(() => reject(err)));
6111
+ child.once("close", (code, signal) => settle(() => reject(/* @__PURE__ */ new Error(`the scenario module's process ended (${signal ?? `exit ${code}`}) before reporting${errors ? `:\n${errors}` : ""}`))));
6112
+ child.send(scenarioPath);
6113
+ });
6114
+ }
6115
+ /** The qualified names the callees' bindings get in the isolate, for a regression test's note. */
6116
+ function isolateBindings(callees) {
6117
+ const names = [];
6118
+ for (const c of callees) {
6119
+ for (const d of c.d1) names.push(qualified(c.name, d.binding));
6120
+ for (const b of c.r2) names.push(qualified(c.name, b.binding));
6121
+ for (const k of c.kv) names.push(qualified(c.name, k.binding));
6122
+ for (const o of c.durableObjects) if (o.scriptName === void 0) names.push(qualified(c.name, o.binding));
6123
+ for (const w of c.workflows) names.push(qualified(c.name, w.binding));
6124
+ for (const s of c.services) names.push(qualified(c.name, s));
6125
+ for (const q of c.queues) names.push(qualified(c.name, q.binding));
6126
+ for (const v of Object.keys(c.vars)) names.push(qualified(c.name, v));
6127
+ }
6128
+ return names;
6129
+ }
6130
+ /**
6131
+ * JSON with comments and trailing commas, as wrangler.jsonc allows: comments
6132
+ * are removed outside strings, a comma before `}` or `]` dropped, and the
6133
+ * rest is JSON.
6134
+ */
6135
+ function parseJsonc(text) {
6136
+ let out = "";
6137
+ let i = 0;
6138
+ /** The index of the next character that is neither whitespace nor inside a comment, from `from`. */
6139
+ const nextToken = (from) => {
6140
+ let k = from;
6141
+ for (;;) {
6142
+ while (k < text.length && /\s/.test(text[k])) k++;
6143
+ if (text[k] === "/" && text[k + 1] === "/") while (k < text.length && text[k] !== "\n") k++;
6144
+ else if (text[k] === "/" && text[k + 1] === "*") {
6145
+ const end = text.indexOf("*/", k + 2);
6146
+ k = end < 0 ? text.length : end + 2;
6147
+ } else return k;
6148
+ }
6149
+ };
6150
+ while (i < text.length) {
6151
+ const c = text[i];
6152
+ if (c === "\"") {
6153
+ let j = i + 1;
6154
+ while (j < text.length && text[j] !== "\"") j += text[j] === "\\" ? 2 : 1;
6155
+ out += text.slice(i, j + 1);
6156
+ i = j + 1;
6157
+ } else if (c === "/" && text[i + 1] === "/") while (i < text.length && text[i] !== "\n") i++;
6158
+ else if (c === "/" && text[i + 1] === "*") {
6159
+ const end = text.indexOf("*/", i + 2);
6160
+ i = end < 0 ? text.length : end + 2;
6161
+ } else if (c === ",") {
6162
+ const next = text[nextToken(i + 1)];
6163
+ if (next !== "}" && next !== "]") out += c;
6164
+ i++;
6165
+ } else {
6166
+ out += c;
6167
+ i++;
6168
+ }
6169
+ }
6170
+ return JSON.parse(out);
6171
+ }
6172
+ /** Read a wrangler config as an object; only JSON and JSONC are read here. */
6173
+ function readWranglerConfig(path) {
6174
+ const ext = extname(path);
6175
+ if (ext !== ".json" && ext !== ".jsonc") throw new Error(`${basename(path)}: eutaxy check reads a callee's wrangler config as JSON or JSONC; a TOML config is not read`);
6176
+ const parsed = parseJsonc(readFileSync(path, "utf8"));
6177
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new Error(`${basename(path)}: not a wrangler config object`);
6178
+ return parsed;
6179
+ }
6180
+ const list$1 = (v) => Array.isArray(v) ? v.filter((x) => typeof x === "object" && x) : [];
6181
+ const str$1 = (v, fallback = "") => typeof v === "string" ? v : fallback;
6182
+ /** The keys of a wrangler config whose bindings the command carries into the isolate. */
6183
+ const carried = /* @__PURE__ */ new Set([
6184
+ "name",
6185
+ "main",
6186
+ "compatibility_date",
6187
+ "compatibility_flags",
6188
+ "d1_databases",
6189
+ "r2_buckets",
6190
+ "kv_namespaces",
6191
+ "durable_objects",
6192
+ "migrations",
6193
+ "workflows",
6194
+ "services",
6195
+ "queues",
6196
+ "vars",
6197
+ "$schema",
6198
+ "observability",
6199
+ "triggers",
6200
+ "routes",
6201
+ "route",
6202
+ "workers_dev",
6203
+ "account_id",
6204
+ "placement",
6205
+ "limits",
6206
+ "upload_source_maps",
6207
+ "minify",
6208
+ "keep_vars",
6209
+ "preview_urls"
6210
+ ]);
6211
+ /** Read a callee's wrangler config into what the isolate needs; `scenarioDir` resolves the step's paths. */
6212
+ function readCalleeConfig(step, scenarioDir) {
6213
+ const path = resolve(scenarioDir, step.config);
6214
+ const config = readWranglerConfig(path);
6215
+ const name = str$1(config["name"]);
6216
+ if (!name) throw new Error(`${basename(path)}: the callee's wrangler config has no name, which qualifies its bindings`);
6217
+ const notAdded = [];
6218
+ const sqlite = /* @__PURE__ */ new Set();
6219
+ const strings = (v) => Array.isArray(v) ? v.filter((x) => typeof x === "string") : [];
6220
+ for (const m of list$1(config["migrations"])) {
6221
+ for (const c of strings(m["new_sqlite_classes"])) sqlite.add(c);
6222
+ for (const r of list$1(m["renamed_classes"])) {
6223
+ const from = str$1(r["from"]);
6224
+ if (sqlite.delete(from)) sqlite.add(str$1(r["to"]));
6225
+ }
6226
+ for (const c of strings(m["deleted_classes"])) sqlite.delete(c);
6227
+ }
6228
+ const durableObjects = [];
6229
+ const dos = config["durable_objects"];
6230
+ for (const b of list$1(dos?.bindings)) {
6231
+ const className = str$1(b["class_name"]);
6232
+ const scriptName = b["script_name"] === void 0 ? void 0 : str$1(b["script_name"]);
6233
+ durableObjects.push({
6234
+ binding: str$1(b["name"]),
6235
+ className,
6236
+ sqlite: sqlite.has(className),
6237
+ ...scriptName === void 0 ? {} : { scriptName }
6238
+ });
6239
+ }
6240
+ const queues = config["queues"];
6241
+ for (const key of Object.keys(config)) if (!carried.has(key)) notAdded.push(key);
6242
+ const vars = {};
6243
+ const rawVars = config["vars"];
6244
+ if (typeof rawVars === "object" && rawVars !== null) for (const [k, v] of Object.entries(rawVars)) vars[k] = v;
6245
+ return {
6246
+ binding: step.binding,
6247
+ name,
6248
+ entry: resolve(scenarioDir, step.entry),
6249
+ d1: list$1(config["d1_databases"]).map((d) => ({
6250
+ binding: str$1(d["binding"]),
6251
+ id: str$1(d["database_id"], str$1(d["database_name"], str$1(d["binding"])))
6252
+ })),
6253
+ r2: list$1(config["r2_buckets"]).map((b) => ({
6254
+ binding: str$1(b["binding"]),
6255
+ bucket: str$1(b["bucket_name"], str$1(b["binding"]))
6256
+ })),
6257
+ kv: list$1(config["kv_namespaces"]).map((k) => ({
6258
+ binding: str$1(k["binding"]),
6259
+ id: str$1(k["id"], str$1(k["binding"]))
6260
+ })),
6261
+ durableObjects,
6262
+ workflows: list$1(config["workflows"]).map((w) => ({
6263
+ binding: str$1(w["binding"]),
6264
+ className: str$1(w["class_name"]),
6265
+ name: str$1(w["name"], str$1(w["binding"]))
6266
+ })),
6267
+ services: list$1(config["services"]).map((s) => str$1(s["binding"])),
6268
+ queues: list$1(queues?.producers).map((p) => ({
6269
+ binding: str$1(p["binding"]),
6270
+ queue: str$1(p["queue"])
6271
+ })),
6272
+ vars,
6273
+ sqliteClasses: [...sqlite],
6274
+ notAdded
6275
+ };
6276
+ }
6277
+ /** A Worker's name as an identifier prefix (`my-worker` → `my_worker`, `1st` → `_1st`). */
6278
+ const ident = (s) => {
6279
+ const safe = s.replace(/[^A-Za-z0-9_$]/g, "_");
6280
+ return /^[A-Za-z_$]/.test(safe) ? safe : `_${safe}`;
6281
+ };
6282
+ /** The export name a callee's class gets in the generated main module. */
6283
+ function classAlias(worker, className) {
6284
+ return `${ident(worker)}__${className}`;
6285
+ }
6286
+ /** The qualified name of a callee's binding. */
6287
+ function qualified(worker, binding) {
6288
+ return `${worker}/${binding}`;
6289
+ }
6290
+ function toPosix$1(p) {
6291
+ const s = p.split("\\").join("/");
6292
+ return s.startsWith(".") ? s : `./${s}`;
6293
+ }
6294
+ /**
6295
+ * The main module the plugin runs: the caller's exports as they are, and
6296
+ * each callee's Durable Object and Workflow classes under qualified aliases,
6297
+ * so the miniflare options can bind them. workerd constructs those classes
6298
+ * with the main Worker's env, so each alias is a subclass handing its parent
6299
+ * the callee's view of it (`calleeEnv`), under which `this.env.DB` is the
6300
+ * callee's `<name>/DB`.
6301
+ */
6302
+ function mainModuleSource(workDir, callerEntry, callees, isolate = noIsolate) {
6303
+ const caller = toPosix$1(relative(workDir, callerEntry));
6304
+ const lines = [
6305
+ "// Generated by eutaxy check; deleted after the run.",
6306
+ `export * from ${JSON.stringify(caller)};`,
6307
+ `export { default } from ${JSON.stringify(caller)};`
6308
+ ];
6309
+ const adapters = [];
6310
+ const emitted = /* @__PURE__ */ new Set();
6311
+ callees.forEach((c, i) => {
6312
+ const classes = [
6313
+ ...c.durableObjects.filter((d) => d.scriptName === void 0).map((d) => d.className),
6314
+ ...c.workflows.map((w) => w.className),
6315
+ ...isolate.extraClasses[c.name] ?? []
6316
+ ];
6317
+ const unique = [...new Set(classes)].filter((n) => n && !emitted.has(classAlias(c.name, n)));
6318
+ if (unique.length === 0) return;
6319
+ lines.push(`import { ${unique.map((n) => `${n} as callee${i}_${n}`).join(", ")} } from ${JSON.stringify(toPosix$1(relative(workDir, c.entry)))};`);
6320
+ const own = Object.fromEntries(Object.entries(isolate.aliases).filter(([k]) => k.startsWith(`${c.name}/`)));
6321
+ const view = `calleeEnv(${JSON.stringify(c.name)}, env${Object.keys(own).length === 0 ? "" : `, ${JSON.stringify(own)}`})`;
6322
+ for (const n of unique) {
6323
+ emitted.add(classAlias(c.name, n));
6324
+ adapters.push(`export class ${classAlias(c.name, n)} extends callee${i}_${n} {`, ` constructor(ctx: unknown, env: object) {`, ` super(ctx as never, ${view} as never);`, ` }`, `}`);
6325
+ }
6326
+ });
6327
+ if (adapters.length > 0) lines.splice(1, 0, "import { calleeEnv } from \"eutaxy/cloudflare\";");
6328
+ return `${[...lines, ...adapters].join("\n")}\n`;
6329
+ }
6330
+ /** The name the generated config gives the function answering a service binding nobody calls. */
6331
+ const neverCalled = "neverCalled";
6332
+ /**
6333
+ * The miniflare options adding the callees' resources under qualified names,
6334
+ * as source (an object literal) for the generated Vitest config. Service
6335
+ * bindings, the caller's to its callees and the callees' own, are answered
6336
+ * by a function of the config's (`neverCalled`): the Worker the caller's
6337
+ * config names is not in the isolate, a worker name given through these
6338
+ * options must be one the plugin knows, and the binding is never called
6339
+ * anyway (the scenario names a callee for it or scripts it); its value is a
6340
+ * Fetcher all the same, which is what the platform recognises.
6341
+ */
6342
+ function miniflareOptionsSource(callees, isolate = noIsolate, callerServices = []) {
6343
+ const d1 = {};
6344
+ const r2 = {};
6345
+ const kv = {};
6346
+ const dos = {};
6347
+ const workflows = {};
6348
+ const services = {};
6349
+ const queues = {};
6350
+ const vars = {};
6351
+ const aliased = (name) => name in isolate.aliases;
6352
+ Object.assign(dos, isolate.redirected);
6353
+ for (const b of callerServices) services[b] = neverCalled;
6354
+ for (const c of callees) {
6355
+ for (const d of c.d1) if (!aliased(qualified(c.name, d.binding))) d1[qualified(c.name, d.binding)] = d.id;
6356
+ for (const b of c.r2) if (!aliased(qualified(c.name, b.binding))) r2[qualified(c.name, b.binding)] = b.bucket;
6357
+ for (const k of c.kv) if (!aliased(qualified(c.name, k.binding))) kv[qualified(c.name, k.binding)] = k.id;
6358
+ for (const o of c.durableObjects) {
6359
+ if (o.scriptName !== void 0 || aliased(qualified(c.name, o.binding))) continue;
6360
+ dos[qualified(c.name, o.binding)] = {
6361
+ className: classAlias(c.name, o.className),
6362
+ ...o.sqlite ? { useSQLite: true } : {}
6363
+ };
6364
+ }
6365
+ for (const w of c.workflows) workflows[qualified(c.name, w.binding)] = {
6366
+ name: w.name,
6367
+ className: classAlias(c.name, w.className)
6368
+ };
6369
+ services[c.binding] = neverCalled;
6370
+ for (const s of c.services) services[qualified(c.name, s)] = neverCalled;
6371
+ for (const q of c.queues) queues[qualified(c.name, q.binding)] = q.queue;
6372
+ for (const [k, v] of Object.entries(c.vars)) vars[qualified(c.name, k)] = v;
6373
+ }
6374
+ const options = {};
6375
+ const add = (key, value) => {
6376
+ if (Object.keys(value).length > 0) options[key] = value;
6377
+ };
6378
+ add("d1Databases", d1);
6379
+ add("r2Buckets", r2);
6380
+ add("kvNamespaces", kv);
6381
+ add("durableObjects", dos);
6382
+ add("workflows", workflows);
6383
+ add("queueProducers", queues);
6384
+ add("bindings", vars);
6385
+ const data = JSON.stringify(options);
6386
+ const bindings = Object.keys(services);
6387
+ if (bindings.length === 0) return data;
6388
+ const literal = `"serviceBindings":{${bindings.map((b) => `${JSON.stringify(b)}:${neverCalled}`).join(",")}}`;
6389
+ return data === "{}" ? `{${literal}}` : `${data.slice(0, -1)},${literal}}`;
6390
+ }
6391
+ /** The caller's resources from its wrangler config, when the config can be read (JSON or JSONC); none otherwise. */
6392
+ function readCallerResources(wranglerPath) {
6393
+ try {
6394
+ const config = readWranglerConfig(wranglerPath);
6395
+ const dos = config["durable_objects"];
6396
+ return {
6397
+ name: str$1(config["name"]) || void 0,
6398
+ d1: list$1(config["d1_databases"]).map((d) => ({
6399
+ binding: str$1(d["binding"]),
6400
+ id: str$1(d["database_id"], str$1(d["database_name"], str$1(d["binding"])))
6401
+ })),
6402
+ r2: list$1(config["r2_buckets"]).map((b) => ({
6403
+ binding: str$1(b["binding"]),
6404
+ bucket: str$1(b["bucket_name"], str$1(b["binding"]))
6405
+ })),
6406
+ kv: list$1(config["kv_namespaces"]).map((k) => ({
6407
+ binding: str$1(k["binding"]),
6408
+ id: str$1(k["id"], str$1(k["binding"]))
6409
+ })),
6410
+ durableObjects: list$1(dos?.bindings).map((b) => ({
6411
+ binding: str$1(b["name"]),
6412
+ className: str$1(b["class_name"]),
6413
+ ...b["script_name"] === void 0 ? {} : { scriptName: str$1(b["script_name"]) }
6414
+ })),
6415
+ services: list$1(config["services"]).map((b) => ({
6416
+ binding: str$1(b["binding"]),
6417
+ ...typeof b["entrypoint"] === "string" ? { entrypoint: b["entrypoint"] } : {},
6418
+ ...typeof b["props"] === "object" && b["props"] !== null ? { props: b["props"] } : {}
6419
+ }))
6420
+ };
6421
+ } catch {
6422
+ return;
6423
+ }
6424
+ }
6425
+ /** What the caller's binding to a callee carries (its entrypoint and props), for the test to pass with the module. */
6426
+ function bindingCarries(caller, binding) {
6427
+ const s = caller?.services.find((x) => x.binding === binding);
6428
+ return {
6429
+ ...s?.entrypoint === void 0 ? {} : { entrypoint: s.entrypoint },
6430
+ ...s?.props === void 0 ? {} : { props: s.props }
6431
+ };
6432
+ }
6433
+ /**
6434
+ * The isolate's shared resources, from the two configs: a callee binding
6435
+ * that names a resource the caller binds too (the same `database_id`,
6436
+ * `bucket_name` or KV `id`; a Durable Object class of the caller's script,
6437
+ * or a caller binding to a class of the callee's script) is an alias of the
6438
+ * caller's binding, set up and snapshotted under the caller's name; a
6439
+ * caller's binding to a callee's class is redirected to the generated alias
6440
+ * class. What a callee binds in a third Worker's script is named as not
6441
+ * added.
6442
+ */
6443
+ function isolateOf(callees, caller) {
6444
+ const aliases = {};
6445
+ const redirected = {};
6446
+ const extraClasses = {};
6447
+ const notAdded = [];
6448
+ const alias = (name, own) => {
6449
+ if (own !== name) aliases[name] = own;
6450
+ };
6451
+ for (const c of callees) {
6452
+ if (caller) {
6453
+ for (const d of c.d1) {
6454
+ const own = caller.d1.find((x) => x.id === d.id);
6455
+ if (own) alias(qualified(c.name, d.binding), own.binding);
6456
+ }
6457
+ for (const b of c.r2) {
6458
+ const own = caller.r2.find((x) => x.bucket === b.bucket);
6459
+ if (own) alias(qualified(c.name, b.binding), own.binding);
6460
+ }
6461
+ for (const k of c.kv) {
6462
+ const own = caller.kv.find((x) => x.id === k.id);
6463
+ if (own) alias(qualified(c.name, k.binding), own.binding);
6464
+ }
6465
+ for (const o of caller.durableObjects) {
6466
+ if (o.scriptName !== c.name) continue;
6467
+ const theirs = c.durableObjects.find((x) => x.className === o.className && x.scriptName === void 0);
6468
+ redirected[o.binding] = {
6469
+ className: classAlias(c.name, o.className),
6470
+ ...c.sqliteClasses.includes(o.className) ? { useSQLite: true } : {}
6471
+ };
6472
+ if (theirs) alias(qualified(c.name, theirs.binding), o.binding);
6473
+ else {
6474
+ const extra = extraClasses[c.name] ?? [];
6475
+ extra.push(o.className);
6476
+ extraClasses[c.name] = extra;
6477
+ }
6478
+ }
6479
+ }
6480
+ for (const o of c.durableObjects) {
6481
+ if (o.scriptName === void 0) continue;
6482
+ const own = caller && o.scriptName === caller.name ? caller.durableObjects.find((x) => x.className === o.className && x.scriptName === void 0) : void 0;
6483
+ if (own) alias(qualified(c.name, o.binding), own.binding);
6484
+ else notAdded.push(`${c.binding}: durable_objects binding ${o.binding} (script_name ${o.scriptName}: a class of another Worker)`);
6485
+ }
6486
+ }
6487
+ return {
6488
+ aliases,
6489
+ redirected,
6490
+ extraClasses,
6491
+ notAdded
6492
+ };
6493
+ }
6494
+ /** An isolate with nothing shared. */
6495
+ const noIsolate = {
6496
+ aliases: {},
6497
+ redirected: {},
6498
+ extraClasses: {},
6499
+ notAdded: []
6500
+ };
6501
+ /** Where a callee's config path and entry sit, for messages. */
6502
+ function describeCallee(c, scenarioDir) {
6503
+ return `${c.binding} (${c.name}, ${toPosix$1(relative(scenarioDir, c.entry))})`;
6504
+ }
5979
6505
  // packages/cli/src/generate.ts
5980
6506
  /**
5981
6507
  * The files `eutaxy check` writes into `<scenario dir>/.eutaxy/` before
5982
6508
  * running Vitest: a test that performs the check inside workerd and prints
5983
6509
  * the verdict on one marked line, and a Vitest config with the Cloudflare
5984
- * plugin pointed at the scenario's wrangler config.
6510
+ * plugin pointed at the scenario's wrangler config. For a scenario with
6511
+ * callees the test imports their modules, the config names a generated main
6512
+ * module and adds their resources through miniflare options (`callees.ts`).
5985
6513
  */
5986
6514
  /** Key under which the generated test stores its result in the Vitest task meta, read back from the JSON reporter. */
5987
6515
  const metaKey = "eutaxy";
@@ -5992,29 +6520,37 @@ const metaKey = "eutaxy";
5992
6520
  */
5993
6521
  function checkTestSource(g) {
5994
6522
  const options = `seed: ${JSON.stringify(g.seed)}` + (g.maxRuns === void 0 ? "" : `, maxRuns: ${g.maxRuns}`) + (g.budgetMs === void 0 ? "" : `, budgetMs: ${g.budgetMs}`) + (g.exhaustive ? ", exhaustive: true" : "");
6523
+ const callees = g.callees ?? [];
6524
+ const sqlImports = g.sqlImports ?? [];
6525
+ const calleeImports = callees.map((c, i) => `import * as callee_${i} from ${JSON.stringify(c.importPath)};\n`);
6526
+ const sqlImportLines = sqlImports.map((f, i) => `import sql_${i} from ${JSON.stringify(`${f.importPath}?raw`)};\n`);
6527
+ const calleesOption = callees.length === 0 ? "" : `, callees: { ${callees.map((c, i) => `${JSON.stringify(c.binding)}: { name: ${JSON.stringify(c.name)}, exports: callee_${i}${c.entrypoint === void 0 ? "" : `, entrypoint: ${JSON.stringify(c.entrypoint)}`}${c.props === void 0 ? "" : `, props: ${JSON.stringify(c.props)}`} }`).join(", ")} }`;
6528
+ const extraSql = sqlImports.length === 0 ? "" : `, extraSql: { ${sqlImports.map((f, i) => `${JSON.stringify(f.key)}: sql_${i}`).join(", ")} }`;
6529
+ const aliases = g.aliases === void 0 || Object.keys(g.aliases).length === 0 ? "" : `, aliases: ${JSON.stringify(g.aliases)}`;
5995
6530
  return `// Generated by eutaxy check; deleted after the run.
5996
6531
  import { checkInWorkerd } from "eutaxy/cloudflare";
5997
6532
  import { env } from "cloudflare:workers";
5998
6533
  import * as durableObjects from "cloudflare:test";
5999
6534
  import { test } from "vitest";
6000
6535
  import scenario from ${JSON.stringify(g.scenarioImport)};
6001
- import { specEntries } from "./specs.ts";
6536
+ ${calleeImports.join("")}${sqlImportLines.join("")}import { specEntries } from "./specs.ts";
6002
6537
 
6003
6538
  const sqlFiles = import.meta.glob("../**/*.sql", { query: "?raw", import: "default", eager: true }) as Record<string, string>;
6004
6539
  const modules = import.meta.glob(["../**/*.ts", "!../**/*.test.ts", "!../**/*.sim.ts", "!../**/node_modules/**", "!../**/.eutaxy/**"]);
6005
6540
 
6006
6541
  test("eutaxy check", async ({ task }) => {
6007
- task.meta[${JSON.stringify(metaKey)}] = await checkInWorkerd({ scenario, env, durableObjects, sqlFiles, modules, specEntries, ${options} });
6542
+ task.meta[${JSON.stringify(metaKey)}] = await checkInWorkerd({ scenario, env, durableObjects, sqlFiles, modules, specEntries${calleesOption}${extraSql}${aliases}, ${options} });
6008
6543
  });
6009
6544
  `;
6010
6545
  }
6011
- function vitestConfigSource(wranglerConfigPath, testPath, outputFile) {
6546
+ function vitestConfigSource(wranglerConfigPath, testPath, outputFile, isolate) {
6547
+ const plugin = isolate === void 0 ? `cloudflareTest({ wrangler: { configPath: ${JSON.stringify(wranglerConfigPath)} } })` : `cloudflareTest({ main: ${JSON.stringify(isolate.main)}, wrangler: { configPath: ${JSON.stringify(wranglerConfigPath)} }${isolate.miniflare === void 0 ? "" : `, miniflare: ${isolate.miniflare}`} })`;
6012
6548
  return `// Generated by eutaxy check; deleted after the run.
6013
6549
  import { cloudflareTest } from "@cloudflare/vitest-plugin";
6014
6550
  import { defineConfig } from "vitest/config";
6015
6551
 
6016
- export default defineConfig({
6017
- plugins: [cloudflareTest({ wrangler: { configPath: ${JSON.stringify(wranglerConfigPath)} } })],
6552
+ ${isolate?.miniflare === void 0 ? "" : `const ${neverCalled} = () => new Response("eutaxy: a service binding the scenario scripts or runs as a callee is never called", { status: 500 });\n\n`}export default defineConfig({
6553
+ plugins: [${plugin}],
6018
6554
  test: {
6019
6555
  include: [${JSON.stringify(testPath)}],
6020
6556
  testTimeout: 600_000,
@@ -6231,23 +6767,65 @@ async function runCheck(o) {
6231
6767
  }
6232
6768
  const dir = dirname(scenarioPath);
6233
6769
  const name = basename(scenarioPath).replace(/\.sim\.ts$/, "").replace(/\.ts$/, "");
6234
- const wrangler = findWrangler(dir, o.wrangler, o.cwd);
6235
- if (!wrangler || !existsSync(wrangler)) {
6236
- o.stderr(`no wrangler config found next to the scenario; pass --wrangler <path>\n`);
6237
- return exitCodes.error;
6238
- }
6239
6770
  const stamp = `${process.pid}-${randomBytes(3).toString("hex")}`;
6240
6771
  const workDir = join(dir, ".eutaxy");
6241
6772
  const testPath = join(workDir, `${name}.${stamp}.check.test.ts`);
6242
6773
  const configPath = join(workDir, `vitest.config.${stamp}.mts`);
6774
+ const mainPath = join(workDir, `main.${stamp}.ts`);
6775
+ let callees = [];
6776
+ let loaded;
6777
+ try {
6778
+ loaded = await loadScenario(scenarioPath);
6779
+ } catch (err) {
6780
+ if (mentionsCallee(readFileSync(scenarioPath, "utf8"))) {
6781
+ o.stderr(`could not read the scenario's callees: ${String(err)}\n`);
6782
+ return exitCodes.error;
6783
+ }
6784
+ o.stderr(`could not read the scenario in Node, so the isolate's main module is the wrangler config's: ${String(err).split("\n")[0]}\n`);
6785
+ }
6786
+ const named = o.wrangler === void 0 ? loaded?.worker.config : void 0;
6787
+ const wrangler = named !== void 0 ? resolve(dir, named) : findWrangler(dir, o.wrangler, o.cwd);
6788
+ if (!wrangler || !existsSync(wrangler)) {
6789
+ o.stderr(named !== void 0 ? `the scenario's wrangler config was not found: ${wrangler}; pass --wrangler <path>\n` : `no wrangler config found next to the scenario; pass --wrangler <path>\n`);
6790
+ return exitCodes.error;
6791
+ }
6792
+ try {
6793
+ callees = calleeSteps(loaded?.setup ?? []).map((step) => readCalleeConfig(step, dir));
6794
+ } catch (err) {
6795
+ o.stderr(`could not read the scenario's callees: ${String(err)}\n`);
6796
+ return exitCodes.error;
6797
+ }
6798
+ for (const c of callees) if (c.notAdded.length > 0) o.stderr(`callee ${describeCallee(c, dir)}: not added to the test's isolate: ${c.notAdded.join(", ")}\n`);
6799
+ const callerResources = readCallerResources(wrangler);
6800
+ const isolate = isolateOf(callees, callees.length > 0 ? callerResources : void 0);
6801
+ const callerServices = (callerResources?.services ?? []).map((s) => s.binding).filter((b) => b);
6802
+ for (const reason of isolate.notAdded) o.stderr(`not added to the test's isolate: ${reason}\n`);
6243
6803
  mkdirSync(workDir, { recursive: true });
6244
6804
  try {
6805
+ const sqlImports = [];
6806
+ if (callees.length > 0 && loaded) for (const step of loaded.setup) {
6807
+ if (step.kind !== "d1") continue;
6808
+ const file = String(step["schemaFile"]);
6809
+ if (!relative(dir, resolve(dir, file)).startsWith("..")) continue;
6810
+ sqlImports.push({
6811
+ key: globKey(file),
6812
+ importPath: toPosix(relative(workDir, resolve(dir, file)))
6813
+ });
6814
+ }
6245
6815
  writeFileSync(testPath, checkTestSource({
6246
6816
  seed: o.seed ?? name,
6247
6817
  ...o.maxRuns === void 0 ? {} : { maxRuns: o.maxRuns },
6248
6818
  ...o.budgetMs === void 0 ? {} : { budgetMs: o.budgetMs },
6249
6819
  ...o.exhaustive ? { exhaustive: true } : {},
6250
- scenarioImport: `../${basename(scenarioPath)}`
6820
+ scenarioImport: `../${basename(scenarioPath)}`,
6821
+ ...callees.length === 0 ? {} : { callees: callees.map((c) => ({
6822
+ binding: c.binding,
6823
+ name: c.name,
6824
+ importPath: toPosix(relative(workDir, c.entry)),
6825
+ ...bindingCarries(callerResources, c.binding)
6826
+ })) },
6827
+ ...sqlImports.length === 0 ? {} : { sqlImports },
6828
+ ...Object.keys(isolate.aliases).length === 0 ? {} : { aliases: isolate.aliases }
6251
6829
  }));
6252
6830
  const specModules = findSpecModules(dir);
6253
6831
  for (const f of specFiles(specModules, workDir)) {
@@ -6256,7 +6834,17 @@ async function runCheck(o) {
6256
6834
  }
6257
6835
  const reportPath = join(workDir, `vitest-report.${stamp}.json`);
6258
6836
  rmSync(reportPath, { force: true });
6259
- writeFileSync(configPath, vitestConfigSource(wrangler, testPath, reportPath));
6837
+ if (callees.length > 0 && loaded) {
6838
+ const callerEntry = resolve(dir, loaded.worker.entry);
6839
+ writeFileSync(mainPath, mainModuleSource(workDir, callerEntry, callees, isolate));
6840
+ writeFileSync(configPath, vitestConfigSource(wrangler, testPath, reportPath, {
6841
+ main: mainPath,
6842
+ miniflare: miniflareOptionsSource(callees, isolate, callerServices)
6843
+ }));
6844
+ } else writeFileSync(configPath, vitestConfigSource(wrangler, testPath, reportPath, loaded ? {
6845
+ main: resolve(dir, loaded.worker.entry),
6846
+ ...callerServices.length > 0 ? { miniflare: miniflareOptionsSource([], void 0, callerServices) } : {}
6847
+ } : void 0));
6260
6848
  const { code, output } = await runVitest(vitestBin(dir), configPath, dir);
6261
6849
  const transport = code === 0 ? readTransport(reportPath) : null;
6262
6850
  if (!transport) {
@@ -6290,11 +6878,31 @@ async function runCheck(o) {
6290
6878
  const outPath = regressionPath;
6291
6879
  const outDir = dirname(outPath);
6292
6880
  const schemaPaths = {};
6293
- for (const step of transport.setup) if (step.kind === "d1") schemaPaths[String(step["binding"])] = toPosix(relative(outDir, resolve(dir, String(step["schemaFile"]))));
6881
+ for (const step of transport.setup) if (step.kind === "d1") {
6882
+ const binding = String(step["binding"]);
6883
+ const path = toPosix(relative(outDir, resolve(dir, String(step["schemaFile"]))));
6884
+ schemaPaths[binding] = [...schemaPaths[binding] ?? [], path];
6885
+ }
6886
+ const calleePaths = {};
6887
+ for (const step of transport.setup) {
6888
+ if (step.kind !== "callee") continue;
6889
+ const binding = String(step["binding"]);
6890
+ const carried = transport.callees?.[binding];
6891
+ if (carried === void 0) continue;
6892
+ calleePaths[binding] = {
6893
+ ...carried,
6894
+ path: toPosix(relative(outDir, resolve(dir, String(step["entry"]))))
6895
+ };
6896
+ }
6294
6897
  const source = cloudflareRegressionTest(verdict, {
6295
6898
  scenarioPath: toPosix(relative(outDir, scenarioPath)),
6296
6899
  workerPath: toPosix(relative(outDir, resolve(dir, transport.worker.entry))),
6297
6900
  schemaPaths,
6901
+ ...Object.keys(calleePaths).length === 0 ? {} : {
6902
+ callees: calleePaths,
6903
+ calleeBindings: isolateBindings(callees).filter((b) => !(b in isolate.aliases)),
6904
+ ...transport.aliases === void 0 ? {} : { aliases: transport.aliases }
6905
+ },
6298
6906
  ...o.budgetMs === void 0 ? {} : { budgetMs: o.budgetMs },
6299
6907
  ...transport.setup.some((s) => s.kind === "durable_object") ? { durableObjects: true } : {},
6300
6908
  ...transport.setup.some((s) => s.kind === "workflow") || transport.drive?.kind === "rpc" && transport.drive["entrypoint"] !== void 0 ? { exports: true } : {},
@@ -6327,6 +6935,480 @@ function cleanUp(workDir, stamp) {
6327
6935
  force: true
6328
6936
  });
6329
6937
  }
6938
+ // packages/cli/src/draft.ts
6939
+ /**
6940
+ * `eutaxy draft`: a scenario skeleton from a wrangler config and the Worker
6941
+ * module it names. The config's bindings become setup steps, the Worker's
6942
+ * handlers the drive, the hosts its code fetches the externals; the
6943
+ * invariants and the drive's events are left as holes marked TODO, since
6944
+ * only the author knows what must hold and which events matter. Nothing is
6945
+ * imported or run: the config is read as JSON or JSONC and the module's
6946
+ * source (with the modules it imports relatively) is scanned as text.
6947
+ */
6948
+ const list = (v) => Array.isArray(v) ? v.filter((x) => typeof x === "object" && x) : [];
6949
+ const text$1 = (v) => typeof v === "string" ? v : "";
6950
+ const record = (v) => typeof v === "object" && v !== null && !Array.isArray(v) ? v : {};
6951
+ /** A path relative to `from`, with forward slashes and a leading `./`. */
6952
+ function ref(from, to) {
6953
+ const p = relative(from, to).split("\\").join("/");
6954
+ return p.startsWith(".") ? p : `./${p}`;
6955
+ }
6956
+ /** Read a wrangler config as JSON or JSONC; TOML is not read. */
6957
+ function readConfig(path) {
6958
+ if (extname(path) !== ".json" && extname(path) !== ".jsonc") throw new Error(`${basename(path)}: eutaxy draft reads a wrangler config as JSON or JSONC; a TOML config is not read`);
6959
+ return readWranglerConfig(path);
6960
+ }
6961
+ /** Binding kinds the simulation does not proxy: a run that touches one is UNSUPPORTED. */
6962
+ const unmodelled = {
6963
+ kv_namespaces: "KV namespace",
6964
+ ai: "Workers AI",
6965
+ vectorize: "Vectorize index",
6966
+ hyperdrive: "Hyperdrive config",
6967
+ analytics_engine_datasets: "Analytics Engine dataset",
6968
+ browser: "Browser Rendering",
6969
+ send_email: "email sender",
6970
+ dispatch_namespaces: "dispatch namespace",
6971
+ mtls_certificates: "mTLS certificate",
6972
+ secrets_store_secrets: "Secrets Store secret",
6973
+ images: "Images",
6974
+ version_metadata: "version metadata",
6975
+ pipelines: "pipeline"
6976
+ };
6977
+ /** The SQLite-backed classes of a config's migrations (the ones created so, as wrangler applies them). */
6978
+ function sqliteClasses(config) {
6979
+ const out = /* @__PURE__ */ new Set();
6980
+ for (const m of list(config["migrations"])) for (const c of Array.isArray(m["new_sqlite_classes"]) ? m["new_sqlite_classes"] : []) if (typeof c === "string") out.add(c);
6981
+ return out;
6982
+ }
6983
+ /**
6984
+ * The schema file of a D1 binding, beside its config: `schema.sql`, else `<database_name>.sql`, else the
6985
+ * only `.sql` file there; `found` false when none is, and the step names `schema.sql` to create.
6986
+ */
6987
+ function schemaOf(configDir, database) {
6988
+ for (const name of ["schema.sql", database ? `${database}.sql` : ""]) if (name && existsSync(join(configDir, name))) return {
6989
+ file: join(configDir, name),
6990
+ found: true
6991
+ };
6992
+ const sql = readdirSync(configDir).filter((f) => f.endsWith(".sql"));
6993
+ if (sql.length === 1) return {
6994
+ file: join(configDir, sql[0]),
6995
+ found: true
6996
+ };
6997
+ return {
6998
+ file: join(configDir, "schema.sql"),
6999
+ found: false
7000
+ };
7001
+ }
7002
+ /**
7003
+ * Migrations in the order wrangler applies them: by the number a name starts with, compared as a number
7004
+ * (`2_add` before `10_seed`), then by name; a name with no number after the numbered ones.
7005
+ */
7006
+ function migrationOrder(a, b) {
7007
+ const na = /^\d+/.exec(a)?.[0];
7008
+ const nb = /^\d+/.exec(b)?.[0];
7009
+ if (na !== void 0 && nb !== void 0 && Number(na) !== Number(nb)) return Number(na) - Number(nb);
7010
+ if (na !== void 0 && nb === void 0) return -1;
7011
+ if (na === void 0 && nb !== void 0) return 1;
7012
+ return a < b ? -1 : a > b ? 1 : 0;
7013
+ }
7014
+ /**
7015
+ * A migrations directory's files in the order wrangler applies them: its `.sql` files, and a
7016
+ * subdirectory's `migration.sql` (one folder per migration, as drizzle-kit writes them).
7017
+ */
7018
+ function migrationFiles(dir) {
7019
+ if (!existsSync(dir)) return [];
7020
+ return readdirSync(dir, { withFileTypes: true }).sort((a, b) => migrationOrder(a.name, b.name)).flatMap((e) => {
7021
+ if (e.isFile() && e.name.endsWith(".sql")) return [join(dir, e.name)];
7022
+ const nested = join(dir, e.name, "migration.sql");
7023
+ return e.isDirectory() && existsSync(nested) ? [nested] : [];
7024
+ });
7025
+ }
7026
+ /** Wrangler configs under `root` (not in node_modules or dot directories), by their `name`. */
7027
+ function configsByName(root, depth = 3) {
7028
+ const out = /* @__PURE__ */ new Map();
7029
+ const walk = (dir, left) => {
7030
+ let entries;
7031
+ try {
7032
+ entries = readdirSync(dir, { withFileTypes: true });
7033
+ } catch {
7034
+ return;
7035
+ }
7036
+ for (const e of entries) {
7037
+ const path = join(dir, e.name);
7038
+ if (e.isDirectory()) {
7039
+ if (left > 0 && e.name !== "node_modules" && !e.name.startsWith(".")) walk(path, left - 1);
7040
+ } else if (e.name === "wrangler.jsonc" || e.name === "wrangler.json") try {
7041
+ const name = text$1(readConfig(path)["name"]);
7042
+ if (name && !out.has(name)) out.set(name, path);
7043
+ } catch {}
7044
+ }
7045
+ };
7046
+ walk(root, depth);
7047
+ return out;
7048
+ }
7049
+ /** The source of a module and of the modules it imports by relative path, transitively. */
7050
+ function sources(entry) {
7051
+ const seen = /* @__PURE__ */ new Set();
7052
+ const out = [];
7053
+ const visit = (file) => {
7054
+ if (seen.has(file) || !existsSync(file)) return;
7055
+ seen.add(file);
7056
+ const src = readFileSync(file, "utf8");
7057
+ out.push(src);
7058
+ for (const m of src.matchAll(/(?:\bfrom\s*|\bimport\s*\(?\s*)["'](\.{1,2}\/[^"']+)["']/g)) {
7059
+ const spec = resolve(dirname(file), m[1]);
7060
+ const found = [
7061
+ spec,
7062
+ spec.replace(/\.js$/, ".ts"),
7063
+ `${spec}.ts`,
7064
+ join(spec, "index.ts")
7065
+ ].find((c) => existsSync(c) && extname(c) !== "");
7066
+ if (found) visit(found);
7067
+ }
7068
+ };
7069
+ visit(entry);
7070
+ return out;
7071
+ }
7072
+ /**
7073
+ * The hosts a module's code fetches by a literal URL, in order of first appearance, as `URL.host` has
7074
+ * them (which the fetch interceptor matches): lowercase, a non-default port kept.
7075
+ */
7076
+ function fetchedHosts(srcs) {
7077
+ const hosts = [];
7078
+ for (const src of srcs) for (const m of src.matchAll(/\bfetch\(\s*["'`](https?):\/\/([a-z0-9.-]+)(?::(\d+))?/gi)) {
7079
+ const port = m[3];
7080
+ const defaultPort = m[1].toLowerCase() === "https" ? "443" : "80";
7081
+ const host = `${m[2].toLowerCase()}${port && port !== defaultPort ? `:${port}` : ""}`;
7082
+ if (!hosts.includes(host)) hosts.push(host);
7083
+ }
7084
+ return hosts;
7085
+ }
7086
+ /** An external's name from its host: the first label, made an identifier-like word, unique. */
7087
+ function externalName(host, taken) {
7088
+ const base = (host.split(".")[0] ?? host).replace(/[^a-z0-9-]/gi, "-") || "external";
7089
+ let name = base;
7090
+ for (let i = 2; taken.has(name); i++) name = `${base}-${i}`;
7091
+ taken.add(name);
7092
+ return name;
7093
+ }
7094
+ /**
7095
+ * The SDK's route segment for an Agent's binding, as `routeAgentRequest` matches it: the Agents SDK's
7096
+ * `camelCaseToKebabCase` (an all-caps name lowercased, else a dash before every capital).
7097
+ */
7098
+ function agentSegment(binding) {
7099
+ if (binding === binding.toUpperCase() && binding !== binding.toLowerCase()) return binding.toLowerCase().replaceAll("_", "-");
7100
+ const kebab = binding.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`);
7101
+ return (kebab.startsWith("-") ? kebab.slice(1) : kebab).replaceAll("_", "-").replace(/-$/, "");
7102
+ }
7103
+ function draftScenario(input) {
7104
+ const config = readConfig(input.config);
7105
+ const configDir = dirname(input.config);
7106
+ const scenarioDir = input.scenarioDir ?? configDir;
7107
+ const name = text$1(config["name"]) || basename(configDir);
7108
+ const main = text$1(config["main"]);
7109
+ if (input.entry === void 0 && !main) throw new Error(`${basename(input.config)} names no main module; pass the Worker's module`);
7110
+ const entry = input.entry ?? resolve(configDir, main);
7111
+ if (!existsSync(entry)) throw new Error(`the Worker module ${entry} does not exist`);
7112
+ const notes = [];
7113
+ const setup = [];
7114
+ const callerSrcs = sources(entry);
7115
+ const srcs = [...callerSrcs];
7116
+ const others = list(config["services"]).length > 0 ? configsByName(scenarioDir) : /* @__PURE__ */ new Map();
7117
+ const callees = /* @__PURE__ */ new Map();
7118
+ for (const s of list(config["services"])) {
7119
+ const service = text$1(s["service"]);
7120
+ const found = service && service !== name ? others.get(service) : void 0;
7121
+ if (found !== void 0) callees.set(service, found);
7122
+ }
7123
+ const d1Id = (db) => text$1(db["database_id"]) || text$1(db["database_name"]) || text$1(db["binding"]);
7124
+ const callerDatabases = new Map(list(config["d1_databases"]).map((db) => [d1Id(db), text$1(db["binding"])]));
7125
+ const callerBuckets = new Map(list(config["r2_buckets"]).map((b) => [text$1(b["bucket_name"]) || text$1(b["binding"]), text$1(b["binding"])]));
7126
+ /** Classes of a callee's script the caller binds itself: one namespace, set up under the caller's name. */
7127
+ const sharedClasses = new Set(list(record(config["durable_objects"])["bindings"]).filter((b) => callees.has(text$1(b["script_name"]))).map((b) => `${text$1(b["script_name"])}:${text$1(b["class_name"])}`));
7128
+ /** The setup steps of one Worker's own resources: the caller's (prefix ""), or a callee's (`<name>/`). */
7129
+ const resourceSteps = (cfg, dir, worker, prefix) => {
7130
+ const sqlite = sqliteClasses(cfg);
7131
+ for (const db of list(cfg["d1_databases"])) {
7132
+ const binding = text$1(db["binding"]);
7133
+ if (!binding) continue;
7134
+ const shared = prefix ? callerDatabases.get(d1Id(db)) : void 0;
7135
+ if (shared !== void 0) {
7136
+ notes.push(`D1 ${prefix}${binding} is the caller's database ${shared}: set it up and read it as ${shared}`);
7137
+ continue;
7138
+ }
7139
+ const schema = schemaOf(dir, text$1(db["database_name"]));
7140
+ const pattern = text$1(db["migrations_pattern"]);
7141
+ if (!schema.found && pattern) notes.push(`D1 ${prefix}${binding}: its migrations are the files matching ${pattern}; add a d1Schema step for each, in the order wrangler applies them`);
7142
+ const migrations = schema.found || pattern ? [] : migrationFiles(join(dir, text$1(db["migrations_dir"]) || "migrations"));
7143
+ if (migrations.length > 0) {
7144
+ for (const file of migrations) setup.push({
7145
+ kind: "d1",
7146
+ binding: `${prefix}${binding}`,
7147
+ schemaFile: ref(scenarioDir, file)
7148
+ });
7149
+ continue;
7150
+ }
7151
+ if (!schema.found && !pattern) notes.push(`D1 ${prefix}${binding}: no schema file found; write the tables it needs into ${ref(scenarioDir, schema.file)}`);
7152
+ setup.push({
7153
+ kind: "d1",
7154
+ binding: `${prefix}${binding}`,
7155
+ schemaFile: ref(scenarioDir, schema.file)
7156
+ });
7157
+ }
7158
+ for (const b of list(record(cfg["durable_objects"])["bindings"])) {
7159
+ const binding = text$1(b["name"]);
7160
+ const className = text$1(b["class_name"]);
7161
+ const script = text$1(b["script_name"]);
7162
+ if (!binding) continue;
7163
+ if (script && script !== worker) {
7164
+ if (!prefix && callees.has(script)) setup.push({
7165
+ kind: "durable_object",
7166
+ binding,
7167
+ sqlite: sqliteClasses(readConfig(callees.get(script))).has(className)
7168
+ });
7169
+ else notes.push(`Durable Object ${prefix}${binding} is ${script}'s class ${className}: name ${script} with callee() to run it`);
7170
+ continue;
7171
+ }
7172
+ if (prefix && sharedClasses.has(`${worker}:${className}`)) {
7173
+ notes.push(`Durable Object ${prefix}${binding} is the namespace the caller binds to ${worker}'s class ${className}: set it up and read it under the caller's name`);
7174
+ continue;
7175
+ }
7176
+ setup.push({
7177
+ kind: "durable_object",
7178
+ binding: `${prefix}${binding}`,
7179
+ sqlite: sqlite.has(className)
7180
+ });
7181
+ }
7182
+ for (const b of list(cfg["r2_buckets"])) {
7183
+ const binding = text$1(b["binding"]);
7184
+ if (!binding) continue;
7185
+ const shared = prefix ? callerBuckets.get(text$1(b["bucket_name"]) || binding) : void 0;
7186
+ if (shared !== void 0) {
7187
+ notes.push(`R2 ${prefix}${binding} is the caller's bucket ${shared}: set it up and read it as ${shared}`);
7188
+ continue;
7189
+ }
7190
+ setup.push({
7191
+ kind: "r2",
7192
+ binding: `${prefix}${binding}`
7193
+ });
7194
+ }
7195
+ for (const w of list(cfg["workflows"])) {
7196
+ const binding = text$1(w["binding"]);
7197
+ const className = text$1(w["class_name"]);
7198
+ const script = text$1(w["script_name"]);
7199
+ if (!binding || !className) continue;
7200
+ if (script && script !== worker) {
7201
+ notes.push(`Workflow ${prefix}${binding} runs in ${script}: name ${script} with callee() to run it`);
7202
+ continue;
7203
+ }
7204
+ const workflowName = text$1(w["name"]);
7205
+ setup.push({
7206
+ kind: "workflow",
7207
+ binding: `${prefix}${binding}`,
7208
+ className,
7209
+ ...workflowName ? { name: workflowName } : {}
7210
+ });
7211
+ }
7212
+ for (const [key, what] of Object.entries(unmodelled)) {
7213
+ const v = cfg[key];
7214
+ const bindings = Array.isArray(v) ? list(v).map((b) => text$1(b["binding"]) || text$1(b["name"])) : v !== void 0 ? [text$1(record(v)["binding"]) || key] : [];
7215
+ for (const b of bindings) notes.push(`not modelled: ${what} ${prefix}${b}; a run that touches it is UNSUPPORTED`);
7216
+ }
7217
+ for (const q of list(record(cfg["queues"])["producers"])) notes.push(`not modelled: Queue producer ${prefix}${text$1(q["binding"])}; a run that sends to it is UNSUPPORTED`);
7218
+ };
7219
+ resourceSteps(config, configDir, name, "");
7220
+ for (const s of list(config["services"])) {
7221
+ const binding = text$1(s["binding"]);
7222
+ const service = text$1(s["service"]);
7223
+ if (!binding) continue;
7224
+ const calleeConfig = callees.get(service);
7225
+ if (calleeConfig === void 0) {
7226
+ setup.push({
7227
+ kind: "service",
7228
+ binding
7229
+ });
7230
+ notes.push(`service binding ${binding}: no wrangler config named ${service || "(none)"} under the scenario's directory, so its answers are scripted; script them with service(), or run that Worker with callee()`);
7231
+ continue;
7232
+ }
7233
+ const callee = readConfig(calleeConfig);
7234
+ const calleeDir = dirname(calleeConfig);
7235
+ const calleeMain = resolve(calleeDir, text$1(callee["main"]));
7236
+ setup.push({
7237
+ kind: "callee",
7238
+ binding,
7239
+ entry: ref(scenarioDir, calleeMain),
7240
+ config: ref(scenarioDir, calleeConfig)
7241
+ });
7242
+ resourceSteps(callee, calleeDir, service, `${service}/`);
7243
+ srcs.push(...sources(calleeMain));
7244
+ }
7245
+ const outside = [entry, ...setup.flatMap((s) => s.kind === "d1" && !s.binding.includes("/") ? [resolve(scenarioDir, s.schemaFile)] : [])].filter((f) => relative(scenarioDir, f).startsWith(".."));
7246
+ if (outside.length > 0) throw new Error(`eutaxy check finds the Worker's module and its schema files beneath the scenario's directory, and ${outside.map((f) => relative(scenarioDir, f)).join(", ")} is not; write the scenario beside the wrangler config or in a directory above the Worker`);
7247
+ const consumers = list(record(config["queues"])["consumers"]);
7248
+ const crons = Array.isArray(record(config["triggers"])["crons"]) ? record(config["triggers"])["crons"].filter((c) => typeof c === "string") : [];
7249
+ const routesAgents = callerSrcs.some((s) => /\brouteAgentRequest\s*\(/.test(s));
7250
+ const firstObject = setup.find((s) => s.kind === "durable_object" && !s.binding.includes("/"));
7251
+ let drive;
7252
+ if (consumers.length > 0) {
7253
+ drive = {
7254
+ kind: "queue",
7255
+ queue: text$1(consumers[0]?.["queue"])
7256
+ };
7257
+ if (consumers.length > 1) notes.push(`the Worker consumes ${consumers.length} queues; one drive per scenario, so a scenario per queue`);
7258
+ } else if (crons.length > 0) drive = {
7259
+ kind: "cron",
7260
+ cron: crons[0]
7261
+ };
7262
+ else if (routesAgents && firstObject) drive = {
7263
+ kind: "websocket",
7264
+ agent: agentSegment(firstObject.binding)
7265
+ };
7266
+ else drive = { kind: "http" };
7267
+ if (drive.kind !== "cron" && crons.length > 0) notes.push(`the Worker also has Cron Triggers (${crons.join(", ")}); a scenario per drive`);
7268
+ const taken = /* @__PURE__ */ new Set();
7269
+ const externals = fetchedHosts(srcs).map((host) => ({
7270
+ name: externalName(host, taken),
7271
+ host
7272
+ }));
7273
+ return {
7274
+ name,
7275
+ worker: {
7276
+ entry: ref(scenarioDir, entry),
7277
+ config: ref(scenarioDir, input.config)
7278
+ },
7279
+ drive,
7280
+ setup,
7281
+ externals,
7282
+ notes
7283
+ };
7284
+ }
7285
+ const q = (s) => JSON.stringify(s);
7286
+ function stepSource(s) {
7287
+ switch (s.kind) {
7288
+ case "d1": return `d1Schema(${q(s.binding)}, ${q(s.schemaFile)}),`;
7289
+ case "durable_object": return s.sqlite ? `// SQLite-backed: seed tables with { sql: { <object name>: { schema, rows } } }.\n durableObject(${q(s.binding)}, {}),` : `durableObject(${q(s.binding)}, {}),`;
7290
+ case "r2": return `r2Bucket(${q(s.binding)}),`;
7291
+ case "workflow": return s.name === void 0 ? `workflow(${q(s.binding)}, ${q(s.className)}),` : `workflow(${q(s.binding)}, ${q(s.className)}, { name: ${q(s.name)} }),`;
7292
+ case "callee": return `callee(${q(s.binding)}, { entry: ${q(s.entry)}, config: ${q(s.config)} }),`;
7293
+ case "service": return `// TODO: the answers of the Worker behind ${s.binding}, e.g. { methods: { <method>: { value: … } } }.\n service(${q(s.binding)}),`;
7294
+ }
7295
+ }
7296
+ function driveSource(d) {
7297
+ switch (d.kind) {
7298
+ case "queue": return {
7299
+ helper: "queue",
7300
+ source: `// TODO: the messages to deliver.\n drive: queue(${q(d.queue)}, [{ body: {} }]),`
7301
+ };
7302
+ case "cron": return {
7303
+ helper: "cron",
7304
+ source: `// TODO: how many ticks, and how many times a failed tick is re-run.\n drive: cron(${q(d.cron)}, { ticks: 2 }),`
7305
+ };
7306
+ case "websocket": return {
7307
+ helper: "websocket",
7308
+ source: `// TODO: the connections, the Agent instance they reach and the messages each sends.\n drive: websocket([\n { id: "a", path: ${q(`/agents/${d.agent}/<name>`)}, messages: [{ data: {} }] },\n ]),`
7309
+ };
7310
+ case "http": return {
7311
+ helper: "http",
7312
+ source: `// TODO: the requests, and how the caller resends one that got no 2xx.\n drive: http([{ path: "/", body: {} }], { retries: 3 }),`
7313
+ };
7314
+ }
7315
+ }
7316
+ /** Example invariants for the draft's bindings, as comments: the hole the author fills. */
7317
+ function invariantHints(d) {
7318
+ const hints = [];
7319
+ const d1 = d.setup.find((s) => s.kind === "d1");
7320
+ if (d1) hints.push(`unique("one-row-per-key", d1Rows(${q(d1.binding)}, "<table>"), "<column>"),`);
7321
+ const sqliteObject = d.setup.find((s) => s.kind === "durable_object" && s.sqlite);
7322
+ if (sqliteObject) hints.push(`everyRow("<rule>", durableObjectTable(${q(sqliteObject.binding)}, "<object name>", "<table>"), [{ column: "<column>", op: "gte", value: 0 }]),`);
7323
+ const external = d.externals[0];
7324
+ if (external) hints.push(`atMostOncePerKey("<call>-once", fetchCall(${q(external.name)}, "POST"), "args.body.<id>"),`);
7325
+ if (hints.length === 0) hints.push(`atMostOncePerKey("<effect>-once", httpResponse("/", { ok: true }), "args.requestId"),`);
7326
+ return hints;
7327
+ }
7328
+ /** The scenario's source. With no invariant it does not check until the holes are filled. */
7329
+ function renderDraft(d) {
7330
+ const drive = driveSource(d.drive);
7331
+ const helpers = /* @__PURE__ */ new Set(["defineScenario", drive.helper]);
7332
+ const stepHelper = {
7333
+ d1: "d1Schema",
7334
+ durable_object: "durableObject",
7335
+ r2: "r2Bucket",
7336
+ workflow: "workflow",
7337
+ callee: "callee",
7338
+ service: "service"
7339
+ };
7340
+ for (const s of d.setup) helpers.add(stepHelper[s.kind]);
7341
+ if (d.externals.length > 0) helpers.add("external");
7342
+ const imports = [...helpers].sort((a, b) => a.localeCompare(b));
7343
+ const lines = [];
7344
+ lines.push(`import { ${imports.join(", ")} } from "eutaxy/cloudflare";`, "");
7345
+ lines.push(`// Drafted by eutaxy draft from ${d.worker.config}. Fill in each TODO, then run`, `// eutaxy check on this file; it does not check until it has an invariant.`);
7346
+ for (const n of d.notes) lines.push(`// Note: ${n}.`);
7347
+ lines.push(`export default defineScenario({`);
7348
+ lines.push(` name: ${q(d.name)},`);
7349
+ lines.push(` worker: { entry: ${q(d.worker.entry)}, config: ${q(d.worker.config)} },`);
7350
+ if (d.setup.length > 0) {
7351
+ lines.push(` setup: [`);
7352
+ for (const s of d.setup) lines.push(` ${stepSource(s)}`);
7353
+ lines.push(` ],`);
7354
+ }
7355
+ lines.push(` ${drive.source}`);
7356
+ if (d.externals.length > 0) {
7357
+ lines.push(` // Each host the Worker fetches answers 200 with an empty body until you script its responses.`);
7358
+ lines.push(` externals: [`);
7359
+ for (const e of d.externals) lines.push(` external(${q(e.name)}, ${q(e.host)}),`);
7360
+ lines.push(` ],`);
7361
+ }
7362
+ lines.push(` invariants: [`);
7363
+ lines.push(` // TODO: what must hold after every run, for example (import what you use from eutaxy/cloudflare):`);
7364
+ for (const h of invariantHints(d)) lines.push(` // ${h}`);
7365
+ lines.push(` ],`);
7366
+ lines.push(` bounds: { maxFaultsPerRun: 1, maxRedeliveries: 2, maxConcurrentInvocations: 1, budgetMs: 2000 },`);
7367
+ lines.push(`});`, "");
7368
+ return lines.join("\n");
7369
+ }
7370
+ /** Exit 0 with the draft printed or written, 3 on an error. */
7371
+ function runDraft(o) {
7372
+ const config = o.config !== void 0 ? resolve(o.cwd, o.config) : ["wrangler.jsonc", "wrangler.json"].map((f) => join(o.cwd, f)).find((p) => existsSync(p));
7373
+ if (config === void 0 || !existsSync(config)) {
7374
+ o.stderr(config === void 0 ? "no wrangler.jsonc or wrangler.json in the working directory; name the config\n" : `wrangler config not found: ${config}\n`);
7375
+ return 3;
7376
+ }
7377
+ const out = o.out === void 0 ? void 0 : resolve(o.cwd, o.out);
7378
+ if (out !== void 0 && existsSync(out)) {
7379
+ o.stderr(`${out} exists; eutaxy draft does not overwrite a file\n`);
7380
+ return 3;
7381
+ }
7382
+ if (out !== void 0 && !existsSync(dirname(out))) {
7383
+ o.stderr(`the directory of ${out} does not exist\n`);
7384
+ return 3;
7385
+ }
7386
+ let draft;
7387
+ try {
7388
+ draft = draftScenario({
7389
+ config,
7390
+ ...o.worker === void 0 ? {} : { entry: resolve(o.cwd, o.worker) },
7391
+ ...out === void 0 ? {} : { scenarioDir: dirname(out) }
7392
+ });
7393
+ } catch (err) {
7394
+ o.stderr(`${err instanceof Error ? err.message : String(err)}\n`);
7395
+ return 3;
7396
+ }
7397
+ const source = renderDraft(draft);
7398
+ if (out !== void 0) writeFileSync(out, source);
7399
+ if (o.json) o.stdout(`${JSON.stringify({
7400
+ schemaVersion: 1,
7401
+ draft,
7402
+ source,
7403
+ ...out === void 0 ? {} : { written: out }
7404
+ }, null, 2)}\n`);
7405
+ else if (out === void 0) o.stdout(source);
7406
+ else {
7407
+ o.stdout(`Scenario drafted in ${relative(o.cwd, out) || out}\n`);
7408
+ for (const n of draft.notes) o.stdout(` note: ${n}\n`);
7409
+ }
7410
+ return 0;
7411
+ }
6330
7412
  // packages/cli/src/archive.ts
6331
7413
  /**
6332
7414
  * Reading the two archive formats the prover releases come in, with Node's
@@ -6864,25 +7946,6 @@ function unknownAll(m, cause, reason) {
6864
7946
  assumptions: []
6865
7947
  })));
6866
7948
  }
6867
- /**
6868
- * Inside the module's process: a relative import from a `.ts` file that Node cannot
6869
- * resolve is tried as TypeScript resolves it, so `./domain.js` and
6870
- * `./domain` find `domain.ts` (or `domain/index.ts`), as `tsc` would.
6871
- */
6872
- function resolveAsTypeScript() {
6873
- registerHooks({ resolve(specifier, context, nextResolve) {
6874
- try {
6875
- return nextResolve(specifier, context);
6876
- } catch (err) {
6877
- if (!(specifier.startsWith("./") || specifier.startsWith("../")) || !context.parentURL?.endsWith(".ts")) throw err;
6878
- const stem = specifier.endsWith(".js") ? specifier.slice(0, -3) : specifier;
6879
- for (const candidate of [`${stem}.ts`, `${stem}/index.ts`]) try {
6880
- return nextResolve(candidate, context);
6881
- } catch {}
6882
- throw err;
6883
- }
6884
- } });
6885
- }
6886
7949
  /** Inside the module's process: load the module and its spec file, run the `TESTED` rung. */
6887
7950
  async function testHere(m, seed) {
6888
7951
  resolveAsTypeScript();
@@ -7052,7 +8115,7 @@ async function runReport(o) {
7052
8115
  }
7053
8116
  // packages/cli/src/version.ts
7054
8117
  /** The published package's version, as the MCP server reports it; the release tooling keeps it in step. */
7055
- const eutaxyVersion = "0.13.0";
8118
+ const eutaxyVersion = "0.15.0";
7056
8119
  // packages/cli/src/mcp.ts
7057
8120
  /**
7058
8121
  * `eutaxy mcp`: a Model Context Protocol server over stdio, so a coding
@@ -7196,7 +8259,7 @@ const tools = [
7196
8259
  },
7197
8260
  wrangler: {
7198
8261
  type: "string",
7199
- description: "Wrangler config path; default: the one beside the scenario"
8262
+ description: "Wrangler config path; default: the one the scenario names, else the one beside it"
7200
8263
  },
7201
8264
  seed: {
7202
8265
  type: "string",
@@ -7375,6 +8438,56 @@ const tools = [
7375
8438
  });
7376
8439
  }
7377
8440
  },
8441
+ {
8442
+ name: "draft",
8443
+ title: "Draft a scenario",
8444
+ description: "Draft a scenario (*.sim.ts) from a wrangler config (JSON or JSONC) and the Worker module it names: the bindings become setup steps (a service binding whose Worker's config is found under the directory becomes a callee), the Worker's handlers the drive, the hosts its code fetches the externals; the invariants and the drive's events are holes marked TODO for you to fill before calling check. Returns the source, the draft as data and its notes (bindings not modelled, guesses made); with out, also writes the file, never over an existing one. Nothing is imported or run.",
8445
+ inputSchema: {
8446
+ type: "object",
8447
+ properties: {
8448
+ config: {
8449
+ type: "string",
8450
+ description: "Wrangler config path, relative to the working directory; default: wrangler.jsonc or wrangler.json there"
8451
+ },
8452
+ worker: {
8453
+ type: "string",
8454
+ description: "The Worker module; default: the config's main"
8455
+ },
8456
+ out: {
8457
+ type: "string",
8458
+ description: "Where to write the scenario; paths in it are relative to its directory. Default: not written"
8459
+ }
8460
+ },
8461
+ additionalProperties: false
8462
+ },
8463
+ async run(args, ctx) {
8464
+ only(args, [
8465
+ "config",
8466
+ "worker",
8467
+ "out"
8468
+ ]);
8469
+ const config = str(args, "config");
8470
+ const worker = str(args, "worker");
8471
+ const out = str(args, "out");
8472
+ let stdout = "";
8473
+ let stderr = "";
8474
+ const code = runDraft({
8475
+ cwd: ctx.cwd,
8476
+ ...config === void 0 ? {} : { config },
8477
+ ...worker === void 0 ? {} : { worker },
8478
+ ...out === void 0 ? {} : { out },
8479
+ json: true,
8480
+ stdout: (t) => {
8481
+ stdout += t;
8482
+ },
8483
+ stderr: (t) => {
8484
+ stderr += t;
8485
+ }
8486
+ });
8487
+ if (code !== 0) throw new ToolError(stderr.trim() || `draft exited ${code}`);
8488
+ return asResult(JSON.parse(stdout));
8489
+ }
8490
+ },
7378
8491
  {
7379
8492
  name: "prover_status",
7380
8493
  title: "Which proof engines are installed",
@@ -7529,12 +8642,14 @@ const usage = `eutaxy — deterministic simulation checks and spec verdicts for
7529
8642
 
7530
8643
  Usage:
7531
8644
  eutaxy check <scenario.sim.ts> [options]
8645
+ eutaxy draft [wrangler config] [--worker <module>] [--out <file>] [--json]
7532
8646
  eutaxy report [dir] [--prover <names>] [--seed <seed>] [--json]
7533
8647
  eutaxy prover install <lean|smt> [--from <url or directory>] [--json]
7534
8648
  eutaxy mcp
7535
8649
 
7536
8650
  check options:
7537
- --wrangler <path> wrangler config (default: wrangler.jsonc/json/toml beside the scenario)
8651
+ --wrangler <path> wrangler config (default: the one the scenario names, else
8652
+ wrangler.jsonc/json/toml beside the scenario)
7538
8653
  --seed <seed> exploration seed (default: the scenario file name)
7539
8654
  --max-runs <n> cap on exploration runs in addition to the scenario's time budget
7540
8655
  --budget-ms <n> replace the scenario's time budget (with --max-runs, the run cap decides)
@@ -7547,6 +8662,14 @@ check options:
7547
8662
  --expect-violation write a regression test that asserts the violation (for corpora)
7548
8663
  --keep keep the generated .eutaxy/ files
7549
8664
 
8665
+ draft writes a scenario skeleton from a wrangler config (JSON or JSONC; default:
8666
+ wrangler.jsonc or wrangler.json in the current directory) and the Worker module it names
8667
+ (--worker to name another): the bindings become setup steps (a service binding whose
8668
+ Worker's config is found under the directory becomes a callee), the handlers the drive,
8669
+ the hosts the code fetches the externals; the invariants and the events are left as holes
8670
+ marked TODO. It prints the scenario, or writes it to --out (never over an existing file);
8671
+ nothing is imported or run.
8672
+
7550
8673
  report runs every spec file (*.props.ts) under dir (default: the current directory)
7551
8674
  through the TESTED rung, on inputs drawn from the parameter types with the seed
7552
8675
  (default: report), and the PROVEN rung with --prover. No scenario runs, so nothing
@@ -7563,7 +8686,8 @@ report options: --goals writes each module's open Lean goals beside its spec fil
7563
8686
 
7564
8687
  mcp serves the Model Context Protocol over stdio (one JSON-RPC message per line, logs on
7565
8688
  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".
8689
+ returning the JSON report, and draft, returning the drafted scenario. Point the agent's
8690
+ MCP configuration at "eutaxy mcp".
7567
8691
 
7568
8692
  Exit codes: 0 BOUNDED, 1 VIOLATED or a REFUTED or CONFLICT spec, 2 UNSUPPORTED, 3 error.
7569
8693
  report: 0, or 1 for a REFUTED or CONFLICT spec, 3 error. prover install: 0, or 3.
@@ -7590,7 +8714,8 @@ async function main(argv, io) {
7590
8714
  "budget-ms",
7591
8715
  "prover",
7592
8716
  "out",
7593
- "from"
8717
+ "from",
8718
+ "worker"
7594
8719
  ]) if (flags[k] === true) {
7595
8720
  io.stderr(`--${k} needs a value\n`);
7596
8721
  return exitCodes.error;
@@ -7658,6 +8783,33 @@ async function main(argv, io) {
7658
8783
  stderr: io.stderr
7659
8784
  });
7660
8785
  }
8786
+ if (command === "draft") {
8787
+ if (positionals.length > 2) {
8788
+ io.stderr(`draft takes one wrangler config\n\n${usage}`);
8789
+ return exitCodes.error;
8790
+ }
8791
+ const other = Object.keys(flags).find((k) => ![
8792
+ "worker",
8793
+ "out",
8794
+ "json"
8795
+ ].includes(k));
8796
+ if (other !== void 0) {
8797
+ io.stderr(`draft does not take --${other}\n`);
8798
+ return exitCodes.error;
8799
+ }
8800
+ const config = positionals[1];
8801
+ const worker = str("worker");
8802
+ const out = str("out");
8803
+ return runDraft({
8804
+ cwd: io.cwd,
8805
+ ...config === void 0 ? {} : { config },
8806
+ ...worker === void 0 ? {} : { worker },
8807
+ ...out === void 0 ? {} : { out },
8808
+ json: flags["json"] === true,
8809
+ stdout: io.stdout,
8810
+ stderr: io.stderr
8811
+ });
8812
+ }
7661
8813
  if (command !== "check") {
7662
8814
  io.stderr(`unknown command ${command}\n\n${usage}`);
7663
8815
  return exitCodes.error;
@@ -7699,4 +8851,4 @@ async function main(argv, io) {
7699
8851
  }
7700
8852
  export { main as t };
7701
8853
 
7702
- //# sourceMappingURL=cli-D3SPblWw.mjs.map
8854
+ //# sourceMappingURL=cli-CzGCMudc.mjs.map