@genroc/eval-node 0.0.0-edge.f85ea85 → 0.0.0-edge.f97de45
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 +202 -0
- package/README.md +67 -33
- package/dist/eval.js +85 -0
- package/dist/import.js +397 -0
- package/dist/realm.js +113 -0
- package/dist/worker.js +305 -0
- package/eval.ts +31 -5
- package/import.ts +190 -80
- package/package.json +6 -4
- package/realm.ts +61 -77
- package/worker.ts +44 -12
- package/bin/import.mjs +0 -4
- package/bin/worker.mjs +0 -2
package/dist/import.js
ADDED
|
@@ -0,0 +1,397 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// The code-phase resolver: manifest on stdin, `{"code": [...]}` on stdout, non-zero exit
|
|
3
|
+
// with the diagnostic on stderr. genctl never parses TypeScript and this never parses YAML
|
|
4
|
+
// — the manifest is the whole contract. See specs/source-resolution.md.
|
|
5
|
+
//
|
|
6
|
+
// Two modes, one binary: "types" writes the declarations an editor needs and returns no
|
|
7
|
+
// code; "build" typechecks and bundles. A separate types hook would mean a second `tsc`
|
|
8
|
+
// over the same project.
|
|
9
|
+
import { spawn } from "node:child_process";
|
|
10
|
+
import { existsSync } from "node:fs";
|
|
11
|
+
import { access, mkdir, writeFile } from "node:fs/promises";
|
|
12
|
+
import { builtinModules } from "node:module";
|
|
13
|
+
import { dirname, join, relative, resolve } from "node:path";
|
|
14
|
+
import { fileURLToPath } from "node:url";
|
|
15
|
+
import commonjs from "@rollup/plugin-commonjs";
|
|
16
|
+
import json from "@rollup/plugin-json";
|
|
17
|
+
import { nodeResolve } from "@rollup/plugin-node-resolve";
|
|
18
|
+
import { rollup } from "rollup";
|
|
19
|
+
import ts from "typescript";
|
|
20
|
+
function die(message) {
|
|
21
|
+
console.error(message);
|
|
22
|
+
process.exit(1);
|
|
23
|
+
}
|
|
24
|
+
async function exists(path) {
|
|
25
|
+
try {
|
|
26
|
+
await access(path);
|
|
27
|
+
return true;
|
|
28
|
+
}
|
|
29
|
+
catch {
|
|
30
|
+
return false;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
/** Creates the parent directory, which `.genroc-cache/` relies on: nothing else makes it. */
|
|
34
|
+
async function write(path, content) {
|
|
35
|
+
await mkdir(dirname(path), { recursive: true });
|
|
36
|
+
await writeFile(path, content);
|
|
37
|
+
}
|
|
38
|
+
// ── JSON Schema → TypeScript ───────────────────────────────────────────────────
|
|
39
|
+
/** Only genroc's keyword set is handled; anything else its strict decoder would have
|
|
40
|
+
* refused before this ran (internal/schema, allowedKeywords). */
|
|
41
|
+
function tsType(s, used) {
|
|
42
|
+
if (s === undefined || s === null)
|
|
43
|
+
return "unknown";
|
|
44
|
+
if (typeof s.$ref === "string") {
|
|
45
|
+
const name = s.$ref.replace(/^#\/\$defs\//, "");
|
|
46
|
+
used.add(name);
|
|
47
|
+
return identifier(name);
|
|
48
|
+
}
|
|
49
|
+
if (Array.isArray(s.enum)) {
|
|
50
|
+
return s.enum.map((v) => JSON.stringify(v)).join(" | ") || "never";
|
|
51
|
+
}
|
|
52
|
+
if (Array.isArray(s.anyOf))
|
|
53
|
+
return union(s.anyOf.map((a) => tsType(a, used)));
|
|
54
|
+
if (Array.isArray(s.oneOf))
|
|
55
|
+
return union(s.oneOf.map((a) => tsType(a, used)));
|
|
56
|
+
if (Array.isArray(s.allOf)) {
|
|
57
|
+
return s.allOf.map((a) => tsType(a, used)).join(" & ") || "unknown";
|
|
58
|
+
}
|
|
59
|
+
const types = s.type === undefined ? [] : Array.isArray(s.type) ? s.type : [s.type];
|
|
60
|
+
if (types.length === 0) {
|
|
61
|
+
// The top type: `{}` means unknown, not "an empty object". specs/unknown-type.md.
|
|
62
|
+
return s.properties ? objectType(s, used) : "unknown";
|
|
63
|
+
}
|
|
64
|
+
return union(types.map((t) => scalarType(t, s, used)));
|
|
65
|
+
}
|
|
66
|
+
function scalarType(t, s, used) {
|
|
67
|
+
switch (t) {
|
|
68
|
+
case "object":
|
|
69
|
+
return objectType(s, used);
|
|
70
|
+
case "array":
|
|
71
|
+
return s.items ? `Array<${tsType(s.items, used)}>` : "unknown[]";
|
|
72
|
+
case "string":
|
|
73
|
+
return "string";
|
|
74
|
+
case "number":
|
|
75
|
+
case "integer":
|
|
76
|
+
return "number";
|
|
77
|
+
case "boolean":
|
|
78
|
+
return "boolean";
|
|
79
|
+
case "null":
|
|
80
|
+
return "null";
|
|
81
|
+
default:
|
|
82
|
+
return "unknown";
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
function objectType(s, used) {
|
|
86
|
+
const props = s.properties ?? {};
|
|
87
|
+
const required = new Set(s.required ?? []);
|
|
88
|
+
const lines = [];
|
|
89
|
+
for (const [key, sub] of Object.entries(props)) {
|
|
90
|
+
const doc = typeof sub.description === "string"
|
|
91
|
+
? ` /** ${sub.description} */\n`
|
|
92
|
+
: "";
|
|
93
|
+
lines.push(`${doc} ${propKey(key)}${required.has(key) ? "" : "?"}: ${tsType(sub, used)};`);
|
|
94
|
+
}
|
|
95
|
+
if (s.additionalProperties && typeof s.additionalProperties === "object") {
|
|
96
|
+
lines.push(` [key: string]: ${tsType(s.additionalProperties, used)};`);
|
|
97
|
+
}
|
|
98
|
+
if (lines.length === 0)
|
|
99
|
+
return "Record<string, unknown>";
|
|
100
|
+
return `{\n${lines.join("\n")}\n}`;
|
|
101
|
+
}
|
|
102
|
+
function union(parts) {
|
|
103
|
+
const seen = [...new Set(parts)];
|
|
104
|
+
return seen.length === 0 ? "unknown" : seen.join(" | ");
|
|
105
|
+
}
|
|
106
|
+
const IDENT = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
|
|
107
|
+
const propKey = (k) => (IDENT.test(k) ? k : JSON.stringify(k));
|
|
108
|
+
const identifier = (n) => IDENT.test(n) ? n : `Def_${n.replace(/[^A-Za-z0-9_$]/g, "_")}`;
|
|
109
|
+
function deref(s, defs) {
|
|
110
|
+
let cur = s;
|
|
111
|
+
for (let i = 0; cur && typeof cur.$ref === "string" && i < 16; i++) {
|
|
112
|
+
cur = defs[cur.$ref.replace(/^#\/\$defs\//, "")];
|
|
113
|
+
}
|
|
114
|
+
return cur;
|
|
115
|
+
}
|
|
116
|
+
/** Emits one named type per reachable $def rather than inlining: a task output may
|
|
117
|
+
* reference itself (specs/recursive-type-inference.md) and inlining would not terminate. */
|
|
118
|
+
function declarations(at) {
|
|
119
|
+
const { site, where } = at;
|
|
120
|
+
const defs = where.$defs ?? {};
|
|
121
|
+
const used = new Set();
|
|
122
|
+
const input = tsType(site.types?.Input, used);
|
|
123
|
+
const output = tsType(site.types?.Output, used);
|
|
124
|
+
const emitted = [];
|
|
125
|
+
const done = new Set();
|
|
126
|
+
while (true) {
|
|
127
|
+
const next = [...used].find((n) => !done.has(n));
|
|
128
|
+
if (next === undefined)
|
|
129
|
+
break;
|
|
130
|
+
done.add(next);
|
|
131
|
+
const body = tsType(defs[next], used);
|
|
132
|
+
emitted.push(`export type ${identifier(next)} = ${body};`);
|
|
133
|
+
}
|
|
134
|
+
return [
|
|
135
|
+
"// Generated by genroc. Do not edit - regenerate with `genctl types`.",
|
|
136
|
+
`// ${where.name} (${address(site.pointer)})`,
|
|
137
|
+
"",
|
|
138
|
+
...emitted,
|
|
139
|
+
emitted.length ? "" : "",
|
|
140
|
+
`export type Input = ${input};`,
|
|
141
|
+
"",
|
|
142
|
+
`export type Output = ${output};`,
|
|
143
|
+
"",
|
|
144
|
+
].join("\n");
|
|
145
|
+
}
|
|
146
|
+
/** Keyed by the script's PATH, not the task id: keyed by task, renaming a task would break
|
|
147
|
+
* the author's `import type` line with the error landing nowhere near the rename. */
|
|
148
|
+
function typesPathFor(scriptPath) {
|
|
149
|
+
return scriptPath.replace(/\.[^.\/]+$/, "") + ".genroc.d.ts";
|
|
150
|
+
}
|
|
151
|
+
// ── typecheck ──────────────────────────────────────────────────────────────────
|
|
152
|
+
/** The nearest tsconfig above the script — the one the author's editor already reads. Two
|
|
153
|
+
* different configs mean a red editor over a clean apply, or the reverse. The walk stops at
|
|
154
|
+
* the project root: above it is not this project. */
|
|
155
|
+
async function nearestTsconfig(from, root) {
|
|
156
|
+
for (let dir = from;; dir = dirname(dir)) {
|
|
157
|
+
const candidate = join(dir, "tsconfig.json");
|
|
158
|
+
if (await exists(candidate))
|
|
159
|
+
return candidate;
|
|
160
|
+
if (dir === root || dirname(dir) === dir)
|
|
161
|
+
return null;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
async function typecheck(sites) {
|
|
165
|
+
// NOT `.genroc`: that is the project config FILE, and a directory of the same name cannot
|
|
166
|
+
// coexist with it. The suffix is what keeps the scratch area out of its way.
|
|
167
|
+
const dir = join(root, ".genroc-cache");
|
|
168
|
+
await write(join(dir, ".gitignore"), "*\n");
|
|
169
|
+
// One tsc per distinct base config: `extends` takes a single base, so merging two would
|
|
170
|
+
// check each script under the other author's options.
|
|
171
|
+
const groups = new Map();
|
|
172
|
+
for (const at of sites) {
|
|
173
|
+
const base = (await nearestTsconfig(dirname(at.file), root)) ?? "";
|
|
174
|
+
const group = groups.get(base);
|
|
175
|
+
if (group)
|
|
176
|
+
group.push(at);
|
|
177
|
+
else
|
|
178
|
+
groups.set(base, [at]);
|
|
179
|
+
}
|
|
180
|
+
let n = 0;
|
|
181
|
+
for (const [base, group] of groups) {
|
|
182
|
+
const config = {
|
|
183
|
+
...(base ? { extends: relative(dir, base) } : {}),
|
|
184
|
+
compilerOptions: {
|
|
185
|
+
noEmit: true,
|
|
186
|
+
strict: true,
|
|
187
|
+
skipLibCheck: true,
|
|
188
|
+
moduleDetection: "force",
|
|
189
|
+
module: "preserve",
|
|
190
|
+
target: "esnext",
|
|
191
|
+
// `lib` DESCRIBES the realm and is written after `extends` so a base cannot widen it:
|
|
192
|
+
// a worker thread has no document, whatever an author's config claims.
|
|
193
|
+
lib: ["esnext", "webworker"],
|
|
194
|
+
// `types` is the author's, and it is how a script opts into the node globals —
|
|
195
|
+
// the worker realm has them, so refusing the declarations would only lie. With no
|
|
196
|
+
// base config there is nothing to opt in with, so the default stays none.
|
|
197
|
+
...(base ? {} : { types: [] }),
|
|
198
|
+
},
|
|
199
|
+
files: group.flatMap((s) => [
|
|
200
|
+
relative(dir, s.file),
|
|
201
|
+
relative(dir, typesPathFor(s.file)),
|
|
202
|
+
]),
|
|
203
|
+
// `files` overrides the base's, but a base `include` survives beside it and would
|
|
204
|
+
// drag the author's whole tree in, to be checked under the worker lib.
|
|
205
|
+
include: [],
|
|
206
|
+
};
|
|
207
|
+
const configPath = join(dir, groups.size === 1 ? "tsconfig.json" : `tsconfig.${n++}.json`);
|
|
208
|
+
await write(configPath, JSON.stringify(config, null, 2));
|
|
209
|
+
await runTsc(root, configPath);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
async function runTsc(root, configPath) {
|
|
213
|
+
const tsc = fileURLToPath(import.meta.resolve("typescript/bin/tsc"));
|
|
214
|
+
const proc = spawn(process.execPath, [tsc, "--noEmit", "-p", configPath], {
|
|
215
|
+
cwd: root,
|
|
216
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
217
|
+
});
|
|
218
|
+
let out = "";
|
|
219
|
+
let err = "";
|
|
220
|
+
proc.stdout.on("data", (c) => (out += c));
|
|
221
|
+
proc.stderr.on("data", (c) => (err += c));
|
|
222
|
+
const code = await new Promise((resolve, reject) => {
|
|
223
|
+
proc.on("error", reject);
|
|
224
|
+
proc.on("close", (c) => resolve(c ?? 1));
|
|
225
|
+
});
|
|
226
|
+
if (code !== 0) {
|
|
227
|
+
// tsc reports on stdout; the exit code IS the type check, so this is the diagnostic
|
|
228
|
+
// genctl surfaces and the reason a failed import never produces a string.
|
|
229
|
+
die([out, err].filter(Boolean).join("\n").trimEnd());
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
// ── bundle ─────────────────────────────────────────────────────────────────────
|
|
233
|
+
/** Transpiles only. The typecheck above already ran over the author's OWN tsconfig, and a
|
|
234
|
+
* second opinion from a config they do not control could fail a build they cannot fix. */
|
|
235
|
+
const transpile = {
|
|
236
|
+
name: "genroc-transpile",
|
|
237
|
+
transform(code, id) {
|
|
238
|
+
if (!id.endsWith(".ts") && !id.endsWith(".tsx"))
|
|
239
|
+
return null;
|
|
240
|
+
const out = ts.transpileModule(code, {
|
|
241
|
+
fileName: id,
|
|
242
|
+
compilerOptions: {
|
|
243
|
+
target: ts.ScriptTarget.ESNext,
|
|
244
|
+
module: ts.ModuleKind.ESNext,
|
|
245
|
+
verbatimModuleSyntax: false,
|
|
246
|
+
jsx: id.endsWith(".tsx") ? ts.JsxEmit.ReactJSX : undefined,
|
|
247
|
+
},
|
|
248
|
+
});
|
|
249
|
+
return { code: out.outputText, map: out.sourceMapText ?? null };
|
|
250
|
+
},
|
|
251
|
+
};
|
|
252
|
+
const BUILTIN = new Set([
|
|
253
|
+
...builtinModules,
|
|
254
|
+
...builtinModules.map((m) => `node:${m}`),
|
|
255
|
+
]);
|
|
256
|
+
/** Resolves imports through TYPESCRIPT, using the same config the typecheck ran under, so a
|
|
257
|
+
* `paths` alias that compiles also bundles. Reimplementing `paths` here would be a second
|
|
258
|
+
* resolver to keep in agreement with tsc; this one cannot disagree.
|
|
259
|
+
* A package resolving to a `.d.ts` is declined — that is a type, not the implementation —
|
|
260
|
+
* which leaves node_modules to nodeResolve. */
|
|
261
|
+
function tsResolve(configPath) {
|
|
262
|
+
let options = {};
|
|
263
|
+
if (configPath) {
|
|
264
|
+
const read = ts.readConfigFile(configPath, ts.sys.readFile);
|
|
265
|
+
options = ts.parseJsonConfigFileContent(read.config ?? {}, ts.sys, dirname(configPath)).options;
|
|
266
|
+
}
|
|
267
|
+
return {
|
|
268
|
+
name: "genroc-ts-resolve",
|
|
269
|
+
resolveId(source, importer) {
|
|
270
|
+
if (!importer || BUILTIN.has(source))
|
|
271
|
+
return null;
|
|
272
|
+
const { resolvedModule } = ts.resolveModuleName(source, importer, options, ts.sys);
|
|
273
|
+
if (!resolvedModule || resolvedModule.isExternalLibraryImport)
|
|
274
|
+
return null;
|
|
275
|
+
return resolvedModule.resolvedFileName.endsWith(".d.ts")
|
|
276
|
+
? null
|
|
277
|
+
: resolvedModule.resolvedFileName;
|
|
278
|
+
},
|
|
279
|
+
};
|
|
280
|
+
}
|
|
281
|
+
/** Bundles to a self-contained ES module, which is what the evaluator imports: the default
|
|
282
|
+
* export it calls is the author's own, so nothing wraps or rewrites the code between the two.
|
|
283
|
+
* Bundling is entirely the importer's job, so a definition version pins its code forever. */
|
|
284
|
+
async function bundle(at) {
|
|
285
|
+
const site = at.site;
|
|
286
|
+
// Builtins are EXTERNALISED as imports the realm resolves natively. Anything else
|
|
287
|
+
// unresolved is a REFUSAL, not an external: rollup's default is to leave it as an import
|
|
288
|
+
// of a module that will not be there, which bundles clean and fails at runtime.
|
|
289
|
+
const built = await rollup({
|
|
290
|
+
input: at.file,
|
|
291
|
+
external: (id) => BUILTIN.has(id),
|
|
292
|
+
plugins: [
|
|
293
|
+
tsResolve(await nearestTsconfig(dirname(at.file), root)),
|
|
294
|
+
nodeResolve({ extensions: [".ts", ".tsx", ".mjs", ".js", ".json"] }),
|
|
295
|
+
commonjs(),
|
|
296
|
+
// A `.json` import is a data file inlined at build time, which the previous bundler
|
|
297
|
+
// did natively; without it rollup hands the JSON to the JS parser.
|
|
298
|
+
json(),
|
|
299
|
+
transpile,
|
|
300
|
+
],
|
|
301
|
+
onwarn(warning) {
|
|
302
|
+
if (warning.code === "UNRESOLVED_IMPORT") {
|
|
303
|
+
die(`${at.file}: cannot resolve ${warning.exporter ?? "an import"} — is it installed?`);
|
|
304
|
+
}
|
|
305
|
+
},
|
|
306
|
+
}).catch((e) => die(`${at.file}: ${e instanceof Error ? e.message : String(e)}`));
|
|
307
|
+
const { output } = await built.generate({
|
|
308
|
+
format: "es",
|
|
309
|
+
inlineDynamicImports: true,
|
|
310
|
+
});
|
|
311
|
+
await built.close();
|
|
312
|
+
// Refused here rather than in the realm: the evaluator can only report it against a running
|
|
313
|
+
// instance, and the file it names is on this machine.
|
|
314
|
+
if (!output[0].exports.includes("default")) {
|
|
315
|
+
die(`${at.file}: a script must \`export default\` the function to run`);
|
|
316
|
+
}
|
|
317
|
+
return output[0].code;
|
|
318
|
+
}
|
|
319
|
+
// ── main ───────────────────────────────────────────────────────────────────────
|
|
320
|
+
const stdin = await new Promise((resolve, reject) => {
|
|
321
|
+
let raw = "";
|
|
322
|
+
process.stdin.setEncoding("utf8");
|
|
323
|
+
process.stdin.on("data", (c) => (raw += c));
|
|
324
|
+
process.stdin.on("end", () => resolve(raw));
|
|
325
|
+
process.stdin.on("error", reject);
|
|
326
|
+
});
|
|
327
|
+
const manifest = JSON.parse(stdin);
|
|
328
|
+
// genctl runs a resolver with the project root as its cwd, so the manifest need not say so.
|
|
329
|
+
const root = process.cwd();
|
|
330
|
+
if (!manifest || !Array.isArray(manifest.processes))
|
|
331
|
+
die("stdin is not a genroc resolver manifest");
|
|
332
|
+
/** A pointer as the address it is, so a generated comment or an error can be pasted into
|
|
333
|
+
* `genctl schema`. A key no identifier can spell is bracketed, as the grammar spells it. */
|
|
334
|
+
function address(pointer) {
|
|
335
|
+
return pointer
|
|
336
|
+
.map((seg) => typeof seg === "string" && /^[A-Za-z_][A-Za-z0-9_]*$/.test(seg)
|
|
337
|
+
? `.${seg}`
|
|
338
|
+
: `[${JSON.stringify(seg)}]`)
|
|
339
|
+
.join("")
|
|
340
|
+
.replace(/^\./, "");
|
|
341
|
+
}
|
|
342
|
+
const located = manifest.processes.flatMap((where) => where.sites.map((site) => ({
|
|
343
|
+
site,
|
|
344
|
+
where,
|
|
345
|
+
file: resolve(where.dir, site.argument),
|
|
346
|
+
})));
|
|
347
|
+
// genctl is agnostic about what a script is for; the contract that an evaluation request carries
|
|
348
|
+
// its module in `code` is THIS resolver's, so it is the one that checks a directive landed there.
|
|
349
|
+
// `child` is the shape the scaffold uses — a call to a process that forwards to the evaluator —
|
|
350
|
+
// and `external` is the same request made directly.
|
|
351
|
+
for (const at of located) {
|
|
352
|
+
// Two halves, from the two places that carry them: the action's KIND is a field, and WHERE in
|
|
353
|
+
// it the directive sits is the pointer. A child call is the shape the scaffold generates — to a
|
|
354
|
+
// process that forwards to the evaluator — and an external task is the same request made
|
|
355
|
+
// directly.
|
|
356
|
+
const kind = at.site.level === "action" ? (at.site.action ?? "") : "";
|
|
357
|
+
const slot = at.site.pointer.slice(-2).join(".");
|
|
358
|
+
if ((kind !== "child" && kind !== "external") || slot !== "input.code") {
|
|
359
|
+
die(`${join(at.where.dir, at.where.file)}: ${address(at.site.pointer)}: an evaluated script ` +
|
|
360
|
+
"belongs in the `code` field of a child or external task's input, and this is " +
|
|
361
|
+
`${kind ? `a ${kind} task's ` : ""}\`${slot}\`.`);
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
// genctl no longer stats the argument — it does not know it is a file — so the resolver that
|
|
365
|
+
// does is the one that must say when it is not there.
|
|
366
|
+
for (const at of located) {
|
|
367
|
+
if (!existsSync(at.file)) {
|
|
368
|
+
die(`${join(at.where.dir, at.where.file)}: ${address(at.site.pointer)}: ` +
|
|
369
|
+
`"$import: ${at.site.argument}" names no file (looked at ${at.file})`);
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
// One script at two sites with different input types is a refusal, not a union: the union
|
|
373
|
+
// is sound and would typecheck a body that is wrong at one of the sites.
|
|
374
|
+
const byPath = new Map();
|
|
375
|
+
for (const at of located) {
|
|
376
|
+
const seen = byPath.get(at.file);
|
|
377
|
+
if (seen &&
|
|
378
|
+
JSON.stringify(seen.site.types) !== JSON.stringify(at.site.types)) {
|
|
379
|
+
die(`${at.file} is imported at ${address(seen.site.pointer)} and ` +
|
|
380
|
+
`${address(at.site.pointer)} with different input types.\n` +
|
|
381
|
+
"Split it into two scripts, or make the two call sites pass the same shape.");
|
|
382
|
+
}
|
|
383
|
+
byPath.set(at.file, at);
|
|
384
|
+
}
|
|
385
|
+
for (const at of byPath.values()) {
|
|
386
|
+
await write(typesPathFor(at.file), declarations(at));
|
|
387
|
+
}
|
|
388
|
+
if (manifest.mode === "types") {
|
|
389
|
+
console.log(JSON.stringify(manifest, null, 2));
|
|
390
|
+
process.exit(0);
|
|
391
|
+
}
|
|
392
|
+
await typecheck([...byPath.values()]);
|
|
393
|
+
const code = [];
|
|
394
|
+
for (const at of located) {
|
|
395
|
+
code.push(await bundle(at));
|
|
396
|
+
}
|
|
397
|
+
process.stdout.write(JSON.stringify({ code }));
|
package/dist/realm.js
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
// The evaluation realm. One Worker per execution: a fresh global object per script, and a
|
|
2
|
+
// thread the host can kill mid-loop — the only thing that bounds a synchronous busy loop.
|
|
3
|
+
// eval.ts owns the budget and does the killing; nothing here knows about time.
|
|
4
|
+
//
|
|
5
|
+
// Everything that touches the script's VALUE lives on this side of the boundary — loading,
|
|
6
|
+
// classifying, serialising — because this is the only realm the value exists in.
|
|
7
|
+
var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
|
|
8
|
+
if (typeof path === "string" && /^\.\.?\//.test(path)) {
|
|
9
|
+
return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
|
|
10
|
+
return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
|
|
11
|
+
});
|
|
12
|
+
}
|
|
13
|
+
return path;
|
|
14
|
+
};
|
|
15
|
+
import { registerHooks } from "node:module";
|
|
16
|
+
import { parentPort } from "node:worker_threads";
|
|
17
|
+
// The script is IMPORTED as a module under a URL of our own, not compiled from a string: its
|
|
18
|
+
// frames then carry the author's own line numbers, and an `import` of a node builtin resolves
|
|
19
|
+
// the way it does everywhere else.
|
|
20
|
+
const SCRIPT_URL = "script:main";
|
|
21
|
+
const STACK_BYTES = 2_048;
|
|
22
|
+
// The only channel a load hook has to the source. Written per request and read once — a realm
|
|
23
|
+
// evaluates one script and is then discarded, so no second execution can observe it.
|
|
24
|
+
let source = "";
|
|
25
|
+
registerHooks({
|
|
26
|
+
resolve: (specifier, context, next) => specifier === SCRIPT_URL ? { url: SCRIPT_URL, shortCircuit: true } : next(specifier, context),
|
|
27
|
+
load: (url, context, next) => url === SCRIPT_URL ? { format: "module", source, shortCircuit: true } : next(url, context),
|
|
28
|
+
});
|
|
29
|
+
/** Keeps the frames that are the script's own. Everything below the last of them is runner
|
|
30
|
+
* plumbing the author cannot act on, and V8 puts this file's path in it. */
|
|
31
|
+
function scriptStack(err) {
|
|
32
|
+
if (!(err instanceof Error) || typeof err.stack !== "string")
|
|
33
|
+
return undefined;
|
|
34
|
+
const lines = err.stack.split("\n");
|
|
35
|
+
let last = 0;
|
|
36
|
+
for (let i = 0; i < lines.length; i++)
|
|
37
|
+
if (lines[i].includes(SCRIPT_URL))
|
|
38
|
+
last = i;
|
|
39
|
+
const stack = lines.slice(0, last + 1).join("\n");
|
|
40
|
+
return stack.length > STACK_BYTES ? stack.slice(0, STACK_BYTES) : stack;
|
|
41
|
+
}
|
|
42
|
+
function describe(err, kind) {
|
|
43
|
+
if (err instanceof Error) {
|
|
44
|
+
return { kind, name: err.name, message: err.message, stack: scriptStack(err) };
|
|
45
|
+
}
|
|
46
|
+
// A script may throw a non-Error (`throw {code: "x"}`), so name/message must not assume one.
|
|
47
|
+
return { kind, name: "Thrown", message: safeText(err) };
|
|
48
|
+
}
|
|
49
|
+
function safeText(v) {
|
|
50
|
+
try {
|
|
51
|
+
return typeof v === "string" ? v : JSON.stringify(v) ?? String(v);
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
return String(v);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
/** A module that will not parse, or names an import nothing resolves, is broken code — only
|
|
58
|
+
* editing it helps. Anything else thrown by the import is the module's top level running,
|
|
59
|
+
* which is the script throwing. */
|
|
60
|
+
function unloadable(err) {
|
|
61
|
+
const code = err?.code;
|
|
62
|
+
return err instanceof SyntaxError || (typeof code === "string" && code.startsWith("ERR_MODULE"));
|
|
63
|
+
}
|
|
64
|
+
async function run(req) {
|
|
65
|
+
source = req.code;
|
|
66
|
+
let main;
|
|
67
|
+
try {
|
|
68
|
+
main = (await import(__rewriteRelativeImportExtension(SCRIPT_URL))).default;
|
|
69
|
+
}
|
|
70
|
+
catch (err) {
|
|
71
|
+
return { ok: false, failure: describe(err, unloadable(err) ? "compile_error" : "threw") };
|
|
72
|
+
}
|
|
73
|
+
if (typeof main !== "function") {
|
|
74
|
+
const got = main === undefined ? "no default export" : `a ${typeof main}`;
|
|
75
|
+
return {
|
|
76
|
+
ok: false,
|
|
77
|
+
failure: {
|
|
78
|
+
kind: "compile_error",
|
|
79
|
+
name: "NoDefaultExport",
|
|
80
|
+
message: `a script must export default a function; this one has ${got}`,
|
|
81
|
+
},
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
let value;
|
|
85
|
+
try {
|
|
86
|
+
value = await main(req.input);
|
|
87
|
+
}
|
|
88
|
+
catch (err) {
|
|
89
|
+
return { ok: false, failure: describe(err, "threw") };
|
|
90
|
+
}
|
|
91
|
+
try {
|
|
92
|
+
// undefined stringifies to undefined, not "undefined"; an empty body is how genroc
|
|
93
|
+
// spells null, which is the right reading of a script that returned nothing.
|
|
94
|
+
return { ok: true, body: value === undefined ? "" : JSON.stringify(value) ?? "" };
|
|
95
|
+
}
|
|
96
|
+
catch (err) {
|
|
97
|
+
return { ok: false, failure: describe(err, "nonserializable") };
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
// The realm's stdio is a pipe to the host thread, and eval.ts terminates this thread the moment
|
|
101
|
+
// the reply lands — so whatever a script wrote last is still in the pipe when it dies. An empty
|
|
102
|
+
// write's callback fires once the queue ahead of it has drained, which makes the reply a barrier
|
|
103
|
+
// for `console` and a direct process.stdout.write alike: both are this stream.
|
|
104
|
+
function flush(stream) {
|
|
105
|
+
return new Promise((resolve) => stream.write("", () => resolve()));
|
|
106
|
+
}
|
|
107
|
+
// Non-null because this module only ever runs as a worker entry point; a null port here
|
|
108
|
+
// would mean eval.ts loaded it as a plain module, which nothing does.
|
|
109
|
+
parentPort.on("message", async (req) => {
|
|
110
|
+
const reply = await run(req);
|
|
111
|
+
await Promise.all([flush(process.stdout), flush(process.stderr)]);
|
|
112
|
+
parentPort.postMessage(reply);
|
|
113
|
+
});
|