eutaxy 0.5.0 → 0.5.1

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 (44) hide show
  1. package/README.md +1 -1
  2. package/dist/aws.d.mts +7 -5
  3. package/dist/aws.d.mts.map +1 -1
  4. package/dist/aws.mjs +41 -135
  5. package/dist/aws.mjs.map +1 -1
  6. package/dist/bin.mjs +2 -2
  7. package/dist/checked-CGpA2-F0.d.mts +285 -0
  8. package/dist/checked-CGpA2-F0.d.mts.map +1 -0
  9. package/dist/cli-IJrKkeYS.mjs +2 -0
  10. package/dist/cli.d.mts.map +1 -1
  11. package/dist/cli.mjs +2 -2
  12. package/dist/cloudflare.d.mts +158 -54
  13. package/dist/cloudflare.d.mts.map +1 -1
  14. package/dist/cloudflare.mjs +3 -1815
  15. package/dist/delivery-invariants-BraYqcYN.d.mts +5 -0
  16. package/dist/delivery-invariants-BraYqcYN.d.mts.map +1 -0
  17. package/dist/delivery-invariants-Cuxdna28.mjs +39 -0
  18. package/dist/delivery-invariants-Cuxdna28.mjs.map +1 -0
  19. package/dist/index.d.mts +22 -189
  20. package/dist/index.d.mts.map +1 -1
  21. package/dist/index.mjs +17 -197
  22. package/dist/index.mjs.map +1 -1
  23. package/dist/{platform-eVgCMbX0.d.mts → platform-DfMwknw1.d.mts} +94 -73
  24. package/dist/platform-DfMwknw1.d.mts.map +1 -0
  25. package/dist/{src-C19_yfMM.mjs → src-Bqc9Eyb1.mjs} +961 -543
  26. package/dist/src-Bqc9Eyb1.mjs.map +1 -0
  27. package/dist/src-DKb-fkdb.mjs +3399 -0
  28. package/dist/src-DKb-fkdb.mjs.map +1 -0
  29. package/dist/{src-CgfGiH25.mjs → src-Dxl9ZlKn.mjs} +223 -17
  30. package/dist/src-Dxl9ZlKn.mjs.map +1 -0
  31. package/package.json +1 -1
  32. package/dist/cli-NqY61bpo.mjs +0 -2
  33. package/dist/cloudflare.mjs.map +0 -1
  34. package/dist/explore-BHYvAZKN.d.mts +0 -84
  35. package/dist/explore-BHYvAZKN.d.mts.map +0 -1
  36. package/dist/platform-eVgCMbX0.d.mts.map +0 -1
  37. package/dist/src-BD3jkjgG.mjs +0 -477
  38. package/dist/src-BD3jkjgG.mjs.map +0 -1
  39. package/dist/src-C19_yfMM.mjs.map +0 -1
  40. package/dist/src-CgfGiH25.mjs.map +0 -1
  41. package/dist/src-s6uYyC0B.mjs +0 -89
  42. package/dist/src-s6uYyC0B.mjs.map +0 -1
  43. package/dist/verdict-evEM5Gxx.mjs +0 -12
  44. package/dist/verdict-evEM5Gxx.mjs.map +0 -1
