@genroc/eval-node 0.0.0-edge.4348678 → 0.0.0-edge.46dbe379

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/dist/import.js CHANGED
@@ -6,11 +6,10 @@
6
6
  // Two modes, one binary: "types" writes the declarations an editor needs and returns no
7
7
  // code; "build" typechecks and bundles. A separate types hook would mean a second `tsc`
8
8
  // over the same project.
9
- import { spawn } from "node:child_process";
10
- import { access, mkdir, writeFile } from "node:fs/promises";
9
+ import { existsSync } from "node:fs";
10
+ import { access, writeFile } from "node:fs/promises";
11
11
  import { builtinModules } from "node:module";
12
- import { dirname, join, relative } from "node:path";
13
- import { fileURLToPath } from "node:url";
12
+ import { dirname, join, resolve } from "node:path";
14
13
  import commonjs from "@rollup/plugin-commonjs";
15
14
  import json from "@rollup/plugin-json";
16
15
  import { nodeResolve } from "@rollup/plugin-node-resolve";
@@ -29,11 +28,6 @@ async function exists(path) {
29
28
  return false;
30
29
  }
31
30
  }
32
- /** Creates the parent directory, which `.genroc-cache/` relies on: nothing else makes it. */
33
- async function write(path, content) {
34
- await mkdir(dirname(path), { recursive: true });
35
- await writeFile(path, content);
36
- }
37
31
  // ── JSON Schema → TypeScript ───────────────────────────────────────────────────
38
32
  /** Only genroc's keyword set is handled; anything else its strict decoder would have
39
33
  * refused before this ran (internal/schema, allowedKeywords). */
@@ -86,45 +80,35 @@ function objectType(s, used) {
86
80
  const required = new Set(s.required ?? []);
87
81
  const lines = [];
88
82
  for (const [key, sub] of Object.entries(props)) {
89
- const doc = typeof sub.description === "string" ? ` /** ${sub.description} */\n` : "";
90
- lines.push(`${doc} ${propKey(key)}${required.has(key) ? "" : "?"}: ${tsType(sub, used)};`);
83
+ const doc = typeof sub.description === "string"
84
+ ? ` /** ${sub.description} */\n`
85
+ : "";
86
+ lines.push(`${doc} ${propKey(key)}${required.has(key) ? "" : "?"}: ${nest(tsType(sub, used))};`);
91
87
  }
92
88
  if (s.additionalProperties && typeof s.additionalProperties === "object") {
93
- lines.push(` [key: string]: ${tsType(s.additionalProperties, used)};`);
89
+ lines.push(` [key: string]: ${nest(tsType(s.additionalProperties, used))};`);
94
90
  }
95
91
  if (lines.length === 0)
96
92
  return "Record<string, unknown>";
97
93
  return `{\n${lines.join("\n")}\n}`;
98
94
  }
95
+ /** Every line but the first, which is already placed by the property that opens it. */
96
+ const nest = (t) => t.replace(/\n/g, "\n ");
99
97
  function union(parts) {
100
98
  const seen = [...new Set(parts)];
101
99
  return seen.length === 0 ? "unknown" : seen.join(" | ");
102
100
  }
103
101
  const IDENT = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
104
102
  const propKey = (k) => (IDENT.test(k) ? k : JSON.stringify(k));
