eutaxy 0.14.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-BppjMaqL.mjs → cli-CzGCMudc.mjs} +637 -55
  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 +79 -8
  12. package/dist/cloudflare.d.mts.map +1 -1
  13. package/dist/cloudflare.mjs +2 -2
  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-_T9ZMwOJ.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-ClXnIi6O.mjs → src-nwQA9Xwr.mjs} +9 -3
  34. package/dist/src-nwQA9Xwr.mjs.map +1 -0
  35. package/dist/{src-DPCF2XGv.mjs → src-ud5wEfnx.mjs} +9 -1
  36. package/dist/src-ud5wEfnx.mjs.map +1 -0
  37. package/dist/{workerd-DVJ8eCLI.mjs → workerd-Be43_PZo.mjs} +160 -39
  38. package/dist/workerd-Be43_PZo.mjs.map +1 -0
  39. package/package.json +1 -1
  40. package/dist/cli-BppjMaqL.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-DZOBkCMR.d.mts +0 -5
  44. package/dist/delivery-invariants-DZOBkCMR.d.mts.map +0 -1
  45. package/dist/delivery-invariants-_T9ZMwOJ.mjs.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-ClXnIi6O.mjs.map +0 -1
  49. package/dist/src-DPCF2XGv.mjs.map +0 -1
  50. package/dist/workerd-DVJ8eCLI.mjs.map +0 -1
@@ -1,8 +1,8 @@
1
- import { L as canonicalJson } from "./src-DPCF2XGv.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-ClXnIi6O.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 { G as cloudflareRegressionTest, n as globKey, r as specKey } from "./workerd-DVJ8eCLI.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";
@@ -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
  }
@@ -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
@@ -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
@@ -6174,7 +6177,7 @@ function readWranglerConfig(path) {
6174
6177
  if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new Error(`${basename(path)}: not a wrangler config object`);
6175
6178
  return parsed;
6176
6179
  }
6177
- const list = (v) => Array.isArray(v) ? v.filter((x) => typeof x === "object" && x) : [];
6180
+ const list$1 = (v) => Array.isArray(v) ? v.filter((x) => typeof x === "object" && x) : [];
6178
6181
  const str$1 = (v, fallback = "") => typeof v === "string" ? v : fallback;
6179
6182
  /** The keys of a wrangler config whose bindings the command carries into the isolate. */
