eutaxy 0.17.2 → 0.19.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 (74) hide show
  1. package/README.md +15 -12
  2. package/dist/aws.d.mts +2 -2
  3. package/dist/aws.mjs +3 -2
  4. package/dist/aws.mjs.map +1 -1
  5. package/dist/bin.mjs +1 -1
  6. package/dist/check-zkHLdWyf.mjs +1281 -0
  7. package/dist/check-zkHLdWyf.mjs.map +1 -0
  8. package/dist/cli-CNAKqV9R.mjs +297 -0
  9. package/dist/cli-CNAKqV9R.mjs.map +1 -0
  10. package/dist/cli.d.mts.map +1 -1
  11. package/dist/cli.mjs +1 -1
  12. package/dist/cloudflare.d.mts +56 -5
  13. package/dist/cloudflare.d.mts.map +1 -1
  14. package/dist/cloudflare.mjs +6417 -3
  15. package/dist/cloudflare.mjs.map +1 -0
  16. package/dist/{delivery-invariants-DO3j1mmD.mjs → delivery-invariants-BJDck0K8.mjs} +2 -2
  17. package/dist/{delivery-invariants-DO3j1mmD.mjs.map → delivery-invariants-BJDck0K8.mjs.map} +1 -1
  18. package/dist/{delivery-invariants-D7DI7i8x.d.mts → delivery-invariants-C3GXJIbg.d.mts} +2 -2
  19. package/dist/{delivery-invariants-D7DI7i8x.d.mts.map → delivery-invariants-C3GXJIbg.d.mts.map} +1 -1
  20. package/dist/draft-DEUDffHa.mjs +467 -0
  21. package/dist/draft-DEUDffHa.mjs.map +1 -0
  22. package/dist/{src-fxWc6oGc.mjs → generate-TBJM3-2P.mjs} +3 -574
  23. package/dist/generate-TBJM3-2P.mjs.map +1 -0
  24. package/dist/index.d.mts +45 -37
  25. package/dist/index.d.mts.map +1 -1
  26. package/dist/index.mjs +7 -4
  27. package/dist/index.mjs.map +1 -1
  28. package/dist/install-DkzpGA5D.mjs +611 -0
  29. package/dist/install-DkzpGA5D.mjs.map +1 -0
  30. package/dist/{explore-CkKiOuz6.d.mts → ir-KpC2epGn.d.mts} +88 -53
  31. package/dist/ir-KpC2epGn.d.mts.map +1 -0
  32. package/dist/keys-xtanNmuR.mjs +111 -0
  33. package/dist/keys-xtanNmuR.mjs.map +1 -0
  34. package/dist/mcp-B64Ko6y7.mjs +539 -0
  35. package/dist/mcp-B64Ko6y7.mjs.map +1 -0
  36. package/dist/{platform-D4hlJjm3.d.mts → platform-Cs9V9t2k.d.mts} +92 -11
  37. package/dist/platform-Cs9V9t2k.d.mts.map +1 -0
  38. package/dist/pool-CXN4CwGY.mjs +61 -0
  39. package/dist/pool-CXN4CwGY.mjs.map +1 -0
  40. package/dist/{provers-DS44OeEm.mjs → provers-D8VaY_OM.mjs} +18 -2
  41. package/dist/provers-D8VaY_OM.mjs.map +1 -0
  42. package/dist/reader-B9FSoEYW.mjs +1 -0
  43. package/dist/reader-Cz6_bLf6.mjs +3774 -0
  44. package/dist/reader-Cz6_bLf6.mjs.map +1 -0
  45. package/dist/report-_Vzavqg0.mjs +310 -0
  46. package/dist/report-_Vzavqg0.mjs.map +1 -0
  47. package/dist/src-B2DpVbMN.mjs +2 -0
  48. package/dist/src-BFGTvuA_.mjs +1235 -0
  49. package/dist/src-BFGTvuA_.mjs.map +1 -0
  50. package/dist/src-BtLZPRyG.mjs +120 -0
  51. package/dist/src-BtLZPRyG.mjs.map +1 -0
  52. package/dist/src-CB8DcvsK.mjs +1 -0
  53. package/dist/src-COuquJvI.mjs +269 -0
  54. package/dist/src-COuquJvI.mjs.map +1 -0
  55. package/dist/src-Chn-m_r1.mjs +1082 -0
  56. package/dist/src-Chn-m_r1.mjs.map +1 -0
  57. package/dist/src-DwYD3QQJ.mjs +346 -0
  58. package/dist/src-DwYD3QQJ.mjs.map +1 -0
  59. package/dist/{src-D_hHC_-3.mjs → src-Dx4QvrQb.mjs} +945 -548
  60. package/dist/src-Dx4QvrQb.mjs.map +1 -0
  61. package/dist/toolchain-DWfymxAJ.mjs +80 -0
  62. package/dist/toolchain-DWfymxAJ.mjs.map +1 -0
  63. package/dist/verdict-evEM5Gxx.mjs +12 -0
  64. package/dist/verdict-evEM5Gxx.mjs.map +1 -0
  65. package/package.json +4 -1
  66. package/dist/cli-B0Gs2mhT.mjs +0 -9445
  67. package/dist/cli-B0Gs2mhT.mjs.map +0 -1
  68. package/dist/explore-CkKiOuz6.d.mts.map +0 -1
  69. package/dist/platform-D4hlJjm3.d.mts.map +0 -1
  70. package/dist/provers-DS44OeEm.mjs.map +0 -1
  71. package/dist/src-D_hHC_-3.mjs.map +0 -1
  72. package/dist/src-fxWc6oGc.mjs.map +0 -1
  73. package/dist/workerd-DhrzU6AZ.mjs +0 -6300
  74. package/dist/workerd-DhrzU6AZ.mjs.map +0 -1