105
- const identifier = (n) => (IDENT.test(n) ? n : `Def_${n.replace(/[^A-Za-z0-9_$]/g, "_")}`);
106
- function deref(s, defs) {
107
- let cur = s;
108
- for (let i = 0; cur && typeof cur.$ref === "string" && i < 16; i++) {
109
- cur = defs[cur.$ref.replace(/^#\/\$defs\//, "")];
110
- }
111
- return cur;
112
- }
113
- /** The manifest's `input` is the type of the whole ACTION input — for /eval that is
114
- * `{code, input, timeout_ms, …}`, and only its `input` field is bound as the script's
115
- * parameter. genroc cannot know that; this file owns the evaluator's wire contract, so
116
- * the navigation belongs here rather than in genctl. */
117
- function scriptInput(site, defs) {
118
- const action = deref(site.input, defs);
119
- const bound = action?.properties?.input;
120
- return bound ?? site.input;
121
- }
103
+ const identifier = (n) => IDENT.test(n) ? n : `Def_${n.replace(/[^A-Za-z0-9_$]/g, "_")}`;
122
104
  /** Emits one named type per reachable $def rather than inlining: a task output may
123
105
  * reference itself (specs/recursive-type-inference.md) and inlining would not terminate. */
124
- function declarations(site, defs) {
106
+ function declarations(at) {
107
+ const { site, where } = at;
108
+ const defs = where.$defs ?? {};
125
109
  const used = new Set();
126
- const input = tsType(scriptInput(site, defs), used);
127
- const output = tsType(site.output, used);
110
+ const input = tsType(site.types?.Input, used);
111
+ const output = tsType(site.types?.Output, used);
128
112
  const emitted = [];
129
113
  const done = new Set();
130
114
  while (true) {
@@ -137,7 +121,7 @@ function declarations(site, defs) {
137
121
  }
138
122
  return [
139
123
  "// Generated by genroc. Do not edit - regenerate with `genctl types`.",
140
- `// ${site.process}${site.task ? ` / ${site.task}` : ""} (${site.pointer})`,
124
+ `// ${where.name} (${address(site.pointer)})`,
141
125
  "",
142
126
  ...emitted,
143
127
  emitted.length ? "" : "",
@@ -165,26 +149,22 @@ async function nearestTsconfig(from, root) {
165
149
  return null;
166
150
  }
167
151
  }
168
- async function typecheck(root, sites) {
169
- // NOT `.genroc`: that is the project config FILE, and a directory of the same name cannot
170
- // coexist with it. The suffix is what keeps the scratch area out of its way.
171
- const dir = join(root, ".genroc-cache");
172
- await write(join(dir, ".gitignore"), "*\n");
173
- // One tsc per distinct base config: `extends` takes a single base, so merging two would
152
+ async function typecheck(sites) {
153
+ // One program per distinct base config: `extends` takes a single base, so merging two would
174
154
  // check each script under the other author's options.
175
155
  const groups = new Map();
176
- for (const site of sites) {
177
- const base = (await nearestTsconfig(dirname(site.path), root)) ?? "";
156
+ for (const at of sites) {
157
+ const base = (await nearestTsconfig(dirname(at.file), root)) ?? "";
178
158
  const group = groups.get(base);
179
159
  if (group)
180
- group.push(site);
160
+ group.push(at);
181
161
  else
182
- groups.set(base, [site]);
162
+ groups.set(base, [at]);
183
163
  }
184
- let n = 0;
164
+ const diagnostics = [];
185
165
  for (const [base, group] of groups) {
186
166
  const config = {
187
- ...(base ? { extends: relative(dir, base) } : {}),
167
+ ...(base ? { extends: base } : {}),
188
168
  compilerOptions: {
189
169
  noEmit: true,
190
170
  strict: true,
@@ -200,34 +180,33 @@ async function typecheck(root, sites) {
200
180
  // base config there is nothing to opt in with, so the default stays none.
201
181
  ...(base ? {} : { types: [] }),
202
182
  },
203
- files: group.flatMap((s) => [relative(dir, s.path), relative(dir, typesPathFor(s.path))]),
183
+ files: group.flatMap((s) => [s.file, typesPathFor(s.file)]),
204
184
  // `files` overrides the base's, but a base `include` survives beside it and would
205
185
  // drag the author's whole tree in, to be checked under the worker lib.
206
186
  include: [],
207
187
  };
208
- const configPath = join(dir, groups.size === 1 ? "tsconfig.json" : `tsconfig.${n++}.json`);
209
- await write(configPath, JSON.stringify(config, null, 2));
210
- await runTsc(root, configPath);
188
+ // Never written: the name only anchors `@types` lookup at the root. It must not be
189
+ // `tsconfig.json`: that is the base the config `extends` whenever the author keeps one at
190
+ // the root, and tsc refuses a config that extends its own path as circular.
191
+ const parsed = ts.parseJsonConfigFileContent(config, ts.sys, root, undefined, join(root, "tsconfig.genroc.json"));
192
+ const program = ts.createProgram({
193
+ rootNames: parsed.fileNames,
194
+ options: parsed.options,
195
+ projectReferences: parsed.projectReferences,
196
+ configFileParsingDiagnostics: parsed.errors,
197
+ });
198
+ diagnostics.push(...parsed.errors, ...ts.getPreEmitDiagnostics(program));
211
199
  }
212
- }
213
- async function runTsc(root, configPath) {
214
- const tsc = fileURLToPath(import.meta.resolve("typescript/bin/tsc"));
215
- const proc = spawn(process.execPath, [tsc, "--noEmit", "-p", configPath], {
216
- cwd: root,
217
- stdio: ["ignore", "pipe", "pipe"],
218
- });
219
- let out = "";
220
- let err = "";
221
- proc.stdout.on("data", (c) => (out += c));
222
- proc.stderr.on("data", (c) => (err += c));
223
- const code = await new Promise((resolve, reject) => {
224
- proc.on("error", reject);
225
- proc.on("close", (c) => resolve(c ?? 1));
226
- });
227
- if (code !== 0) {
228
- // tsc reports on stdout; the exit code IS the type check, so this is the diagnostic
229
- // genctl surfaces and the reason a failed import never produces a string.
230
- die([out, err].filter(Boolean).join("\n").trimEnd());
200
+ if (diagnostics.length > 0) {
201
+ // The diagnostics are the whole type check: this is what genctl surfaces, and the reason a
202
+ // failed import never produces a string.
203
+ die(ts
204
+ .formatDiagnostics(diagnostics, {
205
+ getCanonicalFileName: (f) => f,
206
+ getCurrentDirectory: () => root,
207
+ getNewLine: () => "\n",
208
+ })
209
+ .trimEnd());
231
210
  }
232
211
  }
233
212
  // ── bundle ─────────────────────────────────────────────────────────────────────
@@ -250,7 +229,10 @@ const transpile = {
250
229
  return { code: out.outputText, map: out.sourceMapText ?? null };
251
230
  },
252
231
  };
253
- const BUILTIN = new Set([...builtinModules, ...builtinModules.map((m) => `node:${m}`)]);
232
+ const BUILTIN = new Set([
233
+ ...builtinModules,
234
+ ...builtinModules.map((m) => `node:${m}`),
235
+ ]);
254
236
  /** Resolves imports through TYPESCRIPT, using the same config the typecheck ran under, so a
255
237
  * `paths` alias that compiles also bundles. Reimplementing `paths` here would be a second
256
238
  * resolver to keep in agreement with tsc; this one cannot disagree.
@@ -270,22 +252,25 @@ function tsResolve(configPath) {
270
252
  const { resolvedModule } = ts.resolveModuleName(source, importer, options, ts.sys);
271
253
  if (!resolvedModule || resolvedModule.isExternalLibraryImport)
272
254
  return null;
273
- return resolvedModule.resolvedFileName.endsWith(".d.ts") ? null : resolvedModule.resolvedFileName;
255
+ return resolvedModule.resolvedFileName.endsWith(".d.ts")
256
+ ? null
257
+ : resolvedModule.resolvedFileName;
274
258
  },
275
259
  };
276
260
  }
277
- /** Bundles to CJS and wraps it as an async function BODY, which is what /eval compiles.
278
- * The runtime stays unchanged: bundling is entirely the importer's job, and the string it
279
- * produces is self-contained, so a definition version pins its code forever. */
280
- async function bundle(site, root) {
281
- // Builtins are EXTERNALISED as `require` calls that worker.ts satisfies. Anything else
282
- // unresolved is a REFUSAL, not an external: rollup's default is to leave it as a require
261
+ /** Bundles to a self-contained ES module, which is what the evaluator imports: the default
262
+ * export it calls is the author's own, so nothing wraps or rewrites the code between the two.
263
+ * Bundling is entirely the importer's job, so a definition version pins its code forever. */
264
+ async function bundle(at) {
265
+ const site = at.site;
266
+ // Builtins are EXTERNALISED as imports the realm resolves natively. Anything else
267
+ // unresolved is a REFUSAL, not an external: rollup's default is to leave it as an import
283
268
  // of a module that will not be there, which bundles clean and fails at runtime.
284
269
  const built = await rollup({
285
- input: site.path,
270
+ input: at.file,
286
271
  external: (id) => BUILTIN.has(id),
287
272
  plugins: [
288
- tsResolve(await nearestTsconfig(dirname(site.path), root)),
273
+ tsResolve(await nearestTsconfig(dirname(at.file), root)),
289
274
  nodeResolve({ extensions: [".ts", ".tsx", ".mjs", ".js", ".json"] }),
290
275
  commonjs(),
291
276
  // A `.json` import is a data file inlined at build time, which the previous bundler
@@ -295,22 +280,21 @@ async function bundle(site, root) {
295
280
  ],
296
281
  onwarn(warning) {
297
282
  if (warning.code === "UNRESOLVED_IMPORT") {
298
- die(`${site.path}: cannot resolve ${warning.exporter ?? "an import"} — is it installed?`);
283
+ die(`${at.file}: cannot resolve ${warning.exporter ?? "an import"} — is it installed?`);
299
284
  }
300
285
  },
301
- }).catch((e) => die(`${site.path}: ${e instanceof Error ? e.message : String(e)}`));
302
- const { output } = await built.generate({ format: "cjs", exports: "auto", inlineDynamicImports: true });
286
+ }).catch((e) => die(`${at.file}: ${e instanceof Error ? e.message : String(e)}`));
287
+ const { output } = await built.generate({
288
+ format: "es",
289
+ inlineDynamicImports: true,
290
+ });
303
291
  await built.close();
304
- const cjs = output[0].code;
305
- return [
306
- "var module = { exports: {} }, exports = module.exports;",
307
- cjs,
308
- "var __genroc_main = module.exports.default ?? module.exports;",
309
- 'if (typeof __genroc_main !== "function") {',
310
- ` throw new Error(${JSON.stringify(`${site.path} has no default export function`)});`,
311
- "}",
312
- "return await __genroc_main(input);",
313
- ].join("\n");
292
+ // Refused here rather than in the realm: the evaluator can only report it against a running
293
+ // instance, and the file it names is on this machine.
294
+ if (!output[0].exports.includes("default")) {
295
+ die(`${at.file}: a script must \`export default\` the function to run`);
296
+ }
297
+ return output[0].code;
314
298
  }
315
299
  // ── main ───────────────────────────────────────────────────────────────────────
316
300
  const stdin = await new Promise((resolve, reject) => {
@@ -321,32 +305,73 @@ const stdin = await new Promise((resolve, reject) => {
321
305
  process.stdin.on("error", reject);
322
306
  });
323
307
  const manifest = JSON.parse(stdin);
324
- if (!manifest || !Array.isArray(manifest.sites))
308
+ // genctl runs a resolver with the project root as its cwd, so the manifest need not say so.
309
+ const root = process.cwd();
310
+ if (!manifest || !Array.isArray(manifest.processes))
325
311
  die("stdin is not a genroc resolver manifest");
312
+ /** A pointer as the address it is, so a generated comment or an error can be pasted into
313
+ * `genctl schema`. A key no identifier can spell is bracketed, as the grammar spells it. */
314
+ function address(pointer) {
315
+ return pointer
316
+ .map((seg) => typeof seg === "string" && /^[A-Za-z_][A-Za-z0-9_]*$/.test(seg)
317
+ ? `.${seg}`
318
+ : `[${JSON.stringify(seg)}]`)
319
+ .join("")
320
+ .replace(/^\./, "");
321
+ }
322
+ const located = manifest.processes.flatMap((where) => where.sites.map((site) => ({
323
+ site,
324
+ where,
325
+ file: resolve(where.dir, site.argument),
326
+ })));
327
+ // genctl is agnostic about what a script is for; the contract that an evaluation request carries
328
+ // its module in `code` is THIS resolver's, so it is the one that checks a directive landed there.
329
+ // `child` is the shape the scaffold uses — a call to a process that forwards to the evaluator —
330
+ // and `external` is the same request made directly.
331
+ for (const at of located) {
332
+ // Two halves, from the two places that carry them: the action's KIND is a field, and WHERE in
333
+ // it the directive sits is the pointer. A child call is the shape the scaffold generates — to a
334
+ // process that forwards to the evaluator — and an external task is the same request made
335
+ // directly.
336
+ const kind = at.site.level === "action" ? (at.site.action ?? "") : "";
337
+ const slot = at.site.pointer.slice(-2).join(".");
338
+ if ((kind !== "child" && kind !== "external") || slot !== "input.code") {
339
+ die(`${join(at.where.dir, at.where.file)}: ${address(at.site.pointer)}: an evaluated script ` +
340
+ "belongs in the `code` field of a child or external task's input, and this is " +
341
+ `${kind ? `a ${kind} task's ` : ""}\`${slot}\`.`);
342
+ }
343
+ }
344
+ // genctl no longer stats the argument — it does not know it is a file — so the resolver that
345
+ // does is the one that must say when it is not there.
346
+ for (const at of located) {
347
+ if (!existsSync(at.file)) {
348
+ die(`${join(at.where.dir, at.where.file)}: ${address(at.site.pointer)}: ` +
349
+ `"$import: ${at.site.argument}" names no file (looked at ${at.file})`);
350
+ }
351
+ }
326
352
  // One script at two sites with different input types is a refusal, not a union: the union
327
353
  // is sound and would typecheck a body that is wrong at one of the sites.
328
354
  const byPath = new Map();
329
- for (const site of manifest.sites) {
330
- const seen = byPath.get(site.path);
331
- const defsOf = (x) => (manifest.schemas[x.process]?.$defs ?? {});
355
+ for (const at of located) {
356
+ const seen = byPath.get(at.file);
332
357
  if (seen &&
333
- JSON.stringify(scriptInput(seen, defsOf(seen))) !==
334
- JSON.stringify(scriptInput(site, defsOf(site)))) {
335
- die(`${site.path} is imported at ${seen.pointer} and ${site.pointer} with different input types.\n` +
358
+ JSON.stringify(seen.site.types) !== JSON.stringify(at.site.types)) {
359
+ die(`${at.file} is imported at ${address(seen.site.pointer)} and ` +
360
+ `${address(at.site.pointer)} with different input types.\n` +
336
361
  "Split it into two scripts, or make the two call sites pass the same shape.");
337
362
  }
338
- byPath.set(site.path, site);
363
+ byPath.set(at.file, at);
339
364
  }
340
- for (const site of byPath.values()) {
341
- const defs = (manifest.schemas[site.process]?.$defs ?? {});
342
- await write(typesPathFor(site.path), declarations(site, defs));
365
+ for (const at of byPath.values()) {
366
+ await writeFile(typesPathFor(at.file), declarations(at));
343
367
  }
344
368
  if (manifest.mode === "types") {
369
+ console.log(JSON.stringify(manifest, null, 2));
345
370
  process.exit(0);
346
371
  }
347
- await typecheck(manifest.root, [...byPath.values()]);
372
+ await typecheck([...byPath.values()]);
348
373
  const code = [];
349
- for (const site of manifest.sites) {
350
- code.push(await bundle(site, manifest.root));
374
+ for (const at of located) {
375
+ code.push(await bundle(at));
351
376
  }
352
377
  process.stdout.write(JSON.stringify({ code }));
package/dist/realm.js CHANGED
@@ -2,80 +2,46 @@
2
2
  // thread the host can kill mid-loop — the only thing that bounds a synchronous busy loop.
3
3
  // eval.ts owns the budget and does the killing; nothing here knows about time.
4
4
  //
5
- // Everything that touches the script's VALUE lives on this side of the boundary — compiling,
5
+ // Everything that touches the script's VALUE lives on this side of the boundary — loading,
6
6
  // classifying, serialising — because this is the only realm the value exists in.
7
- import { createRequire } from "node:module";
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";
8
16
  import { parentPort } from "node:worker_threads";
9
- const AsyncFunction = async function () { }.constructor;
10
- const STRICT = '"use strict";\n';
11
- // Bundled `node:*` imports survive as `require` calls — the importer externalises builtins and
12
- // inlines everything else — and a function built by the AsyncFunction constructor has no
13
- // `require` in scope. Passing one in is what makes an import of a builtin work at runtime rather than at
14
- // typecheck only. Resolution is anchored here, which is right: only builtins reach it.
15
- const scriptRequire = createRequire(import.meta.url);
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";
16
21
  const STACK_BYTES = 2_048;
17
- /**
18
- * Line offset the AsyncFunction preamble adds, measured rather than assumed: the generated
19
- * wrapper's shape is engine-specific, and a hardcoded number silently misreports every
20
- * script's error location the day it changes.
21
- */
22
- const lineOffset = (async () => {
23
- // Same parameter list as a real compile: the preamble is what is being measured.
24
- const probe = new AsyncFunction("input", "require", STRICT + "throw new Error('probe');");
25
- try {
26
- await probe();
27
- return 0;
28
- }
29
- catch (err) {
30
- return reportedLine(err) - 1;
31
- }
32
- })();
33
- // V8 marks a frame compiled by the AsyncFunction constructor with the site that CALLED the
34
- // constructor, then the script's OWN position:
35
- // at inner (eval at run (file:///…/worker.ts:107:10), <anonymous>:6:9)
36
- // `eval at` is therefore what separates script frames from runner plumbing — matched without
37
- // the function name, which is whatever encloses the `new AsyncFunction` below. The LAST such
38
- // frame is the body's top level: frames interleave, since a script can throw inside a native
39
- // callback.
40
- const SCRIPT_FRAME = /\(eval at /;
41
- // The trailing `<anonymous>:LINE:COL` — the script's position, after the host file's own.
42
- const POSITION = /<anonymous>:(\d+):(\d+)\)?\s*$/;
43
- // ` at name (` — absent on the top-level frame, which V8 names `eval`.
44
- const FRAME_NAME = /^\s*at\s+(?:async\s+)?([^\s(]+)\s*\(/;
45
- /** Line number of the throw as the engine reported it, or 1 if the stack is unreadable. */
46
- function reportedLine(err) {
47
- const stack = err instanceof Error && typeof err.stack === "string" ? err.stack : "";
48
- const frame = stack.split("\n").find((l) => SCRIPT_FRAME.test(l)) ?? "";
49
- const m = frame.match(POSITION);
50
- return m ? Number(m[1]) : 1;
51
- }
52
- /** Renumbers each script frame to the line the AUTHOR wrote and drops the runner's own.
53
- * Rewriting the whole location is also what keeps the runner's path out of a script's
54
- * stack — V8 puts it inside every compiled frame. */
55
- function scriptStack(err, offset) {
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) {
56
32
  if (!(err instanceof Error) || typeof err.stack !== "string")
57
33
  return undefined;
58
34
  const lines = err.stack.split("\n");
59
- let boundary = -1;
35
+ let last = 0;
60
36
  for (let i = 0; i < lines.length; i++)
61
- if (SCRIPT_FRAME.test(lines[i]))
62
- boundary = i;
63
- const frames = (boundary >= 0 ? lines.slice(0, boundary + 1) : lines.slice(0, 1))
64
- .map((line) => {
65
- const pos = line.match(POSITION);
66
- if (!pos)
67
- return line; // the `Error: message` header and native frames, kept as-is
68
- const name = line.match(FRAME_NAME)?.[1];
69
- const at = name && name !== "eval" && name !== "anonymous" ? `at ${name} ` : "at ";
70
- const indent = line.match(/^\s*/)[0];
71
- return `${indent}${at}(script:${Math.max(1, Number(pos[1]) - offset)}:${pos[2]})`;
72
- })
73
- .join("\n");
74
- return frames.length > STACK_BYTES ? frames.slice(0, STACK_BYTES) : frames;
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;
75
41
  }
76
- function describe(err, kind, offset) {
42
+ function describe(err, kind) {
77
43
  if (err instanceof Error) {
78
- return { kind, name: err.name, message: err.message, stack: scriptStack(err, offset) };
44
+ return { kind, name: err.name, message: err.message, stack: scriptStack(err) };
79
45
  }
80
46
  // A script may throw a non-Error (`throw {code: "x"}`), so name/message must not assume one.
81
47
  return { kind, name: "Thrown", message: safeText(err) };
@@ -88,23 +54,39 @@ function safeText(v) {
88
54
  return String(v);
89
55
  }
90
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
+ }
91
64
  async function run(req) {
92
- const offset = await lineOffset;
93
- let fn;
65
+ source = req.code;
66
+ let main;
94
67
  try {
95
- // No compile cache: the realm is discarded after this execution, so a cache in it could
96
- // never be hit. Repeated compilation is the price of the fresh global object.
97
- fn = new AsyncFunction("input", "require", STRICT + req.code);
68
+ main = (await import(__rewriteRelativeImportExtension(SCRIPT_URL))).default;
98
69
  }
99
70
  catch (err) {
100
- return { ok: false, failure: describe(err, "compile_error", offset) };
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
+ };
101
83
  }
102
84
  let value;
103
85
  try {
104
- value = await fn(req.input, scriptRequire);
86
+ value = await main(req.input);
105
87
  }
106
88
  catch (err) {
107
- return { ok: false, failure: describe(err, "threw", offset) };
89
+ return { ok: false, failure: describe(err, "threw") };
108
90
  }
109
91
  try {
110
92
  // undefined stringifies to undefined, not "undefined"; an empty body is how genroc
@@ -112,11 +94,20 @@ async function run(req) {
112
94
  return { ok: true, body: value === undefined ? "" : JSON.stringify(value) ?? "" };
113
95
  }
114
96
  catch (err) {
115
- return { ok: false, failure: describe(err, "nonserializable", offset) };
97
+ return { ok: false, failure: describe(err, "nonserializable") };
116
98
  }
117
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
+ }
118
107
  // Non-null because this module only ever runs as a worker entry point; a null port here
119
108
  // would mean eval.ts loaded it as a plain module, which nothing does.
120
109
  parentPort.on("message", async (req) => {
121
- parentPort.postMessage(await run(req));
110
+ const reply = await run(req);
111
+ await Promise.all([flush(process.stdout), flush(process.stderr)]);
112
+ parentPort.postMessage(reply);
122
113
  });