@genroc/eval-node 0.0.0-edge.51cbf37 → 0.0.0-edge.51f2744b

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/eval.js CHANGED
@@ -1,35 +1,46 @@
1
- // Evaluation core: run a code string in its OWN realm and classify every outcome into one of
2
- // the failure kinds in README.md. Nothing here knows about genroc — worker.ts is the only
3
- // thing that talks to the queue — so this stays testable and the containment stays swappable.
4
- //
5
- // The containment is a Worker per execution (realm.ts). It is what makes the budget real:
6
- // a synchronous busy loop never yields, so no in-process timer can interrupt it, and only a
7
- // thread the host can kill bounds it.
1
+ // Imports a script module in its own realm (a Worker per execution, realm.ts), calls its default
2
+ // export, and classifies every outcome (README.md). Only a killable thread bounds a synchronous
3
+ // busy loop, which is what makes the budget real. Knows nothing of genroc; worker.ts does.
8
4
  import { Worker } from "node:worker_threads";
9
5
  const DEFAULT_TIMEOUT_MS = 5_000;
10
6
  // Resolved from THIS file's own extension: run from a checkout it is `.ts`, and from the
11
7
  // published package `.js`, because Node will not strip types under node_modules.
12
8
  const REALM_URL = new URL(import.meta.url.endsWith(".ts") ? "./realm.ts" : "./realm.js", import.meta.url);
13
- /** Thrown, not returned: a realm that fails to start is the RUNNER faulting, which worker.ts
14
- * answers by releasing the claim rather than by reporting an outcome. A script fault is a
15
- * return value. */
9
+ /** Thrown, not returned: a realm that fails to start is the runner faulting, which worker.ts
10
+ * answers by releasing the claim. */
16
11
  class RealmFault extends Error {
17
12
  constructor(message) {
18
13
  super(message);
19
14
  this.name = "RealmFault";
20
15
  }
21
16
  }