@@ -0,0 +1,1281 @@
1
+ import { o as canonicalJson } from "./src-BtLZPRyG.mjs";
2
+ import "./src-DwYD3QQJ.mjs";
3
+ import { t as aggregate } from "./provers-D8VaY_OM.mjs";
4
+ import { a as renderText, i as renderSpecs } from "./src-COuquJvI.mjs";
5
+ import { i as cloudflareUnsupportedTest, n as specKey, r as cloudflareRegressionTest, t as globKey } from "./keys-xtanNmuR.mjs";
6
+ import { createRequire, registerHooks } from "node:module";
7
+ import { randomBytes } from "node:crypto";
8
+ import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
9
+ import { basename, dirname, extname, join, relative, resolve } from "node:path";
10
+ import { fork, spawn } from "node:child_process";
11
+ import { fileURLToPath, pathToFileURL } from "node:url";
12
+ // packages/cli/src/resolve.ts
13
+ /**
14
+ * Relative imports from a `.ts` file that Node cannot resolve are tried as
15
+ * TypeScript resolves them, so `./domain.js` and `./domain` find `domain.ts`
16
+ * (or `domain/index.ts`), as `tsc` and Vite would. Used where the command
17
+ * imports a user's module in Node: `eutaxy report` for spec modules, `eutaxy
18
+ * check` for a scenario that names callees.
19
+ */
20
+ let registered = false;
21
+ /** Register the hook once per process. */
22
+ function resolveAsTypeScript() {
23
+ if (registered) return;
24
+ registered = true;
25
+ registerHooks({ resolve(specifier, context, nextResolve) {
26
+ try {
27
+ return nextResolve(specifier, context);
28
+ } catch (err) {
29
+ if (!(specifier.startsWith("./") || specifier.startsWith("../")) || !context.parentURL?.endsWith(".ts")) throw err;
30
+ const stem = specifier.endsWith(".js") ? specifier.slice(0, -3) : specifier;
31
+ for (const candidate of [`${stem}.ts`, `${stem}/index.ts`]) try {
32
+ return nextResolve(candidate, context);
33
+ } catch {}
34
+ throw err;
35
+ }
36
+ } });
37
+ }
38
+ // packages/cli/src/wrangler.ts
39
+ /**
40
+ * Wrangler config reading, one copy for `check` and `draft`: JSON and JSONC
41
+ * parsing, the bindings a config declares, and the rules that name their
42
+ * resources (a D1 database's id, an R2 bucket's name, a KV namespace's id,
43
+ * which Durable Object classes are SQLite-backed). Only JSON and JSONC are
44
+ * read; a TOML config is refused.
45
+ */
46
+ /**
47
+ * JSON with comments and trailing commas, as wrangler.jsonc allows: comments
48
+ * are removed outside strings, a comma before `}` or `]` dropped, and the
49
+ * rest is JSON.
50
+ */
51
+ function parseJsonc(text) {
52
+ let out = "";
53
+ let i = 0;
54
+ /** The index of the next character that is neither whitespace nor inside a comment, from `from`. */
55
+ const nextToken = (from) => {
56
+ let k = from;
57
+ for (;;) {
58
+ while (k < text.length && /\s/.test(text[k])) k++;
59
+ if (text[k] === "/" && text[k + 1] === "/") while (k < text.length && text[k] !== "\n") k++;
60
+ else if (text[k] === "/" && text[k + 1] === "*") {
61
+ const end = text.indexOf("*/", k + 2);
62
+ k = end < 0 ? text.length : end + 2;
63
+ } else return k;
64
+ }
65
+ };
66
+ while (i < text.length) {
67
+ const c = text[i];
68
+ if (c === "\"") {
69
+ let j = i + 1;
70
+ while (j < text.length && text[j] !== "\"") j += text[j] === "\\" ? 2 : 1;
71
+ out += text.slice(i, j + 1);
72
+ i = j + 1;
73
+ } else if (c === "/" && text[i + 1] === "/") while (i < text.length && text[i] !== "\n") i++;
74
+ else if (c === "/" && text[i + 1] === "*") {
75
+ const end = text.indexOf("*/", i + 2);
76
+ i = end < 0 ? text.length : end + 2;
77
+ } else if (c === ",") {
78
+ const next = text[nextToken(i + 1)];
79
+ if (next !== "}" && next !== "]") out += c;
80
+ i++;
81
+ } else {
82
+ out += c;
83
+ i++;
84
+ }
85
+ }
86
+ return JSON.parse(out);
87
+ }
88
+ /** Read a wrangler config as an object; only JSON and JSONC are read. */
89
+ function readWranglerConfig(path) {
90
+ const ext = extname(path);
91
+ if (ext !== ".json" && ext !== ".jsonc") throw new Error(`${basename(path)}: eutaxy reads a wrangler config as JSON or JSONC; a TOML config is not read`);
92
+ const parsed = parseJsonc(readFileSync(path, "utf8"));
93
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new Error(`${basename(path)}: not a wrangler config object`);
94
+ return parsed;
95
+ }
96
+ /** The `name` of a wrangler config, when the config can be read and names one. */
97
+ function workerName(path) {
98
+ try {
99
+ const name = readWranglerConfig(path)["name"];
100
+ return typeof name === "string" && name ? name : void 0;
101
+ } catch {
102
+ return;
103
+ }
104
+ }
105
+ /** The object entries of a config list; anything else is no entry. */
106
+ const list = (v) => Array.isArray(v) ? v.filter((x) => typeof x === "object" && x) : [];
107
+ const str = (v, fallback = "") => typeof v === "string" ? v : fallback;
108
+ const strings = (v) => Array.isArray(v) ? v.filter((x) => typeof x === "string") : [];
109
+ /** A D1 binding's database: its id, else its name, else the binding (the same database in two configs is one). */
110
+ const d1Id = (db) => str(db["database_id"], str(db["database_name"], str(db["binding"])));
111
+ /** An R2 binding's bucket: its name, else the binding. */
112
+ const r2Bucket = (b) => str(b["bucket_name"], str(b["binding"]));
113
+ /** A KV binding's namespace: its id, else the binding. */
114
+ const kvId = (k) => str(k["id"], str(k["binding"]));
115
+ /**
116
+ * The SQLite-backed Durable Object classes of a config, with its migrations applied in order as
117
+ * wrangler applies them: a class is SQLite-backed from the migration that created it so, through
118
+ * renames, until one deletes it.
119
+ */
120
+ function sqliteClasses(config) {
121
+ const sqlite = /* @__PURE__ */ new Set();
122
+ for (const m of list(config["migrations"])) {
123
+ for (const c of strings(m["new_sqlite_classes"])) sqlite.add(c);
124
+ for (const r of list(m["renamed_classes"])) {
125
+ const from = str(r["from"]);
126
+ if (sqlite.delete(from)) sqlite.add(str(r["to"]));
127
+ }
128
+ for (const c of strings(m["deleted_classes"])) sqlite.delete(c);
129
+ }
130
+ return sqlite;
131
+ }
132
+ /** Read a config's bindings. */
133
+ function readBindings(config) {
134
+ const sqlite = sqliteClasses(config);
135
+ const dos = config["durable_objects"];
136
+ const queues = config["queues"];
137
+ const vars = {};
138
+ const rawVars = config["vars"];
139
+ if (typeof rawVars === "object" && rawVars !== null) for (const [k, v] of Object.entries(rawVars)) vars[k] = v;
140
+ return {
141
+ name: str(config["name"]) || void 0,
142
+ main: str(config["main"]) || void 0,
143
+ d1: list(config["d1_databases"]).map((d) => ({
144
+ binding: str(d["binding"]),
145
+ id: d1Id(d)
146
+ })),
147
+ r2: list(config["r2_buckets"]).map((b) => ({
148
+ binding: str(b["binding"]),
149
+ bucket: r2Bucket(b)
150
+ })),
151
+ kv: list(config["kv_namespaces"]).map((k) => ({
152
+ binding: str(k["binding"]),
153
+ id: kvId(k)
154
+ })),
155
+ durableObjects: list(dos?.bindings).map((b) => {
156
+ const className = str(b["class_name"]);
157
+ return {
158
+ binding: str(b["name"]),
159
+ className,
160
+ sqlite: sqlite.has(className),
161
+ ...b["script_name"] === void 0 ? {} : { scriptName: str(b["script_name"]) }
162
+ };
163
+ }),
164
+ workflows: list(config["workflows"]).map((w) => ({
165
+ binding: str(w["binding"]),
166
+ className: str(w["class_name"]),
167
+ name: str(w["name"], str(w["binding"]))
168
+ })),
169
+ services: list(config["services"]).map((s) => ({
170
+ binding: str(s["binding"]),
171
+ service: str(s["service"]),
172
+ ...typeof s["entrypoint"] === "string" ? { entrypoint: s["entrypoint"] } : {},
173
+ ...typeof s["props"] === "object" && s["props"] !== null ? { props: s["props"] } : {}
174
+ })),
175
+ queues: list(queues?.producers).map((p) => ({
176
+ binding: str(p["binding"]),
177
+ queue: str(p["queue"])
178
+ })),
179
+ vars,
180
+ sqliteClasses: [...sqlite],
181
+ keys: Object.keys(config)
182
+ };
183
+ }
184
+ // packages/cli/src/callees.ts
185
+ /**
186
+ * The callees a scenario names (`callee()` steps), read on the Node side for
187
+ * `eutaxy check`. Each callee's wrangler config gives its Worker's name and
188
+ * its bindings; the command adds them to the test's isolate under qualified
189
+ * names (`<name>/<binding>`): the main module it generates re-exports the
190
+ * caller's exports as they are and the callees' Durable Object and Workflow
191
+ * classes under qualified aliases, and the Vitest config's miniflare options
192
+ * add the callees' resources. Probed inside workerd (2026-11): the plugin
193
+ * takes a `main` beside the caller's `wrangler.configPath`, miniflare options
194
+ * add to and override the wrangler config's bindings, and wrangler, miniflare
195
+ * and workerd accept a slash in a binding name.
196
+ */
197
+ /** The `callee` steps of a setup, as the scenario wrote them. */
198
+ /**
199
+ * The vars and secrets the scenario's setup gives a value (`envVar()`, `secret()`), by binding name,
200
+ * a callee's under its qualified one: what the isolate's env holds for them.
201
+ */
202
+ function envSteps(setup) {
203
+ const out = {};
204
+ for (const s of setup) if (s.kind === "env") out[String(s["binding"])] = s["value"];
205
+ return out;
206
+ }
207
+ function calleeSteps(setup) {
208
+ return setup.filter((s) => s.kind === "callee").map((s) => ({
209
+ binding: String(s["binding"]),
210
+ entry: String(s["entry"]),
211
+ config: String(s["config"]),
212
+ ...s["entrypoint"] === void 0 ? {} : { entrypoint: String(s["entrypoint"]) }
213
+ }));
214
+ }
215
+ /**
216
+ * Whether the scenario's source names a callee at all: the command imports
217
+ * the scenario module in Node only then, since reading its steps needs it.
218
+ */
219
+ function mentionsCallee(scenarioSource) {
220
+ return /\bcallee\s*\(/.test(scenarioSource);
221
+ }
222
+ /** The argument that makes a process started on this module load one scenario and report it. */
223
+ const scenarioFlag = "--eutaxy-load-scenario";
224
+ /** Inside the child: import the scenario and keep what the command reads. */
225
+ async function loadHere(scenarioPath) {
226
+ resolveAsTypeScript();
227
+ const spec = (await import(pathToFileURL(scenarioPath).href)).default;
228
+ if (!spec || !Array.isArray(spec.setup) || typeof spec.worker?.entry !== "string") throw new Error("the scenario module's default export is not a scenario");
229
+ return {
230
+ setup: spec.setup,
231
+ worker: spec.worker
232
+ };
233
+ }
234
+ const send = process.send?.bind(process);
235
+ if (process.argv[2] === scenarioFlag && send) {
236
+ process.once("disconnect", () => process.exit(0));
237
+ process.once("message", async (scenarioPath) => {
238
+ let output;
239
+ try {
240
+ output = {
241
+ kind: "eutaxy-scenario",
242
+ scenario: await loadHere(scenarioPath)
243
+ };
244
+ } catch (err) {
245
+ output = {
246
+ kind: "eutaxy-scenario-error",
247
+ message: String(err)
248
+ };
249
+ }
250
+ send(output, () => process.exit(0));
251
+ });
252
+ }
253
+ /** How long a scenario module may take to load before the command gives up on it. */
254
+ const loadBudgetMs = 6e4;
255
+ /**
256
+ * Import the scenario module in Node and return its setup and Worker, in a
257
+ * child process started on this module (as `eutaxy report` loads modules):
258
+ * a long-lived process (the MCP server) would otherwise get Node's cached
259
+ * module after the scenario or what it imports changed. Relative imports
260
+ * are resolved as TypeScript resolves them (`./setup.js` and `./setup` find
261
+ * `setup.ts`). Rejects with what the import threw.
262
+ */
263
+ function loadScenario(scenarioPath) {
264
+ return new Promise((resolveLoad, reject) => {
265
+ const child = fork(fileURLToPath(import.meta.url), [scenarioFlag], {
266
+ stdio: [
267
+ "ignore",
268
+ "ignore",
269
+ "pipe",
270
+ "ipc"
271
+ ],
272
+ serialization: "advanced"
273
+ });
274
+ let errors = "";
275
+ child.stderr?.on("data", (d) => {
276
+ errors += d.toString();
277
+ });
278
+ let settled = false;
279
+ const settle = (outcome) => {
280
+ if (settled) return;
281
+ settled = true;
282
+ clearTimeout(timer);
283
+ outcome();
284
+ };
285
+ const timer = setTimeout(() => {
286
+ child.kill("SIGKILL");
287
+ settle(() => reject(/* @__PURE__ */ new Error(`the scenario module did not load within ${loadBudgetMs} ms`)));
288
+ }, loadBudgetMs);
289
+ child.on("message", (output) => {
290
+ settle(() => {
291
+ if (output.kind === "eutaxy-scenario") resolveLoad(output.scenario);
292
+ else reject(new Error(output.message));
293
+ });
294
+ });
295
+ child.once("error", (err) => settle(() => reject(err)));
296
+ child.once("close", (code, signal) => settle(() => reject(/* @__PURE__ */ new Error(`the scenario module's process ended (${signal ?? `exit ${code}`}) before reporting${errors ? `:\n${errors}` : ""}`))));
297
+ child.send(scenarioPath);
298
+ });
299
+ }
300
+ /** The qualified names the callees' bindings get in the isolate, for a regression test's note. */
301
+ function isolateBindings(callees) {
302
+ const names = [];
303
+ for (const c of callees) {
304
+ for (const d of c.d1) names.push(qualified(c.name, d.binding));
305
+ for (const b of c.r2) names.push(qualified(c.name, b.binding));
306
+ for (const k of c.kv) names.push(qualified(c.name, k.binding));
307
+ for (const o of c.durableObjects) if (o.scriptName === void 0) names.push(qualified(c.name, o.binding));
308
+ for (const w of c.workflows) names.push(qualified(c.name, w.binding));
309
+ for (const s of c.services) names.push(qualified(c.name, s));
310
+ for (const q of c.queues) names.push(qualified(c.name, q.binding));
311
+ for (const v of Object.keys(c.vars)) names.push(qualified(c.name, v));
312
+ }
313
+ return names;
314
+ }
315
+ /** The keys of a wrangler config whose bindings the command carries into the isolate. */
316
+ const carried = /* @__PURE__ */ new Set([
317
+ "name",
318
+ "main",
319
+ "compatibility_date",
320
+ "compatibility_flags",
321
+ "d1_databases",
322
+ "r2_buckets",
323
+ "kv_namespaces",
324
+ "durable_objects",
325
+ "migrations",
326
+ "workflows",
327
+ "services",
328
+ "queues",
329
+ "vars",
330
+ "$schema",
331
+ "observability",
332
+ "triggers",
333
+ "routes",
334
+ "route",
335
+ "workers_dev",
336
+ "account_id",
337
+ "placement",
338
+ "limits",
339
+ "upload_source_maps",
340
+ "minify",
341
+ "keep_vars",
342
+ "preview_urls"
343
+ ]);
344
+ /** Read a callee's wrangler config into what the isolate needs; `scenarioDir` resolves the step's paths. */
345
+ function readCalleeConfig(step, scenarioDir) {
346
+ const path = resolve(scenarioDir, step.config);
347
+ const bindings = readBindings(readWranglerConfig(path));
348
+ if (bindings.name === void 0) throw new Error(`${basename(path)}: the callee's wrangler config has no name, which qualifies its bindings`);
349
+ return {
350
+ binding: step.binding,
351
+ name: bindings.name,
352
+ entry: resolve(scenarioDir, step.entry),
353
+ d1: bindings.d1,
354
+ r2: bindings.r2,
355
+ kv: bindings.kv,
356
+ durableObjects: bindings.durableObjects,
357
+ workflows: bindings.workflows,
358
+ services: bindings.services.map((s) => s.binding),
359
+ carries: bindings.services.map(({ binding, entrypoint, props }) => ({
360
+ binding,
361
+ ...entrypoint === void 0 ? {} : { entrypoint },
362
+ ...props === void 0 ? {} : { props }
363
+ })),
364
+ queues: bindings.queues,
365
+ vars: bindings.vars,
366
+ sqliteClasses: bindings.sqliteClasses,
367
+ notAdded: bindings.keys.filter((key) => !carried.has(key))
368
+ };
369
+ }
370
+ /** A Worker's name as an identifier prefix (`my-worker` → `my_worker`, `1st` → `_1st`). */
371
+ const ident = (s) => {
372
+ const safe = s.replace(/[^A-Za-z0-9_$]/g, "_");
373
+ return /^[A-Za-z_$]/.test(safe) ? safe : `_${safe}`;
374
+ };
375
+ /** The export name a callee's class gets in the generated main module. */
376
+ function classAlias(worker, className) {
377
+ return `${ident(worker)}__${className}`;
378
+ }
379
+ /** The qualified name of a callee's binding. */
380
+ function qualified(worker, binding) {
381
+ return `${worker}/${binding}`;
382
+ }
383
+ function toPosix$1(p) {
384
+ const s = p.split("\\").join("/");
385
+ return s.startsWith(".") ? s : `./${s}`;
386
+ }
387
+ /**
388
+ * The main module the plugin runs: the caller's exports as they are, and
389
+ * each callee's Durable Object and Workflow classes under qualified aliases,
390
+ * so the miniflare options can bind them. workerd constructs those classes
391
+ * with the main Worker's env, so each alias is a subclass handing its parent
392
+ * the callee's view of it (`calleeEnv`), under which `this.env.DB` is the
393
+ * callee's `<name>/DB`.
394
+ */
395
+ function mainModuleSource(workDir, callerEntry, callees, isolate = noIsolate) {
396
+ const caller = toPosix$1(relative(workDir, callerEntry));
397
+ const lines = [
398
+ "// Generated by eutaxy check; deleted after the run.",
399
+ `export * from ${JSON.stringify(caller)};`,
400
+ `export { default } from ${JSON.stringify(caller)};`
401
+ ];
402
+ const adapters = [];
403
+ const emitted = /* @__PURE__ */ new Set();
404
+ callees.forEach((c, i) => {
405
+ const classes = [
406
+ ...c.durableObjects.filter((d) => d.scriptName === void 0).map((d) => d.className),
407
+ ...c.workflows.map((w) => w.className),
408
+ ...isolate.extraClasses[c.name] ?? []
409
+ ];
410
+ const unique = [...new Set(classes)].filter((n) => n && !emitted.has(classAlias(c.name, n)));
411
+ if (unique.length === 0) return;
412
+ lines.push(`import { ${unique.map((n) => `${n} as callee${i}_${n}`).join(", ")} } from ${JSON.stringify(toPosix$1(relative(workDir, c.entry)))};`);
413
+ const own = Object.fromEntries(Object.entries(isolate.aliases).filter(([k]) => k.startsWith(`${c.name}/`)));
414
+ const view = `calleeEnv(${JSON.stringify(c.name)}, env${Object.keys(own).length === 0 ? "" : `, ${JSON.stringify(own)}`})`;
415
+ for (const n of unique) {
416
+ emitted.add(classAlias(c.name, n));
417
+ adapters.push(`export class ${classAlias(c.name, n)} extends callee${i}_${n} {`, ` constructor(ctx: unknown, env: object) {`, ` super(ctx as never, ${view} as never);`, ` }`, `}`);
418
+ }
419
+ });
420
+ if (adapters.length > 0) lines.splice(1, 0, "import { calleeEnv } from \"eutaxy/cloudflare\";");
421
+ return `${[...lines, ...adapters].join("\n")}\n`;
422
+ }
423
+ /** The name the generated config gives the function answering a service binding nobody calls. */
424
+ const neverCalled = "neverCalled";
425
+ /**
426
+ * The miniflare options adding the callees' resources under qualified names,
427
+ * as source (an object literal) for the generated Vitest config. Service
428
+ * bindings, the caller's to its callees and the callees' own, are answered
429
+ * by a function of the config's (`neverCalled`): the Worker the caller's
430
+ * config names is not in the isolate, a worker name given through these
431
+ * options must be one the plugin knows, and the binding is never called
432
+ * anyway (the scenario names a callee for it or scripts it); its value is a
433
+ * Fetcher all the same, which is what the platform recognises.
434
+ */
435
+ function miniflareOptionsSource(callees, isolate = noIsolate, callerServices = [], env = {}) {
436
+ const d1 = {};
437
+ const r2 = {};
438
+ const kv = {};
439
+ const dos = {};
440
+ const workflows = {};
441
+ const services = {};
442
+ const queues = {};
443
+ const vars = {};
444
+ const aliased = (name) => name in isolate.aliases;
445
+ Object.assign(dos, isolate.redirected);
446
+ for (const b of callerServices) services[b] = neverCalled;
447
+ for (const c of callees) {
448
+ for (const d of c.d1) if (!aliased(qualified(c.name, d.binding))) d1[qualified(c.name, d.binding)] = d.id;
449
+ for (const b of c.r2) if (!aliased(qualified(c.name, b.binding))) r2[qualified(c.name, b.binding)] = b.bucket;
450
+ for (const k of c.kv) if (!aliased(qualified(c.name, k.binding))) kv[qualified(c.name, k.binding)] = k.id;
451
+ for (const o of c.durableObjects) {
452
+ if (o.scriptName !== void 0 || aliased(qualified(c.name, o.binding))) continue;
453
+ dos[qualified(c.name, o.binding)] = {
454
+ className: classAlias(c.name, o.className),
455
+ ...o.sqlite ? { useSQLite: true } : {}
456
+ };
457
+ }
458
+ for (const w of c.workflows) workflows[qualified(c.name, w.binding)] = {
459
+ name: w.name,
460
+ className: classAlias(c.name, w.className)
461
+ };
462
+ services[c.binding] = neverCalled;
463
+ for (const s of c.services) services[qualified(c.name, s)] = neverCalled;
464
+ for (const q of c.queues) queues[qualified(c.name, q.binding)] = q.queue;
465
+ for (const [k, v] of Object.entries(c.vars)) vars[qualified(c.name, k)] = v;
466
+ }
467
+ Object.assign(vars, env);
468
+ const options = {};
469
+ const add = (key, value) => {
470
+ if (Object.keys(value).length > 0) options[key] = value;
471
+ };
472
+ add("d1Databases", d1);
473
+ add("r2Buckets", r2);
474
+ add("kvNamespaces", kv);
475
+ add("durableObjects", dos);
476
+ add("workflows", workflows);
477
+ add("queueProducers", queues);
478
+ add("bindings", vars);
479
+ const data = JSON.stringify(options);
480
+ const bindings = Object.keys(services);
481
+ if (bindings.length === 0) return data;
482
+ const literal = `"serviceBindings":{${bindings.map((b) => `${JSON.stringify(b)}:${neverCalled}`).join(",")}}`;
483
+ return data === "{}" ? `{${literal}}` : `${data.slice(0, -1)},${literal}}`;
484
+ }
485
+ /** The caller's resources from its wrangler config, when the config can be read (JSON or JSONC); none otherwise. */
486
+ function readCallerResources(wranglerPath) {
487
+ try {
488
+ const bindings = readBindings(readWranglerConfig(wranglerPath));
489
+ return {
490
+ name: bindings.name,
491
+ d1: bindings.d1,
492
+ r2: bindings.r2,
493
+ kv: bindings.kv,
494
+ durableObjects: bindings.durableObjects,
495
+ services: bindings.services
496
+ };
497
+ } catch {
498
+ return;
499
+ }
500
+ }
501
+ /**
502
+ * What the binding to a callee carries (its entrypoint and props), for the
503
+ * test to pass with the module: from the caller's config, or for a callee's
504
+ * own callee (`<callee>/<binding>`) from that callee's config, where the
505
+ * binding is declared.
506
+ */
507
+ function bindingCarries(caller, binding, callees = []) {
508
+ const owner = callees.find((c) => binding.startsWith(`${c.name}/`));
509
+ const s = caller?.services.find((x) => x.binding === binding) ?? owner?.carries.find((x) => qualified(owner.name, x.binding) === binding);
510
+ return {
511
+ ...s?.entrypoint === void 0 ? {} : { entrypoint: s.entrypoint },
512
+ ...s?.props === void 0 ? {} : { props: s.props }
513
+ };
514
+ }
515
+ /**
516
+ * The isolate's shared resources, from the two configs: a callee binding
517
+ * that names a resource the caller binds too (the same `database_id`,
518
+ * `bucket_name` or KV `id`; a Durable Object class of the caller's script,
519
+ * or a caller binding to a class of the callee's script) is an alias of the
520
+ * caller's binding, set up and snapshotted under the caller's name; a
521
+ * caller's binding to a callee's class is redirected to the generated alias
522
+ * class. What a callee binds in a third Worker's script is named as not
523
+ * added.
524
+ */
525
+ function isolateOf(callees, caller) {
526
+ const aliases = {};
527
+ const redirected = {};
528
+ const extraClasses = {};
529
+ const notAdded = [];
530
+ const alias = (name, own) => {
531
+ if (own !== name) aliases[name] = own;
532
+ };
533
+ for (const c of callees) {
534
+ if (caller) {
535
+ for (const d of c.d1) {
536
+ const own = caller.d1.find((x) => x.id === d.id);
537
+ if (own) alias(qualified(c.name, d.binding), own.binding);
538
+ }
539
+ for (const b of c.r2) {
540
+ const own = caller.r2.find((x) => x.bucket === b.bucket);
541
+ if (own) alias(qualified(c.name, b.binding), own.binding);
542
+ }
543
+ for (const k of c.kv) {
544
+ const own = caller.kv.find((x) => x.id === k.id);
545
+ if (own) alias(qualified(c.name, k.binding), own.binding);
546
+ }
547
+ for (const o of caller.durableObjects) {
548
+ if (o.scriptName !== c.name) continue;
549
+ const theirs = c.durableObjects.find((x) => x.className === o.className && x.scriptName === void 0);
550
+ redirected[o.binding] = {
551
+ className: classAlias(c.name, o.className),
552
+ ...c.sqliteClasses.includes(o.className) ? { useSQLite: true } : {}
553
+ };
554
+ if (theirs) alias(qualified(c.name, theirs.binding), o.binding);
555
+ else {
556
+ const extra = extraClasses[c.name] ?? [];
557
+ extra.push(o.className);
558
+ extraClasses[c.name] = extra;
559
+ }
560
+ }
561
+ }
562
+ for (const o of c.durableObjects) {
563
+ if (o.scriptName === void 0) continue;
564
+ const own = caller && o.scriptName === caller.name ? caller.durableObjects.find((x) => x.className === o.className && x.scriptName === void 0) : void 0;
565
+ if (own) alias(qualified(c.name, o.binding), own.binding);
566
+ else notAdded.push(`${c.binding}: durable_objects binding ${o.binding} (script_name ${o.scriptName}: a class of another Worker)`);
567
+ }
568
+ }
569
+ return {
570
+ aliases,
571
+ redirected,
572
+ extraClasses,
573
+ notAdded
574
+ };
575
+ }
576
+ /** An isolate with nothing shared. */
577
+ const noIsolate = {
578
+ aliases: {},
579
+ redirected: {},
580
+ extraClasses: {},
581
+ notAdded: []
582
+ };
583
+ /** Where a callee's config path and entry sit, for messages. */
584
+ function describeCallee(c, scenarioDir) {
585
+ return `${c.binding} (${c.name}, ${toPosix$1(relative(scenarioDir, c.entry))})`;
586
+ }
587
+ // packages/cli/src/vitest-failure.ts
588
+ /**
589
+ * Why Vitest failed the run a check started, from what that run left: its
590
+ * JSON report (a test file that could not run, a failed test) and the
591
+ * errors nothing handled, which fail a run without being in that report,
592
+ * so the generated config's own reporter writes them beside it
593
+ * (`unhandledErrorsFile`). Without this the command could only say that
594
+ * Vitest exited non-zero: the run's only reporter is the JSON one, and its
595
+ * files are deleted after the run.
596
+ */
597
+ /** Where the run's errors nothing handled are written: beside its report, under its stamp. */
598
+ function unhandledErrorsFile(reportFile) {
599
+ return reportFile.replace(/\.json$/, ".unhandled.json");
600
+ }
601
+ /** Lines of an error kept in the explanation; a stack's first frames say where. */
602
+ const keptLines = 8;
603
+ function parsed(text) {
604
+ if (text === void 0) return void 0;
605
+ try {
606
+ return JSON.parse(text);
607
+ } catch {
608
+ return;
609
+ }
610
+ }
611
+ /** A field as text: a string as it is, anything else as JSON (a thrown value need not be an error). */
612
+ function asText(value) {
613
+ if (typeof value === "string") return value;
614
+ try {
615
+ return JSON.stringify(value) ?? String(value);
616
+ } catch {
617
+ return String(value);
618
+ }
619
+ }
620
+ /** What an error says: its stack or message when either is text, else whatever was thrown, as data. */
621
+ function said(e) {
622
+ for (const v of [e.stack, e.message]) if (typeof v === "string" && v !== "") return v;
623
+ const thrown = e.message ?? e.stack;
624
+ return thrown === void 0 || thrown === null ? "(no message)" : asText(thrown);
625
+ }
626
+ /** An error's first lines, each without its indent; a line at the end says how many were cut. */
627
+ function firstLines(text) {
628
+ const lines = text.trimEnd().split("\n").map((l) => l.trimStart());
629
+ const kept = lines.slice(0, keptLines);
630
+ if (lines.length > keptLines) kept.push(`… ${lines.length - keptLines} more lines`);
631
+ return kept;
632
+ }
633
+ /** An error's text, cut to its first lines and indented under its heading. */
634
+ function cut(text) {
635
+ return firstLines(text).join("\n ");
636
+ }
637
+ /** The errors nothing handled, the same type and text told once with how often it came, in first-seen order. */
638
+ function distinct(unhandled) {
639
+ const seen = /* @__PURE__ */ new Map();
640
+ for (const e of unhandled) {
641
+ const type = typeof e.type === "string" && e.type !== "" ? e.type : "Error";
642
+ const whole = said(e);
643
+ const key = `${type}\n${whole}`;
644
+ const found = seen.get(key);
645
+ if (found) found.times++;
646
+ else seen.set(key, {
647
+ type,
648
+ message: firstLines(whole).join("\n"),
649
+ times: 1
650
+ });
651
+ }
652
+ return [...seen.values()];
653
+ }
654
+ /** The distinct errors, one a line under the count, each error's own lines indented under it. */
655
+ function told(errors) {
656
+ return errors.map(({ type, message, times }) => `\n ${type}${times > 1 ? ` (${times} times)` : ""}: ${message.split("\n").join("\n ")}`).join("");
657
+ }
658
+ /** How many errors came, and how many distinct when more than one. */
659
+ function counted(errors) {
660
+ const all = errors.reduce((n, e) => n + e.times, 0);
661
+ return all === 1 ? "1 error nothing handled" : `${all} errors nothing handled, ${errors.length} distinct`;
662
+ }
663
+ /** Why each test file failed and each failed test's first error, and how many tests passed. */
664
+ function reportCauses(report) {
665
+ const causes = [];
666
+ let passed = 0;
667
+ for (const file of report?.testResults ?? []) {
668
+ const tests = file.assertionResults ?? [];
669
+ if (file.status === "failed" && file.message !== void 0 && file.message !== "") causes.push(`the check's test file ${tests.length === 0 ? "could not run" : "failed outside its test"}: ${cut(asText(file.message))}`);
670
+ for (const t of tests) if (t.status === "passed") passed++;
671
+ else if (t.status === "failed") {
672
+ const [first] = t.failureMessages ?? [];
673
+ causes.push(`the check's test failed${first === void 0 ? "" : `: ${cut(asText(first))}`}`);
674
+ }
675
+ }
676
+ return {
677
+ causes,
678
+ passed
679
+ };
680
+ }
681
+ /**
682
+ * The kinds of error nothing handled that Vitest's error catcher in the
683
+ * test's own runtime records (`listenForErrors`): what code that ran
684
+ * inside the test left behind, the Worker's or the simulation's. The
685
+ * runner, its pool and the reporters record their own failures through the
686
+ * same channel (`Teardown Error`, `Unhandled Error`, `Unhandled Reporter
687
+ * Error`, `Restart Error`, …); those mean the run broke.
688
+ */
689
+ const fromTheTest = /* @__PURE__ */ new Set(["Unhandled Rejection", "Uncaught Exception"]);
690
+ /**
691
+ * The errors nothing handled, when they are the run's only fault: every
692
+ * test in the report passed, at least one did, no file failed outside its
693
+ * tests, and there was at least one such error, every one recorded by the
694
+ * test's own runtime (`fromTheTest`). Cloudflare's runtime only
695
+ * logs an error nothing handled (a promise a Worker leaves rejected, say),
696
+ * while Vitest fails the whole run on one, so then the verdict the test
697
+ * left stands and these are told beside it. Otherwise undefined: the run
698
+ * failed, and `vitestFailure` says why.
699
+ */
700
+ function strayErrors(left) {
701
+ const report = parsed(left.report);
702
+ const unhandled = parsed(left.unhandled);
703
+ if (report === void 0 || !Array.isArray(unhandled) || unhandled.length === 0) return void 0;
704
+ if (!unhandled.every((e) => typeof e?.type === "string" && fromTheTest.has(e.type))) return void 0;
705
+ const { causes, passed } = reportCauses(report);
706
+ const allPassed = (report.testResults ?? []).every((f) => f.status === "passed" && (f.assertionResults ?? []).every((t) => t.status === "passed"));
707
+ return passed > 0 && causes.length === 0 && allPassed ? distinct(unhandled) : void 0;
708
+ }
709
+ /** The note printed beside a verdict that stands despite errors nothing handled. */
710
+ function strayNote(errors) {
711
+ return `note: the check's test passed, and its verdict stands, but there ${errors.reduce((n, e) => n + e.times, 0) === 1 ? "was" : "were"} ${counted(errors)} (Cloudflare's runtime only logs them; Vitest fails the run on them):${told(errors)}\n`;
712
+ }
713
+ /**
714
+ * The explanation, one cause a line (each error's own lines indented under
715
+ * it), from the report's text and the unhandled errors' text, either of
716
+ * which may be missing.
717
+ */
718
+ function vitestFailure(left) {
719
+ const report = parsed(left.report);
720
+ const unhandled = parsed(left.unhandled) ?? [];
721
+ const { causes, passed } = reportCauses(report);
722
+ if (unhandled.length > 0) {
723
+ const errors = distinct(unhandled);
724
+ const passedAlone = passed > 0 && causes.length === 0;
725
+ const onlyFromTheTest = unhandled.every((e) => typeof e?.type === "string" && fromTheTest.has(e.type));
726
+ const intro = !passedAlone ? "" : onlyFromTheTest ? "its test passed but left no verdict in Vitest's report; there " : "its test passed, but Vitest fails a run on any error nothing handled, and there ";
727
+ const also = passedAlone && onlyFromTheTest ? "also " : "";
728
+ const verb = intro === "" ? "" : `${unhandled.length === 1 ? "was" : "were"} ${also}`;
729
+ causes.push(`${intro}${verb}${counted(errors)}:${told(errors)}`);
730
+ }
731
+ if (causes.length === 0) causes.push(report === void 0 ? "Vitest left no report it could be told from" : passed > 0 ? "its test passed but left no verdict in Vitest's report" : "Vitest reported no failed test and no error nothing handled");
732
+ return causes.map((c) => ` ${c}\n`).join("");
733
+ }
734
+ // packages/cli/src/generate.ts
735
+ /**
736
+ * The files `eutaxy check` writes into `<scenario dir>/.eutaxy/` before
737
+ * running Vitest: a test that performs the check inside workerd and prints
738
+ * the verdict on one marked line, and a Vitest config with the Cloudflare
739
+ * plugin pointed at the scenario's wrangler config. For a scenario with
740
+ * callees the test imports their modules, the config names a generated main
741
+ * module and adds their resources through miniflare options (`callees.ts`).
742
+ */
743
+ /** Key under which the generated test stores its result in the Vitest task meta, read back from the JSON reporter. */
744
+ const metaKey = "eutaxy";
745
+ /**
746
+ * The generated test: the module globs (Vite resolves them at build time,
747
+ * so they must be written in the test) and one call to `checkInWorkerd`,
748
+ * which does the rest.
749
+ */
750
+ function checkTestSource(g) {
751
+ 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" : "");
752
+ const callees = g.callees ?? [];
753
+ const sqlImports = g.sqlImports ?? [];
754
+ const calleeImports = callees.map((c, i) => `import * as callee_${i} from ${JSON.stringify(c.importPath)};\n`);
755
+ const sqlImportLines = sqlImports.map((f, i) => `import sql_${i} from ${JSON.stringify(`${f.importPath}?raw`)};\n`);
756
+ const workerImportLine = g.workerImport === void 0 ? "" : `import * as workerModule from ${JSON.stringify(g.workerImport)};\n`;
757
+ const workerOption = g.workerImport === void 0 ? "" : ", worker: workerModule";
758
+ 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)}`}${c.self ? ", self: true" : ""} }`).join(", ")} }`;
759
+ const extraSql = sqlImports.length === 0 ? "" : `, extraSql: { ${sqlImports.map((f, i) => `${JSON.stringify(f.key)}: sql_${i}`).join(", ")} }`;
760
+ const aliases = g.aliases === void 0 || Object.keys(g.aliases).length === 0 ? "" : `, aliases: ${JSON.stringify(g.aliases)}`;
761
+ return `// Generated by eutaxy check; deleted after the run.
762
+ import { checkInWorkerd } from "eutaxy/cloudflare";
763
+ import { env } from "cloudflare:workers";
764
+ import * as durableObjects from "cloudflare:test";
765
+ import { test } from "vitest";
766
+ import scenario from ${JSON.stringify(g.scenarioImport)};
767
+ ${workerImportLine}${calleeImports.join("")}${sqlImportLines.join("")}import { specEntries } from "./specs.ts";
768
+
769
+ const sqlFiles = import.meta.glob("../**/*.sql", { query: "?raw", import: "default", eager: true }) as Record<string, string>;
770
+ const modules = import.meta.glob(["../**/*.ts", "!../**/*.test.ts", "!../**/*.sim.ts", "!../**/node_modules/**", "!../**/.eutaxy/**"]);
771
+
772
+ test("eutaxy check", async ({ task }) => {
773
+ task.meta[${JSON.stringify(metaKey)}] = await checkInWorkerd({ scenario, env, durableObjects, sqlFiles, modules, specEntries${workerOption}${calleesOption}${extraSql}${aliases}, ${options} });
774
+ });
775
+ `;
776
+ }
777
+ /** Where the generated config writes what the Workers wrote to the console, one JSON line per write, when asked to. */
778
+ const consoleFile = (outputFile) => outputFile.replace(/\.json$/, ".console.jsonl");
779
+ function vitestConfigSource(wranglerConfigPath, testPath, outputFile, isolate, keepConsole = false) {
780
+ 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}`} })`;
781
+ const helpers = 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`;
782
+ return `// Generated by eutaxy check; deleted after the run.
783
+ import { ${keepConsole ? "appendFileSync, " : ""}writeFileSync } from "node:fs";
784
+ import { cloudflareTest } from "@cloudflare/vitest-plugin";
785
+ import { defineConfig } from "vitest/config";
786
+
787
+ ${helpers}export default defineConfig({
788
+ // Vite's cache, kept with the generated files so it goes when they do (its default is the
789
+ // project's node_modules/.vite, which a check would leave behind in the scenario's directory).
790
+ cacheDir: ${JSON.stringify(join(dirname(testPath), ".vite"))},
791
+ plugins: [${plugin}],
792
+ test: {
793
+ include: [${JSON.stringify(testPath)}],
794
+ testTimeout: 600_000,
795
+ // An error nothing handled fails the run but is not in the JSON report; kept for the command to tell.
796
+ reporters: ["json", { onTestRunEnd(_modules, errors) {
797
+ if (errors.length > 0)
798
+ writeFileSync(${JSON.stringify(unhandledErrorsFile(outputFile))}, JSON.stringify(errors.map((e) => ({ type: e.type, message: e.message, stack: e.stack }))));
799
+ }${keepConsole ? `, onUserConsoleLog(log) {
800
+ appendFileSync(${JSON.stringify(consoleFile(outputFile))}, JSON.stringify({ type: log.type, content: log.content }) + "\\n");
801
+ }` : ""} }],
802
+ outputFile: ${JSON.stringify(outputFile)},
803
+ },
804
+ });
805
+ `;
806
+ }
807
+ const skipDirs = /* @__PURE__ */ new Set([
808
+ "node_modules",
809
+ ".eutaxy",
810
+ "dist",
811
+ ".git"
812
+ ]);
813
+ /** What the spec reader needs that a project without specs need not have. */
814
+ const typescriptNeeded = "the TypeScript compiler, version 7.1 or later (typescript), which this project does not have: add it to the project's dev dependencies, or update the one there";
815
+ /** A spec file was to be read, or an engine run, where the TypeScript compiler is not installed. */
816
+ var TypescriptNeeded = class extends Error {};
817
+ /**
818
+ * Whether an import failed because the project has no TypeScript compiler the reader can use: none
819
+ * installed (Node finds no package `typescript`), or an older one, which lacks the modules the
820
+ * reader imports (no such export in its package, or no such file in it).
821
+ */
822
+ function typescriptMissing(err) {
823
+ const e = err;
824
+ if (e?.code !== "ERR_MODULE_NOT_FOUND" && e?.code !== "ERR_PACKAGE_PATH_NOT_EXPORTED") return false;
825
+ return /(^|[\\/'"\s])typescript([\\/'"\s]|$)/.test(e.message ?? "");
826
+ }
827
+ /**
828
+ * The spec reader, loaded when a spec file is first read: it runs the
829
+ * TypeScript compiler, which a project that writes no specs need not have
830
+ * installed, so the command does not load it before then.
831
+ */
832
+ async function reader() {
833
+ try {
834
+ return await import("./reader-B9FSoEYW.mjs");
835
+ } catch (err) {
836
+ if (typescriptMissing(err)) throw new TypescriptNeeded(`reading a spec file needs ${typescriptNeeded}`);
837
+ throw err;
838
+ }
839
+ }
840
+ /** Read one module and its spec file; their imports resolve from where they are. */
841
+ async function readSpecModule(modulePath, specPath) {
842
+ const { readSpecs } = await reader();
843
+ return readSpecs({
844
+ module: readFileSync(modulePath, "utf8"),
845
+ spec: readFileSync(specPath, "utf8"),
846
+ modulePath,
847
+ specPath
848
+ });
849
+ }
850
+ /**
851
+ * Spec files under `dir`, each with its module; a spec file without a module beside it is an error
852
+ * entry. A directory with no spec file is walked without the spec reader being loaded.
853
+ */
854
+ async function findSpecModules(dir) {
855
+ const out = [];
856
+ const walk = async (at) => {
857
+ for (const entry of readdirSync(at, { withFileTypes: true })) {
858
+ const path = join(at, entry.name);
859
+ if (entry.isDirectory()) {
860
+ if (!skipDirs.has(entry.name)) await walk(path);
861
+ continue;
862
+ }
863
+ if (!entry.name.endsWith(".props.ts")) continue;
864
+ const modulePath = join(at, `${entry.name.slice(0, -9)}.ts`);
865
+ const key = specKey(relative(dir, modulePath));
866
+ if (!existsSync(modulePath)) {
867
+ out.push({
868
+ key,
869
+ path: modulePath,
870
+ specPath: path,
871
+ specs: {
872
+ functions: [],
873
+ errors: [{
874
+ line: 1,
875
+ message: `${entry.name} has no module ${basename(modulePath)} beside it`
876
+ }]
877
+ }
878
+ });
879
+ continue;
880
+ }
881
+ out.push({
882
+ key,
883
+ path: modulePath,
884
+ specPath: path,
885
+ specs: await readSpecModule(modulePath, path)
886
+ });
887
+ }
888
+ };
889
+ await walk(dir);
890
+ return out.sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
891
+ }
892
+ /** A path as an import specifier from `.eutaxy/`: forward slashes, relative, `.ts` kept (Vite resolves it). */
893
+ function importFrom(workDir, target) {
894
+ const rel = relative(workDir, target).split("\\").join("/");
895
+ return rel.startsWith(".") ? rel : `./${rel}`;
896
+ }
897
+ /**
898
+ * The generated `specs.ts`: each module's key mapped to its specs (plain
899
+ * data read on the Node side) and a loader of its spec file. The loader is
900
+ * lazy, so a spec file elsewhere that does not compile cannot stop a check
901
+ * of a scenario that does not name its module.
902
+ */
903
+ function specFiles(modules, workDir) {
904
+ return [{
905
+ name: "specs.ts",
906
+ source: `${[
907
+ "// Generated by eutaxy check; deleted after the run.",
908
+ "// The `any`: this file runs in the user's Vitest, which does not type-check it; `SpecEntry` in workerd.ts is the shape.",
909
+ "export const specEntries: Record<string, { specs: any; load: () => Promise<any> }> = {",
910
+ ...modules.map((m) => ` ${JSON.stringify(m.key)}: { specs: ${JSON.stringify(m.specs)}, load: () => import(${JSON.stringify(importFrom(workDir, m.specPath))}) },`),
911
+ "};"
912
+ ].join("\n")}\n`
913
+ }];
914
+ }
915
+ // packages/cli/src/check.ts
916
+ /**
917
+ * `eutaxy check <scenario.sim.ts>`: run a scenario inside workerd through
918
+ * the user's Vitest and the Cloudflare plugin, print the verdict as text or
919
+ * JSON, and on a violation write a regression test next to the scenario.
920
+ */
921
+ const exitCodes = {
922
+ BOUNDED: 0,
923
+ VIOLATED: 1,
924
+ UNSUPPORTED: 2,
925
+ error: 3
926
+ };
927
+ /** The engines `--prover` can name. */
928
+ const proverNames = ["lean", "smt"];
929
+ /**
930
+ * An engine, loaded when it is first named: the engines read through the TypeScript compiler,
931
+ * which a project that proves nothing need not have installed.
932
+ */
933
+ async function loadProver(name) {
934
+ try {
935
+ return name === "lean" ? (await import("./src-B2DpVbMN.mjs")).leanProver : (await import("./src-CB8DcvsK.mjs")).smtProver;
936
+ } catch (err) {
937
+ if (typescriptMissing(err)) throw new Error(`the ${name} engine needs ${typescriptNeeded}`);
938
+ throw err;
939
+ }
940
+ }
941
+ /** The engines named, or the error naming the first unknown one, or why one could not be loaded. */
942
+ async function enginesNamed(names) {
943
+ const known = (name) => proverNames.includes(name);
944
+ for (const name of names) if (!known(name)) return { error: `unknown prover ${name}; known: ${proverNames.join(", ")}` };
945
+ const engines = [];
946
+ try {
947
+ for (const name of names) if (known(name)) engines.push(await loadProver(name));
948
+ } catch (err) {
949
+ return { error: err instanceof Error ? err.message : String(err) };
950
+ }
951
+ return { engines };
952
+ }
953
+ /**
954
+ * The PROVEN rung, on the Node side: each engine on each observed spec
955
+ * module's source, the outcomes folded into the simulator's verdicts.
956
+ * An engine that is not installed proves nothing and says so.
957
+ */
958
+ async function proveSpecs(dir, observed, specs, engines, given, onReport) {
959
+ const modules = given ?? await findSpecModules(dir);
960
+ let out = specs;
961
+ for (const m of observed) {
962
+ const key = specKey(m.module);
963
+ const found = modules.find((s) => s.key === key);
964
+ const withSpecs = m.functions.filter((f) => specs.some((v) => v.module === key && v.function === f));
965
+ if (!found || withSpecs.length === 0) continue;
966
+ const source = readFileSync(found.path, "utf8");
967
+ const reports = [];
968
+ for (const engine of engines) {
969
+ const report = {
970
+ engine: engine.name,
971
+ proofs: await engine.prove({
972
+ source,
973
+ specs: found.specs,
974
+ functions: withSpecs,
975
+ modulePath: found.path,
976
+ specPath: found.specPath
977
+ })
978
+ };
979
+ reports.push(report);
980
+ onReport?.(found, report);
981
+ }
982
+ out = aggregate(key, out, reports);
983
+ }
984
+ return out;
985
+ }
986
+ function findWrangler(dir, explicit, cwd) {
987
+ if (explicit) return resolve(cwd, explicit);
988
+ for (const name of [
989
+ "wrangler.jsonc",
990
+ "wrangler.json",
991
+ "wrangler.toml"
992
+ ]) {
993
+ const p = join(dir, name);
994
+ if (existsSync(p)) return p;
995
+ }
996
+ return null;
997
+ }
998
+ function vitestBin(from) {
999
+ const req = createRequire(join(from, "package.json"));
1000
+ return join(dirname(req.resolve("vitest/package.json")), "vitest.mjs");
1001
+ }
1002
+ function runVitest(bin, configPath, cwd) {
1003
+ return new Promise((resolveRun) => {
1004
+ const child = spawn(process.execPath, [
1005
+ bin,
1006
+ "run",
1007
+ "--config",
1008
+ configPath
1009
+ ], {
1010
+ cwd,
1011
+ env: {
1012
+ ...process.env,
1013
+ CI: "1",
1014
+ FORCE_COLOR: "0"
1015
+ },
1016
+ stdio: [
1017
+ "ignore",
1018
+ "pipe",
1019
+ "pipe"
1020
+ ]
1021
+ });
1022
+ let output = "";
1023
+ child.stdout.on("data", (d) => {
1024
+ output += d.toString();
1025
+ });
1026
+ child.stderr.on("data", (d) => {
1027
+ output += d.toString();
1028
+ });
1029
+ child.on("close", (code) => resolveRun({
1030
+ code: code ?? 1,
1031
+ output
1032
+ }));
1033
+ });
1034
+ }
1035
+ /** A colour or style escape, which a console in the isolate adds to an object it prints whatever the terminal. */
1036
+ const styleEscape = new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`, "g");
1037
+ /**
1038
+ * What was written to the console in the isolate during the check, for `--console`: the Workers'
1039
+ * writes, a callee's included, and the scenario file's own, every run of the check (it runs the
1040
+ * scenario many times, so a line a handler writes once appears once per run), without colour
1041
+ * escapes. As Vitest reported it: the writes to one stream are in the order written, but it hands
1042
+ * over what went to stdout before what went to stderr within one stretch of synchronous code, so a
1043
+ * `console.error` can follow a `console.log` that was written after it.
1044
+ */
1045
+ function consoleOutput(file) {
1046
+ const writes = existsSync(file) ? readFileSync(file, "utf8").split("\n").filter((line) => line !== "").map((line) => JSON.parse(line)) : [];
1047
+ if (writes.length === 0) return "Nothing was written to the console during the check.\n";
1048
+ const text = writes.map((w) => w.content).join("").replace(styleEscape, "");
1049
+ return `Console output during the check, every run, as Vitest reported it:\n${text}${text.endsWith("\n") ? "" : "\n"}`;
1050
+ }
1051
+ /** The transport the generated test left in its task meta, via Vitest's JSON reporter. */
1052
+ function readTransport(reportPath) {
1053
+ if (!existsSync(reportPath)) return null;
1054
+ const report = JSON.parse(readFileSync(reportPath, "utf8"));
1055
+ for (const file of report.testResults ?? []) for (const t of file.assertionResults ?? []) {
1056
+ const m = t.meta?.[metaKey];
1057
+ if (m) return m;
1058
+ }
1059
+ return null;
1060
+ }
1061
+ /**
1062
+ * Whether a regression test for a scenario with these setup steps is given the Cloudflare test
1063
+ * helpers: real objects are reset and snapshotted through them, and a scripted namespace is watched
1064
+ * through them for an object that ran after all.
1065
+ */
1066
+ function needsObjectHelpers(setup) {
1067
+ return setup.some((s) => s.kind === "durable_object" || s.kind === "scripted_object");
1068
+ }
1069
+ function toPosix(p) {
1070
+ const s = p.split("\\").join("/");
1071
+ return s.startsWith(".") ? s : `./${s}`;
1072
+ }
1073
+ async function runCheck(o) {
1074
+ const scenarioPath = resolve(o.cwd, o.scenario);
1075
+ if (!existsSync(scenarioPath)) {
1076
+ o.stderr(`scenario not found: ${scenarioPath}\n`);
1077
+ return exitCodes.error;
1078
+ }
1079
+ let engines = [];
1080
+ if (o.provers && o.provers.length > 0) {
1081
+ const named = await enginesNamed(o.provers);
1082
+ if ("error" in named) {
1083
+ o.stderr(`${named.error}\n`);
1084
+ return exitCodes.error;
1085
+ }
1086
+ engines = named.engines;
1087
+ }
1088
+ const dir = dirname(scenarioPath);
1089
+ const name = basename(scenarioPath).replace(/\.sim\.ts$/, "").replace(/\.ts$/, "");
1090
+ const stamp = `${process.pid}-${randomBytes(3).toString("hex")}`;
1091
+ const workDir = join(dir, ".eutaxy");
1092
+ const testPath = join(workDir, `${name}.${stamp}.check.test.ts`);
1093
+ const configPath = join(workDir, `vitest.config.${stamp}.mts`);
1094
+ const mainPath = join(workDir, `main.${stamp}.ts`);
1095
+ let callees = [];
1096
+ let loaded;
1097
+ try {
1098
+ loaded = await loadScenario(scenarioPath);
1099
+ } catch (err) {
1100
+ if (mentionsCallee(readFileSync(scenarioPath, "utf8"))) {
1101
+ o.stderr(`could not read the scenario's callees: ${String(err)}\n`);
1102
+ return exitCodes.error;
1103
+ }
1104
+ 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`);
1105
+ }
1106
+ const named = o.wrangler === void 0 ? loaded?.worker.config : void 0;
1107
+ const wrangler = named !== void 0 ? resolve(dir, named) : findWrangler(dir, o.wrangler, o.cwd);
1108
+ if (!wrangler || !existsSync(wrangler)) {
1109
+ 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`);
1110
+ return exitCodes.error;
1111
+ }
1112
+ try {
1113
+ callees = calleeSteps(loaded?.setup ?? []).map((step) => readCalleeConfig(step, dir));
1114
+ } catch (err) {
1115
+ o.stderr(`could not read the scenario's callees: ${String(err)}\n`);
1116
+ return exitCodes.error;
1117
+ }
1118
+ const callerResources = readCallerResources(wrangler);
1119
+ const isSelf = (c) => callerResources?.name !== void 0 && c.name === callerResources.name;
1120
+ const allCallees = callees;
1121
+ callees = allCallees.filter((c) => !isSelf(c));
1122
+ 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`);
1123
+ const isolate = isolateOf(callees, callees.length > 0 ? callerResources : void 0);
1124
+ const callerServices = (callerResources?.services ?? []).map((s) => s.binding).filter((b) => b);
1125
+ const env = envSteps(loaded?.setup ?? []);
1126
+ for (const reason of isolate.notAdded) o.stderr(`not added to the test's isolate: ${reason}\n`);
1127
+ mkdirSync(workDir, { recursive: true });
1128
+ try {
1129
+ const sqlImports = [];
1130
+ /** Whether a path the scenario names lies outside its directory, where the test's globs do not reach. */
1131
+ const outside = (file) => relative(dir, resolve(dir, file)).startsWith("..");
1132
+ if (loaded) for (const step of loaded.setup) {
1133
+ if (step.kind !== "d1") continue;
1134
+ const file = String(step["schemaFile"]);
1135
+ if (!outside(file)) continue;
1136
+ sqlImports.push({
1137
+ key: globKey(file),
1138
+ importPath: toPosix(relative(workDir, resolve(dir, file)))
1139
+ });
1140
+ }
1141
+ writeFileSync(testPath, checkTestSource({
1142
+ seed: o.seed ?? name,
1143
+ ...o.maxRuns === void 0 ? {} : { maxRuns: o.maxRuns },
1144
+ ...o.budgetMs === void 0 ? {} : { budgetMs: o.budgetMs },
1145
+ ...o.exhaustive ? { exhaustive: true } : {},
1146
+ scenarioImport: `../${basename(scenarioPath)}`,
1147
+ ...loaded && outside(loaded.worker.entry) ? { workerImport: toPosix(relative(workDir, resolve(dir, loaded.worker.entry))) } : {},
1148
+ ...allCallees.length === 0 ? {} : { callees: allCallees.map((c) => ({
1149
+ binding: c.binding,
1150
+ name: c.name,
1151
+ importPath: toPosix(relative(workDir, c.entry)),
1152
+ ...bindingCarries(callerResources, c.binding, callees),
1153
+ ...isSelf(c) ? { self: true } : {}
1154
+ })) },
1155
+ ...sqlImports.length === 0 ? {} : { sqlImports },
1156
+ ...Object.keys(isolate.aliases).length === 0 ? {} : { aliases: isolate.aliases }
1157
+ }));
1158
+ let specModules;
1159
+ try {
1160
+ specModules = await findSpecModules(dir);
1161
+ } catch (err) {
1162
+ if (!(err instanceof TypescriptNeeded)) throw err;
1163
+ o.stderr(`the scenario's directory holds spec files (*.props.ts): ${err.message}\n`);
1164
+ return exitCodes.error;
1165
+ }
1166
+ for (const f of specFiles(specModules, workDir)) {
1167
+ mkdirSync(dirname(join(workDir, f.name)), { recursive: true });
1168
+ writeFileSync(join(workDir, f.name), f.source);
1169
+ }
1170
+ const reportPath = join(workDir, `vitest-report.${stamp}.json`);
1171
+ rmSync(reportPath, { force: true });
1172
+ if (callees.length > 0 && loaded) {
1173
+ const callerEntry = resolve(dir, loaded.worker.entry);
1174
+ writeFileSync(mainPath, mainModuleSource(workDir, callerEntry, callees, isolate));
1175
+ writeFileSync(configPath, vitestConfigSource(wrangler, testPath, reportPath, {
1176
+ main: mainPath,
1177
+ miniflare: miniflareOptionsSource(callees, isolate, callerServices, env)
1178
+ }, o.console === true));
1179
+ } else writeFileSync(configPath, vitestConfigSource(wrangler, testPath, reportPath, loaded ? {
1180
+ main: resolve(dir, loaded.worker.entry),
1181
+ ...callerServices.length > 0 || Object.keys(env).length > 0 ? { miniflare: miniflareOptionsSource([], void 0, callerServices, env) } : {}
1182
+ } : void 0, o.console === true));
1183
+ rmSync(consoleFile(reportPath), { force: true });
1184
+ const { code, output } = await runVitest(vitestBin(dir), configPath, dir);
1185
+ if (o.console === true) o.stderr(consoleOutput(consoleFile(reportPath)));
1186
+ const left = (path) => existsSync(path) ? readFileSync(path, "utf8") : void 0;
1187
+ const ran = {
1188
+ report: left(reportPath),
1189
+ unhandled: left(unhandledErrorsFile(reportPath))
1190
+ };
1191
+ const stray = code === 0 ? void 0 : strayErrors(ran);
1192
+ const transport = code === 0 || stray !== void 0 ? readTransport(reportPath) : null;
1193
+ if (!transport) {
1194
+ const why = vitestFailure(ran);
1195
+ o.stderr(`eutaxy check could not read a verdict from Vitest (exit ${code}):\n${why}Vitest's output:\n${output}\n`);
1196
+ return exitCodes.error;
1197
+ }
1198
+ if (stray !== void 0) o.stderr(strayNote(stray));
1199
+ if (transport.specErrors && transport.specErrors.length > 0) {
1200
+ for (const e of transport.specErrors) o.stderr(`${e.module}${e.line > 0 ? `:${e.line}` : ""}: ${e.message}\n`);
1201
+ return exitCodes.error;
1202
+ }
1203
+ const report = transport.report;
1204
+ const verdict = report.verdict;
1205
+ let specs = report.specs ?? [];
1206
+ if (engines.length > 0) specs = await proveSpecs(dir, transport.observed ?? [], specs, engines, specModules);
1207
+ const regressionPath = (verdict.kind === "VIOLATED" || verdict.kind === "UNSUPPORTED" && verdict.cause === "unsupported_api" && verdict.replay !== void 0) && !o.noRegression ? o.out ? resolve(o.cwd, o.out) : join(dir, `${name}.regression.test.ts`) : void 0;
1208
+ const printed = {
1209
+ ...transport.report,
1210
+ ...o.provers && o.provers.length > 0 ? { specs } : {},
1211
+ ...regressionPath === void 0 ? {} : { regressionTest: toPosix(relative(o.cwd, regressionPath) || regressionPath) },
1212
+ ...stray === void 0 ? {} : { unhandledErrors: stray }
1213
+ };
1214
+ if (o.json) o.stdout(`${canonicalJson(printed)}\n`);
1215
+ else o.stdout(`${renderText(verdict)}\n${specs.length > 0 ? `\n${renderSpecs(specs)}\n` : ""}`);
1216
+ if (regressionPath !== void 0) {
1217
+ const outPath = regressionPath;
1218
+ const outDir = dirname(outPath);
1219
+ const schemaPaths = {};
1220
+ for (const step of transport.setup) if (step.kind === "d1") {
1221
+ const binding = String(step["binding"]);
1222
+ const path = toPosix(relative(outDir, resolve(dir, String(step["schemaFile"]))));
1223
+ schemaPaths[binding] = [...schemaPaths[binding] ?? [], path];
1224
+ }
1225
+ const calleePaths = {};
1226
+ for (const step of transport.setup) {
1227
+ if (step.kind !== "callee") continue;
1228
+ const binding = String(step["binding"]);
1229
+ const carried = transport.callees?.[binding];
1230
+ if (carried === void 0) continue;
1231
+ calleePaths[binding] = {
1232
+ ...carried,
1233
+ path: toPosix(relative(outDir, resolve(dir, String(step["entry"]))))
1234
+ };
1235
+ }
1236
+ const testOptions = {
1237
+ scenarioPath: toPosix(relative(outDir, scenarioPath)),
1238
+ workerPath: toPosix(relative(outDir, resolve(dir, transport.worker.entry))),
1239
+ schemaPaths,
1240
+ ...Object.keys(calleePaths).length === 0 ? {} : {
1241
+ callees: calleePaths,
1242
+ calleeBindings: isolateBindings(callees).filter((b) => !(b in isolate.aliases)),
1243
+ ...transport.aliases === void 0 ? {} : { aliases: transport.aliases }
1244
+ },
1245
+ ...Object.keys(env).length === 0 ? {} : { envBindings: Object.keys(env) },
1246
+ ...o.budgetMs === void 0 ? {} : { budgetMs: o.budgetMs },
1247
+ ...needsObjectHelpers(transport.setup) ? { durableObjects: true } : {},
1248
+ ...transport.setup.some((s) => s.kind === "workflow") || transport.drive?.kind === "rpc" && transport.drive["entrypoint"] !== void 0 ? { exports: true } : {},
1249
+ ...o.expectViolation ? { expect: "violates" } : {},
1250
+ ...(transport.observed ?? []).length > 0 ? { specModules: (transport.observed ?? []).map((m) => ({
1251
+ path: toPosix(relative(outDir, resolve(dir, m.module))),
1252
+ functions: m.functions
1253
+ })) } : {}
1254
+ };
1255
+ const source = verdict.kind === "UNSUPPORTED" ? cloudflareUnsupportedTest(verdict, testOptions) : cloudflareRegressionTest(verdict, testOptions);
1256
+ mkdirSync(outDir, { recursive: true });
1257
+ writeFileSync(outPath, source);
1258
+ if (!o.json) o.stdout(`\n${verdict.kind === "UNSUPPORTED" ? "Test replaying the run" : "Regression test"} written to ${relative(o.cwd, outPath) || outPath}\n`);
1259
+ }
1260
+ if (verdict.kind !== "VIOLATED" && specs.some((v) => v.kind === "REFUTED" || v.kind === "CONFLICT")) return exitCodes.VIOLATED;
1261
+ return exitCodes[verdict.kind];
1262
+ } finally {
1263
+ if (!o.keep) cleanUp(workDir, stamp);
1264
+ }
1265
+ }
1266
+ /**
1267
+ * Remove this run's files; the shared ones and the directory go only when
1268
+ * no other run's files are left there (another check may still be using
1269
+ * them).
1270
+ */
1271
+ function cleanUp(workDir, stamp) {
1272
+ if (!existsSync(workDir)) return;
1273
+ for (const f of readdirSync(workDir)) if (f.includes(`.${stamp}.`)) rmSync(join(workDir, f), { force: true });
1274
+ if (!readdirSync(workDir).some((f) => /\.check\.test\.ts$|^vitest\.config\..*\.mts$|^vitest-report\./.test(f))) rmSync(workDir, {
1275
+ recursive: true,
1276
+ force: true
1277
+ });
1278
+ }
1279
+ export { proverNames as a, typescriptMissing as c, list as d, r2Bucket as f, resolveAsTypeScript as g, workerName as h, proveSpecs as i, typescriptNeeded as l, sqliteClasses as m, exitCodes as n, runCheck as o, readWranglerConfig as p, loadProver as r, findSpecModules as s, enginesNamed as t, d1Id as u };
1280
+
1281
+ //# sourceMappingURL=check-zkHLdWyf.mjs.map