6180
6183
  const carried = /* @__PURE__ */ new Set([
@@ -6214,9 +6217,9 @@ function readCalleeConfig(step, scenarioDir) {
6214
6217
  const notAdded = [];
6215
6218
  const sqlite = /* @__PURE__ */ new Set();
6216
6219
  const strings = (v) => Array.isArray(v) ? v.filter((x) => typeof x === "string") : [];
6217
- for (const m of list(config["migrations"])) {
6220
+ for (const m of list$1(config["migrations"])) {
6218
6221
  for (const c of strings(m["new_sqlite_classes"])) sqlite.add(c);
6219
- for (const r of list(m["renamed_classes"])) {
6222
+ for (const r of list$1(m["renamed_classes"])) {
6220
6223
  const from = str$1(r["from"]);
6221
6224
  if (sqlite.delete(from)) sqlite.add(str$1(r["to"]));
6222
6225
  }
@@ -6224,7 +6227,7 @@ function readCalleeConfig(step, scenarioDir) {
6224
6227
  }
6225
6228
  const durableObjects = [];
6226
6229
  const dos = config["durable_objects"];
6227
- for (const b of list(dos?.bindings)) {
6230
+ for (const b of list$1(dos?.bindings)) {
6228
6231
  const className = str$1(b["class_name"]);
6229
6232
  const scriptName = b["script_name"] === void 0 ? void 0 : str$1(b["script_name"]);
6230
6233
  durableObjects.push({
@@ -6243,26 +6246,26 @@ function readCalleeConfig(step, scenarioDir) {
6243
6246
  binding: step.binding,
6244
6247
  name,
6245
6248
  entry: resolve(scenarioDir, step.entry),
6246
- d1: list(config["d1_databases"]).map((d) => ({
6249
+ d1: list$1(config["d1_databases"]).map((d) => ({
6247
6250
  binding: str$1(d["binding"]),
6248
6251
  id: str$1(d["database_id"], str$1(d["database_name"], str$1(d["binding"])))
6249
6252
  })),
6250
- r2: list(config["r2_buckets"]).map((b) => ({
6253
+ r2: list$1(config["r2_buckets"]).map((b) => ({
6251
6254
  binding: str$1(b["binding"]),
6252
6255
  bucket: str$1(b["bucket_name"], str$1(b["binding"]))
6253
6256
  })),
6254
- kv: list(config["kv_namespaces"]).map((k) => ({
6257
+ kv: list$1(config["kv_namespaces"]).map((k) => ({
6255
6258
  binding: str$1(k["binding"]),
6256
6259
  id: str$1(k["id"], str$1(k["binding"]))
6257
6260
  })),
6258
6261
  durableObjects,
6259
- workflows: list(config["workflows"]).map((w) => ({
6262
+ workflows: list$1(config["workflows"]).map((w) => ({
6260
6263
  binding: str$1(w["binding"]),
6261
6264
  className: str$1(w["class_name"]),
6262
6265
  name: str$1(w["name"], str$1(w["binding"]))
6263
6266
  })),
6264
- services: list(config["services"]).map((s) => str$1(s["binding"])),
6265
- queues: list(queues?.producers).map((p) => ({
6267
+ services: list$1(config["services"]).map((s) => str$1(s["binding"])),
6268
+ queues: list$1(queues?.producers).map((p) => ({
6266
6269
  binding: str$1(p["binding"]),
6267
6270
  queue: str$1(p["queue"])
6268
6271
  })),
@@ -6336,7 +6339,7 @@ const neverCalled = "neverCalled";
6336
6339
  * anyway (the scenario names a callee for it or scripts it); its value is a
6337
6340
  * Fetcher all the same, which is what the platform recognises.
6338
6341
  */
6339
- function miniflareOptionsSource(callees, isolate = noIsolate) {
6342
+ function miniflareOptionsSource(callees, isolate = noIsolate, callerServices = []) {
6340
6343
  const d1 = {};
6341
6344
  const r2 = {};
6342
6345
  const kv = {};
@@ -6347,6 +6350,7 @@ function miniflareOptionsSource(callees, isolate = noIsolate) {
6347
6350
  const vars = {};
6348
6351
  const aliased = (name) => name in isolate.aliases;
6349
6352
  Object.assign(dos, isolate.redirected);
6353
+ for (const b of callerServices) services[b] = neverCalled;
6350
6354
  for (const c of callees) {
6351
6355
  for (const d of c.d1) if (!aliased(qualified(c.name, d.binding))) d1[qualified(c.name, d.binding)] = d.id;
6352
6356
  for (const b of c.r2) if (!aliased(qualified(c.name, b.binding))) r2[qualified(c.name, b.binding)] = b.bucket;
@@ -6391,24 +6395,24 @@ function readCallerResources(wranglerPath) {
6391
6395
  const dos = config["durable_objects"];
6392
6396
  return {
6393
6397
  name: str$1(config["name"]) || void 0,
6394
- d1: list(config["d1_databases"]).map((d) => ({
6398
+ d1: list$1(config["d1_databases"]).map((d) => ({
6395
6399
  binding: str$1(d["binding"]),
6396
6400
  id: str$1(d["database_id"], str$1(d["database_name"], str$1(d["binding"])))
6397
6401
  })),
6398
- r2: list(config["r2_buckets"]).map((b) => ({
6402
+ r2: list$1(config["r2_buckets"]).map((b) => ({
6399
6403
  binding: str$1(b["binding"]),
6400
6404
  bucket: str$1(b["bucket_name"], str$1(b["binding"]))
6401
6405
  })),
6402
- kv: list(config["kv_namespaces"]).map((k) => ({
6406
+ kv: list$1(config["kv_namespaces"]).map((k) => ({
6403
6407
  binding: str$1(k["binding"]),
6404
6408
  id: str$1(k["id"], str$1(k["binding"]))
6405
6409
  })),
6406
- durableObjects: list(dos?.bindings).map((b) => ({
6410
+ durableObjects: list$1(dos?.bindings).map((b) => ({
6407
6411
  binding: str$1(b["name"]),
6408
6412
  className: str$1(b["class_name"]),
6409
6413
  ...b["script_name"] === void 0 ? {} : { scriptName: str$1(b["script_name"]) }
6410
6414
  })),
6411
- services: list(config["services"]).map((b) => ({
6415
+ services: list$1(config["services"]).map((b) => ({
6412
6416
  binding: str$1(b["binding"]),
6413
6417
  ...typeof b["entrypoint"] === "string" ? { entrypoint: b["entrypoint"] } : {},
6414
6418
  ...typeof b["props"] === "object" && b["props"] !== null ? { props: b["props"] } : {}
@@ -6540,12 +6544,12 @@ test("eutaxy check", async ({ task }) => {
6540
6544
  `;
6541
6545
  }
6542
6546
  function vitestConfigSource(wranglerConfigPath, testPath, outputFile, isolate) {
6543
- const plugin = isolate === void 0 ? `cloudflareTest({ wrangler: { configPath: ${JSON.stringify(wranglerConfigPath)} } })` : `cloudflareTest({ main: ${JSON.stringify(isolate.main)}, wrangler: { configPath: ${JSON.stringify(wranglerConfigPath)} }, miniflare: ${isolate.miniflare} })`;
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}`} })`;
6544
6548
  return `// Generated by eutaxy check; deleted after the run.
6545
6549
  import { cloudflareTest } from "@cloudflare/vitest-plugin";
6546
6550
  import { defineConfig } from "vitest/config";
6547
6551
 
6548
- ${isolate === 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({
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({
6549
6553
  plugins: [${plugin}],
6550
6554
  test: {
6551
6555
  include: [${JSON.stringify(testPath)}],
@@ -6763,11 +6767,6 @@ async function runCheck(o) {
6763
6767
  }
6764
6768
  const dir = dirname(scenarioPath);
6765
6769
  const name = basename(scenarioPath).replace(/\.sim\.ts$/, "").replace(/\.ts$/, "");
6766
- const wrangler = findWrangler(dir, o.wrangler, o.cwd);
6767
- if (!wrangler || !existsSync(wrangler)) {
6768
- o.stderr(`no wrangler config found next to the scenario; pass --wrangler <path>\n`);
6769
- return exitCodes.error;
6770
- }
6771
6770
  const stamp = `${process.pid}-${randomBytes(3).toString("hex")}`;
6772
6771
  const workDir = join(dir, ".eutaxy");
6773
6772
  const testPath = join(workDir, `${name}.${stamp}.check.test.ts`);
@@ -6775,18 +6774,31 @@ async function runCheck(o) {
6775
6774
  const mainPath = join(workDir, `main.${stamp}.ts`);
6776
6775
  let callees = [];
6777
6776
  let loaded;
6778
- if (mentionsCallee(readFileSync(scenarioPath, "utf8"))) {
6779
- try {
6780
- loaded = await loadScenario(scenarioPath);
6781
- callees = calleeSteps(loaded.setup).map((step) => readCalleeConfig(step, dir));
6782
- } catch (err) {
6777
+ try {
6778
+ loaded = await loadScenario(scenarioPath);
6779
+ } catch (err) {
6780
+ if (mentionsCallee(readFileSync(scenarioPath, "utf8"))) {
6783
6781
  o.stderr(`could not read the scenario's callees: ${String(err)}\n`);
6784
6782
  return exitCodes.error;
6785
6783
  }
6786
- 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`);
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`);
6787
6785
  }
6788
- const callerResources = callees.length > 0 ? readCallerResources(wrangler) : void 0;
6789
- const isolate = isolateOf(callees, callerResources);
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);
6790
6802
  for (const reason of isolate.notAdded) o.stderr(`not added to the test's isolate: ${reason}\n`);
6791
6803
  mkdirSync(workDir, { recursive: true });
6792
6804
  try {
@@ -6827,9 +6839,12 @@ async function runCheck(o) {
6827
6839
  writeFileSync(mainPath, mainModuleSource(workDir, callerEntry, callees, isolate));
6828
6840
  writeFileSync(configPath, vitestConfigSource(wrangler, testPath, reportPath, {
6829
6841
  main: mainPath,
6830
- miniflare: miniflareOptionsSource(callees, isolate)
6842
+ miniflare: miniflareOptionsSource(callees, isolate, callerServices)
6831
6843
  }));
6832
- } else writeFileSync(configPath, vitestConfigSource(wrangler, testPath, reportPath));
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));
6833
6848
  const { code, output } = await runVitest(vitestBin(dir), configPath, dir);
6834
6849
  const transport = code === 0 ? readTransport(reportPath) : null;
6835
6850
  if (!transport) {
@@ -6863,7 +6878,11 @@ async function runCheck(o) {
6863
6878
  const outPath = regressionPath;
6864
6879
  const outDir = dirname(outPath);
6865
6880
  const schemaPaths = {};
6866
- 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
+ }
6867
6886
  const calleePaths = {};
6868
6887
  for (const step of transport.setup) {
6869
6888
  if (step.kind !== "callee") continue;
@@ -6916,6 +6935,480 @@ function cleanUp(workDir, stamp) {
6916
6935
  force: true
6917
6936
  });
6918
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
+ }
6919
7412
  // packages/cli/src/archive.ts
6920
7413
  /**
6921
7414
  * Reading the two archive formats the prover releases come in, with Node's
@@ -7622,7 +8115,7 @@ async function runReport(o) {
7622
8115
  }
7623
8116
  // packages/cli/src/version.ts
7624
8117
  /** The published package's version, as the MCP server reports it; the release tooling keeps it in step. */
7625
- const eutaxyVersion = "0.14.0";
8118
+ const eutaxyVersion = "0.15.0";
7626
8119
  // packages/cli/src/mcp.ts
7627
8120
  /**
7628
8121
  * `eutaxy mcp`: a Model Context Protocol server over stdio, so a coding
@@ -7766,7 +8259,7 @@ const tools = [
7766
8259
  },
7767
8260
  wrangler: {
7768
8261
  type: "string",
7769
- 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"
7770
8263
  },
7771
8264
  seed: {
7772
8265
  type: "string",
@@ -7945,6 +8438,56 @@ const tools = [
7945
8438
  });
7946
8439
  }
7947
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
+ },
7948
8491
  {
7949
8492
  name: "prover_status",
7950
8493
  title: "Which proof engines are installed",
@@ -8099,12 +8642,14 @@ const usage = `eutaxy — deterministic simulation checks and spec verdicts for
8099
8642
 
8100
8643
  Usage:
8101
8644
  eutaxy check <scenario.sim.ts> [options]
8645
+ eutaxy draft [wrangler config] [--worker <module>] [--out <file>] [--json]
8102
8646
  eutaxy report [dir] [--prover <names>] [--seed <seed>] [--json]
8103
8647
  eutaxy prover install <lean|smt> [--from <url or directory>] [--json]
8104
8648
  eutaxy mcp
8105
8649
 
8106
8650
  check options:
8107
- --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)
8108
8653
  --seed <seed> exploration seed (default: the scenario file name)
8109
8654
  --max-runs <n> cap on exploration runs in addition to the scenario's time budget
8110
8655
  --budget-ms <n> replace the scenario's time budget (with --max-runs, the run cap decides)
@@ -8117,6 +8662,14 @@ check options:
8117
8662
  --expect-violation write a regression test that asserts the violation (for corpora)
8118
8663
  --keep keep the generated .eutaxy/ files
8119
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
+
8120
8673
  report runs every spec file (*.props.ts) under dir (default: the current directory)
8121
8674
  through the TESTED rung, on inputs drawn from the parameter types with the seed
8122
8675
  (default: report), and the PROVEN rung with --prover. No scenario runs, so nothing
@@ -8133,7 +8686,8 @@ report options: --goals writes each module's open Lean goals beside its spec fil
8133
8686
 
8134
8687
  mcp serves the Model Context Protocol over stdio (one JSON-RPC message per line, logs on
8135
8688
  stderr) for a coding agent: tools check, report, goals, prove and prover_status, each
8136
- 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".
8137
8691
 
8138
8692
  Exit codes: 0 BOUNDED, 1 VIOLATED or a REFUTED or CONFLICT spec, 2 UNSUPPORTED, 3 error.
8139
8693
  report: 0, or 1 for a REFUTED or CONFLICT spec, 3 error. prover install: 0, or 3.
@@ -8160,7 +8714,8 @@ async function main(argv, io) {
8160
8714
  "budget-ms",
8161
8715
  "prover",
8162
8716
  "out",
8163
- "from"
8717
+ "from",
8718
+ "worker"
8164
8719
  ]) if (flags[k] === true) {
8165
8720
  io.stderr(`--${k} needs a value\n`);
8166
8721
  return exitCodes.error;
@@ -8228,6 +8783,33 @@ async function main(argv, io) {
8228
8783
  stderr: io.stderr
8229
8784
  });
8230
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
+ }
8231
8813
  if (command !== "check") {
8232
8814
  io.stderr(`unknown command ${command}\n\n${usage}`);
8233
8815
  return exitCodes.error;
@@ -8269,4 +8851,4 @@ async function main(argv, io) {
8269
8851
  }
8270
8852
  export { main as t };
8271
8853
 
8272
- //# sourceMappingURL=cli-BppjMaqL.mjs.map
8854
+ //# sourceMappingURL=cli-CzGCMudc.mjs.map