22
- export async function evaluate(req) {
17
+ /** Thrown when `signal` aborts: the answer is no longer wanted, so worker.ts releases rather
18
+ * than answers. Not a RealmFault: nothing is wrong. */
19
+ export class Cancelled extends Error {
20
+ constructor() {
21
+ super("cancelled");
22
+ this.name = "Cancelled";
23
+ }
24
+ }
25
+ export async function evaluate(req, signal) {
23
26
  const budget = typeof req.timeout_ms === "number" ? req.timeout_ms : DEFAULT_TIMEOUT_MS;
24
27
  const worker = new Worker(REALM_URL);
25
28
  let timer;
29
+ let onAbort;
26
30
  try {
27
31
  return await new Promise((resolve, reject) => {
28
32
  timer = setTimeout(() => resolve(timedOut(budget)), budget);
33
+ // The abort is wired to the same promise as the budget, so both settle through the one
34
+ // finally below -- which is what guarantees the thread is gone before either returns.
35
+ if (signal) {
36
+ if (signal.aborted)
37
+ reject(new Cancelled());
38
+ onAbort = () => reject(new Cancelled());
39
+ signal.addEventListener("abort", onAbort, { once: true });
40
+ }
29
41
  worker.once("message", (reply) => resolve(reply));
30
- // A script may end its own realm (`process.exit()`), which is not a throw and would
31
- // otherwise present as a hang until the budget expired. Our own terminate() raises
32
- // this too, by which time the promise has settled and the first result stands.
42
+ // A script may `process.exit()`, which would otherwise look like a hang until the budget.
43
+ // Our own terminate() fires this too, after the promise has settled.
33
44
  worker.once("exit", (code) => resolve(exited(code)));
34
45
  worker.once("error", (err) => reject(new RealmFault(errorText(err))));
35
46
  worker.postMessage({ code: req.code, input: req.input });
@@ -37,6 +48,8 @@ export async function evaluate(req) {
37
48
  }
38
49
  finally {
39
50
  clearTimeout(timer);
51
+ if (signal && onAbort)
52
+ signal.removeEventListener("abort", onAbort);
40
53
  // Awaited, and the whole point: on the timeout path a thread is still burning a core, and
41
54
  // resolving before it is gone would report an evaluation the machine is still running.
42
55
  await worker.terminate();
package/dist/import.js CHANGED
@@ -1,16 +1,11 @@
1
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 { access, mkdir, writeFile } from "node:fs/promises";
2
+ // The typed-phase resolver: manifest on stdin, `{"values": [...]}` on stdout, diagnostic on stderr
3
+ // with a non-zero exit (specs/source-resolution.md). Two modes share one `tsc` pass: "generate"
4
+ // writes declarations only, "resolve" typechecks and bundles.
5
+ import { existsSync } from "node:fs";
6
+ import { access, writeFile } from "node:fs/promises";
11
7
  import { builtinModules } from "node:module";
12
- import { dirname, join, relative } from "node:path";
13
- import { fileURLToPath } from "node:url";
8
+ import { dirname, join, resolve } from "node:path";
14
9
  import commonjs from "@rollup/plugin-commonjs";
15
10
  import json from "@rollup/plugin-json";
16
11
  import { nodeResolve } from "@rollup/plugin-node-resolve";
@@ -29,11 +24,6 @@ async function exists(path) {
29
24
  return false;
30
25
  }
31
26
  }
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
27
  // ── JSON Schema → TypeScript ───────────────────────────────────────────────────
38
28
  /** Only genroc's keyword set is handled; anything else its strict decoder would have
39
29
  * refused before this ran (internal/schema, allowedKeywords). */
@@ -86,45 +76,35 @@ function objectType(s, used) {
86
76
  const required = new Set(s.required ?? []);
87
77
  const lines = [];
88
78
  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)};`);
79
+ const doc = typeof sub.description === "string"
80
+ ? ` /** ${sub.description} */\n`
81
+ : "";
82
+ lines.push(`${doc} ${propKey(key)}${required.has(key) ? "" : "?"}: ${nest(tsType(sub, used))};`);
91
83
  }
92
84
  if (s.additionalProperties && typeof s.additionalProperties === "object") {
93
- lines.push(` [key: string]: ${tsType(s.additionalProperties, used)};`);
85
+ lines.push(` [key: string]: ${nest(tsType(s.additionalProperties, used))};`);
94
86
  }
95
87
  if (lines.length === 0)
96
88
  return "Record<string, unknown>";
97
89
  return `{\n${lines.join("\n")}\n}`;
98
90
  }
91
+ /** Every line but the first, which is already placed by the property that opens it. */
92
+ const nest = (t) => t.replace(/\n/g, "\n ");
99
93
  function union(parts) {
100
94
  const seen = [...new Set(parts)];
101
95
  return seen.length === 0 ? "unknown" : seen.join(" | ");
102
96
  }
103
97
  const IDENT = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
104
98
  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
- }
99
+ const identifier = (n) => IDENT.test(n) ? n : `Def_${n.replace(/[^A-Za-z0-9_$]/g, "_")}`;
122
100
  /** Emits one named type per reachable $def rather than inlining: a task output may
123
101
  * reference itself (specs/recursive-type-inference.md) and inlining would not terminate. */
124
- function declarations(site, defs) {
102
+ function declarations(at) {
103
+ const { site, where } = at;
104
+ const defs = where.$defs ?? {};
125
105
  const used = new Set();
126
- const input = tsType(scriptInput(site, defs), used);
127
- const output = tsType(site.output, used);
106
+ const input = tsType(site.types?.Input, used);
107
+ const output = tsType(site.types?.Output, used);
128
108
  const emitted = [];
129
109
  const done = new Set();
130
110
  while (true) {
@@ -136,8 +116,8 @@ function declarations(site, defs) {
136
116
  emitted.push(`export type ${identifier(next)} = ${body};`);
137
117
  }
138
118
  return [
139
- "// Generated by genroc. Do not edit - regenerate with `genctl types`.",
140
- `// ${site.process}${site.task ? ` / ${site.task}` : ""} (${site.pointer})`,
119
+ "// Generated by genroc. Do not edit - regenerate with `genctl generate`.",
120
+ `// ${where.name} (${address(site.pointer)})`,
141
121
  "",
142
122
  ...emitted,
143
123
  emitted.length ? "" : "",
@@ -153,9 +133,8 @@ function typesPathFor(scriptPath) {
153
133
  return scriptPath.replace(/\.[^.\/]+$/, "") + ".genroc.d.ts";
154
134
  }
155
135
  // ── typecheck ──────────────────────────────────────────────────────────────────
156
- /** The nearest tsconfig above the script — the one the author's editor already reads. Two
157
- * different configs mean a red editor over a clean apply, or the reverse. The walk stops at
158
- * the project root: above it is not this project. */
136
+ /** The tsconfig the author's editor reads, so editor and apply agree. Stops at the project
137
+ * root. */
159
138
  async function nearestTsconfig(from, root) {
160
139
  for (let dir = from;; dir = dirname(dir)) {
161
140
  const candidate = join(dir, "tsconfig.json");
@@ -165,26 +144,22 @@ async function nearestTsconfig(from, root) {
165
144
  return null;
166
145
  }
167
146
  }
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
147
+ async function typecheck(sites) {
148
+ // One program per distinct base config: `extends` takes a single base, so merging two would
174
149
  // check each script under the other author's options.
175
150
  const groups = new Map();
176
- for (const site of sites) {
177
- const base = (await nearestTsconfig(dirname(site.path), root)) ?? "";
151
+ for (const at of sites) {
152
+ const base = (await nearestTsconfig(dirname(at.file), root)) ?? "";
178
153
  const group = groups.get(base);
179
154
  if (group)
180
- group.push(site);
155
+ group.push(at);
181
156
  else
182
- groups.set(base, [site]);
157
+ groups.set(base, [at]);
183
158
  }
184
- let n = 0;
159
+ const diagnostics = [];
185
160
  for (const [base, group] of groups) {
186
161
  const config = {
187
- ...(base ? { extends: relative(dir, base) } : {}),
162
+ ...(base ? { extends: base } : {}),
188
163
  compilerOptions: {
189
164
  noEmit: true,
190
165
  strict: true,
@@ -195,39 +170,36 @@ async function typecheck(root, sites) {
195
170
  // `lib` DESCRIBES the realm and is written after `extends` so a base cannot widen it:
196
171
  // a worker thread has no document, whatever an author's config claims.
197
172
  lib: ["esnext", "webworker"],
198
- // `types` is the author's, and it is how a script opts into the node globals —
199
- // the worker realm has them, so refusing the declarations would only lie. With no
200
- // base config there is nothing to opt in with, so the default stays none.
173
+ // `types` is the author's opt-in to node globals, which the realm has. With no base
174
+ // config there is nothing to opt in with, so it stays none.
201
175
  ...(base ? {} : { types: [] }),
202
176
  },
203
- files: group.flatMap((s) => [relative(dir, s.path), relative(dir, typesPathFor(s.path))]),
177
+ files: group.flatMap((s) => [s.file, typesPathFor(s.file)]),
204
178
  // `files` overrides the base's, but a base `include` survives beside it and would
205
179
  // drag the author's whole tree in, to be checked under the worker lib.
206
180
  include: [],
207
181
  };
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);
182
+ // Never written; anchors `@types` lookup at the root. Not `tsconfig.json`: that is often the
183
+ // base it extends, and tsc refuses a circular extends.
184
+ const parsed = ts.parseJsonConfigFileContent(config, ts.sys, root, undefined, join(root, "tsconfig.genroc.json"));
185
+ const program = ts.createProgram({
186
+ rootNames: parsed.fileNames,
187
+ options: parsed.options,
188
+ projectReferences: parsed.projectReferences,
189
+ configFileParsingDiagnostics: parsed.errors,
190
+ });
191
+ diagnostics.push(...parsed.errors, ...ts.getPreEmitDiagnostics(program));
211
192
  }
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());
193
+ if (diagnostics.length > 0) {
194
+ // The diagnostics are the whole type check: this is what genctl surfaces, and the reason a
195
+ // failed import never produces a string.
196
+ die(ts
197
+ .formatDiagnostics(diagnostics, {
198
+ getCanonicalFileName: (f) => f,
199
+ getCurrentDirectory: () => root,
200
+ getNewLine: () => "\n",
201
+ })
202
+ .trimEnd());
231
203
  }
232
204
  }
233
205
  // ── bundle ─────────────────────────────────────────────────────────────────────
@@ -250,12 +222,13 @@ const transpile = {
250
222
  return { code: out.outputText, map: out.sourceMapText ?? null };
251
223
  },
252
224
  };
253
- const BUILTIN = new Set([...builtinModules, ...builtinModules.map((m) => `node:${m}`)]);
254
- /** Resolves imports through TYPESCRIPT, using the same config the typecheck ran under, so a
255
- * `paths` alias that compiles also bundles. Reimplementing `paths` here would be a second
256
- * resolver to keep in agreement with tsc; this one cannot disagree.
257
- * A package resolving to a `.d.ts` is declined — that is a type, not the implementation —
258
- * which leaves node_modules to nodeResolve. */
225
+ const BUILTIN = new Set([
226
+ ...builtinModules,
227
+ ...builtinModules.map((m) => `node:${m}`),
228
+ ]);
229
+ /** Resolves through TYPESCRIPT under the typecheck's config, so a `paths` alias that compiles
230
+ * also bundles. A `.d.ts` resolution is declined (a type, not code), leaving node_modules to
231
+ * nodeResolve. */
259
232
  function tsResolve(configPath) {
260
233
  let options = {};
261
234
  if (configPath) {
@@ -270,47 +243,46 @@ function tsResolve(configPath) {
270
243
  const { resolvedModule } = ts.resolveModuleName(source, importer, options, ts.sys);
271
244
  if (!resolvedModule || resolvedModule.isExternalLibraryImport)
272
245
  return null;
273
- return resolvedModule.resolvedFileName.endsWith(".d.ts") ? null : resolvedModule.resolvedFileName;
246
+ return resolvedModule.resolvedFileName.endsWith(".d.ts")
247
+ ? null
248
+ : resolvedModule.resolvedFileName;
274
249
  },
275
250
  };
276
251
  }
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
283
- // of a module that will not be there, which bundles clean and fails at runtime.
252
+ /** A self-contained ES module whose default export is the author's own, unwrapped. Bundling here
253
+ * means a definition version pins its code forever. */
254
+ async function bundle(at) {
255
+ const site = at.site;
256
+ // Builtins are externalised; anything else unresolved is a REFUSAL, since rollup's default
257
+ // leaves an import that bundles clean and fails at runtime.
284
258
  const built = await rollup({
285
- input: site.path,
259
+ input: at.file,
286
260
  external: (id) => BUILTIN.has(id),
287
261
  plugins: [
288
- tsResolve(await nearestTsconfig(dirname(site.path), root)),
262
+ tsResolve(await nearestTsconfig(dirname(at.file), root)),
289
263
  nodeResolve({ extensions: [".ts", ".tsx", ".mjs", ".js", ".json"] }),
290
264
  commonjs(),
291
- // A `.json` import is a data file inlined at build time, which the previous bundler
292
- // did natively; without it rollup hands the JSON to the JS parser.
265
+ // Inlines `.json` imports; without it rollup hands JSON to the JS parser.
293
266
  json(),
294
267
  transpile,
295
268
  ],
296
269
  onwarn(warning) {
297
270
  if (warning.code === "UNRESOLVED_IMPORT") {
298
- die(`${site.path}: cannot resolve ${warning.exporter ?? "an import"} — is it installed?`);
271
+ die(`${at.file}: cannot resolve ${warning.exporter ?? "an import"} — is it installed?`);
299
272
  }
300
273
  },
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 });
274
+ }).catch((e) => die(`${at.file}: ${e instanceof Error ? e.message : String(e)}`));
275
+ const { output } = await built.generate({
276
+ format: "es",
277
+ inlineDynamicImports: true,
278
+ });
303
279
  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");
280
+ // Refused here rather than in the realm: the evaluator can only report it against a running
281
+ // instance, and the file it names is on this machine.
282
+ if (!output[0].exports.includes("default")) {
283
+ die(`${at.file}: a script must \`export default\` the function to run`);
284
+ }
285
+ return output[0].code;
314
286
  }
315
287
  // ── main ───────────────────────────────────────────────────────────────────────
316
288
  const stdin = await new Promise((resolve, reject) => {
@@ -321,32 +293,69 @@ const stdin = await new Promise((resolve, reject) => {
321
293
  process.stdin.on("error", reject);
322
294
  });
323
295
  const manifest = JSON.parse(stdin);
324
- if (!manifest || !Array.isArray(manifest.sites))
296
+ // genctl runs a resolver with the project root as its cwd, so the manifest need not say so.
297
+ const root = process.cwd();
298
+ if (!manifest || !Array.isArray(manifest.processes))
325
299
  die("stdin is not a genroc resolver manifest");
300
+ /** A pointer as the address it is, so a generated comment or an error can be pasted into
301
+ * `genctl schema`. A key no identifier can spell is bracketed, as the grammar spells it. */
302
+ function address(pointer) {
303
+ return pointer
304
+ .map((seg) => typeof seg === "string" && /^[A-Za-z_][A-Za-z0-9_]*$/.test(seg)
305
+ ? `.${seg}`
306
+ : `[${JSON.stringify(seg)}]`)
307
+ .join("")
308
+ .replace(/^\./, "");
309
+ }
310
+ const located = manifest.processes.flatMap((where) => where.sites.map((site) => {
311
+ const [script, ...rest] = site.args;
312
+ if (script === undefined || rest.length > 0) {
313
+ die(`${join(where.dir, where.file)}: ${address(site.pointer)}: $import takes one script, ` +
314
+ `and is given ${site.args.length} arguments`);
315
+ }
316
+ return { site, where, file: resolve(where.dir, script) };
317
+ }));
318
+ // The `code`-field contract is this resolver's, not genctl's, so it checks the directive landed
319
+ // there: in a child call (the scaffold's shape) or an external task's input.
320
+ for (const at of located) {
321
+ // The action's kind is a field; where in it the directive sits is the pointer.
322
+ const kind = at.site.level === "action" ? (at.site.action ?? "") : "";
323
+ const slot = at.site.pointer.slice(-2).join(".");
324
+ if ((kind !== "child" && kind !== "external") || slot !== "input.code") {
325
+ die(`${join(at.where.dir, at.where.file)}: ${address(at.site.pointer)}: an evaluated script ` +
326
+ "belongs in the `code` field of a child or external task's input, and this is " +
327
+ `${kind ? `a ${kind} task's ` : ""}\`${slot}\`.`);
328
+ }
329
+ }
330
+ // genctl does not know the argument is a file, so this resolver reports a missing one.
331
+ for (const at of located) {
332
+ if (!existsSync(at.file)) {
333
+ die(`${join(at.where.dir, at.where.file)}: ${address(at.site.pointer)}: ` +
334
+ `"$import: ${at.site.args[0]}" names no file (looked at ${at.file})`);
335
+ }
336
+ }
326
337
  // One script at two sites with different input types is a refusal, not a union: the union
327
338
  // is sound and would typecheck a body that is wrong at one of the sites.
328
339
  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 ?? {});
340
+ for (const at of located) {
341
+ const seen = byPath.get(at.file);
332
342
  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` +
343
+ JSON.stringify(seen.site.types) !== JSON.stringify(at.site.types)) {
344
+ die(`${at.file} is imported at ${address(seen.site.pointer)} and ` +
345
+ `${address(at.site.pointer)} with different input types.\n` +
336
346
  "Split it into two scripts, or make the two call sites pass the same shape.");
337
347
  }
338
- byPath.set(site.path, site);
348
+ byPath.set(at.file, at);
339
349
  }
340
- for (const site of byPath.values()) {
341
- const defs = (manifest.schemas[site.process]?.$defs ?? {});
342
- await write(typesPathFor(site.path), declarations(site, defs));
350
+ for (const at of byPath.values()) {
351
+ await writeFile(typesPathFor(at.file), declarations(at));
343
352
  }
344
- if (manifest.mode === "types") {
353
+ if (manifest.mode === "generate") {
345
354
  process.exit(0);
346
355
  }
347
- await typecheck(manifest.root, [...byPath.values()]);
348
- const code = [];
349
- for (const site of manifest.sites) {
350
- code.push(await bundle(site, manifest.root));
356
+ await typecheck([...byPath.values()]);
357
+ const values = [];
358
+ for (const at of located) {
359
+ values.push(await bundle(at));
351
360
  }
352
- process.stdout.write(JSON.stringify({ code }));
361
+ process.stdout.write(JSON.stringify({ values }));