eutaxy 0.14.0 → 0.15.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.
- package/README.md +10 -6
- package/dist/aws.d.mts +28 -2
- package/dist/aws.d.mts.map +1 -1
- package/dist/aws.mjs +13 -2
- package/dist/aws.mjs.map +1 -1
- package/dist/bin.mjs +1 -1
- package/dist/{cli-BppjMaqL.mjs → cli-DT4lxaPK.mjs} +863 -89
- package/dist/cli-DT4lxaPK.mjs.map +1 -0
- package/dist/cli.d.mts.map +1 -1
- package/dist/cli.mjs +1 -1
- package/dist/cloudflare.d.mts +79 -8
- package/dist/cloudflare.d.mts.map +1 -1
- package/dist/cloudflare.mjs +2 -2
- package/dist/{combinators-Bsd9HKtw.d.mts → combinators-BecOKcmi.d.mts} +7 -1
- package/dist/combinators-BecOKcmi.d.mts.map +1 -0
- package/dist/{combinators-CVjxodAJ.mjs → combinators-CLfsPfhT.mjs} +6 -1
- package/dist/combinators-CLfsPfhT.mjs.map +1 -0
- package/dist/{delivery-invariants-_T9ZMwOJ.mjs → delivery-invariants-Dr658H1W.mjs} +7 -2
- package/dist/delivery-invariants-Dr658H1W.mjs.map +1 -0
- package/dist/delivery-invariants-DzMy3iPs.d.mts +10 -0
- package/dist/delivery-invariants-DzMy3iPs.d.mts.map +1 -0
- package/dist/{explore-B7aR_5Hy.d.mts → explore-B52m-wmk.d.mts} +13 -2
- package/dist/explore-B52m-wmk.d.mts.map +1 -0
- package/dist/index.d.mts +25 -3
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +2 -2
- package/dist/index.mjs.map +1 -1
- package/dist/{platform-CCz48WF9.d.mts → platform-Ba1Kvdza.d.mts} +18 -1
- package/dist/platform-Ba1Kvdza.d.mts.map +1 -0
- package/dist/provers-DS44OeEm.mjs.map +1 -1
- package/dist/spec.d.mts +1 -1
- package/dist/spec.mjs +1 -1
- package/dist/{src-DPCF2XGv.mjs → src-CPuihHZh.mjs} +225 -238
- package/dist/src-CPuihHZh.mjs.map +1 -0
- package/dist/{src-ClXnIi6O.mjs → src-wa0JZa-T.mjs} +9 -3
- package/dist/src-wa0JZa-T.mjs.map +1 -0
- package/dist/{workerd-DVJ8eCLI.mjs → workerd-DvhVDnQW.mjs} +170 -42
- package/dist/workerd-DvhVDnQW.mjs.map +1 -0
- package/package.json +3 -3
- package/dist/cli-BppjMaqL.mjs.map +0 -1
- package/dist/combinators-Bsd9HKtw.d.mts.map +0 -1
- package/dist/combinators-CVjxodAJ.mjs.map +0 -1
- package/dist/delivery-invariants-DZOBkCMR.d.mts +0 -5
- package/dist/delivery-invariants-DZOBkCMR.d.mts.map +0 -1
- package/dist/delivery-invariants-_T9ZMwOJ.mjs.map +0 -1
- package/dist/explore-B7aR_5Hy.d.mts.map +0 -1
- package/dist/platform-CCz48WF9.d.mts.map +0 -1
- package/dist/src-ClXnIi6O.mjs.map +0 -1
- package/dist/src-DPCF2XGv.mjs.map +0 -1
- package/dist/workerd-DVJ8eCLI.mjs.map +0 -1
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
import { L as canonicalJson } from "./src-
|
|
2
|
-
import { _ as render, a as renderText, c as checkSpecModule, d as shrinkRefutation, g as endpointNumber, h as endpointBigInt, i as renderSpecs, m as conforms, n as renderSpecReport, p as evaluate, r as renderSpecReportJson, v as describeType } from "./src-
|
|
3
|
-
import { n as isSpec } from "./combinators-
|
|
1
|
+
import { L as canonicalJson } from "./src-CPuihHZh.mjs";
|
|
2
|
+
import { _ as render, a as renderText, c as checkSpecModule, d as shrinkRefutation, g as endpointNumber, h as endpointBigInt, i as renderSpecs, m as conforms, n as renderSpecReport, p as evaluate, r as renderSpecReportJson, v as describeType } from "./src-wa0JZa-T.mjs";
|
|
3
|
+
import { n as isSpec } from "./combinators-CLfsPfhT.mjs";
|
|
4
4
|
import { t as aggregate } from "./provers-DS44OeEm.mjs";
|
|
5
|
-
import { G as cloudflareRegressionTest, n as globKey, r as specKey } from "./workerd-
|
|
5
|
+
import { G as cloudflareRegressionTest, n as globKey, r as specKey } from "./workerd-DvhVDnQW.mjs";
|
|
6
6
|
import { createRequire, registerHooks } from "node:module";
|
|
7
7
|
import { Readable } from "node:stream";
|
|
8
8
|
import { createHash, randomBytes } from "node:crypto";
|
|
9
|
-
import { chmodSync, closeSync, copyFileSync, createReadStream, existsSync, mkdirSync, mkdtempSync, openSync, readFileSync, readdirSync, renameSync, rmSync, symlinkSync, writeFileSync, writeSync } from "node:fs";
|
|
10
|
-
import { homedir, tmpdir } from "node:os";
|
|
9
|
+
import { chmodSync, closeSync, copyFileSync, createReadStream, existsSync, mkdirSync, mkdtempSync, openSync, readFileSync, readSync, readdirSync, renameSync, rmSync, symlinkSync, writeFileSync, writeSync } from "node:fs";
|
|
10
|
+
import { availableParallelism, homedir, tmpdir } from "node:os";
|
|
11
11
|
import { basename, dirname, extname, join, relative, resolve, sep } from "node:path";
|
|
12
12
|
import { createZstdDecompress, inflateRawSync } from "node:zlib";
|
|
13
13
|
import { fork, spawn } from "node:child_process";
|
|
@@ -17,6 +17,65 @@ import { API, DiagnosticCategory, SymbolFlags, TypeFlags, TypeFormatFlags } from
|
|
|
17
17
|
import * as is from "typescript/ast/is";
|
|
18
18
|
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
19
19
|
import { createInterface } from "node:readline";
|
|
20
|
+
import { StringDecoder } from "node:string_decoder";
|
|
21
|
+
// packages/prover/src/pool.ts
|
|
22
|
+
/**
|
|
23
|
+
* Independent jobs run a few at a time, with their results in the order of
|
|
24
|
+
* the items whatever order the jobs finish in: what an engine needs to run
|
|
25
|
+
* one solver process per property, or the report one process per module,
|
|
26
|
+
* without the answer depending on which finished first. A job that throws
|
|
27
|
+
* rejects the pool, and no job is started after it.
|
|
28
|
+
*/
|
|
29
|
+
/** `work` on every item, at most `limit` at once; the results in item order. */
|
|
30
|
+
async function inPool(items, limit, work) {
|
|
31
|
+
const results = new Array(items.length);
|
|
32
|
+
let next = 0;
|
|
33
|
+
let failed = false;
|
|
34
|
+
const worker = async () => {
|
|
35
|
+
while (next < items.length && !failed) {
|
|
36
|
+
const i = next++;
|
|
37
|
+
try {
|
|
38
|
+
results[i] = await work(items[i], i);
|
|
39
|
+
} catch (err) {
|
|
40
|
+
failed = true;
|
|
41
|
+
throw err;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
const workers = Math.max(1, Math.min(Math.floor(limit), items.length));
|
|
46
|
+
await Promise.all(Array.from({ length: workers }, worker));
|
|
47
|
+
return results;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* `inPool`, and no item starts `size` or more places past the earliest one
|
|
51
|
+
* not yet finished: when an early job is slow, the jobs behind it wait
|
|
52
|
+
* rather than run ahead, so whatever the finished ones hold for their turn
|
|
53
|
+
* (the report's held output) is never more than `size - 1` items' worth.
|
|
54
|
+
*/
|
|
55
|
+
async function inWindow(items, size, work) {
|
|
56
|
+
const n = Math.max(1, Math.floor(size));
|
|
57
|
+
const finished = items.map(() => false);
|
|
58
|
+
let earliest = 0;
|
|
59
|
+
let failed = false;
|
|
60
|
+
const waiting = /* @__PURE__ */ new Map();
|
|
61
|
+
return inPool(items, n, async (item, i) => {
|
|
62
|
+
if (i >= earliest + n) await new Promise((go) => waiting.set(i, go));
|
|
63
|
+
if (failed) throw new Error("an earlier job failed");
|
|
64
|
+
try {
|
|
65
|
+
return await work(item, i);
|
|
66
|
+
} catch (err) {
|
|
67
|
+
failed = true;
|
|
68
|
+
throw err;
|
|
69
|
+
} finally {
|
|
70
|
+
finished[i] = true;
|
|
71
|
+
while (finished[earliest]) earliest++;
|
|
72
|
+
for (const [j, go] of waiting) if (j < earliest + n) {
|
|
73
|
+
waiting.delete(j);
|
|
74
|
+
go();
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
});
|
|
78
|
+
}
|
|
20
79
|
// packages/cli/src/args.ts
|
|
21
80
|
function parseArgs(argv, booleans = []) {
|
|
22
81
|
const positionals = [];
|
|
@@ -1202,15 +1261,14 @@ function narrowsOf(test, holds) {
|
|
|
1202
1261
|
if (test.kind === "binary" && test.op === "||" && !holds) return [...narrowsOf(test.left, false), ...narrowsOf(test.right, false)];
|
|
1203
1262
|
return [];
|
|
1204
1263
|
}
|
|
1205
|
-
/**
|
|
1264
|
+
/**
|
|
1265
|
+
* The field that tells a union's members apart, as the union names it: the
|
|
1266
|
+
* one the types read chose (`UnionType.tag`), which the engines encode by.
|
|
1267
|
+
* Re-deriving it from the member records could pick another field where two
|
|
1268
|
+
* discriminate, and the reader would then refuse the test the engines take.
|
|
1269
|
+
*/
|
|
1206
1270
|
function tagOf(union, ctx) {
|
|
1207
|
-
|
|
1208
|
-
const first = members[0];
|
|
1209
|
-
if (!first) return void 0;
|
|
1210
|
-
return first.fields.filter((f) => f.literal !== void 0).map((f) => f.name).find((name) => {
|
|
1211
|
-
const values = members.map((m) => m.fields.find((f) => f.name === name)?.literal);
|
|
1212
|
-
return values.every((v) => v !== void 0) && new Set(values.map((v) => JSON.stringify(v))).size === values.length;
|
|
1213
|
-
});
|
|
1271
|
+
return ctx.unions.find((u) => u.name === union)?.tag;
|
|
1214
1272
|
}
|
|
1215
1273
|
/**
|
|
1216
1274
|
* The names a test, holding or failing, shows to be one member of their
|
|
@@ -1925,11 +1983,12 @@ function callees(e, out = /* @__PURE__ */ new Set()) {
|
|
|
1925
1983
|
/** The path a module read from text alone is compiled under: an import of another file does not resolve from it. */
|
|
1926
1984
|
const virtualModulePath = "/eutaxy/reader/module.ts";
|
|
1927
1985
|
/** What typing a module's expressions needs, shared by every function read. */
|
|
1928
|
-
function moduleContext(records) {
|
|
1986
|
+
function moduleContext(records, unions) {
|
|
1929
1987
|
const signatures = /* @__PURE__ */ new Map();
|
|
1930
1988
|
return {
|
|
1931
1989
|
ctx: {
|
|
1932
1990
|
records,
|
|
1991
|
+
unions,
|
|
1933
1992
|
signatures
|
|
1934
1993
|
},
|
|
1935
1994
|
signatures
|
|
@@ -2081,7 +2140,7 @@ function directiveIn(sf, start, end) {
|
|
|
2081
2140
|
const check = (pos, commentEnd) => {
|
|
2082
2141
|
if (found || pos < start || commentEnd > end) return;
|
|
2083
2142
|
const comment = text.slice(pos, commentEnd);
|
|
2084
|
-
const m = comment.startsWith("//") ? singleLine.exec(comment) : lastLine.exec(comment.slice(comment.lastIndexOf("\n") + 1));
|
|
2143
|
+
const m = comment.startsWith("//") ? singleLine.exec(comment) : lastLine.exec(comment.slice(comment.lastIndexOf("\n") + 1).trimStart());
|
|
2085
2144
|
if (m) found = {
|
|
2086
2145
|
text: `@ts-${m[1]}`,
|
|
2087
2146
|
pos
|
|
@@ -2645,7 +2704,7 @@ function readSubset(source, functions, options = {}) {
|
|
|
2645
2704
|
if (err !== skip) throw err;
|
|
2646
2705
|
}
|
|
2647
2706
|
}
|
|
2648
|
-
const { ctx, signatures } = moduleContext(types.records);
|
|
2707
|
+
const { ctx, signatures } = moduleContext(types.records, types.unions);
|
|
2649
2708
|
const names = {
|
|
2650
2709
|
callable: (n) => declared.has(n) && !generic.has(n),
|
|
2651
2710
|
target: (n) => n,
|
|
@@ -2806,6 +2865,7 @@ function arrowReader(sf, module, aliases) {
|
|
|
2806
2865
|
}]));
|
|
2807
2866
|
return new ExprReader(sf, names, typeSource, {
|
|
2808
2867
|
records,
|
|
2868
|
+
unions: module.unions,
|
|
2809
2869
|
signatures
|
|
2810
2870
|
}, () => 0);
|
|
2811
2871
|
}
|
|
@@ -3631,6 +3691,7 @@ function env$1(module) {
|
|
|
3631
3691
|
module,
|
|
3632
3692
|
ctx: {
|
|
3633
3693
|
records: new Map(module.records.map((r) => [r.name, r])),
|
|
3694
|
+
unions: module.unions,
|
|
3634
3695
|
signatures: new Map(module.functions.map((f) => [f.name, {
|
|
3635
3696
|
params: f.params,
|
|
3636
3697
|
returns: f.returns
|
|
@@ -4928,6 +4989,7 @@ function env(module) {
|
|
|
4928
4989
|
types: /* @__PURE__ */ new WeakMap(),
|
|
4929
4990
|
ctx: {
|
|
4930
4991
|
records: new Map(module.records.map((r) => [r.name, r])),
|
|
4992
|
+
unions: module.unions,
|
|
4931
4993
|
signatures: new Map(module.functions.map((f) => [f.name, {
|
|
4932
4994
|
params: f.params,
|
|
4933
4995
|
returns: f.returns
|
|
@@ -5394,8 +5456,9 @@ function prelude(module) {
|
|
|
5394
5456
|
* One property's script: the binders as constants, what their types say
|
|
5395
5457
|
* beyond their sorts, the precondition asserted, the claim's negation
|
|
5396
5458
|
* asserted. `unsat` proves the claim; `sat` comes with the binders' values.
|
|
5459
|
+
* `definitions` is the module's `prelude`, when the caller already has it.
|
|
5397
5460
|
*/
|
|
5398
|
-
function propertyScript(property, module) {
|
|
5461
|
+
function propertyScript(property, module, definitions = prelude(module)) {
|
|
5399
5462
|
if (property.kind !== "forall" || !property.ensures) fail("not a forall property");
|
|
5400
5463
|
const e = env(module);
|
|
5401
5464
|
const types = property.binders.map((b) => binderType(b.name, b.type, module));
|
|
@@ -5406,7 +5469,7 @@ function propertyScript(property, module) {
|
|
|
5406
5469
|
}));
|
|
5407
5470
|
return {
|
|
5408
5471
|
script: `${[
|
|
5409
|
-
|
|
5472
|
+
definitions,
|
|
5410
5473
|
...binders.map((b) => `(declare-const ${b.symbol} ${sort(b.type, module)})`),
|
|
5411
5474
|
...binders.flatMap((b) => {
|
|
5412
5475
|
const c = wellFormed(b.symbol, b.type, module);
|
|
@@ -5783,7 +5846,7 @@ function prepare(input) {
|
|
|
5783
5846
|
for (const property of fn.properties) {
|
|
5784
5847
|
if (property.kind !== "forall") continue;
|
|
5785
5848
|
try {
|
|
5786
|
-
scripts.set(key(fn.name, property.name), propertyScript(property, module));
|
|
5849
|
+
scripts.set(key(fn.name, property.name), propertyScript(property, module, pre));
|
|
5787
5850
|
} catch (err) {
|
|
5788
5851
|
if (!(err instanceof OutsideSubset)) throw err;
|
|
5789
5852
|
skipped.set(key(fn.name, property.name), err.message);
|
|
@@ -5810,6 +5873,8 @@ function prepare(input) {
|
|
|
5810
5873
|
* Node does not, is completed in a sibling copy that is imported and then
|
|
5811
5874
|
* removed, so the copy's own relative imports still resolve.
|
|
5812
5875
|
*/
|
|
5876
|
+
/** Names each sibling copy apart from another made in the same millisecond. */
|
|
5877
|
+
let copies = 0;
|
|
5813
5878
|
async function importSpecFile(specPath) {
|
|
5814
5879
|
try {
|
|
5815
5880
|
return await import(pathToFileURL(specPath).href);
|
|
@@ -5820,7 +5885,7 @@ async function importSpecFile(specPath) {
|
|
|
5820
5885
|
const dir = dirname(specPath);
|
|
5821
5886
|
const rewritten = source.replace(/(from\s*["'])(\.{1,2}\/[^"']+?)(\.js)?(["'])/g, (whole, pre, rel, _js, post) => existsSync(join(dir, `${rel}.ts`)) ? `${pre}${rel}.ts${post}` : whole);
|
|
5822
5887
|
if (rewritten === source) throw err;
|
|
5823
|
-
const copy = join(dir, `.eutaxy-replay-${process.pid}-${Date.now()}.props.ts`);
|
|
5888
|
+
const copy = join(dir, `.eutaxy-replay-${process.pid}-${Date.now()}-${copies++}.props.ts`);
|
|
5824
5889
|
writeFileSync(copy, rewritten);
|
|
5825
5890
|
try {
|
|
5826
5891
|
return await import(pathToFileURL(copy).href);
|
|
@@ -5829,12 +5894,23 @@ async function importSpecFile(specPath) {
|
|
|
5829
5894
|
}
|
|
5830
5895
|
}
|
|
5831
5896
|
}
|
|
5897
|
+
function specLoader() {
|
|
5898
|
+
const loaded = /* @__PURE__ */ new Map();
|
|
5899
|
+
return (specPath) => {
|
|
5900
|
+
let ns = loaded.get(specPath);
|
|
5901
|
+
if (ns === void 0) {
|
|
5902
|
+
ns = importSpecFile(specPath);
|
|
5903
|
+
loaded.set(specPath, ns);
|
|
5904
|
+
}
|
|
5905
|
+
return ns;
|
|
5906
|
+
};
|
|
5907
|
+
}
|
|
5832
5908
|
/** The spec file's export for a property, loaded for replay, or why it could not be. */
|
|
5833
|
-
async function loadSpec(specPath, property, fn) {
|
|
5909
|
+
async function loadSpec(load, specPath, property, fn) {
|
|
5834
5910
|
if (specPath === void 0) return "the engine was not given the spec file's path to replay the counterexample";
|
|
5835
5911
|
let ns;
|
|
5836
5912
|
try {
|
|
5837
|
-
ns = await
|
|
5913
|
+
ns = await load(specPath);
|
|
5838
5914
|
} catch (err) {
|
|
5839
5915
|
return `the spec file could not be loaded to replay the counterexample: ${String(err)}`;
|
|
5840
5916
|
}
|
|
@@ -5890,41 +5966,40 @@ async function proveModule(input) {
|
|
|
5890
5966
|
const errors = readAnswer(checked.run.stdout).errors;
|
|
5891
5967
|
if (checked.run.code !== 0 || errors.length > 0 || answers.length !== input.extra.length || failed >= 0) return allWith(unknown("unsupported", `the emitted SMT failed a translation check${failed >= 0 ? ` (${input.extra[failed]})` : ""}: ${errors[0] ?? (checked.run.stderr || checked.run.stdout).trim().split("\n")[0] ?? ""}`));
|
|
5892
5968
|
}
|
|
5893
|
-
|
|
5894
|
-
|
|
5895
|
-
|
|
5896
|
-
|
|
5897
|
-
|
|
5898
|
-
|
|
5899
|
-
|
|
5900
|
-
|
|
5901
|
-
|
|
5969
|
+
const load = specLoader();
|
|
5970
|
+
const proofs = await inPool(inSubset.flatMap((fn) => fn.properties.map((property) => ({
|
|
5971
|
+
fn,
|
|
5972
|
+
property
|
|
5973
|
+
}))), Math.min(8, availableParallelism()), async ({ fn, property }) => {
|
|
5974
|
+
if (property.kind === "total") return {
|
|
5975
|
+
function: fn.name,
|
|
5976
|
+
property: property.name,
|
|
5977
|
+
outcome: unknown("unsupported", "total is not decided by this engine (Lean proves it by acceptance)")
|
|
5978
|
+
};
|
|
5902
5979
|
const k = key(fn.name, property.name);
|
|
5903
5980
|
const why = skipped.get(k);
|
|
5904
|
-
if (why !== void 0) {
|
|
5905
|
-
|
|
5906
|
-
|
|
5907
|
-
|
|
5908
|
-
|
|
5909
|
-
});
|
|
5910
|
-
continue;
|
|
5911
|
-
}
|
|
5981
|
+
if (why !== void 0) return {
|
|
5982
|
+
function: fn.name,
|
|
5983
|
+
property: property.name,
|
|
5984
|
+
outcome: unknown("unsupported", why)
|
|
5985
|
+
};
|
|
5912
5986
|
const script = scripts.get(k);
|
|
5913
|
-
if (!script)
|
|
5987
|
+
if (!script) return void 0;
|
|
5914
5988
|
const solved = await solve(solver, script.script, options);
|
|
5915
|
-
|
|
5989
|
+
return {
|
|
5916
5990
|
function: fn.name,
|
|
5917
5991
|
property: property.name,
|
|
5918
|
-
outcome: await outcomeOf(solved, script, module, property, fn.name, input)
|
|
5919
|
-
}
|
|
5920
|
-
}
|
|
5992
|
+
outcome: await outcomeOf(solved, script, module, property, fn.name, input, load)
|
|
5993
|
+
};
|
|
5994
|
+
});
|
|
5995
|
+
for (const proof of proofs) if (proof) results.push(proof);
|
|
5921
5996
|
return {
|
|
5922
5997
|
results,
|
|
5923
5998
|
smt,
|
|
5924
5999
|
specErrors
|
|
5925
6000
|
};
|
|
5926
6001
|
}
|
|
5927
|
-
async function outcomeOf(solved, script, module, property, fn, input) {
|
|
6002
|
+
async function outcomeOf(solved, script, module, property, fn, input, load) {
|
|
5928
6003
|
if (solved.run.timedOut) return unknown("gave_up", `Z3 did not finish within ${input.timeoutMs ?? 12e4} ms`);
|
|
5929
6004
|
if (solved.run.code === null) return unknown("unavailable", `Z3 could not be run: ${solved.run.stderr.trim()}`);
|
|
5930
6005
|
const answer = readAnswer(solved.run.stdout);
|
|
@@ -5945,7 +6020,7 @@ async function outcomeOf(solved, script, module, property, fn, input) {
|
|
|
5945
6020
|
}
|
|
5946
6021
|
const rendered = property.binders.map((b, i) => `${b.name} = ${render(values[i])}`).join(", ");
|
|
5947
6022
|
if (!property.binders.every((b, i) => conforms(b.type, values[i]))) return unknown("unsupported", `Z3's model lies outside the parameter types (${rendered}): the engine's model of the types is wider than the types`);
|
|
5948
|
-
const spec = await loadSpec(input.specPath, property, fn);
|
|
6023
|
+
const spec = await loadSpec(load, input.specPath, property, fn);
|
|
5949
6024
|
if (typeof spec === "string") return unknown("unsupported", `${spec} (the model: ${rendered})`);
|
|
5950
6025
|
const evaluation = evaluate(spec, values);
|
|
5951
6026
|
if ("malformed" in evaluation) return unknown("unsupported", `the property could not be evaluated on the model (${rendered}): ${evaluation.malformed}`);
|
|
@@ -6174,7 +6249,7 @@ function readWranglerConfig(path) {
|
|
|
6174
6249
|
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new Error(`${basename(path)}: not a wrangler config object`);
|
|
6175
6250
|
return parsed;
|
|
6176
6251
|
}
|
|
6177
|
-
const list = (v) => Array.isArray(v) ? v.filter((x) => typeof x === "object" && x) : [];
|
|
6252
|
+
const list$1 = (v) => Array.isArray(v) ? v.filter((x) => typeof x === "object" && x) : [];
|
|
6178
6253
|
const str$1 = (v, fallback = "") => typeof v === "string" ? v : fallback;
|
|
6179
6254
|
/** The keys of a wrangler config whose bindings the command carries into the isolate. */
|
|
6180
6255
|
const carried = /* @__PURE__ */ new Set([
|
|
@@ -6214,9 +6289,9 @@ function readCalleeConfig(step, scenarioDir) {
|
|
|
6214
6289
|
const notAdded = [];
|
|
6215
6290
|
const sqlite = /* @__PURE__ */ new Set();
|
|
6216
6291
|
const strings = (v) => Array.isArray(v) ? v.filter((x) => typeof x === "string") : [];
|
|
6217
|
-
for (const m of list(config["migrations"])) {
|
|
6292
|
+
for (const m of list$1(config["migrations"])) {
|
|
6218
6293
|
for (const c of strings(m["new_sqlite_classes"])) sqlite.add(c);
|
|
6219
|
-
for (const r of list(m["renamed_classes"])) {
|
|
6294
|
+
for (const r of list$1(m["renamed_classes"])) {
|
|
6220
6295
|
const from = str$1(r["from"]);
|
|
6221
6296
|
if (sqlite.delete(from)) sqlite.add(str$1(r["to"]));
|
|
6222
6297
|
}
|
|
@@ -6224,7 +6299,7 @@ function readCalleeConfig(step, scenarioDir) {
|
|
|
6224
6299
|
}
|
|
6225
6300
|
const durableObjects = [];
|
|
6226
6301
|
const dos = config["durable_objects"];
|
|
6227
|
-
for (const b of list(dos?.bindings)) {
|
|
6302
|
+
for (const b of list$1(dos?.bindings)) {
|
|
6228
6303
|
const className = str$1(b["class_name"]);
|
|
6229
6304
|
const scriptName = b["script_name"] === void 0 ? void 0 : str$1(b["script_name"]);
|
|
6230
6305
|
durableObjects.push({
|
|
@@ -6243,26 +6318,26 @@ function readCalleeConfig(step, scenarioDir) {
|
|
|
6243
6318
|
binding: step.binding,
|
|
6244
6319
|
name,
|
|
6245
6320
|
entry: resolve(scenarioDir, step.entry),
|
|
6246
|
-
d1: list(config["d1_databases"]).map((d) => ({
|
|
6321
|
+
d1: list$1(config["d1_databases"]).map((d) => ({
|
|
6247
6322
|
binding: str$1(d["binding"]),
|
|
6248
6323
|
id: str$1(d["database_id"], str$1(d["database_name"], str$1(d["binding"])))
|
|
6249
6324
|
})),
|
|
6250
|
-
r2: list(config["r2_buckets"]).map((b) => ({
|
|
6325
|
+
r2: list$1(config["r2_buckets"]).map((b) => ({
|
|
6251
6326
|
binding: str$1(b["binding"]),
|
|
6252
6327
|
bucket: str$1(b["bucket_name"], str$1(b["binding"]))
|
|
6253
6328
|
})),
|
|
6254
|
-
kv: list(config["kv_namespaces"]).map((k) => ({
|
|
6329
|
+
kv: list$1(config["kv_namespaces"]).map((k) => ({
|
|
6255
6330
|
binding: str$1(k["binding"]),
|
|
6256
6331
|
id: str$1(k["id"], str$1(k["binding"]))
|
|
6257
6332
|
})),
|
|
6258
6333
|
durableObjects,
|
|
6259
|
-
workflows: list(config["workflows"]).map((w) => ({
|
|
6334
|
+
workflows: list$1(config["workflows"]).map((w) => ({
|
|
6260
6335
|
binding: str$1(w["binding"]),
|
|
6261
6336
|
className: str$1(w["class_name"]),
|
|
6262
6337
|
name: str$1(w["name"], str$1(w["binding"]))
|
|
6263
6338
|
})),
|
|
6264
|
-
services: list(config["services"]).map((s) => str$1(s["binding"])),
|
|
6265
|
-
queues: list(queues?.producers).map((p) => ({
|
|
6339
|
+
services: list$1(config["services"]).map((s) => str$1(s["binding"])),
|
|
6340
|
+
queues: list$1(queues?.producers).map((p) => ({
|
|
6266
6341
|
binding: str$1(p["binding"]),
|
|
6267
6342
|
queue: str$1(p["queue"])
|
|
6268
6343
|
})),
|
|
@@ -6336,7 +6411,7 @@ const neverCalled = "neverCalled";
|
|
|
6336
6411
|
* anyway (the scenario names a callee for it or scripts it); its value is a
|
|
6337
6412
|
* Fetcher all the same, which is what the platform recognises.
|
|
6338
6413
|
*/
|
|
6339
|
-
function miniflareOptionsSource(callees, isolate = noIsolate) {
|
|
6414
|
+
function miniflareOptionsSource(callees, isolate = noIsolate, callerServices = []) {
|
|
6340
6415
|
const d1 = {};
|
|
6341
6416
|
const r2 = {};
|
|
6342
6417
|
const kv = {};
|
|
@@ -6347,6 +6422,7 @@ function miniflareOptionsSource(callees, isolate = noIsolate) {
|
|
|
6347
6422
|
const vars = {};
|
|
6348
6423
|
const aliased = (name) => name in isolate.aliases;
|
|
6349
6424
|
Object.assign(dos, isolate.redirected);
|
|
6425
|
+
for (const b of callerServices) services[b] = neverCalled;
|
|
6350
6426
|
for (const c of callees) {
|
|
6351
6427
|
for (const d of c.d1) if (!aliased(qualified(c.name, d.binding))) d1[qualified(c.name, d.binding)] = d.id;
|
|
6352
6428
|
for (const b of c.r2) if (!aliased(qualified(c.name, b.binding))) r2[qualified(c.name, b.binding)] = b.bucket;
|
|
@@ -6391,24 +6467,24 @@ function readCallerResources(wranglerPath) {
|
|
|
6391
6467
|
const dos = config["durable_objects"];
|
|
6392
6468
|
return {
|
|
6393
6469
|
name: str$1(config["name"]) || void 0,
|
|
6394
|
-
d1: list(config["d1_databases"]).map((d) => ({
|
|
6470
|
+
d1: list$1(config["d1_databases"]).map((d) => ({
|
|
6395
6471
|
binding: str$1(d["binding"]),
|
|
6396
6472
|
id: str$1(d["database_id"], str$1(d["database_name"], str$1(d["binding"])))
|
|
6397
6473
|
})),
|
|
6398
|
-
r2: list(config["r2_buckets"]).map((b) => ({
|
|
6474
|
+
r2: list$1(config["r2_buckets"]).map((b) => ({
|
|
6399
6475
|
binding: str$1(b["binding"]),
|
|
6400
6476
|
bucket: str$1(b["bucket_name"], str$1(b["binding"]))
|
|
6401
6477
|
})),
|
|
6402
|
-
kv: list(config["kv_namespaces"]).map((k) => ({
|
|
6478
|
+
kv: list$1(config["kv_namespaces"]).map((k) => ({
|
|
6403
6479
|
binding: str$1(k["binding"]),
|
|
6404
6480
|
id: str$1(k["id"], str$1(k["binding"]))
|
|
6405
6481
|
})),
|
|
6406
|
-
durableObjects: list(dos?.bindings).map((b) => ({
|
|
6482
|
+
durableObjects: list$1(dos?.bindings).map((b) => ({
|
|
6407
6483
|
binding: str$1(b["name"]),
|
|
6408
6484
|
className: str$1(b["class_name"]),
|
|
6409
6485
|
...b["script_name"] === void 0 ? {} : { scriptName: str$1(b["script_name"]) }
|
|
6410
6486
|
})),
|
|
6411
|
-
services: list(config["services"]).map((b) => ({
|
|
6487
|
+
services: list$1(config["services"]).map((b) => ({
|
|
6412
6488
|
binding: str$1(b["binding"]),
|
|
6413
6489
|
...typeof b["entrypoint"] === "string" ? { entrypoint: b["entrypoint"] } : {},
|
|
6414
6490
|
...typeof b["props"] === "object" && b["props"] !== null ? { props: b["props"] } : {}
|
|
@@ -6540,12 +6616,12 @@ test("eutaxy check", async ({ task }) => {
|
|
|
6540
6616
|
`;
|
|
6541
6617
|
}
|
|
6542
6618
|
function vitestConfigSource(wranglerConfigPath, testPath, outputFile, isolate) {
|
|
6543
|
-
const plugin = isolate === void 0 ? `cloudflareTest({ wrangler: { configPath: ${JSON.stringify(wranglerConfigPath)} } })` : `cloudflareTest({ main: ${JSON.stringify(isolate.main)}, wrangler: { configPath: ${JSON.stringify(wranglerConfigPath)} }
|
|
6619
|
+
const plugin = isolate === void 0 ? `cloudflareTest({ wrangler: { configPath: ${JSON.stringify(wranglerConfigPath)} } })` : `cloudflareTest({ main: ${JSON.stringify(isolate.main)}, wrangler: { configPath: ${JSON.stringify(wranglerConfigPath)} }${isolate.miniflare === void 0 ? "" : `, miniflare: ${isolate.miniflare}`} })`;
|
|
6544
6620
|
return `// Generated by eutaxy check; deleted after the run.
|
|
6545
6621
|
import { cloudflareTest } from "@cloudflare/vitest-plugin";
|
|
6546
6622
|
import { defineConfig } from "vitest/config";
|
|
6547
6623
|
|
|
6548
|
-
${isolate === void 0 ? "" : `const ${neverCalled} = () => new Response("eutaxy: a service binding the scenario scripts or runs as a callee is never called", { status: 500 });\n\n`}export default defineConfig({
|
|
6624
|
+
${isolate?.miniflare === void 0 ? "" : `const ${neverCalled} = () => new Response("eutaxy: a service binding the scenario scripts or runs as a callee is never called", { status: 500 });\n\n`}export default defineConfig({
|
|
6549
6625
|
plugins: [${plugin}],
|
|
6550
6626
|
test: {
|
|
6551
6627
|
include: [${JSON.stringify(testPath)}],
|
|
@@ -6763,11 +6839,6 @@ async function runCheck(o) {
|
|
|
6763
6839
|
}
|
|
6764
6840
|
const dir = dirname(scenarioPath);
|
|
6765
6841
|
const name = basename(scenarioPath).replace(/\.sim\.ts$/, "").replace(/\.ts$/, "");
|
|
6766
|
-
const wrangler = findWrangler(dir, o.wrangler, o.cwd);
|
|
6767
|
-
if (!wrangler || !existsSync(wrangler)) {
|
|
6768
|
-
o.stderr(`no wrangler config found next to the scenario; pass --wrangler <path>\n`);
|
|
6769
|
-
return exitCodes.error;
|
|
6770
|
-
}
|
|
6771
6842
|
const stamp = `${process.pid}-${randomBytes(3).toString("hex")}`;
|
|
6772
6843
|
const workDir = join(dir, ".eutaxy");
|
|
6773
6844
|
const testPath = join(workDir, `${name}.${stamp}.check.test.ts`);
|
|
@@ -6775,18 +6846,31 @@ async function runCheck(o) {
|
|
|
6775
6846
|
const mainPath = join(workDir, `main.${stamp}.ts`);
|
|
6776
6847
|
let callees = [];
|
|
6777
6848
|
let loaded;
|
|
6778
|
-
|
|
6779
|
-
|
|
6780
|
-
|
|
6781
|
-
|
|
6782
|
-
} catch (err) {
|
|
6849
|
+
try {
|
|
6850
|
+
loaded = await loadScenario(scenarioPath);
|
|
6851
|
+
} catch (err) {
|
|
6852
|
+
if (mentionsCallee(readFileSync(scenarioPath, "utf8"))) {
|
|
6783
6853
|
o.stderr(`could not read the scenario's callees: ${String(err)}\n`);
|
|
6784
6854
|
return exitCodes.error;
|
|
6785
6855
|
}
|
|
6786
|
-
|
|
6856
|
+
o.stderr(`could not read the scenario in Node, so the isolate's main module is the wrangler config's: ${String(err).split("\n")[0]}\n`);
|
|
6787
6857
|
}
|
|
6788
|
-
const
|
|
6789
|
-
const
|
|
6858
|
+
const named = o.wrangler === void 0 ? loaded?.worker.config : void 0;
|
|
6859
|
+
const wrangler = named !== void 0 ? resolve(dir, named) : findWrangler(dir, o.wrangler, o.cwd);
|
|
6860
|
+
if (!wrangler || !existsSync(wrangler)) {
|
|
6861
|
+
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`);
|
|
6862
|
+
return exitCodes.error;
|
|
6863
|
+
}
|
|
6864
|
+
try {
|
|
6865
|
+
callees = calleeSteps(loaded?.setup ?? []).map((step) => readCalleeConfig(step, dir));
|
|
6866
|
+
} catch (err) {
|
|
6867
|
+
o.stderr(`could not read the scenario's callees: ${String(err)}\n`);
|
|
6868
|
+
return exitCodes.error;
|
|
6869
|
+
}
|
|
6870
|
+
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`);
|
|
6871
|
+
const callerResources = readCallerResources(wrangler);
|
|
6872
|
+
const isolate = isolateOf(callees, callees.length > 0 ? callerResources : void 0);
|
|
6873
|
+
const callerServices = (callerResources?.services ?? []).map((s) => s.binding).filter((b) => b);
|
|
6790
6874
|
for (const reason of isolate.notAdded) o.stderr(`not added to the test's isolate: ${reason}\n`);
|
|
6791
6875
|
mkdirSync(workDir, { recursive: true });
|
|
6792
6876
|
try {
|
|
@@ -6827,9 +6911,12 @@ async function runCheck(o) {
|
|
|
6827
6911
|
writeFileSync(mainPath, mainModuleSource(workDir, callerEntry, callees, isolate));
|
|
6828
6912
|
writeFileSync(configPath, vitestConfigSource(wrangler, testPath, reportPath, {
|
|
6829
6913
|
main: mainPath,
|
|
6830
|
-
miniflare: miniflareOptionsSource(callees, isolate)
|
|
6914
|
+
miniflare: miniflareOptionsSource(callees, isolate, callerServices)
|
|
6831
6915
|
}));
|
|
6832
|
-
} else writeFileSync(configPath, vitestConfigSource(wrangler, testPath, reportPath
|
|
6916
|
+
} else writeFileSync(configPath, vitestConfigSource(wrangler, testPath, reportPath, loaded ? {
|
|
6917
|
+
main: resolve(dir, loaded.worker.entry),
|
|
6918
|
+
...callerServices.length > 0 ? { miniflare: miniflareOptionsSource([], void 0, callerServices) } : {}
|
|
6919
|
+
} : void 0));
|
|
6833
6920
|
const { code, output } = await runVitest(vitestBin(dir), configPath, dir);
|
|
6834
6921
|
const transport = code === 0 ? readTransport(reportPath) : null;
|
|
6835
6922
|
if (!transport) {
|
|
@@ -6863,7 +6950,11 @@ async function runCheck(o) {
|
|
|
6863
6950
|
const outPath = regressionPath;
|
|
6864
6951
|
const outDir = dirname(outPath);
|
|
6865
6952
|
const schemaPaths = {};
|
|
6866
|
-
for (const step of transport.setup) if (step.kind === "d1")
|
|
6953
|
+
for (const step of transport.setup) if (step.kind === "d1") {
|
|
6954
|
+
const binding = String(step["binding"]);
|
|
6955
|
+
const path = toPosix(relative(outDir, resolve(dir, String(step["schemaFile"]))));
|
|
6956
|
+
schemaPaths[binding] = [...schemaPaths[binding] ?? [], path];
|
|
6957
|
+
}
|
|
6867
6958
|
const calleePaths = {};
|
|
6868
6959
|
for (const step of transport.setup) {
|
|
6869
6960
|
if (step.kind !== "callee") continue;
|
|
@@ -6916,6 +7007,480 @@ function cleanUp(workDir, stamp) {
|
|
|
6916
7007
|
force: true
|
|
6917
7008
|
});
|
|
6918
7009
|
}
|
|
7010
|
+
// packages/cli/src/draft.ts
|
|
7011
|
+
/**
|
|
7012
|
+
* `eutaxy draft`: a scenario skeleton from a wrangler config and the Worker
|
|
7013
|
+
* module it names. The config's bindings become setup steps, the Worker's
|
|
7014
|
+
* handlers the drive, the hosts its code fetches the externals; the
|
|
7015
|
+
* invariants and the drive's events are left as holes marked TODO, since
|
|
7016
|
+
* only the author knows what must hold and which events matter. Nothing is
|
|
7017
|
+
* imported or run: the config is read as JSON or JSONC and the module's
|
|
7018
|
+
* source (with the modules it imports relatively) is scanned as text.
|
|
7019
|
+
*/
|
|
7020
|
+
const list = (v) => Array.isArray(v) ? v.filter((x) => typeof x === "object" && x) : [];
|
|
7021
|
+
const text$1 = (v) => typeof v === "string" ? v : "";
|
|
7022
|
+
const record = (v) => typeof v === "object" && v !== null && !Array.isArray(v) ? v : {};
|
|
7023
|
+
/** A path relative to `from`, with forward slashes and a leading `./`. */
|
|
7024
|
+
function ref(from, to) {
|
|
7025
|
+
const p = relative(from, to).split("\\").join("/");
|
|
7026
|
+
return p.startsWith(".") ? p : `./${p}`;
|
|
7027
|
+
}
|
|
7028
|
+
/** Read a wrangler config as JSON or JSONC; TOML is not read. */
|
|
7029
|
+
function readConfig(path) {
|
|
7030
|
+
if (extname(path) !== ".json" && extname(path) !== ".jsonc") throw new Error(`${basename(path)}: eutaxy draft reads a wrangler config as JSON or JSONC; a TOML config is not read`);
|
|
7031
|
+
return readWranglerConfig(path);
|
|
7032
|
+
}
|
|
7033
|
+
/** Binding kinds the simulation does not proxy: a run that touches one is UNSUPPORTED. */
|
|
7034
|
+
const unmodelled = {
|
|
7035
|
+
kv_namespaces: "KV namespace",
|
|
7036
|
+
ai: "Workers AI",
|
|
7037
|
+
vectorize: "Vectorize index",
|
|
7038
|
+
hyperdrive: "Hyperdrive config",
|
|
7039
|
+
analytics_engine_datasets: "Analytics Engine dataset",
|
|
7040
|
+
browser: "Browser Rendering",
|
|
7041
|
+
send_email: "email sender",
|
|
7042
|
+
dispatch_namespaces: "dispatch namespace",
|
|
7043
|
+
mtls_certificates: "mTLS certificate",
|
|
7044
|
+
secrets_store_secrets: "Secrets Store secret",
|
|
7045
|
+
images: "Images",
|
|
7046
|
+
version_metadata: "version metadata",
|
|
7047
|
+
pipelines: "pipeline"
|
|
7048
|
+
};
|
|
7049
|
+
/** The SQLite-backed classes of a config's migrations (the ones created so, as wrangler applies them). */
|
|
7050
|
+
function sqliteClasses(config) {
|
|
7051
|
+
const out = /* @__PURE__ */ new Set();
|
|
7052
|
+
for (const m of list(config["migrations"])) for (const c of Array.isArray(m["new_sqlite_classes"]) ? m["new_sqlite_classes"] : []) if (typeof c === "string") out.add(c);
|
|
7053
|
+
return out;
|
|
7054
|
+
}
|
|
7055
|
+
/**
|
|
7056
|
+
* The schema file of a D1 binding, beside its config: `schema.sql`, else `<database_name>.sql`, else the
|
|
7057
|
+
* only `.sql` file there; `found` false when none is, and the step names `schema.sql` to create.
|
|
7058
|
+
*/
|
|
7059
|
+
function schemaOf(configDir, database) {
|
|
7060
|
+
for (const name of ["schema.sql", database ? `${database}.sql` : ""]) if (name && existsSync(join(configDir, name))) return {
|
|
7061
|
+
file: join(configDir, name),
|
|
7062
|
+
found: true
|
|
7063
|
+
};
|
|
7064
|
+
const sql = readdirSync(configDir).filter((f) => f.endsWith(".sql"));
|
|
7065
|
+
if (sql.length === 1) return {
|
|
7066
|
+
file: join(configDir, sql[0]),
|
|
7067
|
+
found: true
|
|
7068
|
+
};
|
|
7069
|
+
return {
|
|
7070
|
+
file: join(configDir, "schema.sql"),
|
|
7071
|
+
found: false
|
|
7072
|
+
};
|
|
7073
|
+
}
|
|
7074
|
+
/**
|
|
7075
|
+
* Migrations in the order wrangler applies them: by the number a name starts with, compared as a number
|
|
7076
|
+
* (`2_add` before `10_seed`), then by name; a name with no number after the numbered ones.
|
|
7077
|
+
*/
|
|
7078
|
+
function migrationOrder(a, b) {
|
|
7079
|
+
const na = /^\d+/.exec(a)?.[0];
|
|
7080
|
+
const nb = /^\d+/.exec(b)?.[0];
|
|
7081
|
+
if (na !== void 0 && nb !== void 0 && Number(na) !== Number(nb)) return Number(na) - Number(nb);
|
|
7082
|
+
if (na !== void 0 && nb === void 0) return -1;
|
|
7083
|
+
if (na === void 0 && nb !== void 0) return 1;
|
|
7084
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
7085
|
+
}
|
|
7086
|
+
/**
|
|
7087
|
+
* A migrations directory's files in the order wrangler applies them: its `.sql` files, and a
|
|
7088
|
+
* subdirectory's `migration.sql` (one folder per migration, as drizzle-kit writes them).
|
|
7089
|
+
*/
|
|
7090
|
+
function migrationFiles(dir) {
|
|
7091
|
+
if (!existsSync(dir)) return [];
|
|
7092
|
+
return readdirSync(dir, { withFileTypes: true }).sort((a, b) => migrationOrder(a.name, b.name)).flatMap((e) => {
|
|
7093
|
+
if (e.isFile() && e.name.endsWith(".sql")) return [join(dir, e.name)];
|
|
7094
|
+
const nested = join(dir, e.name, "migration.sql");
|
|
7095
|
+
return e.isDirectory() && existsSync(nested) ? [nested] : [];
|
|
7096
|
+
});
|
|
7097
|
+
}
|
|
7098
|
+
/** Wrangler configs under `root` (not in node_modules or dot directories), by their `name`. */
|
|
7099
|
+
function configsByName(root, depth = 3) {
|
|
7100
|
+
const out = /* @__PURE__ */ new Map();
|
|
7101
|
+
const walk = (dir, left) => {
|
|
7102
|
+
let entries;
|
|
7103
|
+
try {
|
|
7104
|
+
entries = readdirSync(dir, { withFileTypes: true });
|
|
7105
|
+
} catch {
|
|
7106
|
+
return;
|
|
7107
|
+
}
|
|
7108
|
+
for (const e of entries) {
|
|
7109
|
+
const path = join(dir, e.name);
|
|
7110
|
+
if (e.isDirectory()) {
|
|
7111
|
+
if (left > 0 && e.name !== "node_modules" && !e.name.startsWith(".")) walk(path, left - 1);
|
|
7112
|
+
} else if (e.name === "wrangler.jsonc" || e.name === "wrangler.json") try {
|
|
7113
|
+
const name = text$1(readConfig(path)["name"]);
|
|
7114
|
+
if (name && !out.has(name)) out.set(name, path);
|
|
7115
|
+
} catch {}
|
|
7116
|
+
}
|
|
7117
|
+
};
|
|
7118
|
+
walk(root, depth);
|
|
7119
|
+
return out;
|
|
7120
|
+
}
|
|
7121
|
+
/** The source of a module and of the modules it imports by relative path, transitively. */
|
|
7122
|
+
function sources(entry) {
|
|
7123
|
+
const seen = /* @__PURE__ */ new Set();
|
|
7124
|
+
const out = [];
|
|
7125
|
+
const visit = (file) => {
|
|
7126
|
+
if (seen.has(file) || !existsSync(file)) return;
|
|
7127
|
+
seen.add(file);
|
|
7128
|
+
const src = readFileSync(file, "utf8");
|
|
7129
|
+
out.push(src);
|
|
7130
|
+
for (const m of src.matchAll(/(?:\bfrom\s*|\bimport\s*\(?\s*)["'](\.{1,2}\/[^"']+)["']/g)) {
|
|
7131
|
+
const spec = resolve(dirname(file), m[1]);
|
|
7132
|
+
const found = [
|
|
7133
|
+
spec,
|
|
7134
|
+
spec.replace(/\.js$/, ".ts"),
|
|
7135
|
+
`${spec}.ts`,
|
|
7136
|
+
join(spec, "index.ts")
|
|
7137
|
+
].find((c) => existsSync(c) && extname(c) !== "");
|
|
7138
|
+
if (found) visit(found);
|
|
7139
|
+
}
|
|
7140
|
+
};
|
|
7141
|
+
visit(entry);
|
|
7142
|
+
return out;
|
|
7143
|
+
}
|
|
7144
|
+
/**
|
|
7145
|
+
* The hosts a module's code fetches by a literal URL, in order of first appearance, as `URL.host` has
|
|
7146
|
+
* them (which the fetch interceptor matches): lowercase, a non-default port kept.
|
|
7147
|
+
*/
|
|
7148
|
+
function fetchedHosts(srcs) {
|
|
7149
|
+
const hosts = [];
|
|
7150
|
+
for (const src of srcs) for (const m of src.matchAll(/\bfetch\(\s*["'`](https?):\/\/([a-z0-9.-]+)(?::(\d+))?/gi)) {
|
|
7151
|
+
const port = m[3];
|
|
7152
|
+
const defaultPort = m[1].toLowerCase() === "https" ? "443" : "80";
|
|
7153
|
+
const host = `${m[2].toLowerCase()}${port && port !== defaultPort ? `:${port}` : ""}`;
|
|
7154
|
+
if (!hosts.includes(host)) hosts.push(host);
|
|
7155
|
+
}
|
|
7156
|
+
return hosts;
|
|
7157
|
+
}
|
|
7158
|
+
/** An external's name from its host: the first label, made an identifier-like word, unique. */
|
|
7159
|
+
function externalName(host, taken) {
|
|
7160
|
+
const base = (host.split(".")[0] ?? host).replace(/[^a-z0-9-]/gi, "-") || "external";
|
|
7161
|
+
let name = base;
|
|
7162
|
+
for (let i = 2; taken.has(name); i++) name = `${base}-${i}`;
|
|
7163
|
+
taken.add(name);
|
|
7164
|
+
return name;
|
|
7165
|
+
}
|
|
7166
|
+
/**
|
|
7167
|
+
* The SDK's route segment for an Agent's binding, as `routeAgentRequest` matches it: the Agents SDK's
|
|
7168
|
+
* `camelCaseToKebabCase` (an all-caps name lowercased, else a dash before every capital).
|
|
7169
|
+
*/
|
|
7170
|
+
function agentSegment(binding) {
|
|
7171
|
+
if (binding === binding.toUpperCase() && binding !== binding.toLowerCase()) return binding.toLowerCase().replaceAll("_", "-");
|
|
7172
|
+
const kebab = binding.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`);
|
|
7173
|
+
return (kebab.startsWith("-") ? kebab.slice(1) : kebab).replaceAll("_", "-").replace(/-$/, "");
|
|
7174
|
+
}
|
|
7175
|
+
function draftScenario(input) {
|
|
7176
|
+
const config = readConfig(input.config);
|
|
7177
|
+
const configDir = dirname(input.config);
|
|
7178
|
+
const scenarioDir = input.scenarioDir ?? configDir;
|
|
7179
|
+
const name = text$1(config["name"]) || basename(configDir);
|
|
7180
|
+
const main = text$1(config["main"]);
|
|
7181
|
+
if (input.entry === void 0 && !main) throw new Error(`${basename(input.config)} names no main module; pass the Worker's module`);
|
|
7182
|
+
const entry = input.entry ?? resolve(configDir, main);
|
|
7183
|
+
if (!existsSync(entry)) throw new Error(`the Worker module ${entry} does not exist`);
|
|
7184
|
+
const notes = [];
|
|
7185
|
+
const setup = [];
|
|
7186
|
+
const callerSrcs = sources(entry);
|
|
7187
|
+
const srcs = [...callerSrcs];
|
|
7188
|
+
const others = list(config["services"]).length > 0 ? configsByName(scenarioDir) : /* @__PURE__ */ new Map();
|
|
7189
|
+
const callees = /* @__PURE__ */ new Map();
|
|
7190
|
+
for (const s of list(config["services"])) {
|
|
7191
|
+
const service = text$1(s["service"]);
|
|
7192
|
+
const found = service && service !== name ? others.get(service) : void 0;
|
|
7193
|
+
if (found !== void 0) callees.set(service, found);
|
|
7194
|
+
}
|
|
7195
|
+
const d1Id = (db) => text$1(db["database_id"]) || text$1(db["database_name"]) || text$1(db["binding"]);
|
|
7196
|
+
const callerDatabases = new Map(list(config["d1_databases"]).map((db) => [d1Id(db), text$1(db["binding"])]));
|
|
7197
|
+
const callerBuckets = new Map(list(config["r2_buckets"]).map((b) => [text$1(b["bucket_name"]) || text$1(b["binding"]), text$1(b["binding"])]));
|
|
7198
|
+
/** Classes of a callee's script the caller binds itself: one namespace, set up under the caller's name. */
|
|
7199
|
+
const sharedClasses = new Set(list(record(config["durable_objects"])["bindings"]).filter((b) => callees.has(text$1(b["script_name"]))).map((b) => `${text$1(b["script_name"])}:${text$1(b["class_name"])}`));
|
|
7200
|
+
/** The setup steps of one Worker's own resources: the caller's (prefix ""), or a callee's (`<name>/`). */
|
|
7201
|
+
const resourceSteps = (cfg, dir, worker, prefix) => {
|
|
7202
|
+
const sqlite = sqliteClasses(cfg);
|
|
7203
|
+
for (const db of list(cfg["d1_databases"])) {
|
|
7204
|
+
const binding = text$1(db["binding"]);
|
|
7205
|
+
if (!binding) continue;
|
|
7206
|
+
const shared = prefix ? callerDatabases.get(d1Id(db)) : void 0;
|
|
7207
|
+
if (shared !== void 0) {
|
|
7208
|
+
notes.push(`D1 ${prefix}${binding} is the caller's database ${shared}: set it up and read it as ${shared}`);
|
|
7209
|
+
continue;
|
|
7210
|
+
}
|
|
7211
|
+
const schema = schemaOf(dir, text$1(db["database_name"]));
|
|
7212
|
+
const pattern = text$1(db["migrations_pattern"]);
|
|
7213
|
+
if (!schema.found && pattern) notes.push(`D1 ${prefix}${binding}: its migrations are the files matching ${pattern}; add a d1Schema step for each, in the order wrangler applies them`);
|
|
7214
|
+
const migrations = schema.found || pattern ? [] : migrationFiles(join(dir, text$1(db["migrations_dir"]) || "migrations"));
|
|
7215
|
+
if (migrations.length > 0) {
|
|
7216
|
+
for (const file of migrations) setup.push({
|
|
7217
|
+
kind: "d1",
|
|
7218
|
+
binding: `${prefix}${binding}`,
|
|
7219
|
+
schemaFile: ref(scenarioDir, file)
|
|
7220
|
+
});
|
|
7221
|
+
continue;
|
|
7222
|
+
}
|
|
7223
|
+
if (!schema.found && !pattern) notes.push(`D1 ${prefix}${binding}: no schema file found; write the tables it needs into ${ref(scenarioDir, schema.file)}`);
|
|
7224
|
+
setup.push({
|
|
7225
|
+
kind: "d1",
|
|
7226
|
+
binding: `${prefix}${binding}`,
|
|
7227
|
+
schemaFile: ref(scenarioDir, schema.file)
|
|
7228
|
+
});
|
|
7229
|
+
}
|
|
7230
|
+
for (const b of list(record(cfg["durable_objects"])["bindings"])) {
|
|
7231
|
+
const binding = text$1(b["name"]);
|
|
7232
|
+
const className = text$1(b["class_name"]);
|
|
7233
|
+
const script = text$1(b["script_name"]);
|
|
7234
|
+
if (!binding) continue;
|
|
7235
|
+
if (script && script !== worker) {
|
|
7236
|
+
if (!prefix && callees.has(script)) setup.push({
|
|
7237
|
+
kind: "durable_object",
|
|
7238
|
+
binding,
|
|
7239
|
+
sqlite: sqliteClasses(readConfig(callees.get(script))).has(className)
|
|
7240
|
+
});
|
|
7241
|
+
else notes.push(`Durable Object ${prefix}${binding} is ${script}'s class ${className}: name ${script} with callee() to run it`);
|
|
7242
|
+
continue;
|
|
7243
|
+
}
|
|
7244
|
+
if (prefix && sharedClasses.has(`${worker}:${className}`)) {
|
|
7245
|
+
notes.push(`Durable Object ${prefix}${binding} is the namespace the caller binds to ${worker}'s class ${className}: set it up and read it under the caller's name`);
|
|
7246
|
+
continue;
|
|
7247
|
+
}
|
|
7248
|
+
setup.push({
|
|
7249
|
+
kind: "durable_object",
|
|
7250
|
+
binding: `${prefix}${binding}`,
|
|
7251
|
+
sqlite: sqlite.has(className)
|
|
7252
|
+
});
|
|
7253
|
+
}
|
|
7254
|
+
for (const b of list(cfg["r2_buckets"])) {
|
|
7255
|
+
const binding = text$1(b["binding"]);
|
|
7256
|
+
if (!binding) continue;
|
|
7257
|
+
const shared = prefix ? callerBuckets.get(text$1(b["bucket_name"]) || binding) : void 0;
|
|
7258
|
+
if (shared !== void 0) {
|
|
7259
|
+
notes.push(`R2 ${prefix}${binding} is the caller's bucket ${shared}: set it up and read it as ${shared}`);
|
|
7260
|
+
continue;
|
|
7261
|
+
}
|
|
7262
|
+
setup.push({
|
|
7263
|
+
kind: "r2",
|
|
7264
|
+
binding: `${prefix}${binding}`
|
|
7265
|
+
});
|
|
7266
|
+
}
|
|
7267
|
+
for (const w of list(cfg["workflows"])) {
|
|
7268
|
+
const binding = text$1(w["binding"]);
|
|
7269
|
+
const className = text$1(w["class_name"]);
|
|
7270
|
+
const script = text$1(w["script_name"]);
|
|
7271
|
+
if (!binding || !className) continue;
|
|
7272
|
+
if (script && script !== worker) {
|
|
7273
|
+
notes.push(`Workflow ${prefix}${binding} runs in ${script}: name ${script} with callee() to run it`);
|
|
7274
|
+
continue;
|
|
7275
|
+
}
|
|
7276
|
+
const workflowName = text$1(w["name"]);
|
|
7277
|
+
setup.push({
|
|
7278
|
+
kind: "workflow",
|
|
7279
|
+
binding: `${prefix}${binding}`,
|
|
7280
|
+
className,
|
|
7281
|
+
...workflowName ? { name: workflowName } : {}
|
|
7282
|
+
});
|
|
7283
|
+
}
|
|
7284
|
+
for (const [key, what] of Object.entries(unmodelled)) {
|
|
7285
|
+
const v = cfg[key];
|
|
7286
|
+
const bindings = Array.isArray(v) ? list(v).map((b) => text$1(b["binding"]) || text$1(b["name"])) : v !== void 0 ? [text$1(record(v)["binding"]) || key] : [];
|
|
7287
|
+
for (const b of bindings) notes.push(`not modelled: ${what} ${prefix}${b}; a run that touches it is UNSUPPORTED`);
|
|
7288
|
+
}
|
|
7289
|
+
for (const q of list(record(cfg["queues"])["producers"])) notes.push(`not modelled: Queue producer ${prefix}${text$1(q["binding"])}; a run that sends to it is UNSUPPORTED`);
|
|
7290
|
+
};
|
|
7291
|
+
resourceSteps(config, configDir, name, "");
|
|
7292
|
+
for (const s of list(config["services"])) {
|
|
7293
|
+
const binding = text$1(s["binding"]);
|
|
7294
|
+
const service = text$1(s["service"]);
|
|
7295
|
+
if (!binding) continue;
|
|
7296
|
+
const calleeConfig = callees.get(service);
|
|
7297
|
+
if (calleeConfig === void 0) {
|
|
7298
|
+
setup.push({
|
|
7299
|
+
kind: "service",
|
|
7300
|
+
binding
|
|
7301
|
+
});
|
|
7302
|
+
notes.push(`service binding ${binding}: no wrangler config named ${service || "(none)"} under the scenario's directory, so its answers are scripted; script them with service(), or run that Worker with callee()`);
|
|
7303
|
+
continue;
|
|
7304
|
+
}
|
|
7305
|
+
const callee = readConfig(calleeConfig);
|
|
7306
|
+
const calleeDir = dirname(calleeConfig);
|
|
7307
|
+
const calleeMain = resolve(calleeDir, text$1(callee["main"]));
|
|
7308
|
+
setup.push({
|
|
7309
|
+
kind: "callee",
|
|
7310
|
+
binding,
|
|
7311
|
+
entry: ref(scenarioDir, calleeMain),
|
|
7312
|
+
config: ref(scenarioDir, calleeConfig)
|
|
7313
|
+
});
|
|
7314
|
+
resourceSteps(callee, calleeDir, service, `${service}/`);
|
|
7315
|
+
srcs.push(...sources(calleeMain));
|
|
7316
|
+
}
|
|
7317
|
+
const outside = [entry, ...setup.flatMap((s) => s.kind === "d1" && !s.binding.includes("/") ? [resolve(scenarioDir, s.schemaFile)] : [])].filter((f) => relative(scenarioDir, f).startsWith(".."));
|
|
7318
|
+
if (outside.length > 0) throw new Error(`eutaxy check finds the Worker's module and its schema files beneath the scenario's directory, and ${outside.map((f) => relative(scenarioDir, f)).join(", ")} is not; write the scenario beside the wrangler config or in a directory above the Worker`);
|
|
7319
|
+
const consumers = list(record(config["queues"])["consumers"]);
|
|
7320
|
+
const crons = Array.isArray(record(config["triggers"])["crons"]) ? record(config["triggers"])["crons"].filter((c) => typeof c === "string") : [];
|
|
7321
|
+
const routesAgents = callerSrcs.some((s) => /\brouteAgentRequest\s*\(/.test(s));
|
|
7322
|
+
const firstObject = setup.find((s) => s.kind === "durable_object" && !s.binding.includes("/"));
|
|
7323
|
+
let drive;
|
|
7324
|
+
if (consumers.length > 0) {
|
|
7325
|
+
drive = {
|
|
7326
|
+
kind: "queue",
|
|
7327
|
+
queue: text$1(consumers[0]?.["queue"])
|
|
7328
|
+
};
|
|
7329
|
+
if (consumers.length > 1) notes.push(`the Worker consumes ${consumers.length} queues; one drive per scenario, so a scenario per queue`);
|
|
7330
|
+
} else if (crons.length > 0) drive = {
|
|
7331
|
+
kind: "cron",
|
|
7332
|
+
cron: crons[0]
|
|
7333
|
+
};
|
|
7334
|
+
else if (routesAgents && firstObject) drive = {
|
|
7335
|
+
kind: "websocket",
|
|
7336
|
+
agent: agentSegment(firstObject.binding)
|
|
7337
|
+
};
|
|
7338
|
+
else drive = { kind: "http" };
|
|
7339
|
+
if (drive.kind !== "cron" && crons.length > 0) notes.push(`the Worker also has Cron Triggers (${crons.join(", ")}); a scenario per drive`);
|
|
7340
|
+
const taken = /* @__PURE__ */ new Set();
|
|
7341
|
+
const externals = fetchedHosts(srcs).map((host) => ({
|
|
7342
|
+
name: externalName(host, taken),
|
|
7343
|
+
host
|
|
7344
|
+
}));
|
|
7345
|
+
return {
|
|
7346
|
+
name,
|
|
7347
|
+
worker: {
|
|
7348
|
+
entry: ref(scenarioDir, entry),
|
|
7349
|
+
config: ref(scenarioDir, input.config)
|
|
7350
|
+
},
|
|
7351
|
+
drive,
|
|
7352
|
+
setup,
|
|
7353
|
+
externals,
|
|
7354
|
+
notes
|
|
7355
|
+
};
|
|
7356
|
+
}
|
|
7357
|
+
const q = (s) => JSON.stringify(s);
|
|
7358
|
+
function stepSource(s) {
|
|
7359
|
+
switch (s.kind) {
|
|
7360
|
+
case "d1": return `d1Schema(${q(s.binding)}, ${q(s.schemaFile)}),`;
|
|
7361
|
+
case "durable_object": return s.sqlite ? `// SQLite-backed: seed tables with { sql: { <object name>: { schema, rows } } }.\n durableObject(${q(s.binding)}, {}),` : `durableObject(${q(s.binding)}, {}),`;
|
|
7362
|
+
case "r2": return `r2Bucket(${q(s.binding)}),`;
|
|
7363
|
+
case "workflow": return s.name === void 0 ? `workflow(${q(s.binding)}, ${q(s.className)}),` : `workflow(${q(s.binding)}, ${q(s.className)}, { name: ${q(s.name)} }),`;
|
|
7364
|
+
case "callee": return `callee(${q(s.binding)}, { entry: ${q(s.entry)}, config: ${q(s.config)} }),`;
|
|
7365
|
+
case "service": return `// TODO: the answers of the Worker behind ${s.binding}, e.g. { methods: { <method>: { value: … } } }.\n service(${q(s.binding)}),`;
|
|
7366
|
+
}
|
|
7367
|
+
}
|
|
7368
|
+
function driveSource(d) {
|
|
7369
|
+
switch (d.kind) {
|
|
7370
|
+
case "queue": return {
|
|
7371
|
+
helper: "queue",
|
|
7372
|
+
source: `// TODO: the messages to deliver.\n drive: queue(${q(d.queue)}, [{ body: {} }]),`
|
|
7373
|
+
};
|
|
7374
|
+
case "cron": return {
|
|
7375
|
+
helper: "cron",
|
|
7376
|
+
source: `// TODO: how many ticks, and how many times a failed tick is re-run.\n drive: cron(${q(d.cron)}, { ticks: 2 }),`
|
|
7377
|
+
};
|
|
7378
|
+
case "websocket": return {
|
|
7379
|
+
helper: "websocket",
|
|
7380
|
+
source: `// TODO: the connections, the Agent instance they reach and the messages each sends.\n drive: websocket([\n { id: "a", path: ${q(`/agents/${d.agent}/<name>`)}, messages: [{ data: {} }] },\n ]),`
|
|
7381
|
+
};
|
|
7382
|
+
case "http": return {
|
|
7383
|
+
helper: "http",
|
|
7384
|
+
source: `// TODO: the requests, and how the caller resends one that got no 2xx.\n drive: http([{ path: "/", body: {} }], { retries: 3 }),`
|
|
7385
|
+
};
|
|
7386
|
+
}
|
|
7387
|
+
}
|
|
7388
|
+
/** Example invariants for the draft's bindings, as comments: the hole the author fills. */
|
|
7389
|
+
function invariantHints(d) {
|
|
7390
|
+
const hints = [];
|
|
7391
|
+
const d1 = d.setup.find((s) => s.kind === "d1");
|
|
7392
|
+
if (d1) hints.push(`unique("one-row-per-key", d1Rows(${q(d1.binding)}, "<table>"), "<column>"),`);
|
|
7393
|
+
const sqliteObject = d.setup.find((s) => s.kind === "durable_object" && s.sqlite);
|
|
7394
|
+
if (sqliteObject) hints.push(`everyRow("<rule>", durableObjectTable(${q(sqliteObject.binding)}, "<object name>", "<table>"), [{ column: "<column>", op: "gte", value: 0 }]),`);
|
|
7395
|
+
const external = d.externals[0];
|
|
7396
|
+
if (external) hints.push(`atMostOncePerKey("<call>-once", fetchCall(${q(external.name)}, "POST"), "args.body.<id>"),`);
|
|
7397
|
+
if (hints.length === 0) hints.push(`atMostOncePerKey("<effect>-once", httpResponse("/", { ok: true }), "args.requestId"),`);
|
|
7398
|
+
return hints;
|
|
7399
|
+
}
|
|
7400
|
+
/** The scenario's source. With no invariant it does not check until the holes are filled. */
|
|
7401
|
+
function renderDraft(d) {
|
|
7402
|
+
const drive = driveSource(d.drive);
|
|
7403
|
+
const helpers = /* @__PURE__ */ new Set(["defineScenario", drive.helper]);
|
|
7404
|
+
const stepHelper = {
|
|
7405
|
+
d1: "d1Schema",
|
|
7406
|
+
durable_object: "durableObject",
|
|
7407
|
+
r2: "r2Bucket",
|
|
7408
|
+
workflow: "workflow",
|
|
7409
|
+
callee: "callee",
|
|
7410
|
+
service: "service"
|
|
7411
|
+
};
|
|
7412
|
+
for (const s of d.setup) helpers.add(stepHelper[s.kind]);
|
|
7413
|
+
if (d.externals.length > 0) helpers.add("external");
|
|
7414
|
+
const imports = [...helpers].sort((a, b) => a.localeCompare(b));
|
|
7415
|
+
const lines = [];
|
|
7416
|
+
lines.push(`import { ${imports.join(", ")} } from "eutaxy/cloudflare";`, "");
|
|
7417
|
+
lines.push(`// Drafted by eutaxy draft from ${d.worker.config}. Fill in each TODO, then run`, `// eutaxy check on this file; it does not check until it has an invariant.`);
|
|
7418
|
+
for (const n of d.notes) lines.push(`// Note: ${n}.`);
|
|
7419
|
+
lines.push(`export default defineScenario({`);
|
|
7420
|
+
lines.push(` name: ${q(d.name)},`);
|
|
7421
|
+
lines.push(` worker: { entry: ${q(d.worker.entry)}, config: ${q(d.worker.config)} },`);
|
|
7422
|
+
if (d.setup.length > 0) {
|
|
7423
|
+
lines.push(` setup: [`);
|
|
7424
|
+
for (const s of d.setup) lines.push(` ${stepSource(s)}`);
|
|
7425
|
+
lines.push(` ],`);
|
|
7426
|
+
}
|
|
7427
|
+
lines.push(` ${drive.source}`);
|
|
7428
|
+
if (d.externals.length > 0) {
|
|
7429
|
+
lines.push(` // Each host the Worker fetches answers 200 with an empty body until you script its responses.`);
|
|
7430
|
+
lines.push(` externals: [`);
|
|
7431
|
+
for (const e of d.externals) lines.push(` external(${q(e.name)}, ${q(e.host)}),`);
|
|
7432
|
+
lines.push(` ],`);
|
|
7433
|
+
}
|
|
7434
|
+
lines.push(` invariants: [`);
|
|
7435
|
+
lines.push(` // TODO: what must hold after every run, for example (import what you use from eutaxy/cloudflare):`);
|
|
7436
|
+
for (const h of invariantHints(d)) lines.push(` // ${h}`);
|
|
7437
|
+
lines.push(` ],`);
|
|
7438
|
+
lines.push(` bounds: { maxFaultsPerRun: 1, maxRedeliveries: 2, maxConcurrentInvocations: 1, budgetMs: 2000 },`);
|
|
7439
|
+
lines.push(`});`, "");
|
|
7440
|
+
return lines.join("\n");
|
|
7441
|
+
}
|
|
7442
|
+
/** Exit 0 with the draft printed or written, 3 on an error. */
|
|
7443
|
+
function runDraft(o) {
|
|
7444
|
+
const config = o.config !== void 0 ? resolve(o.cwd, o.config) : ["wrangler.jsonc", "wrangler.json"].map((f) => join(o.cwd, f)).find((p) => existsSync(p));
|
|
7445
|
+
if (config === void 0 || !existsSync(config)) {
|
|
7446
|
+
o.stderr(config === void 0 ? "no wrangler.jsonc or wrangler.json in the working directory; name the config\n" : `wrangler config not found: ${config}\n`);
|
|
7447
|
+
return 3;
|
|
7448
|
+
}
|
|
7449
|
+
const out = o.out === void 0 ? void 0 : resolve(o.cwd, o.out);
|
|
7450
|
+
if (out !== void 0 && existsSync(out)) {
|
|
7451
|
+
o.stderr(`${out} exists; eutaxy draft does not overwrite a file\n`);
|
|
7452
|
+
return 3;
|
|
7453
|
+
}
|
|
7454
|
+
if (out !== void 0 && !existsSync(dirname(out))) {
|
|
7455
|
+
o.stderr(`the directory of ${out} does not exist\n`);
|
|
7456
|
+
return 3;
|
|
7457
|
+
}
|
|
7458
|
+
let draft;
|
|
7459
|
+
try {
|
|
7460
|
+
draft = draftScenario({
|
|
7461
|
+
config,
|
|
7462
|
+
...o.worker === void 0 ? {} : { entry: resolve(o.cwd, o.worker) },
|
|
7463
|
+
...out === void 0 ? {} : { scenarioDir: dirname(out) }
|
|
7464
|
+
});
|
|
7465
|
+
} catch (err) {
|
|
7466
|
+
o.stderr(`${err instanceof Error ? err.message : String(err)}\n`);
|
|
7467
|
+
return 3;
|
|
7468
|
+
}
|
|
7469
|
+
const source = renderDraft(draft);
|
|
7470
|
+
if (out !== void 0) writeFileSync(out, source);
|
|
7471
|
+
if (o.json) o.stdout(`${JSON.stringify({
|
|
7472
|
+
schemaVersion: 1,
|
|
7473
|
+
draft,
|
|
7474
|
+
source,
|
|
7475
|
+
...out === void 0 ? {} : { written: out }
|
|
7476
|
+
}, null, 2)}\n`);
|
|
7477
|
+
else if (out === void 0) o.stdout(source);
|
|
7478
|
+
else {
|
|
7479
|
+
o.stdout(`Scenario drafted in ${relative(o.cwd, out) || out}\n`);
|
|
7480
|
+
for (const n of draft.notes) o.stdout(` note: ${n}\n`);
|
|
7481
|
+
}
|
|
7482
|
+
return 0;
|
|
7483
|
+
}
|
|
6919
7484
|
// packages/cli/src/archive.ts
|
|
6920
7485
|
/**
|
|
6921
7486
|
* Reading the two archive formats the prover releases come in, with Node's
|
|
@@ -7424,6 +7989,75 @@ async function runInstall(options) {
|
|
|
7424
7989
|
return exitCodes.error;
|
|
7425
7990
|
}
|
|
7426
7991
|
}
|
|
7992
|
+
// packages/cli/src/held-output.ts
|
|
7993
|
+
/**
|
|
7994
|
+
* What a module running ahead of its turn writes, held until its turn:
|
|
7995
|
+
* in memory up to a limit, then in a file, so a module that writes a lot
|
|
7996
|
+
* while an earlier one is still running cannot exhaust the report's heap.
|
|
7997
|
+
* Drained, it gives back exactly the text it was given, in order.
|
|
7998
|
+
*/
|
|
7999
|
+
var HeldOutput = class {
|
|
8000
|
+
#limit;
|
|
8001
|
+
#readBytes;
|
|
8002
|
+
#chunks = [];
|
|
8003
|
+
#bytes = 0;
|
|
8004
|
+
#dir;
|
|
8005
|
+
#fd;
|
|
8006
|
+
/** `limitBytes` is held in memory; past it, everything goes to a file, read back `readBytes` at a time. */
|
|
8007
|
+
constructor(limitBytes = 1 << 20, readBytes = 65536) {
|
|
8008
|
+
this.#limit = limitBytes;
|
|
8009
|
+
this.#readBytes = readBytes;
|
|
8010
|
+
}
|
|
8011
|
+
/** Whether the text held so far went past the limit into a file. */
|
|
8012
|
+
get spilled() {
|
|
8013
|
+
return this.#fd !== void 0;
|
|
8014
|
+
}
|
|
8015
|
+
push(text) {
|
|
8016
|
+
const bytes = Buffer.byteLength(text);
|
|
8017
|
+
if (this.#fd === void 0 && this.#bytes + bytes <= this.#limit) {
|
|
8018
|
+
this.#chunks.push(text);
|
|
8019
|
+
this.#bytes += bytes;
|
|
8020
|
+
return;
|
|
8021
|
+
}
|
|
8022
|
+
if (this.#fd === void 0) {
|
|
8023
|
+
this.#dir = mkdtempSync(join(tmpdir(), "eutaxy-report-"));
|
|
8024
|
+
this.#fd = openSync(join(this.#dir, "held"), "w+");
|
|
8025
|
+
}
|
|
8026
|
+
writeSync(this.#fd, text);
|
|
8027
|
+
}
|
|
8028
|
+
/** Everything held, in order, to `out`; then nothing is held and the file is gone. */
|
|
8029
|
+
drain(out) {
|
|
8030
|
+
for (const text of this.#chunks) out(text);
|
|
8031
|
+
this.#chunks = [];
|
|
8032
|
+
this.#bytes = 0;
|
|
8033
|
+
if (this.#fd === void 0) return;
|
|
8034
|
+
try {
|
|
8035
|
+
const decoder = new StringDecoder("utf8");
|
|
8036
|
+
const buffer = Buffer.alloc(this.#readBytes);
|
|
8037
|
+
for (let at = 0;;) {
|
|
8038
|
+
const n = readSync(this.#fd, buffer, 0, buffer.length, at);
|
|
8039
|
+
if (n === 0) break;
|
|
8040
|
+
at += n;
|
|
8041
|
+
const text = decoder.write(buffer.subarray(0, n));
|
|
8042
|
+
if (text !== "") out(text);
|
|
8043
|
+
}
|
|
8044
|
+
const rest = decoder.end();
|
|
8045
|
+
if (rest !== "") out(rest);
|
|
8046
|
+
} finally {
|
|
8047
|
+
this.discard();
|
|
8048
|
+
}
|
|
8049
|
+
}
|
|
8050
|
+
/** Drop the file, if any. */
|
|
8051
|
+
discard() {
|
|
8052
|
+
if (this.#fd !== void 0) closeSync(this.#fd);
|
|
8053
|
+
if (this.#dir !== void 0) rmSync(this.#dir, {
|
|
8054
|
+
recursive: true,
|
|
8055
|
+
force: true
|
|
8056
|
+
});
|
|
8057
|
+
this.#fd = void 0;
|
|
8058
|
+
this.#dir = void 0;
|
|
8059
|
+
}
|
|
8060
|
+
};
|
|
7427
8061
|
// packages/cli/src/report.ts
|
|
7428
8062
|
/**
|
|
7429
8063
|
* `eutaxy report [dir]`: every spec file under a directory through the
|
|
@@ -7534,6 +8168,36 @@ function testModule(m, seed, budgetMs, stderr) {
|
|
|
7534
8168
|
});
|
|
7535
8169
|
}
|
|
7536
8170
|
/**
|
|
8171
|
+
* Every module's verdicts, a few modules' processes at a time. The verdicts
|
|
8172
|
+
* come back in module order, and what each module writes reaches `stderr`
|
|
8173
|
+
* in module order too: a module's output is held until every module before
|
|
8174
|
+
* it has finished (in memory up to a limit, then in a file), so the report
|
|
8175
|
+
* reads as if they ran one after another. No module starts eight or more
|
|
8176
|
+
* places past the earliest unfinished one, so at most seven modules' output
|
|
8177
|
+
* is held at once.
|
|
8178
|
+
*/
|
|
8179
|
+
async function testModules(modules, seed, budgetMs, stderr) {
|
|
8180
|
+
const held = modules.map(() => new HeldOutput());
|
|
8181
|
+
const finished = modules.map(() => false);
|
|
8182
|
+
let current = 0;
|
|
8183
|
+
try {
|
|
8184
|
+
return await inWindow(modules, Math.min(8, availableParallelism()), async (m, i) => {
|
|
8185
|
+
const verdicts = await testModule(m, seed, budgetMs, (text) => {
|
|
8186
|
+
if (i === current) stderr(text);
|
|
8187
|
+
else held[i]?.push(text);
|
|
8188
|
+
});
|
|
8189
|
+
finished[i] = true;
|
|
8190
|
+
while (finished[current]) {
|
|
8191
|
+
current++;
|
|
8192
|
+
held[current]?.drain(stderr);
|
|
8193
|
+
}
|
|
8194
|
+
return verdicts;
|
|
8195
|
+
});
|
|
8196
|
+
} finally {
|
|
8197
|
+
for (const h of held) h.discard();
|
|
8198
|
+
}
|
|
8199
|
+
}
|
|
8200
|
+
/**
|
|
7537
8201
|
* Write a module's open Lean goals beside its spec file as
|
|
7538
8202
|
* `<spec>.goals.lean`, a proof file with every proof open, and list them.
|
|
7539
8203
|
* No open goal removes a goal file left from an earlier run.
|
|
@@ -7597,8 +8261,7 @@ async function runReport(o) {
|
|
|
7597
8261
|
for (const e of errors) o.stderr(`${e}\n`);
|
|
7598
8262
|
return exitCodes.error;
|
|
7599
8263
|
}
|
|
7600
|
-
let specs =
|
|
7601
|
-
for (const m of modules) specs = [...specs, ...await testModule(m, o.seed ?? "report", o.moduleBudgetMs ?? 6e4, o.stderr)];
|
|
8264
|
+
let specs = (await testModules(modules, o.seed ?? "report", o.moduleBudgetMs ?? 6e4, o.stderr)).flat();
|
|
7602
8265
|
const goals = [];
|
|
7603
8266
|
if (engines.length > 0) specs = await proveSpecs(root, modules.map((m) => ({
|
|
7604
8267
|
module: m.key,
|
|
@@ -7622,7 +8285,7 @@ async function runReport(o) {
|
|
|
7622
8285
|
}
|
|
7623
8286
|
// packages/cli/src/version.ts
|
|
7624
8287
|
/** The published package's version, as the MCP server reports it; the release tooling keeps it in step. */
|
|
7625
|
-
const eutaxyVersion = "0.
|
|
8288
|
+
const eutaxyVersion = "0.15.1";
|
|
7626
8289
|
// packages/cli/src/mcp.ts
|
|
7627
8290
|
/**
|
|
7628
8291
|
* `eutaxy mcp`: a Model Context Protocol server over stdio, so a coding
|
|
@@ -7766,7 +8429,7 @@ const tools = [
|
|
|
7766
8429
|
},
|
|
7767
8430
|
wrangler: {
|
|
7768
8431
|
type: "string",
|
|
7769
|
-
description: "Wrangler config path; default: the one
|
|
8432
|
+
description: "Wrangler config path; default: the one the scenario names, else the one beside it"
|
|
7770
8433
|
},
|
|
7771
8434
|
seed: {
|
|
7772
8435
|
type: "string",
|
|
@@ -7945,6 +8608,56 @@ const tools = [
|
|
|
7945
8608
|
});
|
|
7946
8609
|
}
|
|
7947
8610
|
},
|
|
8611
|
+
{
|
|
8612
|
+
name: "draft",
|
|
8613
|
+
title: "Draft a scenario",
|
|
8614
|
+
description: "Draft a scenario (*.sim.ts) from a wrangler config (JSON or JSONC) and the Worker module it names: the bindings become setup steps (a service binding whose Worker's config is found under the directory becomes a callee), the Worker's handlers the drive, the hosts its code fetches the externals; the invariants and the drive's events are holes marked TODO for you to fill before calling check. Returns the source, the draft as data and its notes (bindings not modelled, guesses made); with out, also writes the file, never over an existing one. Nothing is imported or run.",
|
|
8615
|
+
inputSchema: {
|
|
8616
|
+
type: "object",
|
|
8617
|
+
properties: {
|
|
8618
|
+
config: {
|
|
8619
|
+
type: "string",
|
|
8620
|
+
description: "Wrangler config path, relative to the working directory; default: wrangler.jsonc or wrangler.json there"
|
|
8621
|
+
},
|
|
8622
|
+
worker: {
|
|
8623
|
+
type: "string",
|
|
8624
|
+
description: "The Worker module; default: the config's main"
|
|
8625
|
+
},
|
|
8626
|
+
out: {
|
|
8627
|
+
type: "string",
|
|
8628
|
+
description: "Where to write the scenario; paths in it are relative to its directory. Default: not written"
|
|
8629
|
+
}
|
|
8630
|
+
},
|
|
8631
|
+
additionalProperties: false
|
|
8632
|
+
},
|
|
8633
|
+
async run(args, ctx) {
|
|
8634
|
+
only(args, [
|
|
8635
|
+
"config",
|
|
8636
|
+
"worker",
|
|
8637
|
+
"out"
|
|
8638
|
+
]);
|
|
8639
|
+
const config = str(args, "config");
|
|
8640
|
+
const worker = str(args, "worker");
|
|
8641
|
+
const out = str(args, "out");
|
|
8642
|
+
let stdout = "";
|
|
8643
|
+
let stderr = "";
|
|
8644
|
+
const code = runDraft({
|
|
8645
|
+
cwd: ctx.cwd,
|
|
8646
|
+
...config === void 0 ? {} : { config },
|
|
8647
|
+
...worker === void 0 ? {} : { worker },
|
|
8648
|
+
...out === void 0 ? {} : { out },
|
|
8649
|
+
json: true,
|
|
8650
|
+
stdout: (t) => {
|
|
8651
|
+
stdout += t;
|
|
8652
|
+
},
|
|
8653
|
+
stderr: (t) => {
|
|
8654
|
+
stderr += t;
|
|
8655
|
+
}
|
|
8656
|
+
});
|
|
8657
|
+
if (code !== 0) throw new ToolError(stderr.trim() || `draft exited ${code}`);
|
|
8658
|
+
return asResult(JSON.parse(stdout));
|
|
8659
|
+
}
|
|
8660
|
+
},
|
|
7948
8661
|
{
|
|
7949
8662
|
name: "prover_status",
|
|
7950
8663
|
title: "Which proof engines are installed",
|
|
@@ -8099,12 +8812,14 @@ const usage = `eutaxy — deterministic simulation checks and spec verdicts for
|
|
|
8099
8812
|
|
|
8100
8813
|
Usage:
|
|
8101
8814
|
eutaxy check <scenario.sim.ts> [options]
|
|
8815
|
+
eutaxy draft [wrangler config] [--worker <module>] [--out <file>] [--json]
|
|
8102
8816
|
eutaxy report [dir] [--prover <names>] [--seed <seed>] [--json]
|
|
8103
8817
|
eutaxy prover install <lean|smt> [--from <url or directory>] [--json]
|
|
8104
8818
|
eutaxy mcp
|
|
8105
8819
|
|
|
8106
8820
|
check options:
|
|
8107
|
-
--wrangler <path> wrangler config (default:
|
|
8821
|
+
--wrangler <path> wrangler config (default: the one the scenario names, else
|
|
8822
|
+
wrangler.jsonc/json/toml beside the scenario)
|
|
8108
8823
|
--seed <seed> exploration seed (default: the scenario file name)
|
|
8109
8824
|
--max-runs <n> cap on exploration runs in addition to the scenario's time budget
|
|
8110
8825
|
--budget-ms <n> replace the scenario's time budget (with --max-runs, the run cap decides)
|
|
@@ -8117,6 +8832,14 @@ check options:
|
|
|
8117
8832
|
--expect-violation write a regression test that asserts the violation (for corpora)
|
|
8118
8833
|
--keep keep the generated .eutaxy/ files
|
|
8119
8834
|
|
|
8835
|
+
draft writes a scenario skeleton from a wrangler config (JSON or JSONC; default:
|
|
8836
|
+
wrangler.jsonc or wrangler.json in the current directory) and the Worker module it names
|
|
8837
|
+
(--worker to name another): the bindings become setup steps (a service binding whose
|
|
8838
|
+
Worker's config is found under the directory becomes a callee), the handlers the drive,
|
|
8839
|
+
the hosts the code fetches the externals; the invariants and the events are left as holes
|
|
8840
|
+
marked TODO. It prints the scenario, or writes it to --out (never over an existing file);
|
|
8841
|
+
nothing is imported or run.
|
|
8842
|
+
|
|
8120
8843
|
report runs every spec file (*.props.ts) under dir (default: the current directory)
|
|
8121
8844
|
through the TESTED rung, on inputs drawn from the parameter types with the seed
|
|
8122
8845
|
(default: report), and the PROVEN rung with --prover. No scenario runs, so nothing
|
|
@@ -8133,7 +8856,8 @@ report options: --goals writes each module's open Lean goals beside its spec fil
|
|
|
8133
8856
|
|
|
8134
8857
|
mcp serves the Model Context Protocol over stdio (one JSON-RPC message per line, logs on
|
|
8135
8858
|
stderr) for a coding agent: tools check, report, goals, prove and prover_status, each
|
|
8136
|
-
returning the JSON report. Point the agent's
|
|
8859
|
+
returning the JSON report, and draft, returning the drafted scenario. Point the agent's
|
|
8860
|
+
MCP configuration at "eutaxy mcp".
|
|
8137
8861
|
|
|
8138
8862
|
Exit codes: 0 BOUNDED, 1 VIOLATED or a REFUTED or CONFLICT spec, 2 UNSUPPORTED, 3 error.
|
|
8139
8863
|
report: 0, or 1 for a REFUTED or CONFLICT spec, 3 error. prover install: 0, or 3.
|
|
@@ -8160,7 +8884,8 @@ async function main(argv, io) {
|
|
|
8160
8884
|
"budget-ms",
|
|
8161
8885
|
"prover",
|
|
8162
8886
|
"out",
|
|
8163
|
-
"from"
|
|
8887
|
+
"from",
|
|
8888
|
+
"worker"
|
|
8164
8889
|
]) if (flags[k] === true) {
|
|
8165
8890
|
io.stderr(`--${k} needs a value\n`);
|
|
8166
8891
|
return exitCodes.error;
|
|
@@ -8228,6 +8953,33 @@ async function main(argv, io) {
|
|
|
8228
8953
|
stderr: io.stderr
|
|
8229
8954
|
});
|
|
8230
8955
|
}
|
|
8956
|
+
if (command === "draft") {
|
|
8957
|
+
if (positionals.length > 2) {
|
|
8958
|
+
io.stderr(`draft takes one wrangler config\n\n${usage}`);
|
|
8959
|
+
return exitCodes.error;
|
|
8960
|
+
}
|
|
8961
|
+
const other = Object.keys(flags).find((k) => ![
|
|
8962
|
+
"worker",
|
|
8963
|
+
"out",
|
|
8964
|
+
"json"
|
|
8965
|
+
].includes(k));
|
|
8966
|
+
if (other !== void 0) {
|
|
8967
|
+
io.stderr(`draft does not take --${other}\n`);
|
|
8968
|
+
return exitCodes.error;
|
|
8969
|
+
}
|
|
8970
|
+
const config = positionals[1];
|
|
8971
|
+
const worker = str("worker");
|
|
8972
|
+
const out = str("out");
|
|
8973
|
+
return runDraft({
|
|
8974
|
+
cwd: io.cwd,
|
|
8975
|
+
...config === void 0 ? {} : { config },
|
|
8976
|
+
...worker === void 0 ? {} : { worker },
|
|
8977
|
+
...out === void 0 ? {} : { out },
|
|
8978
|
+
json: flags["json"] === true,
|
|
8979
|
+
stdout: io.stdout,
|
|
8980
|
+
stderr: io.stderr
|
|
8981
|
+
});
|
|
8982
|
+
}
|
|
8231
8983
|
if (command !== "check") {
|
|
8232
8984
|
io.stderr(`unknown command ${command}\n\n${usage}`);
|
|
8233
8985
|
return exitCodes.error;
|
|
@@ -8237,6 +8989,28 @@ async function main(argv, io) {
|
|
|
8237
8989
|
io.stderr(`check needs a scenario file\n\n${usage}`);
|
|
8238
8990
|
return exitCodes.error;
|
|
8239
8991
|
}
|
|
8992
|
+
if (positionals.length > 2) {
|
|
8993
|
+
io.stderr(`check takes one scenario file\n\n${usage}`);
|
|
8994
|
+
return exitCodes.error;
|
|
8995
|
+
}
|
|
8996
|
+
const checkFlags = [
|
|
8997
|
+
"wrangler",
|
|
8998
|
+
"seed",
|
|
8999
|
+
"max-runs",
|
|
9000
|
+
"budget-ms",
|
|
9001
|
+
"exhaustive",
|
|
9002
|
+
"prover",
|
|
9003
|
+
"json",
|
|
9004
|
+
"out",
|
|
9005
|
+
"no-regression",
|
|
9006
|
+
"expect-violation",
|
|
9007
|
+
"keep"
|
|
9008
|
+
];
|
|
9009
|
+
const unknownFlag = Object.keys(flags).find((k) => !checkFlags.includes(k));
|
|
9010
|
+
if (unknownFlag !== void 0) {
|
|
9011
|
+
io.stderr(`check does not take --${unknownFlag}\n`);
|
|
9012
|
+
return exitCodes.error;
|
|
9013
|
+
}
|
|
8240
9014
|
const maxRunsText = str("max-runs");
|
|
8241
9015
|
const maxRuns = maxRunsText === void 0 ? void 0 : Number(maxRunsText);
|
|
8242
9016
|
if (maxRuns !== void 0 && !(Number.isInteger(maxRuns) && maxRuns > 0)) {
|
|
@@ -8269,4 +9043,4 @@ async function main(argv, io) {
|
|
|
8269
9043
|
}
|
|
8270
9044
|
export { main as t };
|
|
8271
9045
|
|
|
8272
|
-
//# sourceMappingURL=cli-
|
|
9046
|
+
//# sourceMappingURL=cli-DT4lxaPK.mjs.map
|