@agentswf/lab 0.0.0-stage → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +15 -2
- package/package.json +46 -4
- package/schema/lab-check.schema.json +64 -0
- package/schema/lab-config.schema.json +187 -0
- package/schema/lab-final.schema.json +48 -0
- package/schema/lab-good-record.schema.json +70 -0
- package/schema/lab-grade.schema.json +49 -0
- package/schema/lab-key.schema.json +124 -0
- package/schema/lab-label.schema.json +32 -0
- package/schema/lab-loop-report.schema.json +221 -0
- package/schema/lab-loop.schema.json +141 -0
- package/schema/lab-plan.schema.json +128 -0
- package/schema/lab-previous.schema.json +70 -0
- package/schema/lab-proposal.schema.json +52 -0
- package/schema/lab-report.schema.json +1128 -0
- package/schema/lab-run.schema.json +253 -0
- package/schema/lab-runs.schema.json +132 -0
- package/schema/lab-score.schema.json +319 -0
- package/schema/lab-spread.schema.json +110 -0
- package/schema/lab-trial.schema.json +543 -0
- package/schema/lab-try.schema.json +113 -0
- package/schema/local.json +155 -0
- package/src/cli.ts +9 -0
- package/src/env/capture.ts +48 -0
- package/src/env/compare.ts +201 -0
- package/src/env/facts.ts +51 -0
- package/src/env/fetch.ts +57 -0
- package/src/env/files.ts +228 -0
- package/src/env/grade-case.ts +80 -0
- package/src/env/grade-helper.ts +352 -0
- package/src/env/grader.ts +131 -0
- package/src/env/index.ts +727 -0
- package/src/env/mock.ts +374 -0
- package/src/env/routes.ts +90 -0
- package/src/env/sources.ts +19 -0
- package/src/env/state.ts +79 -0
- package/src/env/trial.ts +185 -0
- package/src/format/key.ts +168 -0
- package/src/format/loop.ts +179 -0
- package/src/format/output.ts +542 -0
- package/src/format/records.ts +443 -0
- package/src/format/schema-files.ts +64 -0
- package/src/format/settings.ts +559 -0
- package/src/format/trial-env.ts +67 -0
- package/src/format/trial-file.ts +134 -0
- package/src/help/awf-lab.txt +29 -0
- package/src/help/case.txt +39 -0
- package/src/help/config.txt +14 -0
- package/src/help/label.txt +12 -0
- package/src/help/loop.txt +44 -0
- package/src/help/report.txt +20 -0
- package/src/help/run.txt +61 -0
- package/src/help/runs.txt +11 -0
- package/src/help/score.txt +28 -0
- package/src/judge/criteria.workflow.ts +237 -0
- package/src/judge/version.ts +6 -0
- package/src/lab/answer.ts +47 -0
- package/src/lab/blame.ts +204 -0
- package/src/lab/box.ts +251 -0
- package/src/lab/capture-command.ts +302 -0
- package/src/lab/capture.ts +234 -0
- package/src/lab/check-command.ts +187 -0
- package/src/lab/cli.ts +325 -0
- package/src/lab/code-graders.ts +108 -0
- package/src/lab/columns.ts +138 -0
- package/src/lab/command-context.ts +436 -0
- package/src/lab/compare.ts +123 -0
- package/src/lab/config-command.ts +283 -0
- package/src/lab/criteria.ts +69 -0
- package/src/lab/dataset.ts +375 -0
- package/src/lab/eval-files.ts +196 -0
- package/src/lab/expect.ts +79 -0
- package/src/lab/facts.ts +59 -0
- package/src/lab/families.ts +32 -0
- package/src/lab/folders.ts +172 -0
- package/src/lab/git.ts +128 -0
- package/src/lab/good.ts +224 -0
- package/src/lab/grading-stub.txt +8 -0
- package/src/lab/grading.ts +332 -0
- package/src/lab/inspect.ts +227 -0
- package/src/lab/labels.ts +211 -0
- package/src/lab/loop-code.ts +255 -0
- package/src/lab/loop-command.ts +774 -0
- package/src/lab/loop-records.ts +144 -0
- package/src/lab/loop.ts +864 -0
- package/src/lab/marker.ts +23 -0
- package/src/lab/outcome.ts +196 -0
- package/src/lab/pooled.ts +106 -0
- package/src/lab/project-env.ts +39 -0
- package/src/lab/rates.ts +155 -0
- package/src/lab/reach.ts +111 -0
- package/src/lab/record-copies.ts +202 -0
- package/src/lab/refusal.ts +2 -0
- package/src/lab/report-command.ts +157 -0
- package/src/lab/report.ts +936 -0
- package/src/lab/reuse.ts +134 -0
- package/src/lab/run-command.ts +958 -0
- package/src/lab/run-logs.ts +89 -0
- package/src/lab/run-report.ts +286 -0
- package/src/lab/runs-command.ts +171 -0
- package/src/lab/runs.ts +172 -0
- package/src/lab/scaffold.ts +94 -0
- package/src/lab/score-command.ts +197 -0
- package/src/lab/score.ts +396 -0
- package/src/lab/store.ts +383 -0
- package/src/lab/target-stub.txt +18 -0
- package/src/lab/text.ts +29 -0
- package/src/lab/trial-settings.ts +105 -0
- package/src/lab/trial.ts +439 -0
- package/src/lab/usage.ts +274 -0
- package/src/lab/verdict.ts +161 -0
- package/src/lab/workflow-graders.ts +164 -0
- package/src/lab/workspace.ts +496 -0
- package/src/loop/propose.workflow.ts +84 -0
- package/src/shared/allowance.ts +185 -0
- package/src/shared/compare/index.ts +3 -0
- package/src/shared/compare/paired.ts +397 -0
- package/src/shared/compare/stats.ts +139 -0
- package/src/shared/compare/types.ts +75 -0
- package/src/shared/config.ts +15 -0
- package/src/shared/runner.ts +321 -0
- package/src/shared/validate.ts +181 -0
- package/src/shared/version.ts +41 -0
- package/src/write-schemas.ts +10 -0
package/src/env/mock.ts
ADDED
|
@@ -0,0 +1,374 @@
|
|
|
1
|
+
import { type Mock, mock, spyOn } from "bun:test";
|
|
2
|
+
import { builtinModules } from "node:module";
|
|
3
|
+
import { basename, dirname, extname } from "node:path";
|
|
4
|
+
import { refuse, shared } from "./state";
|
|
5
|
+
|
|
6
|
+
/** What the case stood in for, by name, and whether it was used. */
|
|
7
|
+
type Entry = {
|
|
8
|
+
what: string;
|
|
9
|
+
spy: Mock<(...args: unknown[]) => unknown>;
|
|
10
|
+
kind: "fake" | "refuser";
|
|
11
|
+
/** `evidence` read its `.mock`: a fake meant never to be called isn't unused. */
|
|
12
|
+
read: boolean;
|
|
13
|
+
/** The name the case gave the mock or fake, and the function's: where the record keeps its calls. */
|
|
14
|
+
at?: { mock: string; fn: string };
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
type Fn = (...args: unknown[]) => unknown;
|
|
18
|
+
|
|
19
|
+
/** Every fake and refusing stand-in of one trial: what `unused` and the module checks read. */
|
|
20
|
+
export class Mocks {
|
|
21
|
+
readonly #entries: Entry[] = [];
|
|
22
|
+
readonly #byTarget = new WeakMap<object, Map<string, Entry>>();
|
|
23
|
+
/** The files of the modules mocked, for the copy check. */
|
|
24
|
+
readonly files = new Set<string>();
|
|
25
|
+
readonly #names = new Set<string>();
|
|
26
|
+
#fakes = 0;
|
|
27
|
+
|
|
28
|
+
unused(): string[] {
|
|
29
|
+
return this.#entries
|
|
30
|
+
.filter((entry) => entry.kind === "fake" && !entry.read && entry.spy.mock.calls.length === 0)
|
|
31
|
+
.map((entry) => entry.what);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Each fake's calls, `{mock}.{function}`, every argument as JSON. */
|
|
35
|
+
calls(): Record<string, Record<string, unknown[][]>> {
|
|
36
|
+
const calls: Record<string, Record<string, unknown[][]>> = {};
|
|
37
|
+
for (const entry of this.#entries) {
|
|
38
|
+
if (entry.kind !== "fake" || !entry.at) continue;
|
|
39
|
+
calls[entry.at.mock] ??= {};
|
|
40
|
+
calls[entry.at.mock]![entry.at.fn] = entry.spy.mock.calls.map((args) => args.map(asJson));
|
|
41
|
+
}
|
|
42
|
+
return calls;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
#name(what: string, name: unknown): string {
|
|
46
|
+
if (typeof name !== "string" || !/^[A-Za-z_$][A-Za-z0-9_$-]*$/.test(name)) {
|
|
47
|
+
throw new Error(
|
|
48
|
+
`${what} takes its name first, the one the trial record keeps its calls under, such as trial.mock("shop", shop, { … }): got ${JSON.stringify(name)}`,
|
|
49
|
+
);
|
|
50
|
+
}
|
|
51
|
+
if (this.#names.has(name)) {
|
|
52
|
+
throw new Error(`${what}: ${name} is named twice; give each mock and fake its own name`);
|
|
53
|
+
}
|
|
54
|
+
this.#names.add(name);
|
|
55
|
+
return name;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
module<T extends object>(
|
|
59
|
+
given: string,
|
|
60
|
+
target: T,
|
|
61
|
+
fakes: Record<string, unknown>,
|
|
62
|
+
options: { real?: readonly string[] } = {},
|
|
63
|
+
): Record<string, unknown> {
|
|
64
|
+
const mockName = this.#name("trial.mock", given);
|
|
65
|
+
if (target === null || (typeof target !== "object" && typeof target !== "function")) {
|
|
66
|
+
throw new Error("trial.mock takes a module (import * as name), an object or a prototype");
|
|
67
|
+
}
|
|
68
|
+
const builtin = builtinName(target);
|
|
69
|
+
if (builtin) {
|
|
70
|
+
throw new Error(
|
|
71
|
+
`trial.mock refuses ${builtin}: the engine shares the process and calls it too; mock the workflow's own module that wraps it`,
|
|
72
|
+
);
|
|
73
|
+
}
|
|
74
|
+
const record = target as Record<string, unknown>;
|
|
75
|
+
const file = fileOf(target);
|
|
76
|
+
if (file) this.files.add(file);
|
|
77
|
+
const label = labelOf(target, file);
|
|
78
|
+
for (const [name, fake] of Object.entries(fakes)) {
|
|
79
|
+
if (!(name in target)) throw new Error(`trial.mock: ${label} has no export ${name}`);
|
|
80
|
+
if (typeof record[name] !== "function") {
|
|
81
|
+
throw new Error(`trial.mock: ${label}.${name} is not a function`);
|
|
82
|
+
}
|
|
83
|
+
if (typeof fake !== "function")
|
|
84
|
+
throw new Error(`trial.mock: the fake for ${name} is no function`);
|
|
85
|
+
}
|
|
86
|
+
const real = new Set(options.real ?? []);
|
|
87
|
+
// A CommonJS module: its exports object is `default`, and both it and the named export are
|
|
88
|
+
// patched, since a caller may reach either.
|
|
89
|
+
const exportsObject = file && isCommonJs(target, file) ? record.default : undefined;
|
|
90
|
+
const spies: Record<string, unknown> = {};
|
|
91
|
+
|
|
92
|
+
for (const name of ownFunctionNames(target)) {
|
|
93
|
+
if (name === "constructor") continue;
|
|
94
|
+
if (exportsObject !== undefined && name === "default") continue;
|
|
95
|
+
const value = record[name] as Fn;
|
|
96
|
+
const fake = fakes[name] as Fn | undefined;
|
|
97
|
+
const holder =
|
|
98
|
+
exportsObject && typeof exportsObject === "object" && name in exportsObject
|
|
99
|
+
? (exportsObject as object)
|
|
100
|
+
: target;
|
|
101
|
+
// Mocked already, by an earlier `trial.mock`: only a fake given now replaces it.
|
|
102
|
+
const existing = this.#byTarget.get(holder)?.get(name);
|
|
103
|
+
if (fake === undefined && existing) {
|
|
104
|
+
spies[name] = tracked(existing);
|
|
105
|
+
continue;
|
|
106
|
+
}
|
|
107
|
+
if (fake === undefined && (real.has(name) || isClass(value))) continue;
|
|
108
|
+
const what = `${label}.${name}`;
|
|
109
|
+
const impl =
|
|
110
|
+
fake ??
|
|
111
|
+
this.#refuser(what, "fake it, or name it in `real` if it is a pure helper", isAsync(value));
|
|
112
|
+
const entry = this.#install(holder, name, what, impl, fake ? "fake" : "refuser");
|
|
113
|
+
if (fake) entry.at = { mock: mockName, fn: name };
|
|
114
|
+
if (holder !== target && !existing) {
|
|
115
|
+
spyOn(record, name as never).mockImplementation(((...args: unknown[]) =>
|
|
116
|
+
entry.spy(...args)) as never);
|
|
117
|
+
}
|
|
118
|
+
spies[name] = tracked(entry);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// An exported plain object's function members are the module's surface too.
|
|
122
|
+
if (isNamespace(target) || exportsObject !== undefined) {
|
|
123
|
+
for (const name of Object.getOwnPropertyNames(target)) {
|
|
124
|
+
const value = record[name];
|
|
125
|
+
if (value === exportsObject || real.has(name) || !isPlainObject(value)) continue;
|
|
126
|
+
for (const member of ownFunctionNames(value)) {
|
|
127
|
+
if (real.has(`${name}.${member}`) || isClass((value as Record<string, Fn>)[member]!)) {
|
|
128
|
+
continue;
|
|
129
|
+
}
|
|
130
|
+
const what = `${label}.${name}.${member}`;
|
|
131
|
+
if (this.#byTarget.get(value)?.has(member)) continue;
|
|
132
|
+
this.#install(
|
|
133
|
+
value,
|
|
134
|
+
member,
|
|
135
|
+
what,
|
|
136
|
+
this.#refuser(
|
|
137
|
+
what,
|
|
138
|
+
`fake it with trial.mock(${label}.${name}, …), or name it in \`real\``,
|
|
139
|
+
isAsync((value as Record<string, Fn>)[member]!),
|
|
140
|
+
),
|
|
141
|
+
"refuser",
|
|
142
|
+
);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
return spies;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
fake<T extends object>(fakes: Partial<T>, options: { name?: string } = {}): T {
|
|
150
|
+
this.#fakes += 1;
|
|
151
|
+
const label = this.#name(
|
|
152
|
+
"trial.fake",
|
|
153
|
+
options.name ?? (this.#fakes === 1 ? "fake" : `fake${this.#fakes}`),
|
|
154
|
+
);
|
|
155
|
+
const given = fakes as Record<PropertyKey, unknown>;
|
|
156
|
+
const members = new Map<PropertyKey, unknown>();
|
|
157
|
+
for (const [key, value] of Object.entries(given)) {
|
|
158
|
+
if (typeof value !== "function") continue;
|
|
159
|
+
const spy = mock(value as Fn) as unknown as Mock<Fn>;
|
|
160
|
+
const entry: Entry = {
|
|
161
|
+
what: `${label}.${key}`,
|
|
162
|
+
spy,
|
|
163
|
+
kind: "fake",
|
|
164
|
+
read: false,
|
|
165
|
+
at: { mock: label, fn: key },
|
|
166
|
+
};
|
|
167
|
+
this.#entries.push(entry);
|
|
168
|
+
members.set(key, tracked(entry));
|
|
169
|
+
}
|
|
170
|
+
const refusers = new Map<string, Fn>();
|
|
171
|
+
return new Proxy(given, {
|
|
172
|
+
get: (target, key) => {
|
|
173
|
+
if (members.has(key)) return members.get(key);
|
|
174
|
+
if (key in target) return target[key];
|
|
175
|
+
if (typeof key === "symbol" || key === "then" || key === "toJSON") return undefined;
|
|
176
|
+
let refuser = refusers.get(key);
|
|
177
|
+
if (!refuser) {
|
|
178
|
+
refuser = this.#refuser(`${label}.${key}`, "fake it");
|
|
179
|
+
refusers.set(key, refuser);
|
|
180
|
+
}
|
|
181
|
+
return refuser;
|
|
182
|
+
},
|
|
183
|
+
}) as T;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
#install(holder: object, name: string, what: string, impl: Fn, kind: Entry["kind"]): Entry {
|
|
187
|
+
let byName = this.#byTarget.get(holder);
|
|
188
|
+
if (!byName) {
|
|
189
|
+
byName = new Map();
|
|
190
|
+
this.#byTarget.set(holder, byName);
|
|
191
|
+
}
|
|
192
|
+
const existing = byName.get(name);
|
|
193
|
+
if (existing) {
|
|
194
|
+
existing.spy.mockImplementation(impl);
|
|
195
|
+
existing.kind = kind;
|
|
196
|
+
existing.what = what;
|
|
197
|
+
return existing;
|
|
198
|
+
}
|
|
199
|
+
const spy = spyOn(holder as Record<string, Fn>, name).mockImplementation(impl) as Mock<Fn>;
|
|
200
|
+
const entry: Entry = { what, spy, kind, read: false };
|
|
201
|
+
byName.set(name, entry);
|
|
202
|
+
this.#entries.push(entry);
|
|
203
|
+
return entry;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/** A stand-in that refuses: rejecting, for an async function, as the real one would fail. */
|
|
207
|
+
#refuser(what: string, advice: string, async = false): Fn {
|
|
208
|
+
const refused = () => refuse(what, "function", `no fake for ${what} in this case: ${advice}`);
|
|
209
|
+
return async
|
|
210
|
+
? () => Promise.reject(refused())
|
|
211
|
+
: () => {
|
|
212
|
+
throw refused();
|
|
213
|
+
};
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/** The spy, noting when `evidence` reads its `.mock`. */
|
|
218
|
+
function tracked(entry: Entry): unknown {
|
|
219
|
+
return new Proxy(entry.spy, {
|
|
220
|
+
get(target, key) {
|
|
221
|
+
if (key === "mock" && shared().phase === "evidence") entry.read = true;
|
|
222
|
+
const value = Reflect.get(target, key, target);
|
|
223
|
+
return typeof value === "function" ? value.bind(target) : value;
|
|
224
|
+
},
|
|
225
|
+
});
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* An argument as JSON holds it: what JSON can't (a function, a symbol) is dropped as it would be,
|
|
230
|
+
* a cycle is `"[circular]"`, a bigint its digits. `evidence` gathers what JSON can't hold.
|
|
231
|
+
*/
|
|
232
|
+
export function asJson(value: unknown): unknown {
|
|
233
|
+
const within: object[] = [];
|
|
234
|
+
const walk = (each: unknown): unknown => {
|
|
235
|
+
if (typeof each === "bigint") return each.toString();
|
|
236
|
+
if (typeof each !== "object" || each === null) return each;
|
|
237
|
+
const json = (each as { toJSON?: unknown }).toJSON;
|
|
238
|
+
if (typeof json === "function") return walk(json.call(each));
|
|
239
|
+
if (within.includes(each)) return "[circular]";
|
|
240
|
+
within.push(each);
|
|
241
|
+
try {
|
|
242
|
+
if (Array.isArray(each)) {
|
|
243
|
+
return each.map((item) => {
|
|
244
|
+
const made = walk(item);
|
|
245
|
+
return made === undefined || typeof made === "function" || typeof made === "symbol"
|
|
246
|
+
? null
|
|
247
|
+
: made;
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
const out: Record<string, unknown> = {};
|
|
251
|
+
for (const [key, item] of Object.entries(each)) {
|
|
252
|
+
const made = walk(item);
|
|
253
|
+
if (made !== undefined && typeof made !== "function" && typeof made !== "symbol") {
|
|
254
|
+
out[key] = made;
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
return out;
|
|
258
|
+
} finally {
|
|
259
|
+
within.pop();
|
|
260
|
+
}
|
|
261
|
+
};
|
|
262
|
+
try {
|
|
263
|
+
const made = walk(value);
|
|
264
|
+
return made === undefined || typeof made === "function" || typeof made === "symbol"
|
|
265
|
+
? null
|
|
266
|
+
: made;
|
|
267
|
+
} catch {
|
|
268
|
+
return null;
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
function ownFunctionNames(target: object): string[] {
|
|
273
|
+
return Object.getOwnPropertyNames(target).filter((name) => {
|
|
274
|
+
const descriptor = Object.getOwnPropertyDescriptor(target, name);
|
|
275
|
+
return (
|
|
276
|
+
descriptor !== undefined && "value" in descriptor && typeof descriptor.value === "function"
|
|
277
|
+
);
|
|
278
|
+
});
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
function isAsync(value: Fn): boolean {
|
|
282
|
+
return value.constructor?.name === "AsyncFunction";
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
function isClass(value: Fn): boolean {
|
|
286
|
+
return /^class[\s{]/.test(Function.prototype.toString.call(value));
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
function isNamespace(value: object): boolean {
|
|
290
|
+
return Object.prototype.toString.call(value) === "[object Module]";
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
function isPlainObject(value: unknown): value is object {
|
|
294
|
+
if (typeof value !== "object" || value === null) return false;
|
|
295
|
+
const proto = Object.getPrototypeOf(value);
|
|
296
|
+
return proto === Object.prototype || proto === null;
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
function cacheEntries(): [string, unknown][] {
|
|
300
|
+
return Object.entries(require.cache).map(([file, entry]) => [file, entry?.exports]);
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
/** The file a namespace, or a CommonJS module's exports, was loaded from. */
|
|
304
|
+
export function fileOf(target: object): string | undefined {
|
|
305
|
+
const exportsOfDefault = isNamespace(target)
|
|
306
|
+
? (target as { default?: unknown }).default
|
|
307
|
+
: undefined;
|
|
308
|
+
for (const [file, exported] of cacheEntries()) {
|
|
309
|
+
if (exported === target) return file;
|
|
310
|
+
if (exportsOfDefault !== undefined && exported === exportsOfDefault && isNamespace(target)) {
|
|
311
|
+
return file;
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
return undefined;
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
function isCommonJs(target: object, file: string): boolean {
|
|
318
|
+
return (
|
|
319
|
+
isNamespace(target) &&
|
|
320
|
+
require.cache[file]?.exports === (target as { default?: unknown }).default
|
|
321
|
+
);
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
function moduleName(file: string): string {
|
|
325
|
+
const name = basename(file, extname(file));
|
|
326
|
+
return name === "index" ? basename(dirname(file)) : name;
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
function labelOf(target: object, file: string | undefined): string {
|
|
330
|
+
if (file) return moduleName(file);
|
|
331
|
+
const owner = Object.getOwnPropertyDescriptor(target, "constructor")?.value;
|
|
332
|
+
if (typeof owner === "function" && owner.prototype === target) {
|
|
333
|
+
return owner.name || "prototype";
|
|
334
|
+
}
|
|
335
|
+
for (const [file, exported] of cacheEntries()) {
|
|
336
|
+
if (typeof exported !== "object" || exported === null) continue;
|
|
337
|
+
for (const name of Object.getOwnPropertyNames(exported)) {
|
|
338
|
+
try {
|
|
339
|
+
if ((exported as Record<string, unknown>)[name] === target) {
|
|
340
|
+
return name === "default" ? moduleName(file) : `${moduleName(file)}.${name}`;
|
|
341
|
+
}
|
|
342
|
+
} catch {
|
|
343
|
+
// An export still in its temporal dead zone.
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
return "object";
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
let builtins: Map<unknown, string> | undefined;
|
|
351
|
+
|
|
352
|
+
function builtinName(target: object): string | undefined {
|
|
353
|
+
if (target === Bun) return "bun";
|
|
354
|
+
const file = fileOf(target);
|
|
355
|
+
if (file !== undefined) {
|
|
356
|
+
if (/^(node|bun):/.test(file) || file === "bun") return file;
|
|
357
|
+
return builtinModules.includes(file) ? `node:${file}` : undefined;
|
|
358
|
+
}
|
|
359
|
+
if (!builtins) {
|
|
360
|
+
builtins = new Map();
|
|
361
|
+
// `_`-prefixed modules are Node's internals, deprecated, and warn when loaded.
|
|
362
|
+
for (const name of builtinModules.filter((each) => !each.startsWith("_"))) {
|
|
363
|
+
try {
|
|
364
|
+
builtins.set(process.getBuiltinModule(name), `node:${name.replace(/^node:/, "")}`);
|
|
365
|
+
} catch {
|
|
366
|
+
// Not loadable here.
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
return (
|
|
371
|
+
builtins.get(target) ??
|
|
372
|
+
(isNamespace(target) ? builtins.get((target as { default?: unknown }).default) : undefined)
|
|
373
|
+
);
|
|
374
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/** Answers one routed request, as a router's handler would. */
|
|
2
|
+
export type RouteHandler = (
|
|
3
|
+
request: Request,
|
|
4
|
+
match: { params: Record<string, string> },
|
|
5
|
+
) => Response | Promise<Response>;
|
|
6
|
+
|
|
7
|
+
export type Route = {
|
|
8
|
+
/** As the case wrote it: `GET https://school.example/posts/:id`. */
|
|
9
|
+
key: string;
|
|
10
|
+
method: string;
|
|
11
|
+
hostname: string;
|
|
12
|
+
pattern: URLPattern;
|
|
13
|
+
handler: RouteHandler;
|
|
14
|
+
calls: number;
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
const METHOD = /^[A-Z]+$/;
|
|
18
|
+
// A hostname a route names is literal: a pattern there would make "a host a route names" unknowable.
|
|
19
|
+
const NOT_LITERAL = /[*:{}()?+\\]/;
|
|
20
|
+
|
|
21
|
+
/** A route from its key; throws why the key isn't one. */
|
|
22
|
+
export function parseRoute(key: string, handler: RouteHandler): Route {
|
|
23
|
+
const space = key.indexOf(" ");
|
|
24
|
+
const method = space > 0 ? key.slice(0, space) : "";
|
|
25
|
+
const url = key.slice(space + 1).trim();
|
|
26
|
+
if (!METHOD.test(method)) {
|
|
27
|
+
throw new Error(
|
|
28
|
+
`trial.mockFetch: "${key}" is not "{METHOD} {URL pattern}", such as "GET https://x/y"`,
|
|
29
|
+
);
|
|
30
|
+
}
|
|
31
|
+
const authority = /^[A-Za-z][A-Za-z0-9+.-]*:\/\/([^/?#]*)/.exec(url)?.[1];
|
|
32
|
+
if (authority === undefined) {
|
|
33
|
+
throw new Error(
|
|
34
|
+
`trial.mockFetch: "${key}" names no host: a route's URL is absolute, with a literal host`,
|
|
35
|
+
);
|
|
36
|
+
}
|
|
37
|
+
const hostname = authority.replace(/:\d+$/, "").toLowerCase();
|
|
38
|
+
if (hostname === "" || NOT_LITERAL.test(hostname)) {
|
|
39
|
+
throw new Error(`trial.mockFetch: "${key}": a route names a literal host, not "${hostname}"`);
|
|
40
|
+
}
|
|
41
|
+
let parsed: URLPattern;
|
|
42
|
+
try {
|
|
43
|
+
parsed = new URLPattern(url);
|
|
44
|
+
} catch (error) {
|
|
45
|
+
throw new Error(`trial.mockFetch: "${key}" is not a URL pattern: ${(error as Error).message}`);
|
|
46
|
+
}
|
|
47
|
+
// Routed hosts compare by hostname: a route's scheme and port neither widen nor split it.
|
|
48
|
+
const pattern = new URLPattern({
|
|
49
|
+
hostname: parsed.hostname,
|
|
50
|
+
pathname: parsed.pathname,
|
|
51
|
+
search: parsed.search,
|
|
52
|
+
hash: parsed.hash,
|
|
53
|
+
});
|
|
54
|
+
return { key, method, hostname, pattern, handler, calls: 0 };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* The route for a request: `unrouted` when no route names its host, `missing` when one does and none
|
|
59
|
+
* matches.
|
|
60
|
+
*/
|
|
61
|
+
export function routeFor(
|
|
62
|
+
routes: readonly Route[],
|
|
63
|
+
method: string,
|
|
64
|
+
url: URL,
|
|
65
|
+
): { route: Route; params: Record<string, string> } | "unrouted" | "missing" {
|
|
66
|
+
const hostname = url.hostname.toLowerCase();
|
|
67
|
+
if (!routes.some((route) => route.hostname === hostname)) return "unrouted";
|
|
68
|
+
for (const route of routes) {
|
|
69
|
+
if (route.method !== method) continue;
|
|
70
|
+
const match = route.pattern.exec(url.href);
|
|
71
|
+
if (!match) continue;
|
|
72
|
+
const params: Record<string, string> = {};
|
|
73
|
+
for (const part of [match.hostname, match.pathname, match.search, match.hash]) {
|
|
74
|
+
for (const [name, value] of Object.entries(part.groups)) {
|
|
75
|
+
if (value !== undefined && !/^\d+$/.test(name)) params[name] = value;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
return { route, params };
|
|
79
|
+
}
|
|
80
|
+
return "missing";
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Whether `hostname` is one `hosts` lists: exactly, or under a `*.` entry. */
|
|
84
|
+
export function hostListed(hosts: readonly string[], hostname: string): boolean {
|
|
85
|
+
const host = hostname.toLowerCase();
|
|
86
|
+
return hosts.some((entry) => {
|
|
87
|
+
const listed = entry.toLowerCase();
|
|
88
|
+
return listed.startsWith("*.") ? host.endsWith(listed.slice(1)) : host === listed;
|
|
89
|
+
});
|
|
90
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { join, relative, sep } from "node:path";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* A module mocked in the code folder while the workflow loaded the same file from its copy in the
|
|
5
|
+
* scratch folder: the mock misses it. Its path from the code folder; undefined when none.
|
|
6
|
+
*/
|
|
7
|
+
export function copiedModule(
|
|
8
|
+
mocked: ReadonlySet<string>,
|
|
9
|
+
root: string,
|
|
10
|
+
scratch: string,
|
|
11
|
+
): string | undefined {
|
|
12
|
+
if (root === scratch) return undefined;
|
|
13
|
+
for (const file of mocked) {
|
|
14
|
+
const path = relative(root, file);
|
|
15
|
+
if (path.startsWith("..") || file.startsWith(scratch + sep)) continue;
|
|
16
|
+
if (require.cache[join(scratch, path)]) return path;
|
|
17
|
+
}
|
|
18
|
+
return undefined;
|
|
19
|
+
}
|
package/src/env/state.ts
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { appendFileSync } from "node:fs";
|
|
2
|
+
import { TRIAL_ENV, type TrialSettings } from "../format/trial-env";
|
|
3
|
+
import type { Phase, Refused, TrialLine } from "../format/trial-file";
|
|
4
|
+
import type { Route } from "./routes";
|
|
5
|
+
|
|
6
|
+
/** A request the lab's `fetch` saw: routed, real, refused or over a unix socket. */
|
|
7
|
+
export type HttpRequest = {
|
|
8
|
+
method: string;
|
|
9
|
+
url: string;
|
|
10
|
+
body?: string;
|
|
11
|
+
/** Bun's `unix` option, for a `fetch` over a socket. */
|
|
12
|
+
unix?: string;
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* What the `fetch` preload and `defineEnv` share. On a `globalThis` symbol rather than in a module,
|
|
17
|
+
* so the preload's copy and the copy `env.ts` imports share it even when they resolve apart.
|
|
18
|
+
*/
|
|
19
|
+
export type Shared = {
|
|
20
|
+
phase: Phase;
|
|
21
|
+
refused: Refused[];
|
|
22
|
+
routes: Route[];
|
|
23
|
+
/** Hosts this case lets through to the real `fetch`, with `trial.mockFetch.allow`, beside `sandbox.network.code`. */
|
|
24
|
+
allowed: string[];
|
|
25
|
+
requests: HttpRequest[];
|
|
26
|
+
/** `globalThis.fetch` as it was before the preload; undefined until it ran. */
|
|
27
|
+
realFetch?: typeof fetch;
|
|
28
|
+
/** The `writeLine`s after this are dropped: a timed-out trial's file ends at its line. */
|
|
29
|
+
closed: boolean;
|
|
30
|
+
/** The first precondition `trial.require` found failed: the trial errors even if setup caught it. */
|
|
31
|
+
precondition?: string;
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
const KEY = Symbol.for("agentswf.lab.cases");
|
|
35
|
+
// A copy taken at load: a mock of `node:fs` that `spyOn` set up by hand doesn't reach the trial file.
|
|
36
|
+
const append = appendFileSync;
|
|
37
|
+
|
|
38
|
+
export function shared(): Shared {
|
|
39
|
+
const holder = globalThis as { [KEY]?: Shared };
|
|
40
|
+
holder[KEY] ??= {
|
|
41
|
+
phase: "setup",
|
|
42
|
+
refused: [],
|
|
43
|
+
routes: [],
|
|
44
|
+
allowed: [],
|
|
45
|
+
requests: [],
|
|
46
|
+
closed: false,
|
|
47
|
+
};
|
|
48
|
+
return holder[KEY];
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Appends a line to the trial file; nothing outside a trial. */
|
|
52
|
+
export function writeLine(line: TrialLine): void {
|
|
53
|
+
const file = process.env[TRIAL_ENV.trial];
|
|
54
|
+
if (!file || shared().closed) return;
|
|
55
|
+
append(file, `${JSON.stringify(line)}\n`);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Records a call the case doesn't fake, in the trial file and on the lab's side, and returns the
|
|
60
|
+
* error to throw: the trial errors as the dataset's even when the workflow catches it.
|
|
61
|
+
*/
|
|
62
|
+
export function refuse(what: string, by: Refused["by"], message: string): Error {
|
|
63
|
+
const state = shared();
|
|
64
|
+
const refused: Refused = { what, by, phase: state.phase, message };
|
|
65
|
+
state.refused.push(refused);
|
|
66
|
+
writeLine({ refused });
|
|
67
|
+
return new Error(message);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** The trial's parameters, `{}` when the lab gave none. */
|
|
71
|
+
export function trialParams(): Record<string, string> {
|
|
72
|
+
const text = process.env[TRIAL_ENV.params];
|
|
73
|
+
return text ? (JSON.parse(text) as Record<string, string>) : {};
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export function trialSettings(): TrialSettings | undefined {
|
|
77
|
+
const text = process.env[TRIAL_ENV.settings];
|
|
78
|
+
return text ? (JSON.parse(text) as TrialSettings) : undefined;
|
|
79
|
+
}
|