@@ -1,477 +0,0 @@
1
- import { i as canonicalJson } from "./src-s6uYyC0B.mjs";
2
- import { a as emitRegressionTest, n as renderSpecs, o as predicateSource, r as renderText, s as extractSpecs } from "./src-CgfGiH25.mjs";
3
- import { createRequire } from "node:module";
4
- import { spawn } from "node:child_process";
5
- import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
6
- import { basename, dirname, join, relative, resolve } from "node:path";
7
- // packages/cli/src/args.ts
8
- function parseArgs(argv, booleans = []) {
9
- const positionals = [];
10
- const flags = {};
11
- for (let i = 0; i < argv.length; i++) {
12
- const a = argv[i];
13
- if (!a.startsWith("--")) {
14
- positionals.push(a);
15
- continue;
16
- }
17
- const eq = a.indexOf("=");
18
- if (eq !== -1) {
19
- flags[a.slice(2, eq)] = a.slice(eq + 1);
20
- continue;
21
- }
22
- const name = a.slice(2);
23
- const next = argv[i + 1];
24
- if (booleans.includes(name) || next === void 0 || next.startsWith("--")) flags[name] = true;
25
- else {
26
- flags[name] = next;
27
- i++;
28
- }
29
- }
30
- return {
31
- positionals,
32
- flags
33
- };
34
- }
35
- // packages/cli/src/generate.ts
36
- /**
37
- * The files `eutaxy check` writes into `<scenario dir>/.eutaxy/` before
38
- * running Vitest: a test that performs the check inside workerd and prints
39
- * the verdict on one marked line, and a Vitest config with the Cloudflare
40
- * plugin pointed at the scenario's wrangler config.
41
- */
42
- /** Key under which the generated test stores its result in the Vitest task meta, read back from the JSON reporter. */
43
- const metaKey = "eutaxy";
44
- function checkTestSource(g) {
45
- const maxRuns = (g.maxRuns === void 0 ? "" : `, maxRuns: ${g.maxRuns}`) + (g.exhaustive ? ", exhaustive: true" : "");
46
- return `// Generated by eutaxy check; deleted after the run.
47
- import { checkSpecModule, observeCore, renderJson } from "eutaxy";
48
- import { check, createCloudflarePlatform, type QueueHandler } from "eutaxy/cloudflare";
49
- import { env } from "cloudflare:workers";
50
- import * as cloudflareTest from "cloudflare:test";
51
- import { test } from "vitest";
52
- import scenario from ${JSON.stringify(g.scenarioImport)};
53
- import { specLoaders } from "./specs.ts";
54
-
55
- const sqlFiles = import.meta.glob("../**/*.sql", { query: "?raw", import: "default", eager: true }) as Record<string, string>;
56
- const modules = import.meta.glob(["../**/*.ts", "!../**/*.test.ts", "!../**/*.sim.ts", "!../**/node_modules/**", "!../**/.eutaxy/**"]) as Record<string, () => Promise<{ default: QueueHandler }>>;
57
-
58
- function key(path: string): string {
59
- return \`../\${path.replace(/^\\.\\//, "")}\`;
60
- }
61
-
62
- test("eutaxy check", async ({ task }) => {
63
- const schemas: Record<string, string> = {};
64
- for (const step of scenario.setup) {
65
- if (step.kind !== "d1") continue;
66
- const sql = sqlFiles[key(String(step.schemaFile))];
67
- if (sql === undefined) throw new Error(\`schema file \${String(step.schemaFile)} not found next to the scenario\`);
68
- schemas[String(step.binding)] = sql;
69
- }
70
- const load = modules[key(scenario.worker.entry)];
71
- if (!load) throw new Error(\`worker entry \${scenario.worker.entry} not found next to the scenario\`);
72
- const handler = (await load()).default;
73
- const platform = createCloudflarePlatform({ env, handler, schemas, durableObjects: cloudflareTest });
74
- // The modules the scenario's specs name: their annotated functions, and the core functions
75
- // refines invariants name, are observed while it runs.
76
- const decisions = scenario.invariants.flatMap((i) => (i.kind === "refines" ? [i.decision] : []));
77
- const specErrors: { module: string; line: number; message: string }[] = [];
78
- const selected = [];
79
- for (const path of scenario.specs ?? []) {
80
- const specKey = \`./\${path.replace(/^(\\.\\/)+/, "")}\`;
81
- const loadSpec = modules[key(path)];
82
- if (!loadSpec) {
83
- specErrors.push({ module: path, line: 0, message: "no such module next to the scenario" });
84
- continue;
85
- }
86
- const namespace = await loadSpec();
87
- const entry = specLoaders[specKey] ? await specLoaders[specKey]() : undefined;
88
- const specs = entry?.specs ?? { functions: [], exports: [], errors: [] };
89
- for (const e of specs.errors) specErrors.push({ module: path, ...e });
90
- const names = [...new Set([...specs.functions.map((f) => f.name), ...decisions.filter((d) => typeof (namespace as Record<string, unknown>)[d] === "function")])];
91
- selected.push({ path, key: specKey, namespace, specs, predicates: entry ? entry.predicates(namespace) : {}, names });
92
- }
93
- // Decisions are logged by function name: one name in two modules would make them ambiguous.
94
- const observedIn = new Map<string, string>();
95
- for (const m of selected)
96
- for (const n of m.names) {
97
- const other = observedIn.get(n);
98
- if (other !== undefined) specErrors.push({ module: m.path, line: 0, message: \`\${n} is observed in both \${other} and \${m.path}; decisions of one name must come from one module\` });
99
- else observedIn.set(n, m.path);
100
- }
101
- if (specErrors.length > 0) {
102
- task.meta[${JSON.stringify(metaKey)}] = { report: null, specErrors, worker: scenario.worker, setup: scenario.setup };
103
- return;
104
- }
105
- const observers = selected.map((m) => observeCore(m.namespace, m.names));
106
- let verdict;
107
- try {
108
- verdict = await check(scenario, platform, { seed: ${JSON.stringify(g.seed)}${maxRuns} });
109
- } finally {
110
- for (const o of observers) o.restore();
111
- }
112
- const specs = selected.flatMap((m, i) => checkSpecModule(m.key, m.specs, m.predicates, observers[i]));
113
- const observed = selected.map((m) => ({ module: m.path, functions: m.names }));
114
- task.meta[${JSON.stringify(metaKey)}] = { report: JSON.parse(renderJson(verdict, specs)), worker: scenario.worker, setup: scenario.setup, observed };
115
- });
116
- `;
117
- }
118
- function vitestConfigSource(wranglerConfigPath, testPath, outputFile) {
119
- return `// Generated by eutaxy check; deleted after the run.
120
- import { cloudflareTest } from "@cloudflare/vitest-plugin";
121
- import { defineConfig } from "vitest/config";
122
-
123
- export default defineConfig({
124
- plugins: [cloudflareTest({ wrangler: { configPath: ${JSON.stringify(wranglerConfigPath)} } })],
125
- test: {
126
- include: [${JSON.stringify(testPath)}],
127
- testTimeout: 600_000,
128
- reporters: ["json"],
129
- outputFile: ${JSON.stringify(outputFile)},
130
- },
131
- });
132
- `;
133
- }
134
- // packages/cli/src/regression.ts
135
- /** A Vitest regression test for a Cloudflare scenario, to run under the Cloudflare Vitest plugin. */
136
- function cloudflareRegressionTest(verdict, options) {
137
- const bindings = Object.keys(options.schemaPaths).sort();
138
- const imports = [
139
- "import { createCloudflarePlatform } from \"eutaxy/cloudflare\";",
140
- "import { env } from \"cloudflare:workers\";",
141
- ...options.durableObjects ? ["import * as cloudflareTest from \"cloudflare:test\";"] : [],
142
- `import scenario from ${JSON.stringify(options.scenarioPath)};`,
143
- ...bindings.map((b) => `import schema_${b} from ${JSON.stringify(`${options.schemaPaths[b]}?raw`)};`),
144
- `import handler from ${JSON.stringify(options.workerPath)};`,
145
- ...(options.specModules ?? []).map((m, i) => `import * as core_${i} from ${JSON.stringify(m.path)};`)
146
- ];
147
- const schemas = `{ ${bindings.map((b) => `${b}: schema_${b}`).join(", ")} }`;
148
- const retries = options.maxRetries === void 0 ? "" : `, maxRetries: ${options.maxRetries}`;
149
- const objects = options.durableObjects ? ", durableObjects: cloudflareTest" : "";
150
- return emitRegressionTest(verdict, {
151
- imports,
152
- platform: `createCloudflarePlatform({ env, handler, schemas: ${schemas}${retries}${objects} })`,
153
- scenario: "scenario",
154
- ...options.expect ? { expect: options.expect } : {},
155
- ...options.engineModule ? { engineModule: options.engineModule } : {},
156
- ...options.specModules && options.specModules.length > 0 ? { observe: options.specModules.map((m, i) => ({
157
- namespace: `core_${i}`,
158
- functions: m.functions
159
- })) } : {}
160
- });
161
- }
162
- // packages/cli/src/specs.ts
163
- /**
164
- * Spec modules for `eutaxy check`: every TypeScript module next to the
165
- * scenario with Lemma annotations, and the generated module that holds
166
- * their predicates as compiled code (workerd runs no `eval`). Which of them
167
- * a run checks is the scenario's `specs`, read where the scenario is loaded,
168
- * inside the generated test.
169
- */
170
- const skipDirs = /* @__PURE__ */ new Set([
171
- "node_modules",
172
- ".eutaxy",
173
- "dist",
174
- ".git"
175
- ]);
176
- /** Normalize a module path from a scenario's `specs` to a key. */
177
- function specKey(path) {
178
- return `./${path.split("\\").join("/").replace(/^(\.\/)+/, "")}`;
179
- }
180
- /** Annotated modules under `dir`, tests and scenarios excepted. */
181
- function findSpecModules(dir) {
182
- const out = [];
183
- const walk = (at) => {
184
- for (const entry of readdirSync(at, { withFileTypes: true })) {
185
- const path = join(at, entry.name);
186
- if (entry.isDirectory()) {
187
- if (!skipDirs.has(entry.name)) walk(path);
188
- continue;
189
- }
190
- const name = entry.name;
191
- if (!name.endsWith(".ts") || name.endsWith(".d.ts") || name.endsWith(".test.ts") || name.endsWith(".sim.ts")) continue;
192
- const source = readFileSync(path, "utf8");
193
- if (!/@(ensures|total|throws)\b/.test(source)) continue;
194
- const specs = extractSpecs(source);
195
- if (specs.functions.length === 0 && specs.errors.length === 0) continue;
196
- out.push({
197
- key: specKey(relative(dir, path)),
198
- path,
199
- specs
200
- });
201
- }
202
- };
203
- walk(dir);
204
- return out.sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
205
- }
206
- /** The generated module's own names; each predicate takes them as parameters, so nothing in a property shadows them. */
207
- const helpers = {
208
- bool: "__eutaxyBool",
209
- same: "__eutaxySame",
210
- scope: "__eutaxyNamespace",
211
- unresolved: "__eutaxyUnresolved"
212
- };
213
- /**
214
- * The generated spec files: `specs.ts`, which maps each annotated module's
215
- * key to a loader, and one file per module with its extracted specs and a
216
- * function from its namespace to its predicates. A module's file loads only
217
- * when a scenario names the module, so an annotation elsewhere that does not
218
- * compile cannot stop a check. Each predicate binds its free names from the
219
- * namespace (else the globals) when it is built, which happens before
220
- * anything is observed, so checking a property never counts as a call the
221
- * simulator made.
222
- */
223
- function specFiles(modules) {
224
- const header = "// Generated by eutaxy check; deleted after the run.";
225
- const index = [
226
- header,
227
- "export const specLoaders: Record<string, () => Promise<{ specs: any; predicates: (ns: any) => any }>> = {",
228
- ...modules.map((m, i) => ` ${JSON.stringify(m.key)}: () => import("./specs/m${i}.ts"),`),
229
- "};"
230
- ];
231
- const files = modules.map((m, i) => {
232
- const lines = [
233
- header,
234
- `import { lemmaBool as ${helpers.bool}, lemmaUnresolved as ${helpers.unresolved} } from "eutaxy";`,
235
- `const ${helpers.same} = Object.is;`,
236
- "",
237
- `export const specs = ${JSON.stringify(m.specs)};`,
238
- "",
239
- `export const predicates = (${helpers.scope}: any) => ({`
240
- ];
241
- for (const fn of m.specs.functions) {
242
- lines.push(` [${JSON.stringify(fn.name)}]: {`);
243
- for (const p of fn.ensures) {
244
- const source = predicateSource(p.property, helpers).split("\n").join("\n ");
245
- lines.push(` [${JSON.stringify(p.name)}]: ${source},`);
246
- }
247
- lines.push(" },");
248
- }
249
- lines.push("});");
250
- return {
251
- name: `specs/m${i}.ts`,
252
- source: `${lines.join("\n")}\n`
253
- };
254
- });
255
- return [{
256
- name: "specs.ts",
257
- source: `${index.join("\n")}\n`
258
- }, ...files];
259
- }
260
- // packages/cli/src/check.ts
261
- /**
262
- * `eutaxy check <scenario.sim.ts>`: run a scenario inside workerd through
263
- * the user's Vitest and the Cloudflare plugin, print the verdict as text or
264
- * JSON, and on a violation write a regression test next to the scenario.
265
- */
266
- const exitCodes = {
267
- BOUNDED: 0,
268
- VIOLATED: 1,
269
- UNSUPPORTED: 2,
270
- error: 3
271
- };
272
- function findWrangler(dir, explicit, cwd) {
273
- if (explicit) return resolve(cwd, explicit);
274
- for (const name of [
275
- "wrangler.jsonc",
276
- "wrangler.json",
277
- "wrangler.toml"
278
- ]) {
279
- const p = join(dir, name);
280
- if (existsSync(p)) return p;
281
- }
282
- return null;
283
- }
284
- function vitestBin(from) {
285
- const req = createRequire(join(from, "package.json"));
286
- return join(dirname(req.resolve("vitest/package.json")), "vitest.mjs");
287
- }
288
- function runVitest(bin, configPath, cwd) {
289
- return new Promise((resolveRun) => {
290
- const child = spawn(process.execPath, [
291
- bin,
292
- "run",
293
- "--config",
294
- configPath
295
- ], {
296
- cwd,
297
- env: {
298
- ...process.env,
299
- CI: "1",
300
- FORCE_COLOR: "0"
301
- },
302
- stdio: [
303
- "ignore",
304
- "pipe",
305
- "pipe"
306
- ]
307
- });
308
- let output = "";
309
- child.stdout.on("data", (d) => {
310
- output += d.toString();
311
- });
312
- child.stderr.on("data", (d) => {
313
- output += d.toString();
314
- });
315
- child.on("close", (code) => resolveRun({
316
- code: code ?? 1,
317
- output
318
- }));
319
- });
320
- }
321
- /** The transport the generated test left in its task meta, via Vitest's JSON reporter. */
322
- function readTransport(reportPath) {
323
- if (!existsSync(reportPath)) return null;
324
- const report = JSON.parse(readFileSync(reportPath, "utf8"));
325
- for (const file of report.testResults ?? []) for (const t of file.assertionResults ?? []) {
326
- const m = t.meta?.[metaKey];
327
- if (m) return m;
328
- }
329
- return null;
330
- }
331
- function toPosix(p) {
332
- const s = p.split("\\").join("/");
333
- return s.startsWith(".") ? s : `./${s}`;
334
- }
335
- async function runCheck(o) {
336
- const scenarioPath = resolve(o.cwd, o.scenario);
337
- if (!existsSync(scenarioPath)) {
338
- o.stderr(`scenario not found: ${scenarioPath}\n`);
339
- return exitCodes.error;
340
- }
341
- const dir = dirname(scenarioPath);
342
- const name = basename(scenarioPath).replace(/\.sim\.ts$/, "").replace(/\.ts$/, "");
343
- const wrangler = findWrangler(dir, o.wrangler, o.cwd);
344
- if (!wrangler || !existsSync(wrangler)) {
345
- o.stderr(`no wrangler config found next to the scenario; pass --wrangler <path>\n`);
346
- return exitCodes.error;
347
- }
348
- const workDir = join(dir, ".eutaxy");
349
- const testPath = join(workDir, `${name}.check.test.ts`);
350
- const configPath = join(workDir, "vitest.config.mts");
351
- mkdirSync(workDir, { recursive: true });
352
- try {
353
- writeFileSync(testPath, checkTestSource({
354
- seed: o.seed ?? name,
355
- ...o.maxRuns === void 0 ? {} : { maxRuns: o.maxRuns },
356
- ...o.exhaustive ? { exhaustive: true } : {},
357
- scenarioImport: `../${basename(scenarioPath)}`
358
- }));
359
- for (const f of specFiles(findSpecModules(dir))) {
360
- mkdirSync(dirname(join(workDir, f.name)), { recursive: true });
361
- writeFileSync(join(workDir, f.name), f.source);
362
- }
363
- const reportPath = join(workDir, "vitest-report.json");
364
- rmSync(reportPath, { force: true });
365
- writeFileSync(configPath, vitestConfigSource(wrangler, testPath, reportPath));
366
- const { code, output } = await runVitest(vitestBin(dir), configPath, dir);
367
- const transport = code === 0 ? readTransport(reportPath) : null;
368
- if (!transport) {
369
- o.stderr(`eutaxy check could not read a verdict from Vitest (exit ${code}):\n${output}\n`);
370
- return exitCodes.error;
371
- }
372
- if (transport.specErrors && transport.specErrors.length > 0) {
373
- for (const e of transport.specErrors) o.stderr(`${e.module}${e.line > 0 ? `:${e.line}` : ""}: ${e.message}\n`);
374
- return exitCodes.error;
375
- }
376
- const report = transport.report;
377
- const verdict = report.verdict;
378
- const specs = report.specs ?? [];
379
- if (o.json) o.stdout(`${canonicalJson(transport.report)}\n`);
380
- else o.stdout(`${renderText(verdict)}\n${specs.length > 0 ? `\n${renderSpecs(specs)}\n` : ""}`);
381
- if (verdict.kind === "VIOLATED" && !o.noRegression) {
382
- const outPath = o.out ? resolve(o.cwd, o.out) : join(dir, `${name}.regression.test.ts`);
383
- const outDir = dirname(outPath);
384
- const schemaPaths = {};
385
- for (const step of transport.setup) if (step.kind === "d1") schemaPaths[String(step["binding"])] = toPosix(relative(outDir, resolve(dir, String(step["schemaFile"]))));
386
- const source = cloudflareRegressionTest(verdict, {
387
- scenarioPath: toPosix(relative(outDir, scenarioPath)),
388
- workerPath: toPosix(relative(outDir, resolve(dir, transport.worker.entry))),
389
- schemaPaths,
390
- ...transport.setup.some((s) => s.kind === "durable_object") ? { durableObjects: true } : {},
391
- ...o.expectViolation ? { expect: "violates" } : {},
392
- ...(transport.observed ?? []).length > 0 ? { specModules: (transport.observed ?? []).map((m) => ({
393
- path: toPosix(relative(outDir, resolve(dir, m.module))),
394
- functions: m.functions
395
- })) } : {}
396
- });
397
- mkdirSync(outDir, { recursive: true });
398
- writeFileSync(outPath, source);
399
- if (!o.json) o.stdout(`\nRegression test written to ${relative(o.cwd, outPath) || outPath}\n`);
400
- }
401
- if (verdict.kind !== "VIOLATED" && specs.some((v) => v.kind === "REFUTED")) return exitCodes.VIOLATED;
402
- return exitCodes[verdict.kind];
403
- } finally {
404
- if (!o.keep) rmSync(workDir, {
405
- recursive: true,
406
- force: true
407
- });
408
- }
409
- }
410
- // packages/cli/src/main.ts
411
- const usage = `eutaxy — deterministic simulation checks for Cloudflare Workers
412
-
413
- Usage:
414
- eutaxy check <scenario.sim.ts> [options]
415
-
416
- Options:
417
- --wrangler <path> wrangler config (default: wrangler.jsonc/json/toml beside the scenario)
418
- --seed <seed> exploration seed (default: the scenario file name)
419
- --max-runs <n> cap on exploration runs in addition to the scenario's time budget
420
- --exhaustive run every schedule within the bounds once (with partial-order reduction)
421
- --json print the versioned JSON report instead of text
422
- --out <path> where to write the regression test on a violation
423
- --no-regression do not write a regression test
424
- --expect-violation write a regression test that asserts the violation (for corpora)
425
- --keep keep the generated .eutaxy/ files
426
-
427
- Exit codes: 0 BOUNDED, 1 VIOLATED or a REFUTED spec, 2 UNSUPPORTED, 3 error.
428
- `;
429
- async function main(argv, io) {
430
- const { positionals, flags } = parseArgs(argv, [
431
- "json",
432
- "no-regression",
433
- "expect-violation",
434
- "keep",
435
- "help",
436
- "exhaustive"
437
- ]);
438
- const command = positionals[0];
439
- if (!command || command === "help" || flags["help"] === true) {
440
- io.stdout(usage);
441
- return command ? exitCodes.BOUNDED : exitCodes.error;
442
- }
443
- if (command !== "check") {
444
- io.stderr(`unknown command ${command}\n\n${usage}`);
445
- return exitCodes.error;
446
- }
447
- const scenario = positionals[1];
448
- if (!scenario) {
449
- io.stderr(`check needs a scenario file\n\n${usage}`);
450
- return exitCodes.error;
451
- }
452
- const str = (k) => typeof flags[k] === "string" ? flags[k] : void 0;
453
- const maxRunsText = str("max-runs");
454
- const maxRuns = maxRunsText === void 0 ? void 0 : Number(maxRunsText);
455
- if (maxRuns !== void 0 && !(Number.isInteger(maxRuns) && maxRuns > 0)) {
456
- io.stderr(`--max-runs must be a positive integer, got ${JSON.stringify(maxRunsText)}\n`);
457
- return exitCodes.error;
458
- }
459
- return runCheck({
460
- scenario,
461
- cwd: io.cwd,
462
- ...str("wrangler") ? { wrangler: str("wrangler") } : {},
463
- ...str("seed") ? { seed: str("seed") } : {},
464
- ...maxRuns === void 0 ? {} : { maxRuns },
465
- exhaustive: flags["exhaustive"] === true,
466
- json: flags["json"] === true,
467
- ...str("out") ? { out: str("out") } : {},
468
- noRegression: flags["no-regression"] === true,
469
- expectViolation: flags["expect-violation"] === true,
470
- keep: flags["keep"] === true,
471
- stdout: io.stdout,
472
- stderr: io.stderr
473
- });
474
- }
475
- export { cloudflareRegressionTest as n, main as t };
476
-
477
- //# sourceMappingURL=src-BD3jkjgG.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"src-BD3jkjgG.mjs","names":[],"sources":["../../cli/src/args.ts","../../cli/src/generate.ts","../../cli/src/regression.ts","../../cli/src/specs.ts","../../cli/src/check.ts","../../cli/src/main.ts"],"sourcesContent":["/** A small argument parser: positionals, `--flag value`, `--flag=value` and boolean `--flag`. */\n\nexport interface ParsedArgs {\n readonly positionals: readonly string[];\n readonly flags: Readonly<Record<string, string | true>>;\n}\n\nexport function parseArgs(argv: readonly string[], booleans: readonly string[] = []): ParsedArgs {\n const positionals: string[] = [];\n const flags: Record<string, string | true> = {};\n for (let i = 0; i < argv.length; i++) {\n const a = argv[i] as string;\n if (!a.startsWith(\"--\")) {\n positionals.push(a);\n continue;\n }\n const eq = a.indexOf(\"=\");\n if (eq !== -1) {\n flags[a.slice(2, eq)] = a.slice(eq + 1);\n continue;\n }\n const name = a.slice(2);\n const next = argv[i + 1];\n if (booleans.includes(name) || next === undefined || next.startsWith(\"--\")) {\n flags[name] = true;\n } else {\n flags[name] = next;\n i++;\n }\n }\n return { positionals, flags };\n}\n","/**\n * The files `eutaxy check` writes into `<scenario dir>/.eutaxy/` before\n * running Vitest: a test that performs the check inside workerd and prints\n * the verdict on one marked line, and a Vitest config with the Cloudflare\n * plugin pointed at the scenario's wrangler config.\n */\n\n/** Key under which the generated test stores its result in the Vitest task meta, read back from the JSON reporter. */\nexport const metaKey = \"eutaxy\";\n\nexport interface GeneratedCheck {\n readonly seed: string;\n readonly maxRuns?: number;\n /** Exhaustive exploration instead of seeded. */\n readonly exhaustive?: boolean;\n /** Import specifier of the scenario from the generated test (e.g. \"../scenario.sim.ts\"). */\n readonly scenarioImport: string;\n}\n\n/** What the generated test stores in its task meta. */\nexport interface CheckTransport {\n readonly report: unknown;\n /** Set instead of a report when a module the scenario's `specs` names has no usable annotations. */\n readonly specErrors?: readonly {\n readonly module: string;\n readonly line: number;\n readonly message: string;\n }[];\n readonly worker: { readonly entry: string; readonly config: string };\n readonly setup: readonly { readonly kind: string; readonly [key: string]: unknown }[];\n /** The core modules observed (as the scenario's specs name them) and the functions on each. */\n readonly observed?: readonly { readonly module: string; readonly functions: readonly string[] }[];\n}\n\nexport function checkTestSource(g: GeneratedCheck): string {\n const maxRuns =\n (g.maxRuns === undefined ? \"\" : `, maxRuns: ${g.maxRuns}`) +\n (g.exhaustive ? \", exhaustive: true\" : \"\");\n return `// Generated by eutaxy check; deleted after the run.\nimport { checkSpecModule, observeCore, renderJson } from \"eutaxy\";\nimport { check, createCloudflarePlatform, type QueueHandler } from \"eutaxy/cloudflare\";\nimport { env } from \"cloudflare:workers\";\nimport * as cloudflareTest from \"cloudflare:test\";\nimport { test } from \"vitest\";\nimport scenario from ${JSON.stringify(g.scenarioImport)};\nimport { specLoaders } from \"./specs.ts\";\n\nconst sqlFiles = import.meta.glob(\"../**/*.sql\", { query: \"?raw\", import: \"default\", eager: true }) as Record<string, string>;\nconst modules = import.meta.glob([\"../**/*.ts\", \"!../**/*.test.ts\", \"!../**/*.sim.ts\", \"!../**/node_modules/**\", \"!../**/.eutaxy/**\"]) as Record<string, () => Promise<{ default: QueueHandler }>>;\n\nfunction key(path: string): string {\n return \\`../\\${path.replace(/^\\\\.\\\\//, \"\")}\\`;\n}\n\ntest(\"eutaxy check\", async ({ task }) => {\n const schemas: Record<string, string> = {};\n for (const step of scenario.setup) {\n if (step.kind !== \"d1\") continue;\n const sql = sqlFiles[key(String(step.schemaFile))];\n if (sql === undefined) throw new Error(\\`schema file \\${String(step.schemaFile)} not found next to the scenario\\`);\n schemas[String(step.binding)] = sql;\n }\n const load = modules[key(scenario.worker.entry)];\n if (!load) throw new Error(\\`worker entry \\${scenario.worker.entry} not found next to the scenario\\`);\n const handler = (await load()).default;\n const platform = createCloudflarePlatform({ env, handler, schemas, durableObjects: cloudflareTest });\n // The modules the scenario's specs name: their annotated functions, and the core functions\n // refines invariants name, are observed while it runs.\n const decisions = scenario.invariants.flatMap((i) => (i.kind === \"refines\" ? [i.decision] : []));\n const specErrors: { module: string; line: number; message: string }[] = [];\n const selected = [];\n for (const path of scenario.specs ?? []) {\n const specKey = \\`./\\${path.replace(/^(\\\\.\\\\/)+/, \"\")}\\`;\n const loadSpec = modules[key(path)];\n if (!loadSpec) {\n specErrors.push({ module: path, line: 0, message: \"no such module next to the scenario\" });\n continue;\n }\n const namespace = await loadSpec();\n const entry = specLoaders[specKey] ? await specLoaders[specKey]() : undefined;\n const specs = entry?.specs ?? { functions: [], exports: [], errors: [] };\n for (const e of specs.errors) specErrors.push({ module: path, ...e });\n const names = [...new Set([...specs.functions.map((f) => f.name), ...decisions.filter((d) => typeof (namespace as Record<string, unknown>)[d] === \"function\")])];\n selected.push({ path, key: specKey, namespace, specs, predicates: entry ? entry.predicates(namespace) : {}, names });\n }\n // Decisions are logged by function name: one name in two modules would make them ambiguous.\n const observedIn = new Map<string, string>();\n for (const m of selected)\n for (const n of m.names) {\n const other = observedIn.get(n);\n if (other !== undefined) specErrors.push({ module: m.path, line: 0, message: \\`\\${n} is observed in both \\${other} and \\${m.path}; decisions of one name must come from one module\\` });\n else observedIn.set(n, m.path);\n }\n if (specErrors.length > 0) {\n task.meta[${JSON.stringify(metaKey)}] = { report: null, specErrors, worker: scenario.worker, setup: scenario.setup };\n return;\n }\n const observers = selected.map((m) => observeCore(m.namespace, m.names));\n let verdict;\n try {\n verdict = await check(scenario, platform, { seed: ${JSON.stringify(g.seed)}${maxRuns} });\n } finally {\n for (const o of observers) o.restore();\n }\n const specs = selected.flatMap((m, i) => checkSpecModule(m.key, m.specs, m.predicates, observers[i]));\n const observed = selected.map((m) => ({ module: m.path, functions: m.names }));\n task.meta[${JSON.stringify(metaKey)}] = { report: JSON.parse(renderJson(verdict, specs)), worker: scenario.worker, setup: scenario.setup, observed };\n});\n`;\n}\n\nexport function vitestConfigSource(\n wranglerConfigPath: string,\n testPath: string,\n outputFile: string,\n): string {\n return `// Generated by eutaxy check; deleted after the run.\nimport { cloudflareTest } from \"@cloudflare/vitest-plugin\";\nimport { defineConfig } from \"vitest/config\";\n\nexport default defineConfig({\n plugins: [cloudflareTest({ wrangler: { configPath: ${JSON.stringify(wranglerConfigPath)} } })],\n test: {\n include: [${JSON.stringify(testPath)}],\n testTimeout: 600_000,\n reporters: [\"json\"],\n outputFile: ${JSON.stringify(outputFile)},\n },\n});\n`;\n}\n","import type { Violated } from \"@eutaxy/core\";\nimport { emitRegressionTest } from \"@eutaxy/report\";\n\nexport interface CloudflareRegressionOptions {\n /** Import path of the scenario module, relative to the emitted file. */\n readonly scenarioPath: string;\n /** Import path of the Worker module. */\n readonly workerPath: string;\n /** D1 binding name to schema file path, imported with `?raw`. */\n readonly schemaPaths: Readonly<Record<string, string>>;\n /** The platform's retry limit, when the scenario was checked with a non-default one. */\n readonly maxRetries?: number;\n /** The scenario sets up Durable Objects: pass the Cloudflare test helpers to the platform. */\n readonly durableObjects?: boolean;\n readonly expect?: \"holds\" | \"violates\";\n readonly engineModule?: string;\n /** Core modules to observe during the replay (import path, functions), for `refines`. */\n readonly specModules?: readonly {\n readonly path: string;\n readonly functions: readonly string[];\n }[];\n}\n\n/** A Vitest regression test for a Cloudflare scenario, to run under the Cloudflare Vitest plugin. */\nexport function cloudflareRegressionTest(\n verdict: Violated,\n options: CloudflareRegressionOptions,\n): string {\n const bindings = Object.keys(options.schemaPaths).sort();\n const imports = [\n 'import { createCloudflarePlatform } from \"eutaxy/cloudflare\";',\n 'import { env } from \"cloudflare:workers\";',\n ...(options.durableObjects ? ['import * as cloudflareTest from \"cloudflare:test\";'] : []),\n `import scenario from ${JSON.stringify(options.scenarioPath)};`,\n ...bindings.map(\n (b) => `import schema_${b} from ${JSON.stringify(`${options.schemaPaths[b]}?raw`)};`,\n ),\n `import handler from ${JSON.stringify(options.workerPath)};`,\n ...(options.specModules ?? []).map(\n (m, i) => `import * as core_${i} from ${JSON.stringify(m.path)};`,\n ),\n ];\n const schemas = `{ ${bindings.map((b) => `${b}: schema_${b}`).join(\", \")} }`;\n const retries = options.maxRetries === undefined ? \"\" : `, maxRetries: ${options.maxRetries}`;\n const objects = options.durableObjects ? \", durableObjects: cloudflareTest\" : \"\";\n return emitRegressionTest(verdict, {\n imports,\n platform: `createCloudflarePlatform({ env, handler, schemas: ${schemas}${retries}${objects} })`,\n scenario: \"scenario\",\n ...(options.expect ? { expect: options.expect } : {}),\n ...(options.engineModule ? { engineModule: options.engineModule } : {}),\n ...(options.specModules && options.specModules.length > 0\n ? {\n observe: options.specModules.map((m, i) => ({\n namespace: `core_${i}`,\n functions: m.functions,\n })),\n }\n : {}),\n });\n}\n","/**\n * Spec modules for `eutaxy check`: every TypeScript module next to the\n * scenario with Lemma annotations, and the generated module that holds\n * their predicates as compiled code (workerd runs no `eval`). Which of them\n * a run checks is the scenario's `specs`, read where the scenario is loaded,\n * inside the generated test.\n */\n\nimport { readdirSync, readFileSync } from \"node:fs\";\nimport { join, relative } from \"node:path\";\nimport { extractSpecs, type ModuleSpecs, predicateSource } from \"@eutaxy/spec\";\n\nexport interface SpecModule {\n /** The path relative to the scenario's directory, as a scenario names it: \"./domain.ts\". */\n readonly key: string;\n readonly path: string;\n readonly specs: ModuleSpecs;\n}\n\nconst skipDirs = new Set([\"node_modules\", \".eutaxy\", \"dist\", \".git\"]);\n\n/** Normalize a module path from a scenario's `specs` to a key. */\nexport function specKey(path: string): string {\n const posix = path\n .split(\"\\\\\")\n .join(\"/\")\n .replace(/^(\\.\\/)+/, \"\");\n return `./${posix}`;\n}\n\n/** Annotated modules under `dir`, tests and scenarios excepted. */\nexport function findSpecModules(dir: string): SpecModule[] {\n const out: SpecModule[] = [];\n const walk = (at: string): void => {\n for (const entry of readdirSync(at, { withFileTypes: true })) {\n const path = join(at, entry.name);\n if (entry.isDirectory()) {\n if (!skipDirs.has(entry.name)) walk(path);\n continue;\n }\n const name = entry.name;\n if (\n !name.endsWith(\".ts\") ||\n name.endsWith(\".d.ts\") ||\n name.endsWith(\".test.ts\") ||\n name.endsWith(\".sim.ts\")\n )\n continue;\n const source = readFileSync(path, \"utf8\");\n if (!/@(ensures|total|throws)\\b/.test(source)) continue;\n const specs = extractSpecs(source);\n if (specs.functions.length === 0 && specs.errors.length === 0) continue;\n out.push({ key: specKey(relative(dir, path)), path, specs });\n }\n };\n walk(dir);\n return out.sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0));\n}\n\n/** The generated module's own names; each predicate takes them as parameters, so nothing in a property shadows them. */\nconst helpers = {\n bool: \"__eutaxyBool\",\n same: \"__eutaxySame\",\n scope: \"__eutaxyNamespace\",\n unresolved: \"__eutaxyUnresolved\",\n};\n\n/** A file `eutaxy check` writes into `.eutaxy/`, by its path there. */\nexport interface GeneratedFile {\n readonly name: string;\n readonly source: string;\n}\n\n/**\n * The generated spec files: `specs.ts`, which maps each annotated module's\n * key to a loader, and one file per module with its extracted specs and a\n * function from its namespace to its predicates. A module's file loads only\n * when a scenario names the module, so an annotation elsewhere that does not\n * compile cannot stop a check. Each predicate binds its free names from the\n * namespace (else the globals) when it is built, which happens before\n * anything is observed, so checking a property never counts as a call the\n * simulator made.\n */\nexport function specFiles(modules: readonly SpecModule[]): GeneratedFile[] {\n const header = \"// Generated by eutaxy check; deleted after the run.\";\n const index = [\n header,\n \"export const specLoaders: Record<string, () => Promise<{ specs: any; predicates: (ns: any) => any }>> = {\",\n ...modules.map((m, i) => ` ${JSON.stringify(m.key)}: () => import(\"./specs/m${i}.ts\"),`),\n \"};\",\n ];\n const files = modules.map((m, i) => {\n const lines = [\n header,\n `import { lemmaBool as ${helpers.bool}, lemmaUnresolved as ${helpers.unresolved} } from \"eutaxy\";`,\n `const ${helpers.same} = Object.is;`,\n \"\",\n `export const specs = ${JSON.stringify(m.specs)};`,\n \"\",\n `export const predicates = (${helpers.scope}: any) => ({`,\n ];\n for (const fn of m.specs.functions) {\n // Computed keys: a name like __proto__ stays an ordinary entry.\n lines.push(` [${JSON.stringify(fn.name)}]: {`);\n for (const p of fn.ensures) {\n const source = predicateSource(p.property, helpers).split(\"\\n\").join(\"\\n \");\n lines.push(` [${JSON.stringify(p.name)}]: ${source},`);\n }\n lines.push(\" },\");\n }\n lines.push(\"});\");\n return { name: `specs/m${i}.ts`, source: `${lines.join(\"\\n\")}\\n` };\n });\n return [{ name: \"specs.ts\", source: `${index.join(\"\\n\")}\\n` }, ...files];\n}\n","/**\n * `eutaxy check <scenario.sim.ts>`: run a scenario inside workerd through\n * the user's Vitest and the Cloudflare plugin, print the verdict as text or\n * JSON, and on a violation write a regression test next to the scenario.\n */\n\nimport { spawn } from \"node:child_process\";\nimport { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { basename, dirname, join, relative, resolve } from \"node:path\";\nimport {\n canonicalJson,\n type JsonValue,\n type ScenarioVerdict,\n type SpecVerdict,\n type Violated,\n} from \"@eutaxy/core\";\nimport { renderSpecs, renderText } from \"@eutaxy/report\";\nimport { type CheckTransport, checkTestSource, metaKey, vitestConfigSource } from \"./generate.ts\";\nimport { cloudflareRegressionTest } from \"./regression.ts\";\nimport { findSpecModules, specFiles } from \"./specs.ts\";\n\nexport interface CheckOptions {\n readonly scenario: string;\n readonly cwd: string;\n readonly wrangler?: string;\n readonly seed?: string;\n readonly maxRuns?: number;\n /** Run every schedule within the bounds once instead of drawing them from the seed. */\n readonly exhaustive?: boolean;\n readonly json: boolean;\n /** Where to write the regression test on a violation; default `<name>.regression.test.ts` beside the scenario. */\n readonly out?: string;\n readonly noRegression: boolean;\n /** Emit a regression test that asserts the violation (for corpora) rather than one that expects it fixed. */\n readonly expectViolation: boolean;\n /** Keep the generated `.eutaxy/` files for inspection. */\n readonly keep: boolean;\n readonly stdout: (text: string) => void;\n readonly stderr: (text: string) => void;\n}\n\nexport const exitCodes = { BOUNDED: 0, VIOLATED: 1, UNSUPPORTED: 2, error: 3 } as const;\n\nfunction findWrangler(dir: string, explicit: string | undefined, cwd: string): string | null {\n if (explicit) return resolve(cwd, explicit);\n for (const name of [\"wrangler.jsonc\", \"wrangler.json\", \"wrangler.toml\"]) {\n const p = join(dir, name);\n if (existsSync(p)) return p;\n }\n return null;\n}\n\nfunction vitestBin(from: string): string {\n const req = createRequire(join(from, \"package.json\"));\n return join(dirname(req.resolve(\"vitest/package.json\")), \"vitest.mjs\");\n}\n\nfunction runVitest(\n bin: string,\n configPath: string,\n cwd: string,\n): Promise<{ code: number; output: string }> {\n return new Promise((resolveRun) => {\n const child = spawn(process.execPath, [bin, \"run\", \"--config\", configPath], {\n cwd,\n env: { ...process.env, CI: \"1\", FORCE_COLOR: \"0\" },\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n });\n let output = \"\";\n child.stdout.on(\"data\", (d: Buffer) => {\n output += d.toString();\n });\n child.stderr.on(\"data\", (d: Buffer) => {\n output += d.toString();\n });\n child.on(\"close\", (code) => resolveRun({ code: code ?? 1, output }));\n });\n}\n\n/** The transport the generated test left in its task meta, via Vitest's JSON reporter. */\nfunction readTransport(reportPath: string): CheckTransport | null {\n if (!existsSync(reportPath)) return null;\n const report = JSON.parse(readFileSync(reportPath, \"utf8\")) as {\n testResults?: { assertionResults?: { meta?: Record<string, unknown> }[] }[];\n };\n for (const file of report.testResults ?? []) {\n for (const t of file.assertionResults ?? []) {\n const m = t.meta?.[metaKey];\n if (m) return m as CheckTransport;\n }\n }\n return null;\n}\n\nfunction toPosix(p: string): string {\n const s = p.split(\"\\\\\").join(\"/\");\n return s.startsWith(\".\") ? s : `./${s}`;\n}\n\nexport async function runCheck(o: CheckOptions): Promise<number> {\n const scenarioPath = resolve(o.cwd, o.scenario);\n if (!existsSync(scenarioPath)) {\n o.stderr(`scenario not found: ${scenarioPath}\\n`);\n return exitCodes.error;\n }\n const dir = dirname(scenarioPath);\n const name = basename(scenarioPath)\n .replace(/\\.sim\\.ts$/, \"\")\n .replace(/\\.ts$/, \"\");\n const wrangler = findWrangler(dir, o.wrangler, o.cwd);\n if (!wrangler || !existsSync(wrangler)) {\n o.stderr(`no wrangler config found next to the scenario; pass --wrangler <path>\\n`);\n return exitCodes.error;\n }\n const workDir = join(dir, \".eutaxy\");\n const testPath = join(workDir, `${name}.check.test.ts`);\n const configPath = join(workDir, \"vitest.config.mts\");\n mkdirSync(workDir, { recursive: true });\n try {\n writeFileSync(\n testPath,\n checkTestSource({\n seed: o.seed ?? name,\n ...(o.maxRuns === undefined ? {} : { maxRuns: o.maxRuns }),\n ...(o.exhaustive ? { exhaustive: true } : {}),\n scenarioImport: `../${basename(scenarioPath)}`,\n }),\n );\n for (const f of specFiles(findSpecModules(dir))) {\n mkdirSync(dirname(join(workDir, f.name)), { recursive: true });\n writeFileSync(join(workDir, f.name), f.source);\n }\n const reportPath = join(workDir, \"vitest-report.json\");\n rmSync(reportPath, { force: true }); // never read a report left by an earlier --keep run\n writeFileSync(configPath, vitestConfigSource(wrangler, testPath, reportPath));\n const { code, output } = await runVitest(vitestBin(dir), configPath, dir);\n const transport = code === 0 ? readTransport(reportPath) : null;\n if (!transport) {\n o.stderr(`eutaxy check could not read a verdict from Vitest (exit ${code}):\\n${output}\\n`);\n return exitCodes.error;\n }\n if (transport.specErrors && transport.specErrors.length > 0) {\n for (const e of transport.specErrors)\n o.stderr(`${e.module}${e.line > 0 ? `:${e.line}` : \"\"}: ${e.message}\\n`);\n return exitCodes.error;\n }\n const report = transport.report as { verdict: ScenarioVerdict; specs?: readonly SpecVerdict[] };\n const verdict = report.verdict;\n const specs = report.specs ?? [];\n if (o.json) o.stdout(`${canonicalJson(transport.report as JsonValue)}\\n`);\n else o.stdout(`${renderText(verdict)}\\n${specs.length > 0 ? `\\n${renderSpecs(specs)}\\n` : \"\"}`);\n\n if (verdict.kind === \"VIOLATED\" && !o.noRegression) {\n const outPath = o.out ? resolve(o.cwd, o.out) : join(dir, `${name}.regression.test.ts`);\n const outDir = dirname(outPath);\n const schemaPaths: Record<string, string> = {};\n for (const step of transport.setup) {\n if (step.kind === \"d1\") {\n schemaPaths[String(step[\"binding\"])] = toPosix(\n relative(outDir, resolve(dir, String(step[\"schemaFile\"]))),\n );\n }\n }\n const source = cloudflareRegressionTest(verdict as Violated, {\n scenarioPath: toPosix(relative(outDir, scenarioPath)),\n workerPath: toPosix(relative(outDir, resolve(dir, transport.worker.entry))),\n schemaPaths,\n ...(transport.setup.some((s) => s.kind === \"durable_object\")\n ? { durableObjects: true }\n : {}),\n ...(o.expectViolation ? { expect: \"violates\" as const } : {}),\n ...((transport.observed ?? []).length > 0\n ? {\n specModules: (transport.observed ?? []).map((m) => ({\n path: toPosix(relative(outDir, resolve(dir, m.module))),\n functions: m.functions,\n })),\n }\n : {}),\n });\n mkdirSync(outDir, { recursive: true });\n writeFileSync(outPath, source);\n if (!o.json)\n o.stdout(`\\nRegression test written to ${relative(o.cwd, outPath) || outPath}\\n`);\n }\n // A refuted spec fails the check like a violation does.\n if (verdict.kind !== \"VIOLATED\" && specs.some((v) => v.kind === \"REFUTED\"))\n return exitCodes.VIOLATED;\n return exitCodes[verdict.kind];\n } finally {\n if (!o.keep) rmSync(workDir, { recursive: true, force: true });\n }\n}\n","import { parseArgs } from \"./args.ts\";\nimport { exitCodes, runCheck } from \"./check.ts\";\n\nconst usage = `eutaxy — deterministic simulation checks for Cloudflare Workers\n\nUsage:\n eutaxy check <scenario.sim.ts> [options]\n\nOptions:\n --wrangler <path> wrangler config (default: wrangler.jsonc/json/toml beside the scenario)\n --seed <seed> exploration seed (default: the scenario file name)\n --max-runs <n> cap on exploration runs in addition to the scenario's time budget\n --exhaustive run every schedule within the bounds once (with partial-order reduction)\n --json print the versioned JSON report instead of text\n --out <path> where to write the regression test on a violation\n --no-regression do not write a regression test\n --expect-violation write a regression test that asserts the violation (for corpora)\n --keep keep the generated .eutaxy/ files\n\nExit codes: 0 BOUNDED, 1 VIOLATED or a REFUTED spec, 2 UNSUPPORTED, 3 error.\n`;\n\nexport interface Io {\n readonly cwd: string;\n readonly stdout: (text: string) => void;\n readonly stderr: (text: string) => void;\n}\n\nexport async function main(argv: readonly string[], io: Io): Promise<number> {\n const { positionals, flags } = parseArgs(argv, [\n \"json\",\n \"no-regression\",\n \"expect-violation\",\n \"keep\",\n \"help\",\n \"exhaustive\",\n ]);\n const command = positionals[0];\n if (!command || command === \"help\" || flags[\"help\"] === true) {\n io.stdout(usage);\n return command ? exitCodes.BOUNDED : exitCodes.error;\n }\n if (command !== \"check\") {\n io.stderr(`unknown command ${command}\\n\\n${usage}`);\n return exitCodes.error;\n }\n const scenario = positionals[1];\n if (!scenario) {\n io.stderr(`check needs a scenario file\\n\\n${usage}`);\n return exitCodes.error;\n }\n const str = (k: string): string | undefined =>\n typeof flags[k] === \"string\" ? (flags[k] as string) : undefined;\n const maxRunsText = str(\"max-runs\");\n const maxRuns = maxRunsText === undefined ? undefined : Number(maxRunsText);\n if (maxRuns !== undefined && !(Number.isInteger(maxRuns) && maxRuns > 0)) {\n io.stderr(`--max-runs must be a positive integer, got ${JSON.stringify(maxRunsText)}\\n`);\n return exitCodes.error;\n }\n return runCheck({\n scenario,\n cwd: io.cwd,\n ...(str(\"wrangler\") ? { wrangler: str(\"wrangler\") as string } : {}),\n ...(str(\"seed\") ? { seed: str(\"seed\") as string } : {}),\n ...(maxRuns === undefined ? {} : { maxRuns }),\n exhaustive: flags[\"exhaustive\"] === true,\n json: flags[\"json\"] === true,\n ...(str(\"out\") ? { out: str(\"out\") as string } : {}),\n noRegression: flags[\"no-regression\"] === true,\n expectViolation: flags[\"expect-violation\"] === true,\n keep: flags[\"keep\"] === true,\n stdout: io.stdout,\n stderr: io.stderr,\n });\n}\n"],"mappings":";;;;;;;AAOA,SAAgB,UAAU,MAAyB,WAA8B,CAAC,GAAe;CAC/F,MAAM,cAAwB,CAAC;CAC/B,MAAM,QAAuC,CAAC;CAC9C,KAAK,IAAI,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;EACpC,MAAM,IAAI,KAAK;EACf,IAAI,CAAC,EAAE,WAAW,IAAI,GAAG;GACvB,YAAY,KAAK,CAAC;GAClB;EACF;EACA,MAAM,KAAK,EAAE,QAAQ,GAAG;EACxB,IAAI,OAAO,IAAI;GACb,MAAM,EAAE,MAAM,GAAG,EAAE,KAAK,EAAE,MAAM,KAAK,CAAC;GACtC;EACF;EACA,MAAM,OAAO,EAAE,MAAM,CAAC;EACtB,MAAM,OAAO,KAAK,IAAI;EACtB,IAAI,SAAS,SAAS,IAAI,KAAK,SAAS,KAAA,KAAa,KAAK,WAAW,IAAI,GACvE,MAAM,QAAQ;OACT;GACL,MAAM,QAAQ;GACd;EACF;CACF;CACA,OAAO;EAAE;EAAa;CAAM;AAC9B;;;;;;;;;ACvBA,MAAa,UAAU;AA0BvB,SAAgB,gBAAgB,GAA2B;CACzD,MAAM,WACH,EAAE,YAAY,KAAA,IAAY,KAAK,cAAc,EAAE,cAC/C,EAAE,aAAa,uBAAuB;CACzC,OAAO;;;;;;uBAMc,KAAK,UAAU,EAAE,cAAc,EAAE;;;;;;;;;;;;;;;;;;;;;;;;;;;;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