@powerhousedao/host-core 6.2.3-dev.69 → 6.2.3-dev.71

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.
Files changed (36) hide show
  1. package/dist/compound-B6RZMA0Y.mjs +2804 -0
  2. package/dist/compound-B6RZMA0Y.mjs.map +1 -0
  3. package/dist/compound-PhoVeqe1.d.mts +2401 -0
  4. package/dist/compound-PhoVeqe1.d.mts.map +1 -0
  5. package/dist/env-substitution-C_fVirPh.d.mts +17 -0
  6. package/dist/env-substitution-C_fVirPh.d.mts.map +1 -0
  7. package/dist/env-substitution-Dj3pdsut.mjs +330 -0
  8. package/dist/env-substitution-Dj3pdsut.mjs.map +1 -0
  9. package/dist/host-schemas-mqOYNGot.d.mts +2153 -0
  10. package/dist/host-schemas-mqOYNGot.d.mts.map +1 -0
  11. package/dist/index.d.mts +908 -691
  12. package/dist/index.d.mts.map +1 -1
  13. package/dist/index.mjs +335 -109
  14. package/dist/index.mjs.map +1 -1
  15. package/dist/plugins-XL6WsvTL.d.mts +182 -0
  16. package/dist/plugins-XL6WsvTL.d.mts.map +1 -0
  17. package/dist/plugins.d.mts +2 -120
  18. package/dist/plugins.mjs.map +1 -1
  19. package/dist/projection.d.mts +586 -0
  20. package/dist/projection.d.mts.map +1 -0
  21. package/dist/projection.mjs +1505 -0
  22. package/dist/projection.mjs.map +1 -0
  23. package/dist/runners/compound.d.mts +157 -12
  24. package/dist/runners/compound.d.mts.map +1 -1
  25. package/dist/runners/compound.mjs +5 -13
  26. package/dist/runners/compound.mjs.map +1 -1
  27. package/dist/schema.d.mts +105 -0
  28. package/dist/schema.d.mts.map +1 -0
  29. package/dist/schema.mjs +35 -0
  30. package/dist/schema.mjs.map +1 -0
  31. package/package.json +16 -4
  32. package/dist/compound-C8P0kvPJ.d.mts +0 -157
  33. package/dist/compound-C8P0kvPJ.d.mts.map +0 -1
  34. package/dist/host-schemas-CtPNRr5v.mjs +0 -720
  35. package/dist/host-schemas-CtPNRr5v.mjs.map +0 -1
  36. package/dist/plugins.d.mts.map +0 -1
@@ -0,0 +1,2804 @@
1
+ import { createRequire } from "node:module";
2
+ import { createHash } from "node:crypto";
3
+ import fs, { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
4
+ import path from "node:path";
5
+ import { pathToFileURL } from "node:url";
6
+ import { z } from "zod";
7
+ import { TOKEN_ESCAPE_KEY, TOKEN_KEYS, concatTokenSchema, envTokenSchema, envTokenable, findToken, forbidRef, isToken, itemTokenSchema, keyTokenSchema, mapTokenSchema, outputTokenSchema, ref, tokenKeyOf, tokenSchema, tokenable } from "@powerhousedao/shared/host-tokens";
8
+ import { resolvePhDir } from "@powerhousedao/shared/clis/ph-dir";
9
+ //#region src/plugins.ts
10
+ /**
11
+ * R1 — the host plugin framework (bridge-runners-to-plugins plan,
12
+ * customization-references/host-core as the blueprint).
13
+ *
14
+ * A plugin is hooks + contributions; hooks are boot wiring (main realm only),
15
+ * contributions are declarative, serializable surface. Host RUNTIMES define
16
+ * the hook vocabulary and interleave their own wiring between stages — they
17
+ * are never plugins themselves.
18
+ *
19
+ * host.js carries the COMPOSITION as `runner.plugins` entries:
20
+ * string | { module, enabled?, verbs?, config? }
21
+ * Presence is activation (enabled defaults true); `verbs` scopes an entry to
22
+ * matching run verbs; `config` is validated against the plugin's declared
23
+ * zod schema. Entries resolve from the PROJECT's dependency tree exactly
24
+ * like runner modules.
25
+ */
26
+ var PluginError = class extends Error {
27
+ constructor(message, hint) {
28
+ super(hint ? `${message}\n Hint: ${hint}` : message);
29
+ this.name = "PluginError";
30
+ }
31
+ };
32
+ const pluginEntryObjectSchema = z.strictObject({
33
+ module: z.string().min(1),
34
+ /** Presence is activation BY DEFAULT; false is the explicit off-switch. */
35
+ enabled: z.boolean().optional(),
36
+ /** "*" (default) or the run verbs this entry is active for. */
37
+ verbs: z.union([z.literal("*"), z.array(z.string().min(1)).min(1)]).optional(),
38
+ /** Validated against the plugin's declared configSchema at resolution. */
39
+ config: z.record(z.string(), z.unknown()).optional()
40
+ });
41
+ const pluginEntrySchema = z.union([z.string().min(1), pluginEntryObjectSchema]);
42
+ function normalizePluginEntry(entry) {
43
+ if (typeof entry === "string") return {
44
+ module: entry,
45
+ enabled: true,
46
+ verbs: "*",
47
+ config: {}
48
+ };
49
+ return {
50
+ module: entry.module,
51
+ enabled: entry.enabled ?? true,
52
+ verbs: entry.verbs ?? "*",
53
+ config: entry.config ?? {}
54
+ };
55
+ }
56
+ /** Module is the identity key: a duplicate makes override targeting and
57
+ * ordering ambiguous, so it fails loudly. */
58
+ function normalizePluginEntries(entries, where) {
59
+ const normalized = entries.map(normalizePluginEntry);
60
+ const seen = /* @__PURE__ */ new Set();
61
+ for (const entry of normalized) {
62
+ if (seen.has(entry.module)) throw new PluginError(`${where}: plugin "${entry.module}" is listed twice.`, "Module specifiers are the identity key of a composition; a plugin meant to run twice needs distinct subpath specifiers.");
63
+ seen.add(entry.module);
64
+ }
65
+ return normalized;
66
+ }
67
+ function entryActiveForVerb(entry, verb) {
68
+ if (!entry.enabled) return false;
69
+ return entry.verbs === "*" || entry.verbs.includes(verb);
70
+ }
71
+ /**
72
+ * The appliesTo hierarchy. "reactor" is the base every reactor host extends;
73
+ * "compound" is its own branch (plugins over the member set — e.g. the clint
74
+ * proxy). Host runtimes register their id with a parent; compatibility walks
75
+ * the parent chain.
76
+ */
77
+ const HOST_TYPE_PARENTS = {
78
+ reactor: null,
79
+ compound: null,
80
+ connect: "reactor",
81
+ switchboard: "reactor",
82
+ mastra: "reactor"
83
+ };
84
+ function registerHostType(id, parent) {
85
+ if (id in HOST_TYPE_PARENTS && HOST_TYPE_PARENTS[id] !== parent) throw new PluginError(`Host type "${id}" is already registered with parent "${String(HOST_TYPE_PARENTS[id])}".`);
86
+ HOST_TYPE_PARENTS[id] = parent;
87
+ }
88
+ function hostTypeSatisfies(hostType, appliesTo) {
89
+ let current = hostType;
90
+ while (current !== null) {
91
+ if (current === appliesTo) return true;
92
+ current = current in HOST_TYPE_PARENTS ? HOST_TYPE_PARENTS[current] : null;
93
+ }
94
+ return false;
95
+ }
96
+ /** Registration order, bucketed pre → normal → post (stable within buckets),
97
+ * then dependsOn topo-sorted within the bucketed order. */
98
+ function resolveOrder(plugins) {
99
+ const buckets = {
100
+ pre: [],
101
+ normal: [],
102
+ post: []
103
+ };
104
+ for (const plugin of plugins) buckets[plugin.enforce ?? "normal"].push(plugin);
105
+ const bucketed = [
106
+ ...buckets.pre,
107
+ ...buckets.normal,
108
+ ...buckets.post
109
+ ];
110
+ const byName = new Map(bucketed.map((p) => [p.name, p]));
111
+ for (const plugin of bucketed) for (const dep of plugin.dependsOn ?? []) if (!byName.has(dep)) throw new PluginError(`Plugin "${plugin.name}" depends on missing plugin "${dep}".`, "dependsOn names PLUGINS only — the host runtime is implied and never named.");
112
+ const ordered = [];
113
+ const state = /* @__PURE__ */ new Map();
114
+ const visit = (plugin, chain) => {
115
+ const mark = state.get(plugin.name);
116
+ if (mark === "done") return;
117
+ if (mark === "visiting") throw new PluginError(`Plugin dependency cycle: ${[...chain, plugin.name].join(" -> ")}.`);
118
+ state.set(plugin.name, "visiting");
119
+ for (const dep of plugin.dependsOn ?? []) visit(byName.get(dep), [...chain, plugin.name]);
120
+ state.set(plugin.name, "done");
121
+ ordered.push(plugin);
122
+ };
123
+ for (const plugin of bucketed) visit(plugin, []);
124
+ return ordered;
125
+ }
126
+ async function runProvideHook(name, plugins, ctx) {
127
+ const impls = plugins.filter((p) => typeof p.hooks?.[name] === "function");
128
+ if (impls.length > 1) throw new PluginError(`Hook "${name}" is provided by ${impls.map((p) => `"${p.name}"`).join(" and ")} — provide hooks have one winner.`);
129
+ const impl = impls[0]?.hooks?.[name];
130
+ return impl ? await impl(ctx) : void 0;
131
+ }
132
+ async function runTransformHook(name, plugins, ctx, seed) {
133
+ let value = seed;
134
+ for (const plugin of plugins) {
135
+ const impl = plugin.hooks?.[name];
136
+ if (typeof impl === "function") value = await impl(value, ctx);
137
+ }
138
+ return value;
139
+ }
140
+ /** Sequential observe, in plugin order — for lifecycle moments whose order
141
+ * is load-bearing (teardown: the switchboard stops privacy before workflows
142
+ * before the api, per the carve map). */
143
+ async function runObserveHookSequential(name, plugins, ctx) {
144
+ for (const plugin of plugins) {
145
+ const impl = plugin.hooks?.[name];
146
+ if (typeof impl === "function") await impl(ctx);
147
+ }
148
+ }
149
+ async function runObserveHook(name, plugins, ctx) {
150
+ await Promise.all(plugins.map(async (plugin) => {
151
+ const impl = plugin.hooks?.[name];
152
+ if (typeof impl === "function") await impl(ctx);
153
+ }));
154
+ }
155
+ /** Array kinds concatenate in provenance-then-order sequence (built-in first,
156
+ * so later sources read as overrides where consumers want last-wins). */
157
+ function mergeContributions(resolved) {
158
+ const rank = {
159
+ "built-in": 0,
160
+ local: 1,
161
+ dependency: 2
162
+ };
163
+ const sorted = [...resolved].sort((a, b) => rank[a.provenance] - rank[b.provenance]);
164
+ const merged = {};
165
+ for (const { plugin, provenance } of sorted) for (const [kind, values] of Object.entries(plugin.contributions ?? {})) {
166
+ if (!values) continue;
167
+ const bucket = merged[kind] ??= [];
168
+ for (const value of values) bucket.push({
169
+ value,
170
+ source: {
171
+ pluginName: plugin.name,
172
+ provenance
173
+ }
174
+ });
175
+ }
176
+ return merged;
177
+ }
178
+ //#endregion
179
+ //#region src/plugins-resolve.ts
180
+ /**
181
+ * NODE-ONLY plugin resolution (split from plugins.ts so the pure runner core
182
+ * stays browser-safe for ConnectCore — R3). Resolves host.js entries from the
183
+ * PROJECT dependency tree, exactly like runner modules.
184
+ */
185
+ function isHostPluginShape(value) {
186
+ return value !== null && typeof value === "object" && typeof value.name === "string";
187
+ }
188
+ /**
189
+ * Resolve host.js plugin entries into live plugins for one host boot:
190
+ * verb-filter → module resolution from the project tree (default condition,
191
+ * like runners) → factory/object contract → config validation → appliesTo.
192
+ */
193
+ async function resolveHostPlugins(projectRoot, hostType, verb, entries, where) {
194
+ const normalized = normalizePluginEntries(entries, where);
195
+ const projectRequire = createRequire(pathToFileURL(path.join(projectRoot, "package.json")).href);
196
+ const resolved = [];
197
+ for (const entry of normalized) {
198
+ if (!entryActiveForVerb(entry, verb)) continue;
199
+ let file;
200
+ try {
201
+ file = projectRequire.resolve(entry.module);
202
+ } catch {
203
+ throw new PluginError(`${where}: cannot resolve plugin "${entry.module}" from ${projectRoot}.`, "Plugins resolve from the project dependency tree, exactly like runner modules.");
204
+ }
205
+ const exported = (await import(pathToFileURL(file).href)).default;
206
+ let plugin;
207
+ if (typeof exported === "function") plugin = exported(entry.config);
208
+ else if (isHostPluginShape(exported)) {
209
+ if (Object.keys(entry.config).length > 0 && !exported.configSchema) throw new PluginError(`${where}: plugin "${entry.module}" takes no config, but the entry passes one.`);
210
+ plugin = exported;
211
+ } else throw new PluginError(`${where}: "${entry.module}" does not default-export a plugin object or factory.`, "Export `{ name, hooks?, contributions? }` or `(config) => plugin`.");
212
+ if (plugin.configSchema) {
213
+ const parsed = plugin.configSchema.safeParse(entry.config);
214
+ if (!parsed.success) throw new PluginError(`${where}: config for plugin "${plugin.name}" is invalid:\n` + z.prettifyError(parsed.error));
215
+ }
216
+ const appliesTo = plugin.appliesTo ?? "reactor";
217
+ if (!hostTypeSatisfies(hostType, appliesTo)) throw new PluginError(`${where}: plugin "${plugin.name}" applies to "${appliesTo}" hosts, but this host is "${hostType}".`);
218
+ resolved.push({
219
+ entry,
220
+ plugin,
221
+ provenance: "dependency"
222
+ });
223
+ }
224
+ return resolved;
225
+ }
226
+ /**
227
+ * LENIENT resolution for diagnostics (`ph run <host> --explain drives`):
228
+ * collects the drive contributions of the entries active for `verb`. Unlike
229
+ * resolveHostPlugins it does not know the host type (so appliesTo is not
230
+ * checked) and does not fail on a specifier the project tree cannot resolve
231
+ * — the entry is listed under `unresolved` instead. Config is still validated
232
+ * against the plugin's schema, so a bad entry surfaces here too.
233
+ */
234
+ async function resolvePluginContributions(projectRoot, verb, entries, where) {
235
+ const normalized = normalizePluginEntries(entries, where);
236
+ const projectRequire = createRequire(pathToFileURL(path.join(projectRoot, "package.json")).href);
237
+ const plan = {
238
+ drives: [],
239
+ unresolved: []
240
+ };
241
+ for (const entry of normalized) {
242
+ if (!entryActiveForVerb(entry, verb)) continue;
243
+ let file;
244
+ try {
245
+ file = projectRequire.resolve(entry.module);
246
+ } catch {
247
+ plan.unresolved.push(entry.module);
248
+ continue;
249
+ }
250
+ const exported = (await import(pathToFileURL(file).href)).default;
251
+ let plugin;
252
+ if (typeof exported === "function") plugin = exported(entry.config);
253
+ else if (isHostPluginShape(exported)) plugin = exported;
254
+ else {
255
+ plan.unresolved.push(entry.module);
256
+ continue;
257
+ }
258
+ if (plugin.configSchema) {
259
+ const parsed = plugin.configSchema.safeParse(entry.config);
260
+ if (!parsed.success) throw new PluginError(`${where}: config for plugin "${plugin.name}" is invalid:\n` + z.prettifyError(parsed.error));
261
+ }
262
+ for (const declaration of plugin.contributions?.drives ?? []) plan.drives.push({
263
+ declaration,
264
+ source: plugin.name
265
+ });
266
+ }
267
+ return plan;
268
+ }
269
+ /**
270
+ * The connect config slices each built-in Connect plugin owns, by specifier
271
+ * (typed-host-configs 1.6). Under a declared composition Connect zeroes a
272
+ * slice whose plugin is absent — presence is activation — so an authored
273
+ * value there is dead config. Connect's built-ins are browser modules with no
274
+ * Node-resolvable identity, so their ownership is declared here as data; a
275
+ * Connect test pins it to plugin-host's zeroing.
276
+ */
277
+ const CONNECT_PLUGIN_OWNED_SLICES = {
278
+ "@powerhousedao/connect/plugins/generic": { slices: [
279
+ {
280
+ path: "drives.allowAddDrive",
281
+ absent: false,
282
+ entryKey: "allowAddDrive"
283
+ },
284
+ {
285
+ path: "drives.sections",
286
+ absent: {
287
+ remote: {
288
+ enabled: false,
289
+ allowAdd: false,
290
+ allowDelete: false
291
+ },
292
+ local: {
293
+ enabled: false,
294
+ allowAdd: false,
295
+ allowDelete: false
296
+ }
297
+ },
298
+ entryKey: "sections"
299
+ },
300
+ {
301
+ path: "drives.icons",
302
+ absent: null,
303
+ entryKey: "icons"
304
+ },
305
+ {
306
+ path: "home.background",
307
+ absent: null,
308
+ entryKey: "homeBackground"
309
+ }
310
+ ] },
311
+ "@powerhousedao/connect/plugins/sentry": { slices: [{
312
+ path: "sentry.dsn",
313
+ absent: null,
314
+ entryKey: "dsn"
315
+ }] },
316
+ "@powerhousedao/connect/plugins/openpanel": {
317
+ slices: [
318
+ {
319
+ path: "openPanel.clientId",
320
+ absent: "",
321
+ entryKey: "clientId"
322
+ },
323
+ {
324
+ path: "openPanel.trackUiEvents",
325
+ absent: false,
326
+ entryKey: "trackUiEvents"
327
+ },
328
+ {
329
+ path: "openPanel.trackOperations",
330
+ absent: false,
331
+ entryKey: "trackOperations"
332
+ }
333
+ ],
334
+ inertUnless: "openPanel.clientId"
335
+ },
336
+ "@powerhousedao/connect/plugins/assistant": { slices: [{
337
+ path: "ai.assistantEnabled",
338
+ absent: false
339
+ }] },
340
+ "@powerhousedao/vetra-studio/connect": { slices: [{
341
+ path: "app.studioMode",
342
+ absent: false
343
+ }] },
344
+ "@powerhousedao/connect/plugins/workflows": { slices: [{
345
+ path: "app.workflowsEnabled",
346
+ absent: false
347
+ }] }
348
+ };
349
+ function valueAt$1(root, dotted) {
350
+ let current = root;
351
+ for (const key of dotted.split(".")) {
352
+ if (current === null || typeof current !== "object") return void 0;
353
+ current = current[key];
354
+ }
355
+ return current;
356
+ }
357
+ /** Whether Connect already serves what the author wrote: every authored leaf
358
+ * equals the served one. An unset leaf asks for nothing, so a partial object
359
+ * (`sections: { remote: { enabled: false } }`) is satisfied by the zeroed
360
+ * slice. */
361
+ function alreadyServed(authored, served) {
362
+ if (authored === void 0 || Object.is(authored, served)) return true;
363
+ if (authored === null || served === null || typeof authored !== "object" || typeof served !== "object" || Array.isArray(authored) !== Array.isArray(served)) return false;
364
+ if (Array.isArray(authored) && authored.length !== served.length) return false;
365
+ const want = authored;
366
+ const have = served;
367
+ return Object.keys(want).every((key) => alreadyServed(want[key], have[key]));
368
+ }
369
+ /**
370
+ * Dead-config warnings for a Connect host (typed-host-configs 1.6): an
371
+ * authored connect config value whose owning plugin is not in the
372
+ * composition active for `verb`. Connect zeroes such a slice, so the value
373
+ * has no effect — e.g. Sektar's `connect.drives.allowAddDrive: true` without
374
+ * the generic plugin.
375
+ *
376
+ * Nothing is reported when the host declares no composition
377
+ * (`runner.plugins` absent: the classic boot serves the config as is), or
378
+ * when Connect already serves every leaf of the authored value. Warnings, not
379
+ * errors: the host still boots, it just does not do what the value says.
380
+ */
381
+ function findDeadConnectConfig(config, entries, verb, where) {
382
+ if (!config || entries === void 0) return [];
383
+ const active = new Set(normalizePluginEntries(entries, where).filter((entry) => entryActiveForVerb(entry, verb)).map((entry) => entry.module));
384
+ const warnings = [];
385
+ for (const [owner, { slices, inertUnless }] of Object.entries(CONNECT_PLUGIN_OWNED_SLICES)) {
386
+ if (active.has(owner)) continue;
387
+ if (inertUnless !== void 0) {
388
+ const gate = slices.find((slice) => slice.path === inertUnless);
389
+ if (alreadyServed(valueAt$1(config, inertUnless), gate?.absent)) continue;
390
+ }
391
+ for (const { path: slicePath, absent, entryKey } of slices) {
392
+ const value = valueAt$1(config, slicePath);
393
+ if (alreadyServed(value, absent)) continue;
394
+ const move = entryKey === void 0 ? `compose "${owner}" (presence is the switch)` : `compose "${owner}" and set \`${entryKey}\` in its entry config`;
395
+ warnings.push({
396
+ path: slicePath,
397
+ value,
398
+ served: absent,
399
+ owner,
400
+ message: `${where}: config.${slicePath} is dead config: it is owned by plugin "${owner}", which this host does not compose for verb "${verb}", so Connect serves ${JSON.stringify(absent)} instead of ${JSON.stringify(value)}.\n Hint: ${move}, or delete the value.`
401
+ });
402
+ }
403
+ }
404
+ return warnings;
405
+ }
406
+ //#endregion
407
+ //#region src/drive-schema.ts
408
+ /**
409
+ * The schema half of drives.ts, zod only so `./schema` stays neutral.
410
+ * - slug: the SEEDING KEY (idempotence); id optional (stable identity).
411
+ * - preferredEditor: stored at header.meta.preferredEditor; Connect config's
412
+ * `app` is the legacy alias.
413
+ * - remote.url: a drive served elsewhere; local fields are ignored for it.
414
+ * Token-able (`$output` on a producer's `drives.<slug>.url`).
415
+ */
416
+ function buildDriveDeclarationSchema(urlField) {
417
+ return z.strictObject({
418
+ slug: z.string().min(1),
419
+ id: z.string().min(1).optional(),
420
+ /** Derive the id from the project path, like generateProjectDriveId — the
421
+ * same ids classic `ph vetra` produces. `true` serves the drive under the
422
+ * hashed slug too (the vetra drive's slug IS its hashed id); `"id"` hashes
423
+ * only the id and keeps the declared slug (the classic Workflows drive:
424
+ * `/d/workflows`, id `workflows-<hash>`). */
425
+ projectHash: z.union([z.boolean(), z.literal("id")]).optional(),
426
+ name: z.string().min(1).optional(),
427
+ icon: z.string().optional(),
428
+ preferredEditor: z.string().optional(),
429
+ sharingType: z.enum([
430
+ "public",
431
+ "private",
432
+ "shared"
433
+ ]).optional(),
434
+ availableOffline: z.boolean().optional(),
435
+ remote: z.strictObject({ url: urlField(z.string().min(1)) }).optional()
436
+ });
437
+ }
438
+ const driveDeclarationSchema = buildDriveDeclarationSchema(tokenable);
439
+ const drivesSchema = z.array(driveDeclarationSchema);
440
+ /** The project-hashed drive id (`${slug}-${sha256(projectRoot)[0..8]}`) with
441
+ * the hash function injected, so neutral consumers (a browser monitor) can
442
+ * pass `crypto.subtle`-derived or precomputed hex. drives.ts binds it to
443
+ * node:crypto as `projectDriveId`. */
444
+ function projectDriveIdWith(sha256Hex, projectRoot, slug) {
445
+ return `${slug}-${sha256Hex(projectRoot).substring(0, 8)}`;
446
+ }
447
+ //#endregion
448
+ //#region src/host-schemas.ts
449
+ /**
450
+ * The zod single source for host.js blocks (typed-host-configs G1). Every
451
+ * host type is z.input/z.output of these schemas; nothing is hand-mirrored.
452
+ * Top-level host objects and the `reactor` block are STRICT (a typo fails);
453
+ * `runner` stays loose until each runner declares its options (T2), and
454
+ * `config` is runner-defined.
455
+ *
456
+ * Token-able fields (typed-host-configs 3.5): `reactor.backends.*.remote.url`
457
+ * (required), `reactor.drives` (whole list, e.g. `$map`),
458
+ * `reactor.drives[].remote.url` and `storage.dataDir` (`$env` only). Their z.input admits tokens, their z.output is the resolved type.
459
+ */
460
+ const profileSchema = z.strictObject({
461
+ appId: z.string().min(1).optional(),
462
+ name: z.string().min(1).optional(),
463
+ description: z.string().optional(),
464
+ icon: z.string().optional()
465
+ });
466
+ const reactorProtocolSchema = z.strictObject({
467
+ featureFlags: z.strictObject({
468
+ documentDecisions: z.boolean().optional(),
469
+ authEnforcement: z.boolean().optional(),
470
+ authGroups: z.boolean().optional(),
471
+ authConditions: z.boolean().optional()
472
+ }).optional(),
473
+ createSignaturePolicy: z.enum(["legacy", "v2-required"]).optional(),
474
+ unsupportedStoredDocuments: z.enum(["refuse", "read-only"]).optional()
475
+ });
476
+ const runnerKindSchema = z.enum(["reactor", "compound"]);
477
+ const reactorBackendKindSchema = z.enum([
478
+ "in-process",
479
+ "worker",
480
+ "remote"
481
+ ]);
482
+ const samePath = (a, b) => {
483
+ const norm = (p) => p.replace(/\\/g, "/").replace(/\/+$/, "").replace(/^\.\//, "");
484
+ return norm(a) === norm(b);
485
+ };
486
+ /** Compound wiring: the generic compound runner's `config` block.
487
+ * (`projectDrivesIntoConnect` and `drivesPublicBase` were removed in T3: a
488
+ * member consumes another member's drives through `$output` tokens.) */
489
+ const compoundWiringSchema = z.strictObject({
490
+ /** Member start order; must name declared children and agree with the
491
+ * output-token dependencies (resolve/plan.ts). Optional: without it the
492
+ * order is derived from the tokens. Unnamed members start after the named
493
+ * ones, in declaration order. */
494
+ startOrder: z.array(z.string().min(1)).optional(),
495
+ /** Write .ph/run/<host>.json (default true). */
496
+ runtimeRecord: z.boolean().optional(),
497
+ /** Patch the baked CSP for the runtime registry on a served Connect
498
+ * member (forwarded as `runner.cspRegistrySync` to every member whose
499
+ * runner is `@powerhousedao/ph-cli/runners/connect`). */
500
+ cspRegistrySync: z.boolean().optional()
501
+ });
502
+ /** `config.startOrder ⊆ keys(children)`, checked where both are visible.
503
+ * Apply it LAST (`.superRefine(refineStartOrder)`) to a runner's final host
504
+ * schema: zod refuses to `.extend()` a refined object. */
505
+ function refineStartOrder(host, ctx) {
506
+ const startOrder = host.config?.startOrder;
507
+ if (!Array.isArray(startOrder)) return;
508
+ const members = Object.keys(host.children);
509
+ startOrder.forEach((name, index) => {
510
+ if (startOrder.indexOf(name) !== index) {
511
+ ctx.addIssue({
512
+ code: "custom",
513
+ path: [
514
+ "config",
515
+ "startOrder",
516
+ index
517
+ ],
518
+ message: `startOrder names "${String(name)}" twice; each member starts once.`
519
+ });
520
+ return;
521
+ }
522
+ if (typeof name === "string" && members.includes(name)) return;
523
+ ctx.addIssue({
524
+ code: "custom",
525
+ path: [
526
+ "config",
527
+ "startOrder",
528
+ index
529
+ ],
530
+ message: `startOrder names "${String(name)}", which is not a member. Members: ${members.join(", ") || "(none)"}.`
531
+ });
532
+ });
533
+ }
534
+ const ALLOW_TOKENS = {
535
+ any: tokenable,
536
+ env: envTokenable
537
+ };
538
+ const FORBID_TOKENS = {
539
+ any: (schema) => z.union([schema]),
540
+ env: (schema) => z.union([schema])
541
+ };
542
+ /**
543
+ * Builds the host schema set. "allow" (declared form) accepts `T | Token` in
544
+ * every token-able field; "forbid" (resolved form) accepts `T` only.
545
+ */
546
+ function buildHostSchemas(tokenField) {
547
+ const reactorBackendSchema = z.strictObject({
548
+ kind: reactorBackendKindSchema,
549
+ storage: z.strictObject({
550
+ kind: z.enum([
551
+ "idb",
552
+ "memory",
553
+ "path",
554
+ "postgres"
555
+ ]),
556
+ /** `"${userData}/…"` sugar or `{ $env: "NAME" }`. */
557
+ dataDir: tokenField.env(z.string()).optional(),
558
+ url: z.string().optional()
559
+ }).optional(),
560
+ readModel: z.strictObject({ url: z.string().optional() }).optional(),
561
+ packages: z.strictObject({
562
+ cdnUrl: z.string().optional(),
563
+ specs: z.array(z.string()).optional(),
564
+ /** on-demand model resolution (was DYNAMIC_MODEL_LOADING). */
565
+ dynamic: z.boolean().optional()
566
+ }).optional(),
567
+ remote: z.strictObject({ url: tokenField.any(z.url()) }).optional(),
568
+ projection: z.strictObject({
569
+ enabled: z.boolean().optional(),
570
+ dbPoolSize: z.number().int().positive().optional()
571
+ }).optional(),
572
+ executors: z.strictObject({ numWorkers: z.union([z.number().int().positive(), z.literal("auto")]).optional() }).optional()
573
+ }).superRefine((backend, ctx) => {
574
+ if (backend.kind === "remote" && !backend.remote) ctx.addIssue({
575
+ code: "custom",
576
+ path: ["remote", "url"],
577
+ message: "a \"remote\" backend needs remote.url: remote: { url: switchboard.endpoints.graphql } with switchboard from ../switchboard/outputs.js, or remote: { url: { $output: { host: \"switchboard\", path: [\"endpoints\", \"graphql\"] } } }."
578
+ });
579
+ const store = backend.storage;
580
+ const storeDir = store?.kind === "path" ? store.dataDir : void 0;
581
+ const readModel = backend.readModel?.url;
582
+ if (typeof storeDir === "string" && readModel && samePath(storeDir, readModel)) ctx.addIssue({
583
+ code: "custom",
584
+ path: ["readModel", "url"],
585
+ message: `readModel.url must not be the reactor's storage dir (${readModel}): two PGlite instances on one data dir corrupt it. Omit readModel.url to get the classic <root>/.ph/read-storage next to the reactor store.`
586
+ });
587
+ });
588
+ const reactorSchema = z.strictObject({
589
+ backends: z.record(z.string(), reactorBackendSchema).optional(),
590
+ placement: z.strictObject({
591
+ primary: z.string().optional(),
592
+ default: z.looseObject({}).optional()
593
+ }).optional(),
594
+ protocol: reactorProtocolSchema.optional(),
595
+ /** DEPRECATED (dies in R2): workflows become a listed plugin. */
596
+ workflows: z.boolean().optional(),
597
+ renown: z.strictObject({
598
+ url: z.string().optional(),
599
+ networkId: z.string().optional(),
600
+ chainId: z.number().int().optional()
601
+ }).optional(),
602
+ packages: z.strictObject({ registryUrl: z.string().optional() }).optional(),
603
+ namespace: z.string().min(1).optional(),
604
+ auth: z.strictObject({
605
+ enabled: z.boolean().optional(),
606
+ admins: z.array(z.string()).optional(),
607
+ renown: z.looseObject({}).optional()
608
+ }).optional(),
609
+ drives: tokenField.any(z.array(buildDriveDeclarationSchema(tokenField.any))).optional()
610
+ });
611
+ /** Common runner options; runner modules extend it with their own. */
612
+ const runnerBaseSchema = z.looseObject({
613
+ module: z.string().min(1),
614
+ defaultVerb: z.string().min(1).optional(),
615
+ port: z.number().int().positive().optional(),
616
+ /** Bind address; each runner documents its default. */
617
+ host: z.string().min(1).optional(),
618
+ /** THE COMPOSITION: plugin entries; presence is activation. */
619
+ plugins: z.array(pluginEntrySchema).optional()
620
+ });
621
+ /** A compound member wrapper. Sections are FULL STATEMENTS except `runner`,
622
+ * which key-merges over the member's own. Plugins live in `runner.plugins`
623
+ * (as on a standalone host); there is no wrapper-level `plugins`. */
624
+ const childWrapperSchema = z.strictObject({
625
+ host: z.string().min(1),
626
+ runner: runnerBaseSchema.partial().optional(),
627
+ config: z.looseObject({}).optional(),
628
+ reactor: reactorSchema.optional()
629
+ });
630
+ const childrenSchema = z.record(z.string(), childWrapperSchema);
631
+ return {
632
+ reactorBackendSchema,
633
+ reactorSchema,
634
+ runnerBaseSchema,
635
+ childWrapperSchema,
636
+ childrenSchema,
637
+ reactorHostSchema: z.strictObject({
638
+ name: z.string().min(1),
639
+ runner: runnerBaseSchema,
640
+ config: z.looseObject({}).optional(),
641
+ profile: profileSchema.optional(),
642
+ reactor: reactorSchema.optional()
643
+ }),
644
+ compoundHostSchema: z.strictObject({
645
+ name: z.string().min(1),
646
+ runner: runnerBaseSchema,
647
+ children: childrenSchema,
648
+ config: z.looseObject({}).optional(),
649
+ profile: profileSchema.optional()
650
+ }),
651
+ /** This set's field wrapper, for a runner's OWN token-able fields inside
652
+ * `defineHostSchemas`: declared, `T | Token` in and `T` out; resolved,
653
+ * `T` only. Both modes share one static type. */
654
+ tokenable: tokenField.any,
655
+ /** As `tokenable`, but the only token accepted is `$env`. */
656
+ envTokenable: tokenField.env
657
+ };
658
+ }
659
+ /** The host schema set in declared ("allow": token-able fields take tokens)
660
+ * or resolved ("forbid") form. */
661
+ function makeHostSchemas(options) {
662
+ return buildHostSchemas(options.tokens === "allow" ? ALLOW_TOKENS : FORBID_TOKENS);
663
+ }
664
+ /**
665
+ * One runner definition, two schemas (3.5): `build` runs over the DECLARED
666
+ * set (tokens allowed; its z.input types host files) and the RESOLVED set
667
+ * (no tokens; `validateHost` checks it before the verb). Export both, type
668
+ * the host as `z.input<typeof declaredHostSchema>`, refine last inside the
669
+ * builder (zod can't extend a refined object), and wrap the runner's own
670
+ * token-able fields with `s.tokenable` / `s.envTokenable`.
671
+ */
672
+ function defineHostSchemas(build) {
673
+ return {
674
+ declaredHostSchema: build(declaredSchemas),
675
+ hostSchema: build(resolvedSchemas)
676
+ };
677
+ }
678
+ const declaredSchemas = makeHostSchemas({ tokens: "allow" });
679
+ const resolvedSchemas = makeHostSchemas({ tokens: "forbid" });
680
+ const declaredHostSchemas = declaredSchemas;
681
+ const reactorBackendSchema = resolvedSchemas.reactorBackendSchema;
682
+ const reactorSchema = resolvedSchemas.reactorSchema;
683
+ const runnerBaseSchema = resolvedSchemas.runnerBaseSchema;
684
+ const childWrapperSchema = resolvedSchemas.childWrapperSchema;
685
+ const childrenSchema = resolvedSchemas.childrenSchema;
686
+ const reactorHostSchema = resolvedSchemas.reactorHostSchema;
687
+ const compoundHostSchema = resolvedSchemas.compoundHostSchema;
688
+ /** The generic compound runner's host: the base with its wiring config. */
689
+ const genericCompound = defineHostSchemas((s) => s.compoundHostSchema.extend({ config: compoundWiringSchema.optional() }).superRefine(refineStartOrder));
690
+ const genericCompoundHostSchema = genericCompound.hostSchema;
691
+ const declaredGenericCompoundHostSchema = genericCompound.declaredHostSchema;
692
+ const SCHEMA_BASE = "https://powerhouse.inc/schemas";
693
+ /** One host schema as an editor JSON Schema with a stable `$id` — the
694
+ * per-runner emission helper (runner packages emit their own hostSchema). */
695
+ function emitHostJsonSchema(name, schema) {
696
+ return {
697
+ $id: `${SCHEMA_BASE}/${name}.schema.json`,
698
+ ...z.toJSONSchema(schema, { io: "input" })
699
+ };
700
+ }
701
+ /** The emitted-schema set, keyed by published filename. Pure — the
702
+ * emit-schemas script writes these and the drift test re-derives them. */
703
+ function emittedHostSchemas() {
704
+ return {
705
+ "host-reactor.schema.json": emitHostJsonSchema("host-reactor", declaredSchemas.reactorHostSchema),
706
+ "host-compound.schema.json": emitHostJsonSchema("host-compound", declaredSchemas.compoundHostSchema)
707
+ };
708
+ }
709
+ //#endregion
710
+ //#region src/resolve/walk.ts
711
+ function isPlainObject(value) {
712
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
713
+ const proto = Object.getPrototypeOf(value);
714
+ return proto === Object.prototype || proto === null;
715
+ }
716
+ /** `a.b[2].c` (or `<root>`). */
717
+ function formatPath(path) {
718
+ let out = "";
719
+ for (const segment of path) if (typeof segment === "number") out += `[${segment}]`;
720
+ else out += out ? `.${segment}` : segment;
721
+ return out || "<root>";
722
+ }
723
+ /** Is this object a `$$` escape (`{ $$: literal }`)? */
724
+ function isEscape(value) {
725
+ const keys = Object.keys(value);
726
+ return keys.length === 1 && keys[0] === TOKEN_ESCAPE_KEY;
727
+ }
728
+ /** Every token in `value`, in document order. `$concat` parts and `$map`
729
+ * operands (`over`, then the `to` template) are visited: they may hold tokens
730
+ * themselves. Each site carries the `$map` scopes it sits in. A `$$` escape
731
+ * hides its operand. */
732
+ function collectTokenSites(value) {
733
+ const sites = [];
734
+ visit(value, [], "root", [], sites);
735
+ return sites;
736
+ }
737
+ function visit(value, path, position, scopes, sites) {
738
+ const key = tokenKeyOf(value);
739
+ if (key && isPlainObject(value)) {
740
+ sites.push({
741
+ path,
742
+ key,
743
+ token: value,
744
+ position,
745
+ scopes
746
+ });
747
+ const operand = value[key];
748
+ if (key === "$concat" && Array.isArray(operand)) operand.forEach((part, index) => visit(part, [
749
+ ...path,
750
+ "$concat",
751
+ index
752
+ ], "concat", scopes, sites));
753
+ if (key === "$map" && isPlainObject(operand)) {
754
+ const at = [...path, "$map"];
755
+ if ("over" in operand) visit(operand.over, [...at, "over"], "over", scopes, sites);
756
+ if ("to" in operand) {
757
+ const scope = {
758
+ path,
759
+ token: value,
760
+ ...typeof operand.as === "string" ? { as: operand.as } : {}
761
+ };
762
+ visit(operand.to, [...at, "to"], "template", [...scopes, scope], sites);
763
+ }
764
+ }
765
+ return;
766
+ }
767
+ if (Array.isArray(value)) {
768
+ value.forEach((child, index) => visit(child, [...path, index], "element", scopes, sites));
769
+ return;
770
+ }
771
+ if (!isPlainObject(value) || isEscape(value)) return;
772
+ for (const [childKey, child] of Object.entries(value)) visit(child, [...path, childKey], "property", scopes, sites);
773
+ }
774
+ /** An `$item` path as text: `url`, `drives.x`, `<element>` for `[]`. */
775
+ function pathText(path) {
776
+ if (path.length === 0) return "<element>";
777
+ return formatPath(path.filter((p) => typeof p === "string" || typeof p === "number"));
778
+ }
779
+ /** A one-line human rendering of a token, for `--explain` and messages. */
780
+ function describeToken(token) {
781
+ const key = tokenKeyOf(token);
782
+ if (!key || !isPlainObject(token)) return JSON.stringify(token);
783
+ const operand = token[key];
784
+ if (key === "$output" && isPlainObject(operand)) return `$output ${typeof operand.host === "string" ? operand.host : "?"}${typeof operand.member === "string" ? ` (member ${operand.member})` : ""} › ${Array.isArray(operand.path) ? formatPath(operand.path.filter((p) => typeof p === "string" || typeof p === "number")) : "?"}`;
785
+ if (key === "$env") {
786
+ if (typeof operand === "string") return `$env ${operand}`;
787
+ if (isPlainObject(operand) && typeof operand.name === "string") return `$env ${operand.name} (optional)`;
788
+ }
789
+ if (key === "$item") {
790
+ const named = isPlainObject(operand) ? operand : void 0;
791
+ const raw = named ? named.path : operand;
792
+ const path = Array.isArray(raw) ? pathText(raw) : "?";
793
+ return `$item${named && typeof named.as === "string" ? `(${named.as})` : ""} ${path}`;
794
+ }
795
+ if (key === "$key") return typeof operand === "string" ? `$key(${operand})` : "$key";
796
+ if (key === "$map" && isPlainObject(operand)) {
797
+ const as = typeof operand.as === "string" ? ` as ${operand.as}` : "";
798
+ const into = operand.into === "record" ? " into record" : "";
799
+ return `$map over [${describeToken(operand.over)}]${as}${into} → ${JSON.stringify(render(operand.to))}`;
800
+ }
801
+ if (key === "$concat" && Array.isArray(operand)) return `$concat ${operand.map((part) => typeof part === "string" ? JSON.stringify(part) : typeof part === "number" ? String(part) : `[${describeToken(part)}]`).join(" + ")}`;
802
+ return `${key} ${JSON.stringify(operand)}`;
803
+ }
804
+ /** A display copy of `value` with every token replaced by `«description»`
805
+ * (for printing declared hosts, e.g. `--explain drives`). */
806
+ function renderTokens(value) {
807
+ return render(value);
808
+ }
809
+ function render(value) {
810
+ if (tokenKeyOf(value)) return `«${describeToken(value)}»`;
811
+ if (Array.isArray(value)) return value.map(render);
812
+ if (!isPlainObject(value) || isEscape(value)) return value;
813
+ const out = {};
814
+ for (const [key, child] of Object.entries(value)) out[key] = render(child);
815
+ return out;
816
+ }
817
+ /** A copy of `value` with every `$$` escape replaced by its operand (the
818
+ * literal it protects). Run after the no-token walk. */
819
+ function unwrapEscapes(value) {
820
+ return unwrap(value);
821
+ }
822
+ function unwrap(value) {
823
+ if (Array.isArray(value)) return value.map(unwrap);
824
+ if (!isPlainObject(value)) return value;
825
+ if (isEscape(value)) return structuredClone(value[TOKEN_ESCAPE_KEY]);
826
+ const out = {};
827
+ for (const [key, child] of Object.entries(value)) out[key] = unwrap(child);
828
+ return out;
829
+ }
830
+ //#endregion
831
+ //#region src/resolve/declared.ts
832
+ function refOf(site) {
833
+ const operand = site.token.$output;
834
+ if (!isPlainObject(operand) || typeof operand.host !== "string") return;
835
+ return typeof operand.member === "string" ? {
836
+ host: operand.host,
837
+ member: operand.member
838
+ } : { host: operand.host };
839
+ }
840
+ function pathOf(site) {
841
+ const operand = site.token.$output;
842
+ if (!isPlainObject(operand) || !Array.isArray(operand.path)) return [];
843
+ return operand.path.filter((p) => typeof p === "string" || typeof p === "number");
844
+ }
845
+ function refKey(ref) {
846
+ return ref.member ? `${ref.host}#${ref.member}` : ref.host;
847
+ }
848
+ /** The distinct producers a host's `$output` tokens name, in document order. */
849
+ function outputRefsOf(host) {
850
+ const seen = /* @__PURE__ */ new Map();
851
+ for (const site of collectTokenSites(host)) {
852
+ if (site.key !== "$output") continue;
853
+ const ref = refOf(site);
854
+ if (ref && !seen.has(refKey(ref))) seen.set(refKey(ref), ref);
855
+ }
856
+ return [...seen.values()];
857
+ }
858
+ /** Every `$output` token with its host path and producer (for the plan and
859
+ * `--explain outputs`). */
860
+ function outputSitesOf(host) {
861
+ return collectTokenSites(host).flatMap((site) => {
862
+ if (site.key !== "$output") return [];
863
+ const ref = refOf(site);
864
+ return ref ? [{
865
+ path: formatPath(site.path),
866
+ ref,
867
+ outputPath: pathOf(site)
868
+ }] : [];
869
+ });
870
+ }
871
+ /** Every `$env` token with its host path (for `--explain outputs`). */
872
+ function envSitesOf(host) {
873
+ return collectTokenSites(host).flatMap((site) => {
874
+ if (site.key !== "$env") return [];
875
+ const operand = site.token.$env;
876
+ if (typeof operand === "string") return [{
877
+ path: formatPath(site.path),
878
+ name: operand,
879
+ optional: false
880
+ }];
881
+ if (isPlainObject(operand) && typeof operand.name === "string") return [{
882
+ path: formatPath(site.path),
883
+ name: operand.name,
884
+ optional: true
885
+ }];
886
+ return [];
887
+ });
888
+ }
889
+ /** The binding name an `$item`/`$key` site names (undefined: innermost). */
890
+ function bindingNameOf(site) {
891
+ const operand = site.token[site.key];
892
+ if (site.key === "$key") return typeof operand === "string" ? operand : void 0;
893
+ if (site.key === "$item" && isPlainObject(operand)) return typeof operand.as === "string" ? operand.as : void 0;
894
+ }
895
+ /** The enclosing `$map` an `$item`/`$key` site binds to, or why none. */
896
+ function scopeOf(site) {
897
+ const name = bindingNameOf(site);
898
+ if (site.scopes.length === 0) return { error: `${site.key} is used outside any $map; it reads the element a $map template is rendering, so it is legal only inside a $map's \`to\` (or a nested $map's \`over\`).` };
899
+ if (name === void 0) return site.scopes[site.scopes.length - 1];
900
+ for (let i = site.scopes.length - 1; i >= 0; i--) if (site.scopes[i].as === name) return site.scopes[i];
901
+ const named = site.scopes.flatMap((s) => s.as ? [`"${s.as}"`] : []);
902
+ return { error: `${describeToken(site.token)} names the $map binding "${name}", which no enclosing $map declares (enclosing bindings: ${named.join(", ") || "none; add as: \"" + name + "\" to the outer $map"}).` };
903
+ }
904
+ /** Item path of an `$item` site. */
905
+ function itemPathOf(site) {
906
+ const operand = site.token.$item;
907
+ const raw = isPlainObject(operand) ? operand.path : operand;
908
+ return Array.isArray(raw) ? raw.filter((p) => typeof p === "string" || typeof p === "number") : [];
909
+ }
910
+ /** Operator shapes and placement: malformed operands, `$item`/`$key`
911
+ * outside any `$map` or naming an unknown binding, and
912
+ * `{ $env: { name, optional: true } }` anywhere but the direct value of an
913
+ * object property (it omits that property when unset). */
914
+ function checkTokenSites(host) {
915
+ const issues = [];
916
+ for (const site of collectTokenSites(host)) {
917
+ const path = formatPath(site.path);
918
+ if (!tokenSchema.safeParse(site.token).success) {
919
+ issues.push({
920
+ path,
921
+ message: `malformed ${site.key} token ${JSON.stringify(site.token)}. Shapes: { $output: { host, member?, path: [...] } }, { $concat: [string | number | token, ...] }, { $env: "NAME" } or { $env: { name: "NAME", optional: true } }, { $map: { over: $output | $item, as?: "name", to: template, into?: "record" } }, { $item: [path] } or { $item: { as: "name", path: [...] } }, { $key: true } or { $key: "name" }.`
922
+ });
923
+ continue;
924
+ }
925
+ if (site.key === "$item" || site.key === "$key") {
926
+ const scope = scopeOf(site);
927
+ if ("error" in scope) issues.push({
928
+ path,
929
+ message: scope.error
930
+ });
931
+ continue;
932
+ }
933
+ const operand = site.token.$env;
934
+ if (site.key === "$env" && isPlainObject(operand) && site.position !== "property") {
935
+ const where = site.position === "concat" ? "a $concat part" : site.position === "element" ? "an array element" : site.position === "template" ? "the whole $map template" : "the whole host";
936
+ issues.push({
937
+ path,
938
+ message: `{ $env: { name, optional: true } } is legal only as the direct value of an object property (it omits that property when ${String(operand.name)} is unset), not as ${where}. Use { $env: ${JSON.stringify(operand.name)} } here.`
939
+ });
940
+ }
941
+ }
942
+ return issues;
943
+ }
944
+ function defOf(schema) {
945
+ if (!isPlainObjectLike(schema)) return void 0;
946
+ const internals = schema._zod;
947
+ if (!isPlainObjectLike(internals)) return void 0;
948
+ const def = internals.def;
949
+ if (!isPlainObjectLike(def) || typeof def.type !== "string") return void 0;
950
+ return {
951
+ ...def,
952
+ type: def.type
953
+ };
954
+ }
955
+ function isPlainObjectLike(value) {
956
+ return (typeof value === "object" || typeof value === "function") && value !== null;
957
+ }
958
+ const WRAPPERS = /* @__PURE__ */ new Set([
959
+ "optional",
960
+ "nullable",
961
+ "default",
962
+ "prefault",
963
+ "readonly",
964
+ "nonoptional",
965
+ "catch",
966
+ "success"
967
+ ]);
968
+ /** The schema at `path` inside a zod schema (walking objects, records,
969
+ * arrays, tuples, unions and wrappers), or why the path does not exist. */
970
+ function schemaAtPath(schema, path) {
971
+ let current = schema;
972
+ for (let i = 0; i <= path.length; i++) {
973
+ for (let guard = 0; guard < 32; guard++) {
974
+ const def = defOf(current);
975
+ if (!def) break;
976
+ if (WRAPPERS.has(def.type)) current = def.innerType;
977
+ else if (def.type === "lazy" && typeof def.getter === "function") {
978
+ const getter = def.getter;
979
+ current = getter();
980
+ } else if (def.type === "pipe") {
981
+ const out = defOf(def.out);
982
+ current = out && out.type !== "transform" ? def.out : def.in;
983
+ } else break;
984
+ }
985
+ if (i === path.length) return {
986
+ ok: true,
987
+ schema: current
988
+ };
989
+ const segment = path[i];
990
+ const def = defOf(current);
991
+ if (!def) return {
992
+ ok: false,
993
+ at: i,
994
+ reason: "is not a schema"
995
+ };
996
+ switch (def.type) {
997
+ case "any":
998
+ case "unknown": return {
999
+ ok: true,
1000
+ schema: current
1001
+ };
1002
+ case "object": {
1003
+ const shape = isPlainObjectLike(def.shape) ? def.shape : {};
1004
+ if (typeof segment === "string" && segment in shape) {
1005
+ current = shape[segment];
1006
+ break;
1007
+ }
1008
+ const catchall = defOf(def.catchall);
1009
+ if (catchall && catchall.type !== "never") {
1010
+ current = def.catchall;
1011
+ break;
1012
+ }
1013
+ const keys = Object.keys(shape);
1014
+ return {
1015
+ ok: false,
1016
+ at: i,
1017
+ reason: `has no key ${JSON.stringify(segment)} (keys: ${keys.join(", ") || "none"})`
1018
+ };
1019
+ }
1020
+ case "record":
1021
+ if (typeof segment !== "string") return {
1022
+ ok: false,
1023
+ at: i,
1024
+ reason: "is a record (string keys)"
1025
+ };
1026
+ current = def.valueType;
1027
+ break;
1028
+ case "array":
1029
+ if (typeof segment !== "number") return {
1030
+ ok: false,
1031
+ at: i,
1032
+ reason: "is an array (numeric index)"
1033
+ };
1034
+ current = def.element;
1035
+ break;
1036
+ case "tuple": {
1037
+ const items = Array.isArray(def.items) ? def.items : [];
1038
+ if (typeof segment !== "number" || segment >= items.length) return {
1039
+ ok: false,
1040
+ at: i,
1041
+ reason: `is a ${items.length}-tuple`
1042
+ };
1043
+ current = items[segment];
1044
+ break;
1045
+ }
1046
+ case "union": {
1047
+ const options = Array.isArray(def.options) ? def.options : [];
1048
+ for (const option of options) {
1049
+ const hit = schemaAtPath(option, path.slice(i));
1050
+ if (hit.ok) return hit;
1051
+ }
1052
+ return {
1053
+ ok: false,
1054
+ at: i,
1055
+ reason: "matches no union member"
1056
+ };
1057
+ }
1058
+ default: return {
1059
+ ok: false,
1060
+ at: i,
1061
+ reason: `is a ${def.type}, not a container`
1062
+ };
1063
+ }
1064
+ }
1065
+ return {
1066
+ ok: true,
1067
+ schema: current
1068
+ };
1069
+ }
1070
+ /** Whether the object schema at `path` names `key` in its shape (a
1071
+ * catchall does not count): what a runner's schema explicitly declares,
1072
+ * e.g. `runner.cspRegistrySync`. A union declares a key any member does. */
1073
+ function declaresKey(schema, path, key) {
1074
+ const at = schemaAtPath(schema, path);
1075
+ if (!at.ok) return false;
1076
+ const def = defOf(at.schema);
1077
+ if (def?.type === "object") return isPlainObjectLike(def.shape) && key in def.shape;
1078
+ if (def?.type === "union" && Array.isArray(def.options)) return def.options.some((option) => declaresKey(option, [], key));
1079
+ return false;
1080
+ }
1081
+ /** Whether a (property) schema admits an absent value on the OUTPUT side:
1082
+ * `.optional()` does; `.default()`/`.prefault()` fill it in, and
1083
+ * `.nonoptional()` forbids it. */
1084
+ function mayBeAbsent(schema) {
1085
+ let current = schema;
1086
+ for (let guard = 0; guard < 32; guard++) {
1087
+ const internals = isPlainObjectLike(current) ? current._zod : void 0;
1088
+ if (isPlainObjectLike(internals) && internals.optout === "optional") return true;
1089
+ const def = defOf(current);
1090
+ if (!def) return false;
1091
+ if (def.type === "optional") return true;
1092
+ if (def.type === "default" || def.type === "prefault" || def.type === "nonoptional" || !WRAPPERS.has(def.type)) return false;
1093
+ current = def.innerType;
1094
+ }
1095
+ return false;
1096
+ }
1097
+ /** Whether `key` may be absent from a value of the object schema `schema`:
1098
+ * an optional property, or (in a union) one some member makes optional or
1099
+ * lacks. A record value or an array element is never optional. */
1100
+ function optionalKeyIn(schema, key) {
1101
+ const unwrapped = schemaAtPath(schema, []);
1102
+ const def = unwrapped.ok ? defOf(unwrapped.schema) : void 0;
1103
+ if (def?.type === "object") {
1104
+ const shape = isPlainObjectLike(def.shape) ? def.shape : {};
1105
+ return key in shape && mayBeAbsent(shape[key]);
1106
+ }
1107
+ if (def?.type === "union" && Array.isArray(def.options)) return def.options.some((option) => {
1108
+ const inner = schemaAtPath(option, []);
1109
+ const optionDef = inner.ok ? defOf(inner.schema) : void 0;
1110
+ const shape = optionDef?.type === "object" && isPlainObjectLike(optionDef.shape) ? optionDef.shape : void 0;
1111
+ return shape !== void 0 && (!(key in shape) || mayBeAbsent(shape[key]));
1112
+ });
1113
+ return false;
1114
+ }
1115
+ /**
1116
+ * Whether the field `path[at]` is OPTIONAL in `schema` (a producer's
1117
+ * `outputsSchema`, or a `$map` element schema), given that `path[0..at-1]`
1118
+ * exists: the codegen'd `OutputToken<T | undefined>` / `ItemToken<T |
1119
+ * undefined>` positions, whose rendered property the resolver omits when
1120
+ * the field is absent. False for a record key, an array index, or a path
1121
+ * the schema does not describe.
1122
+ */
1123
+ function isOptionalField(schema, path, at) {
1124
+ const key = path[at];
1125
+ if (typeof key !== "string") return false;
1126
+ const parent = schemaAtPath(schema, path.slice(0, at));
1127
+ return parent.ok && optionalKeyIn(parent.schema, key);
1128
+ }
1129
+ /** The element schema of a collection schema (array element, record
1130
+ * value), or undefined when the schema does not say. */
1131
+ function elementSchemaOf(schema) {
1132
+ const collection = collectionOf(schema);
1133
+ return collection.kind === "array" || collection.kind === "record" ? collection.element : void 0;
1134
+ }
1135
+ /** The collection kind of a schema (unwrapped): array, record, unknown (no
1136
+ * check possible) or something else. */
1137
+ function collectionOf(schema) {
1138
+ const unwrapped = schemaAtPath(schema, []);
1139
+ const def = unwrapped.ok ? defOf(unwrapped.schema) : void 0;
1140
+ if (!def) return { kind: "unknown" };
1141
+ if (def.type === "array") return {
1142
+ kind: "array",
1143
+ element: def.element
1144
+ };
1145
+ if (def.type === "record") return {
1146
+ kind: "record",
1147
+ element: def.valueType
1148
+ };
1149
+ if (def.type === "object") {
1150
+ const catchall = defOf(def.catchall);
1151
+ if (catchall && catchall.type !== "never") {
1152
+ const shape = isPlainObjectLike(def.shape) ? def.shape : {};
1153
+ return Object.keys(shape).length === 0 ? {
1154
+ kind: "record",
1155
+ element: def.catchall
1156
+ } : {
1157
+ kind: "record",
1158
+ element: void 0
1159
+ };
1160
+ }
1161
+ }
1162
+ if (def.type === "tuple") return {
1163
+ kind: "array",
1164
+ element: void 0
1165
+ };
1166
+ if (def.type === "any" || def.type === "unknown" || def.type === "union") return { kind: "unknown" };
1167
+ return {
1168
+ kind: "other",
1169
+ type: def.type
1170
+ };
1171
+ }
1172
+ /** Every `$output` token's producer exists and its path is valid against
1173
+ * the producer's `outputsSchema`; every `$map`'s `over` is a collection
1174
+ * there (a record under `into: "record"`), and every `$item` path exists
1175
+ * in the element schema of the map it binds. */
1176
+ function checkOutputPaths(host, outputsSchemaOf) {
1177
+ const issues = [];
1178
+ const elements = /* @__PURE__ */ new Map();
1179
+ const elementOf = (scope) => "error" in scope ? void 0 : elements.get(scope.token);
1180
+ for (const site of collectTokenSites(host)) {
1181
+ if (!tokenSchema.safeParse(site.token).success) continue;
1182
+ if (site.key === "$map") {
1183
+ elements.set(site.token, checkMap(site, outputsSchemaOf, elementOf, issues));
1184
+ continue;
1185
+ }
1186
+ if (site.key === "$item") {
1187
+ const scope = scopeOf(site);
1188
+ const element = elementOf(scope);
1189
+ if (!element || element.element === void 0 || "error" in scope) continue;
1190
+ const itemPath = itemPathOf(site);
1191
+ const hit = schemaAtPath(element.element, itemPath);
1192
+ if (!hit.ok) {
1193
+ const parent = itemPath.slice(0, hit.at);
1194
+ issues.push({
1195
+ path: formatPath(site.path),
1196
+ message: `${describeToken(site.token)}: the element${parent.length ? `'s ${formatPath(parent)}` : ""} of the $map at ${formatPath(scope.path)}${scope.as ? ` (as "${scope.as}")` : ""} ${hit.reason} (element of ${element.label}).`
1197
+ });
1198
+ }
1199
+ continue;
1200
+ }
1201
+ if (site.key !== "$output") continue;
1202
+ const ref = refOf(site);
1203
+ if (!ref) continue;
1204
+ const path = formatPath(site.path);
1205
+ const lookup = outputsSchemaOf(ref);
1206
+ if ("error" in lookup) {
1207
+ issues.push({
1208
+ path,
1209
+ message: lookup.error
1210
+ });
1211
+ continue;
1212
+ }
1213
+ const outputPath = pathOf(site);
1214
+ const hit = schemaAtPath(lookup.schema, outputPath);
1215
+ if (!hit.ok) {
1216
+ const parent = outputPath.slice(0, hit.at);
1217
+ const where = parent.length ? `outputs.${formatPath(parent)}` : "the outputs";
1218
+ issues.push({
1219
+ path,
1220
+ message: `${describeToken(site.token)}: ${where} ${hit.reason} in the outputsSchema of ${lookup.label}.`
1221
+ });
1222
+ }
1223
+ }
1224
+ return issues;
1225
+ }
1226
+ /** A `$map`'s `over` against its schema: a collection (a record under
1227
+ * `into: "record"`). Returns the element schema for the map's `$item`s. */
1228
+ function checkMap(site, outputsSchemaOf, elementOf, issues) {
1229
+ const operand = site.token.$map;
1230
+ if (!isPlainObject(operand)) return void 0;
1231
+ const over = operand.over;
1232
+ const into = operand.into === "record";
1233
+ let schema;
1234
+ let label;
1235
+ if (isPlainObject(over) && "$output" in over) {
1236
+ const overSite = {
1237
+ ...site,
1238
+ key: "$output",
1239
+ token: over
1240
+ };
1241
+ const ref = refOf(overSite);
1242
+ if (!ref) return void 0;
1243
+ const lookup = outputsSchemaOf(ref);
1244
+ if ("error" in lookup) return void 0;
1245
+ const hit = schemaAtPath(lookup.schema, pathOf(overSite));
1246
+ if (!hit.ok) return void 0;
1247
+ schema = hit.schema;
1248
+ label = `${describeToken(over)} in the outputsSchema of ${lookup.label}`;
1249
+ } else if (isPlainObject(over) && "$item" in over) {
1250
+ const overSite = {
1251
+ ...site,
1252
+ key: "$item",
1253
+ token: over
1254
+ };
1255
+ const outer = elementOf(scopeOf(overSite));
1256
+ if (!outer || outer.element === void 0) return void 0;
1257
+ const hit = schemaAtPath(outer.element, itemPathOf(overSite));
1258
+ if (!hit.ok) return void 0;
1259
+ schema = hit.schema;
1260
+ label = `${describeToken(over)} (element of ${outer.label})`;
1261
+ } else return;
1262
+ const path = formatPath(site.path);
1263
+ const collection = collectionOf(schema);
1264
+ if (collection.kind === "unknown") return void 0;
1265
+ if (collection.kind === "other") {
1266
+ issues.push({
1267
+ path,
1268
+ message: `$map over ${label} is a ${collection.type}, not an array or a record; a $map iterates a collection.`
1269
+ });
1270
+ return;
1271
+ }
1272
+ if (into && collection.kind === "array") {
1273
+ issues.push({
1274
+ path,
1275
+ message: `$map with into: "record" maps over ${label}, which is an array: an array has no keys to keep. Drop into: "record" (the result is an array) or map over a record.`
1276
+ });
1277
+ return;
1278
+ }
1279
+ return {
1280
+ element: collection.element,
1281
+ label
1282
+ };
1283
+ }
1284
+ //#endregion
1285
+ //#region src/resolve/removed-forms.ts
1286
+ function outputToken(host, path, member) {
1287
+ return `{ $output: { host: "${host}"${member ? `, member: "${member}"` : ""}, path: [${path.map((p) => JSON.stringify(p)).join(", ")}] } }`;
1288
+ }
1289
+ function isDriveReference(value) {
1290
+ if (!isPlainObject(value)) return false;
1291
+ const keys = Object.keys(value).sort();
1292
+ return keys.length === 2 && keys[0] === "from" && keys[1] === "slug" && typeof value.from === "string" && typeof value.slug === "string";
1293
+ }
1294
+ function checkReactor(reactor, base, found) {
1295
+ if (!isPlainObject(reactor) || !isPlainObject(reactor.backends)) return;
1296
+ for (const [name, backend] of Object.entries(reactor.backends)) {
1297
+ if (!isPlainObject(backend) || !isPlainObject(backend.remote)) continue;
1298
+ const host = backend.remote.host;
1299
+ if (host === void 0) continue;
1300
+ const producer = typeof host === "string" ? host : "switchboard";
1301
+ found.push({
1302
+ path: `${base}reactor.backends.${name}.remote.host`,
1303
+ message: `remote: { host } was removed; use remote: { url: ${producer}.endpoints.graphql } with ${producer} from ../${producer}/outputs.js, or remote: { url: ${outputToken(producer, ["endpoints", "graphql"])} }.`
1304
+ });
1305
+ }
1306
+ }
1307
+ function checkPlugins(runner, base, memberHosts, found) {
1308
+ if (!isPlainObject(runner) || !Array.isArray(runner.plugins)) return;
1309
+ runner.plugins.forEach((entry, index) => {
1310
+ if (!isPlainObject(entry) || !isPlainObject(entry.config)) return;
1311
+ for (const [key, value] of Object.entries(entry.config)) {
1312
+ if (!isDriveReference(value)) continue;
1313
+ const host = memberHosts[value.from] ?? value.from;
1314
+ const member = memberHosts[value.from] ? value.from : void 0;
1315
+ found.push({
1316
+ path: `${base}runner.plugins[${index}].config.${key}`,
1317
+ message: `${key}: { from, slug } was removed; use ${host}.drives.${value.slug}.url from ../${host}/outputs.js, or ${outputToken(host, [
1318
+ "drives",
1319
+ value.slug,
1320
+ "url"
1321
+ ])}${member ? ` (add member: "${member}" if two members run host "${host}")` : ""}.`
1322
+ });
1323
+ }
1324
+ });
1325
+ }
1326
+ /** Every removed form in a host file (reactor or compound), in document
1327
+ * order. Compound wrappers are checked too. */
1328
+ function findRemovedForms(host) {
1329
+ const found = [];
1330
+ if (!isPlainObject(host)) return found;
1331
+ const children = isPlainObject(host.children) ? host.children : void 0;
1332
+ const memberHosts = {};
1333
+ for (const [key, wrapper] of Object.entries(children ?? {})) if (isPlainObject(wrapper) && typeof wrapper.host === "string") memberHosts[key] = wrapper.host;
1334
+ checkReactor(host.reactor, "", found);
1335
+ checkPlugins(host.runner, "", memberHosts, found);
1336
+ for (const [key, wrapper] of Object.entries(children ?? {})) {
1337
+ if (!isPlainObject(wrapper)) continue;
1338
+ checkReactor(wrapper.reactor, `children.${key}.`, found);
1339
+ checkPlugins(wrapper.runner, `children.${key}.`, memberHosts, found);
1340
+ }
1341
+ if (children && isPlainObject(host.config)) for (const key of ["projectDrivesIntoConnect", "drivesPublicBase"]) {
1342
+ if (host.config[key] === void 0) continue;
1343
+ found.push({
1344
+ path: `config.${key}`,
1345
+ message: `config.${key} was removed; declare the drives on the member that consumes them, by output token: reactor.drives: [{ slug: "<slug>", remote: { url: ${outputToken("switchboard", [
1346
+ "drives",
1347
+ "<slug>",
1348
+ "url"
1349
+ ])} } }].`
1350
+ });
1351
+ }
1352
+ return found;
1353
+ }
1354
+ //#endregion
1355
+ //#region src/env-substitution.ts
1356
+ const BUILTIN = /\$\{(userData|projectRoot)\}/g;
1357
+ function substitute(text, env) {
1358
+ return text.replace(BUILTIN, (match, name) => env[name] ?? match);
1359
+ }
1360
+ /** Deep-substitute the built-ins that `env` provides in every string; an
1361
+ * absent built-in is left as written. The input is never mutated. */
1362
+ function substituteBuiltinEnv(value, env) {
1363
+ return substituteValue(value, env);
1364
+ }
1365
+ function substituteValue(value, env) {
1366
+ if (typeof value === "string") return substitute(value, env);
1367
+ if (Array.isArray(value)) return value.map((v) => substituteValue(v, env));
1368
+ if (value !== null && typeof value === "object") {
1369
+ const out = {};
1370
+ for (const [k, v] of Object.entries(value)) out[k] = substituteValue(v, env);
1371
+ return out;
1372
+ }
1373
+ return value;
1374
+ }
1375
+ //#endregion
1376
+ //#region src/resolve/plan.ts
1377
+ /**
1378
+ * The dependency plan (pipeline step 4): which compound member consumes
1379
+ * which member's outputs, and the start order that follows. Producers start
1380
+ * before consumers; `config.startOrder` is optional and, when given, must
1381
+ * agree with the tokens. Cycles fail. Pure.
1382
+ */
1383
+ var PlanError = class extends Error {
1384
+ constructor(message) {
1385
+ super(message);
1386
+ this.name = "PlanError";
1387
+ }
1388
+ };
1389
+ /** The member a ref names: the unique member running `ref.host`, or the
1390
+ * member `ref.member` when given (it must run `ref.host`). */
1391
+ function memberForRef(ref, members) {
1392
+ if (ref.member !== void 0) {
1393
+ const named = members.find((m) => m.key === ref.member);
1394
+ if (!named) return { error: `names member "${ref.member}", which this compound does not declare (members: ${members.map((m) => m.key).join(", ")}).` };
1395
+ if (named.host !== ref.host) return { error: `names member "${ref.member}" of host "${ref.host}", but that member runs host "${named.host}".` };
1396
+ return { key: named.key };
1397
+ }
1398
+ const running = members.filter((m) => m.host === ref.host);
1399
+ if (running.length === 1) return { key: running[0].key };
1400
+ if (running.length === 0) return { error: `names host "${ref.host}", which no member of this compound runs (members run: ${[...new Set(members.map((m) => m.host))].join(", ")}).` };
1401
+ return { error: `names host "${ref.host}", which members ${running.map((m) => `"${m.key}"`).join(" and ")} both run; add member: "<key>" to pick one.` };
1402
+ }
1403
+ function edgesOf(members) {
1404
+ const edges = [];
1405
+ const problems = [];
1406
+ for (const member of members) {
1407
+ const seen = /* @__PURE__ */ new Set();
1408
+ for (const { ref, path } of member.refs) {
1409
+ const target = memberForRef(ref, members);
1410
+ if ("error" in target) {
1411
+ problems.push(`${member.key}: ${path} ${target.error}`);
1412
+ continue;
1413
+ }
1414
+ if (target.key === member.key) {
1415
+ problems.push(`${member.key}: ${path} reads ${refKey(ref)}'s outputs, which is this member itself.`);
1416
+ continue;
1417
+ }
1418
+ if (seen.has(target.key)) continue;
1419
+ seen.add(target.key);
1420
+ edges.push({
1421
+ consumer: member.key,
1422
+ producer: target.key,
1423
+ path
1424
+ });
1425
+ }
1426
+ }
1427
+ if (problems.length > 0) throw new PlanError(problems.join("\n"));
1428
+ return edges;
1429
+ }
1430
+ /** Declared start order: the named members first, then the rest in
1431
+ * declaration order. */
1432
+ function declaredOrder(members, startOrder) {
1433
+ const keys = members.map((m) => m.key);
1434
+ const named = [...new Set(startOrder)].filter((k) => keys.includes(k));
1435
+ return [...named, ...keys.filter((k) => !named.includes(k))];
1436
+ }
1437
+ function planCompound(members, startOrder) {
1438
+ const edges = edgesOf(members);
1439
+ if (startOrder) {
1440
+ const order = declaredOrder(members, startOrder);
1441
+ const index = new Map(order.map((k, i) => [k, i]));
1442
+ const bad = edges.filter((e) => (index.get(e.producer) ?? 0) > (index.get(e.consumer) ?? 0));
1443
+ if (bad.length > 0) throw new PlanError(bad.map((e) => `config.startOrder starts "${e.consumer}" before "${e.producer}", but ${e.consumer}.${e.path} consumes "${e.producer}"'s outputs. Reorder startOrder (or omit it: the order follows the tokens).`).join("\n"));
1444
+ return {
1445
+ order,
1446
+ edges,
1447
+ source: "startOrder"
1448
+ };
1449
+ }
1450
+ const pending = new Map(members.map((m) => [m.key, /* @__PURE__ */ new Set()]));
1451
+ for (const e of edges) pending.get(e.consumer)?.add(e.producer);
1452
+ const order = [];
1453
+ while (order.length < members.length) {
1454
+ const next = members.find((m) => !order.includes(m.key) && pending.get(m.key)?.size === 0);
1455
+ if (!next) {
1456
+ const stuck = members.filter((m) => !order.includes(m.key));
1457
+ throw new PlanError(`output tokens form a cycle between ${stuck.map((m) => `"${m.key}"`).join(", ")}: ${edges.filter((e) => stuck.some((m) => m.key === e.consumer) && stuck.some((m) => m.key === e.producer)).map((e) => `${e.consumer} (${e.path}) needs ${e.producer}`).join("; ")}.`);
1458
+ }
1459
+ order.push(next.key);
1460
+ for (const set of pending.values()) set.delete(next.key);
1461
+ }
1462
+ return {
1463
+ order,
1464
+ edges,
1465
+ source: "tokens"
1466
+ };
1467
+ }
1468
+ //#endregion
1469
+ //#region src/resolve/resolve.ts
1470
+ var TokenResolutionError = class extends Error {
1471
+ constructor(message) {
1472
+ super(message);
1473
+ this.name = "TokenResolutionError";
1474
+ }
1475
+ };
1476
+ /** A resolved `{ $env: { name, optional: true } }` whose variable is unset,
1477
+ * or an `$output`/`$item` reading an absent optional field: its enclosing
1478
+ * property is omitted. */
1479
+ const OMIT = Symbol("omit");
1480
+ /** `reactor.drives["workflows"]` (or `…[2]` for an array element). */
1481
+ function elementText(binding) {
1482
+ const key = typeof binding.key === "number" ? `[${binding.key}]` : `[${JSON.stringify(binding.key)}]`;
1483
+ return `${formatPath(binding.path)}${key}`;
1484
+ }
1485
+ /** Provenance of `$map`-rendered arrays: element index → the input key
1486
+ * (record key, or array index) it was rendered from. Lets resolved
1487
+ * validation name the element key, not just the result index. */
1488
+ const renderedKeys = /* @__PURE__ */ new WeakMap();
1489
+ /**
1490
+ * The `$map` elements an issue path (from resolved validation of a resolved
1491
+ * host) passes through, as text: `$map element "workflows"`. Undefined when
1492
+ * the path crosses no `$map`-rendered array. Walk the SAME object
1493
+ * `resolveHostOutputs` returned (provenance is by identity).
1494
+ */
1495
+ function describeMapElements(host, path) {
1496
+ const found = [];
1497
+ let current = host;
1498
+ for (const segment of path) if (Array.isArray(current) && typeof segment === "number") {
1499
+ const key = renderedKeys.get(current)?.[segment];
1500
+ if (key !== void 0) found.push(`$map element ${typeof key === "number" ? `[${key}]` : JSON.stringify(key)}`);
1501
+ current = current[segment];
1502
+ } else if (isPlainObject(current) && typeof segment === "string") current = current[segment];
1503
+ else break;
1504
+ return found.length ? found.join(" › ") : void 0;
1505
+ }
1506
+ /** A deep copy of a resolved (JSON-shaped) value that keeps the `$map`
1507
+ * provenance of its rendered arrays (structuredClone would drop it). */
1508
+ function cloneWithProvenance(value) {
1509
+ if (Array.isArray(value)) {
1510
+ const copy = value.map(cloneWithProvenance);
1511
+ const keys = renderedKeys.get(value);
1512
+ if (keys) renderedKeys.set(copy, keys);
1513
+ return copy;
1514
+ }
1515
+ if (isPlainObject(value)) {
1516
+ const copy = {};
1517
+ for (const [key, child] of Object.entries(value)) copy[key] = cloneWithProvenance(child);
1518
+ return copy;
1519
+ }
1520
+ return value;
1521
+ }
1522
+ /** The value at `path` inside `root` (output data: records and arrays). */
1523
+ function walkPath(root, path) {
1524
+ let current = root;
1525
+ for (let i = 0; i < path.length; i++) {
1526
+ const segment = path[i];
1527
+ const next = Array.isArray(current) ? typeof segment === "number" ? current[segment] : void 0 : isPlainObject(current) && typeof segment === "string" ? current[segment] : void 0;
1528
+ if (next === void 0) {
1529
+ const has = isPlainObject(current) ? Object.keys(current).join(", ") || "nothing" : Array.isArray(current) ? `${current.length} elements` : JSON.stringify(current);
1530
+ return {
1531
+ ok: false,
1532
+ at: i,
1533
+ has
1534
+ };
1535
+ }
1536
+ current = next;
1537
+ }
1538
+ return {
1539
+ ok: true,
1540
+ value: current
1541
+ };
1542
+ }
1543
+ /** The schema at `path` inside `schema`, when both are known. */
1544
+ function schemaOf(schema, path) {
1545
+ if (schema === void 0) return void 0;
1546
+ const hit = schemaAtPath(schema, path);
1547
+ return hit.ok ? hit.schema : void 0;
1548
+ }
1549
+ function pathSegments(path) {
1550
+ return path.filter((p) => typeof p === "string" || typeof p === "number");
1551
+ }
1552
+ var Resolver = class {
1553
+ sources;
1554
+ self;
1555
+ deferred = [];
1556
+ /** What the last OMIT stood for, for the "nothing to omit" errors. */
1557
+ omitted = "an optional $env";
1558
+ constructor(sources, self) {
1559
+ this.sources = sources;
1560
+ this.self = self;
1561
+ }
1562
+ /** The member keys a token reads (`$output` on a member's host), when
1563
+ * resolving a compound's own fields with `deferSelf`. */
1564
+ selfRefs(token, trail) {
1565
+ if (!this.self) return [];
1566
+ const keys = /* @__PURE__ */ new Set();
1567
+ for (const site of collectTokenSites(token)) {
1568
+ const operand = site.token.$output;
1569
+ if (site.key !== "$output" || !isPlainObject(operand)) continue;
1570
+ if (typeof operand.host !== "string") continue;
1571
+ const ref = typeof operand.member === "string" ? {
1572
+ host: operand.host,
1573
+ member: operand.member
1574
+ } : { host: operand.host };
1575
+ if (!this.self.members.some((m) => m.host === ref.host)) continue;
1576
+ const target = memberForRef(ref, this.self.members);
1577
+ if ("error" in target) this.fail([...trail, ...site.path], `in a compound ${target.error}`);
1578
+ keys.add(target.key);
1579
+ }
1580
+ return [...keys];
1581
+ }
1582
+ fail(trail, message, scope = []) {
1583
+ const where = this.sources.where ? `${this.sources.where}: ` : "";
1584
+ const inside = scope.length ? ` (rendering $map element ${scope.map(elementText).join(" › ")})` : "";
1585
+ throw new TokenResolutionError(`${where}\`${formatPath(trail)}\` ${message}${inside}`);
1586
+ }
1587
+ value(value, trail, scope = []) {
1588
+ if (typeof value === "string") return this.sources.builtins ? substituteBuiltinEnv(value, this.sources.builtins) : value;
1589
+ if (Array.isArray(value)) return value.map((child, index) => {
1590
+ const out = this.value(child, [...trail, index], scope);
1591
+ if (out === OMIT) this.fail([...trail, index], `is ${this.omitted} inside an array.`, scope);
1592
+ return out;
1593
+ });
1594
+ if (!isPlainObject(value)) return value;
1595
+ if (isEscape(value)) return structuredClone(value);
1596
+ if (tokenKeyOf(value)) {
1597
+ const members = scope.length === 0 ? this.selfRefs(value, trail) : [];
1598
+ if (members.length > 0) {
1599
+ this.deferred.push({
1600
+ trail,
1601
+ token: value,
1602
+ members
1603
+ });
1604
+ return structuredClone(value);
1605
+ }
1606
+ return this.token(value, trail, scope);
1607
+ }
1608
+ const out = {};
1609
+ for (const [key, child] of Object.entries(value)) {
1610
+ if (this.self && trail.length === 0 && key === "children") {
1611
+ out[key] = child;
1612
+ continue;
1613
+ }
1614
+ const resolved = this.value(child, [...trail, key], scope);
1615
+ if (resolved !== OMIT) out[key] = resolved;
1616
+ }
1617
+ return out;
1618
+ }
1619
+ token(token, trail, scope = []) {
1620
+ if (!tokenSchema.safeParse(token).success) this.fail(trail, `is a malformed token: ${JSON.stringify(token)}.`, scope);
1621
+ switch (tokenKeyOf(token)) {
1622
+ case "$output": return this.output(token, trail, scope);
1623
+ case "$env": return this.env(token.$env, trail, scope);
1624
+ case "$concat": return this.concat(token.$concat, trail, scope);
1625
+ case "$map": return this.map(token.$map, trail, scope);
1626
+ case "$item": return this.item(token.$item, trail, scope);
1627
+ case "$key": return this.key(token.$key, trail, scope);
1628
+ default: return this.fail(trail, `is not a token.`, scope);
1629
+ }
1630
+ }
1631
+ /** The binding an `$item`/`$key` names: the innermost map, or the
1632
+ * enclosing map whose `as` is `name`. */
1633
+ binding(name, operator, trail, scope) {
1634
+ if (scope.length === 0) return this.fail(trail, `uses ${operator} outside any $map; ${operator} reads the element a $map template is rendering.`);
1635
+ if (name === void 0) return scope[scope.length - 1];
1636
+ for (let i = scope.length - 1; i >= 0; i--) if (scope[i].as === name) return scope[i];
1637
+ const named = scope.flatMap((b) => b.as ? [`"${b.as}"`] : []);
1638
+ return this.fail(trail, `uses ${operator} with binding "${name}", which no enclosing $map declares (as: ${named.join(", ") || "none"}).`, scope);
1639
+ }
1640
+ map(operand, trail, scope) {
1641
+ if (!isPlainObject(operand)) return this.fail(trail, "is a malformed $map token.", scope);
1642
+ const into = operand.into === "record";
1643
+ const as = typeof operand.as === "string" ? operand.as : void 0;
1644
+ const read = this.readWithSchema(operand.over, [
1645
+ ...trail,
1646
+ "$map",
1647
+ "over"
1648
+ ], scope);
1649
+ const over = read.value;
1650
+ if (over === OMIT) return OMIT;
1651
+ const element = read.schema === void 0 ? void 0 : elementSchemaOf(read.schema);
1652
+ const render = (key, item) => {
1653
+ const inner = [...scope, {
1654
+ path: trail,
1655
+ key,
1656
+ item,
1657
+ ...as !== void 0 ? { as } : {},
1658
+ ...element !== void 0 ? { schema: element } : {}
1659
+ }];
1660
+ const at = [
1661
+ ...trail,
1662
+ "$map",
1663
+ "to"
1664
+ ];
1665
+ const out = this.value(operand.to, at, inner);
1666
+ if (out === OMIT) return this.fail(at, `is ${this.omitted} as the whole $map template; there is no property to omit.`, inner);
1667
+ return out;
1668
+ };
1669
+ if (Array.isArray(over)) {
1670
+ if (into) return this.fail(trail, `is a $map with into: "record", but its over (${describeToken(operand.over)}) resolved to an array, which has no keys to keep. Drop into: "record" (the result is an array) or map over a record.`, scope);
1671
+ const rendered = over.map((item, index) => render(index, item));
1672
+ renderedKeys.set(rendered, over.map((_, index) => index));
1673
+ return rendered;
1674
+ }
1675
+ if (isPlainObject(over)) {
1676
+ const keys = Object.keys(over).sort();
1677
+ if (!into) {
1678
+ const rendered = keys.map((key) => render(key, over[key]));
1679
+ renderedKeys.set(rendered, keys);
1680
+ return rendered;
1681
+ }
1682
+ const out = {};
1683
+ for (const key of keys) out[key] = render(key, over[key]);
1684
+ return out;
1685
+ }
1686
+ return this.fail(trail, `is a $map whose over (${describeToken(operand.over)}) resolved to ${JSON.stringify(over)}${into ? `; into: "record" needs a record` : ", which is not an array or a record"}.`, scope);
1687
+ }
1688
+ item(operand, trail, scope) {
1689
+ return this.readItem(operand, trail, scope).value;
1690
+ }
1691
+ /** A `$map`'s `over` with the schema describing it, when it reads a
1692
+ * schema'd `$output` (or an `$item` of a schema'd element). */
1693
+ readWithSchema(value, trail, scope) {
1694
+ const key = tokenKeyOf(value);
1695
+ if (isPlainObject(value) && (key === "$output" || key === "$item") && tokenSchema.safeParse(value).success) return key === "$output" ? this.readOutput(value, trail, scope) : this.readItem(value.$item, trail, scope);
1696
+ return { value: this.value(value, trail, scope) };
1697
+ }
1698
+ omit(what) {
1699
+ this.omitted = what;
1700
+ return { value: OMIT };
1701
+ }
1702
+ readItem(operand, trail, scope) {
1703
+ const named = isPlainObject(operand) ? operand : void 0;
1704
+ const name = named && typeof named.as === "string" ? named.as : void 0;
1705
+ const raw = named ? named.path : operand;
1706
+ const path = pathSegments(Array.isArray(raw) ? raw : []);
1707
+ const binding = this.binding(name, "$item", trail, scope);
1708
+ const hit = walkPath(binding.item, path);
1709
+ if (!hit.ok) {
1710
+ if (binding.schema !== void 0 && isOptionalField(binding.schema, path, hit.at)) return this.omit("an absent optional $item field");
1711
+ const missing = formatPath(path.slice(0, hit.at + 1));
1712
+ return this.fail(trail, `reads $item ${formatPath(path)}, but $map element ${elementText(binding)} has no ${missing} (it has: ${hit.has}).`, scope);
1713
+ }
1714
+ return {
1715
+ value: structuredClone(hit.value),
1716
+ schema: schemaOf(binding.schema, path)
1717
+ };
1718
+ }
1719
+ key(operand, trail, scope) {
1720
+ const name = typeof operand === "string" ? operand : void 0;
1721
+ return this.binding(name, "$key", trail, scope).key;
1722
+ }
1723
+ output(token, trail, scope = []) {
1724
+ return this.readOutput(token, trail, scope).value;
1725
+ }
1726
+ readOutput(token, trail, scope) {
1727
+ const operand = token.$output;
1728
+ if (!isPlainObject(operand) || typeof operand.host !== "string") return this.fail(trail, "is a malformed $output token.", scope);
1729
+ const ref = typeof operand.member === "string" ? {
1730
+ host: operand.host,
1731
+ member: operand.member
1732
+ } : { host: operand.host };
1733
+ const path = pathSegments(Array.isArray(operand.path) ? operand.path : []);
1734
+ if (!this.sources.outputs) return this.fail(trail, `reads ${describeToken(token)}, but no outputs are available here.`, scope);
1735
+ const lookup = this.sources.outputs.lookup(ref);
1736
+ if (lookup.status === "unavailable") throw new TokenResolutionError(`${this.sources.where ? `${this.sources.where}: ` : ""}${lookup.message}\n (needed by \`${formatPath(trail)}\`: ${describeToken(token)})`);
1737
+ const hit = walkPath(lookup.outputs, path);
1738
+ if (!hit.ok) {
1739
+ if (lookup.schema !== void 0 && isOptionalField(lookup.schema, path, hit.at)) return this.omit("an absent optional output");
1740
+ const parent = path.slice(0, hit.at);
1741
+ const container = parent.length ? `outputs.${formatPath(parent)}` : "its outputs";
1742
+ const missing = formatPath(path.slice(0, hit.at + 1));
1743
+ return this.fail(trail, `reads ${describeToken(token)}, but host "${ref.host}" has no output at ${missing} (${container} has: ${hit.has}).`, scope);
1744
+ }
1745
+ return {
1746
+ value: structuredClone(hit.value),
1747
+ schema: schemaOf(lookup.schema, path)
1748
+ };
1749
+ }
1750
+ env(operand, trail, scope = []) {
1751
+ const optional = isPlainObject(operand);
1752
+ const name = optional ? operand.name : operand;
1753
+ if (typeof name !== "string") return this.fail(trail, "is a malformed $env token.", scope);
1754
+ const builtins = this.sources.builtins;
1755
+ if ((name === "userData" || name === "projectRoot") && builtins?.[name]) return builtins[name];
1756
+ const value = this.sources.env?.[name];
1757
+ if (value !== void 0) return value;
1758
+ if (optional) return this.omit("an optional $env").value;
1759
+ return this.fail(trail, `reads $env ${name}, which is not set. Set ${name} in the environment of the process that resolves this host (or declare { $env: { name: "${name}", optional: true } } to omit the property when unset).`, scope);
1760
+ }
1761
+ concat(parts, trail, scope = []) {
1762
+ if (!Array.isArray(parts)) return this.fail(trail, "is a malformed $concat token.", scope);
1763
+ return parts.map((part, index) => {
1764
+ const at = [
1765
+ ...trail,
1766
+ "$concat",
1767
+ index
1768
+ ];
1769
+ const value = this.value(part, at, scope);
1770
+ if (value === OMIT) return this.fail(at, `is ${this.omitted} inside $concat.`, scope);
1771
+ if (typeof value === "string") return value;
1772
+ if (typeof value === "number") return String(value);
1773
+ return this.fail(at, `resolved to ${JSON.stringify(value)}; every $concat part must be a string or a number.`, scope);
1774
+ }).join("");
1775
+ }
1776
+ };
1777
+ function resolveHostOutputs(host, sources, options) {
1778
+ const resolver = new Resolver(sources, options?.deferSelf);
1779
+ const out = resolver.value(host, []);
1780
+ if (out === OMIT) resolver.fail([], `is ${resolver.omitted} with nothing to omit it from.`);
1781
+ const partial = out;
1782
+ if (!options) return partial;
1783
+ const sites = resolver.deferred;
1784
+ return {
1785
+ host: partial,
1786
+ deferred: sites.map((d) => ({
1787
+ path: formatPath(d.trail),
1788
+ members: d.members
1789
+ })),
1790
+ needs: [...new Set(sites.flatMap((d) => d.members))],
1791
+ finish(outputs) {
1792
+ const done = cloneWithProvenance(partial);
1793
+ const late = new Resolver({
1794
+ ...sources,
1795
+ outputs
1796
+ });
1797
+ for (const site of sites) {
1798
+ const value = late.token(site.token, site.trail);
1799
+ if (value === OMIT && typeof site.trail.at(-1) === "number") late.fail(site.trail, `is ${late.omitted} inside an array.`);
1800
+ setAt(done, site.trail, value === OMIT ? void 0 : value, value === OMIT);
1801
+ }
1802
+ return done;
1803
+ }
1804
+ };
1805
+ }
1806
+ function setAt(root, trail, value, omit) {
1807
+ let current = root;
1808
+ for (const key of trail.slice(0, -1)) if (Array.isArray(current) && typeof key === "number") current = current[key];
1809
+ else if (isPlainObject(current) && typeof key === "string") current = current[key];
1810
+ else return;
1811
+ const last = trail[trail.length - 1];
1812
+ if (Array.isArray(current) && typeof last === "number") current[last] = value;
1813
+ else if (isPlainObject(current) && typeof last === "string") {
1814
+ if (omit) delete current[last];
1815
+ else current[last] = value;
1816
+ }
1817
+ }
1818
+ //#endregion
1819
+ //#region src/runner-resolver.ts
1820
+ /**
1821
+ * Resolves a host's `runner.module` specifier from the PROJECT's dependency
1822
+ * tree (not ph-cli's), imports it, and checks the runner-module contract:
1823
+ * `{ run, hostSchema, kind, outputsSchema?, verbs?, ...optionalVerbs }`.
1824
+ */
1825
+ var RunnerError = class extends Error {
1826
+ constructor(message, hint) {
1827
+ super(hint ? `${message}\n Hint: ${hint}` : message);
1828
+ this.name = "RunnerError";
1829
+ }
1830
+ };
1831
+ /** Whether a value is zod-shaped (has a `safeParse` function): a runner's
1832
+ * `outputsSchema`, a plugin's config schema. */
1833
+ function isSchemaLike(value) {
1834
+ return typeof value === "object" && value !== null && "safeParse" in value && typeof value.safeParse === "function";
1835
+ }
1836
+ /** The Connect runner's specifier: compounds forward `cspRegistrySync` to
1837
+ * it, and `--explain` prints its dead-config warnings. */
1838
+ const CONNECT_RUNNER = "@powerhousedao/ph-cli/runners/connect";
1839
+ /** Exports that are part of the contract but are not verbs. */
1840
+ const NON_VERB_EXPORTS = /* @__PURE__ */ new Set([
1841
+ "hostSchema",
1842
+ "declaredHostSchema",
1843
+ "outputsSchema",
1844
+ "verbs",
1845
+ "kind",
1846
+ "default"
1847
+ ]);
1848
+ async function resolveRunnerModule(projectRoot, specifier) {
1849
+ const projectRequire = createRequire(pathToFileURL(path.join(projectRoot, "package.json")).href);
1850
+ let resolved;
1851
+ try {
1852
+ resolved = projectRequire.resolve(specifier);
1853
+ } catch {
1854
+ throw new RunnerError(`Cannot resolve runner module "${specifier}" from ${projectRoot}.`, "The runner must be a dependency of the project (install it, then retry).");
1855
+ }
1856
+ const module = await import(pathToFileURL(resolved).href);
1857
+ if (typeof module.run !== "function") throw new RunnerError(`Runner "${specifier}" does not export a \`run\` function (required verb).`);
1858
+ const hostSchema = module.hostSchema;
1859
+ if (!hostSchema || typeof hostSchema.safeParse !== "function") throw new RunnerError(`Runner "${specifier}" does not export a \`hostSchema\` — runners validate their own host shape.`);
1860
+ const declared = module.declaredHostSchema;
1861
+ if (declared !== void 0 && typeof declared.safeParse !== "function") throw new RunnerError(`Runner "${specifier}" exports a \`declaredHostSchema\` without safeParse.`);
1862
+ const verbs = module.verbs;
1863
+ if (verbs !== void 0 && (!Array.isArray(verbs) || !verbs.every((verb) => typeof verb === "string" && typeof module[verb] === "function"))) throw new RunnerError(`Runner "${specifier}" exports \`verbs\` ${JSON.stringify(verbs)}, which must list names of exported functions.`);
1864
+ if (!runnerKindSchema.safeParse(module.kind).success) throw new RunnerError(`Runner "${specifier}" does not export a valid \`kind\` (got ${JSON.stringify(module.kind)}; expected "reactor" | "compound").`);
1865
+ return module;
1866
+ }
1867
+ /** Verbs that produce something and start nothing (`build`): no outputs, no
1868
+ * record, no lock — and no token resolution, since what they read (output
1869
+ * dirs, packages) never comes from another host's outputs. Their verb gets
1870
+ * the declared host (tokens may remain in token-able fields). */
1871
+ const ONE_SHOT_VERBS = /* @__PURE__ */ new Set(["build"]);
1872
+ function listVerbs(runner) {
1873
+ if (runner.verbs) return runner.verbs.filter((name) => typeof runner[name] === "function").toSorted();
1874
+ return Object.entries(runner).filter(([name, value]) => typeof value === "function" && !NON_VERB_EXPORTS.has(name)).map(([name]) => name).sort();
1875
+ }
1876
+ function getVerb(runner, specifier, verb) {
1877
+ const candidate = runner[verb];
1878
+ if (typeof candidate !== "function" || !listVerbs(runner).includes(verb)) throw new RunnerError(`Runner "${specifier}" does not support the verb "${verb}". Supported verbs: ${listVerbs(runner).join(", ")}.`);
1879
+ return candidate;
1880
+ }
1881
+ function isRecord$2(value) {
1882
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1883
+ }
1884
+ /** reactor XOR children, decided by the runner's declared `kind`. */
1885
+ function assertKindShape(kind, specifier, host, file) {
1886
+ if (kind === "reactor" && host.children !== void 0) throw new RunnerError(`${file}: "${specifier}" is a reactor runner, so the host must not declare \`children\`.`, "`children` belongs to compound hosts; a reactor host configures its own `reactor` block.");
1887
+ if (kind === "compound" && host.reactor !== void 0) throw new RunnerError(`${file}: "${specifier}" is a compound runner, so the host must not declare \`reactor\`.`, "A compound's reactors are its members': configure them in the member host or a wrapper's `reactor` override.");
1888
+ }
1889
+ /** `runner.defaultVerb` and every plugin entry's `verbs` must name verbs
1890
+ * this runner exports. */
1891
+ function assertKnownVerbs(runner, specifier, host, file) {
1892
+ const options = host.runner;
1893
+ if (!isRecord$2(options)) return;
1894
+ const verbs = listVerbs(runner);
1895
+ const unknownVerb = (verb) => typeof verb === "string" && !verbs.includes(verb);
1896
+ if (unknownVerb(options.defaultVerb)) throw new RunnerError(`${file}: runner.defaultVerb "${options.defaultVerb}" is not a verb of "${specifier}". Supported verbs: ${verbs.join(", ")}.`);
1897
+ const plugins = Array.isArray(options.plugins) ? options.plugins : [];
1898
+ for (const entry of plugins) {
1899
+ if (!isRecord$2(entry) || !Array.isArray(entry.verbs)) continue;
1900
+ const bad = entry.verbs.find(unknownVerb);
1901
+ if (bad !== void 0) throw new RunnerError(`${file}: plugin "${String(entry.module)}" is scoped to verb "${bad}", which "${specifier}" does not export. Supported verbs: ${verbs.join(", ")}.`);
1902
+ }
1903
+ }
1904
+ function formatIssues(issues) {
1905
+ return issues.map((i) => ` - ${i.path}: ${i.message}`).join("\n");
1906
+ }
1907
+ function valueAt(host, path) {
1908
+ let current = host;
1909
+ for (const key of path) if (Array.isArray(current) && typeof key === "number") current = current[key];
1910
+ else if (isRecord$2(current) && typeof key === "string") current = current[key];
1911
+ else return;
1912
+ return current;
1913
+ }
1914
+ /**
1915
+ * Resolved validation (pipeline step 6): validate a RESOLVED host against
1916
+ * its runner's `hostSchema` and return the PARSED host (what the verb
1917
+ * receives). Run `resolveHostOutputs` first; a token still present fails
1918
+ * with its path.
1919
+ */
1920
+ function validateHost(runner, specifier, host, file, options = {}) {
1921
+ return parseHost(runner, options.tokens === "allow" ? runner.declaredHostSchema ?? runner.hostSchema : runner.hostSchema, specifier, host, file, options);
1922
+ }
1923
+ function parseHost(runner, schema, specifier, host, file, options) {
1924
+ if (isRecord$2(host)) {
1925
+ assertKindShape(runner.kind, specifier, host, file);
1926
+ if (options.tokens !== "allow") {
1927
+ const token = findToken(host);
1928
+ if (token) throw new RunnerError(`${file}: \`${token.path}\` is an unresolved output token (${token.key}).`, "Resolve the host (resolveHostOutputs) before validating it for a verb; `ph run` does this.");
1929
+ }
1930
+ assertKnownVerbs(runner, specifier, host, file);
1931
+ }
1932
+ const result = schema.safeParse(unwrapEscapes(host));
1933
+ if (!result.success) throw new RunnerError(`${file} failed validation against the hostSchema of "${specifier}":\n${result.error.issues.map((issue) => {
1934
+ const element = describeMapElements(host, issue.path);
1935
+ return ` - ${(issue.path.map(String).join(".") || "<root>") + (element ? ` (${element})` : "")}: ${tokenKeyOf(valueAt(host, issue.path)) ? "this field does not take an output token (it is not token-able); spell the value literally." : issue.message}`;
1936
+ }).join("\n") || " (no details reported)"}`);
1937
+ return result.data;
1938
+ }
1939
+ /**
1940
+ * Declared validation (pipeline step 3): the removed cross-host forms
1941
+ * (each error names its token form), token shapes and `$env` `optional`
1942
+ * placement, `$output` paths against the producers' `outputsSchema`s, then
1943
+ * the runner's `declaredHostSchema` (tokens allowed in token-able fields).
1944
+ * Reads no environment value and needs no producer running. Throws on the
1945
+ * first failing stage; resolve, then `validateHost`, before a verb runs.
1946
+ */
1947
+ function validateDeclaredHost(runner, specifier, host, file, options = {}) {
1948
+ const removed = findRemovedForms(host);
1949
+ if (removed.length > 0) throw new RunnerError(`${file}: removed form:\n${formatIssues(removed)}`);
1950
+ const issues = checkTokenSites(host);
1951
+ if (options.outputsSchemaOf) issues.push(...checkOutputPaths(host, options.outputsSchemaOf));
1952
+ if (issues.length > 0) throw new RunnerError(`${file}: invalid output token:\n${formatIssues(issues)}`);
1953
+ if (isRecord$2(host)) assertKindShape(runner.kind, specifier, host, file);
1954
+ if (!runner.declaredHostSchema) return;
1955
+ parseHost(runner, runner.declaredHostSchema, specifier, host, file, { tokens: "allow" });
1956
+ }
1957
+ //#endregion
1958
+ //#region src/host-loader.ts
1959
+ /**
1960
+ * Loads and pre-validates a `hosts/<name>/host.js` definition.
1961
+ *
1962
+ * A host file is a static PROJECTION of powerhouse.config.json: plain ESM,
1963
+ * default-exporting a data object. Three gates run before any runner sees it:
1964
+ * 1. import lint — the only legal imports are the project's
1965
+ * powerhouse.config.json, sibling `../<host>/host.js` files and sibling
1966
+ * generated `../<host>/outputs.js` token trees (host files are data, not
1967
+ * programs; `process.` is banned, environment values go through `$env`).
1968
+ * An imported outputs.js whose schema hash no longer matches its
1969
+ * producer fails here ("run `ph generate hosts`");
1970
+ * 2. static check — the exported object must survive a JSON round trip
1971
+ * (functions, undefined, class instances, Dates etc. are rejected,
1972
+ * reporting the offending path);
1973
+ * 3. shape pre-check — `name`, `runner.module`, and the reactor XOR children
1974
+ * rule. Full validation is the runner's `hostSchema` (phase 2).
1975
+ *
1976
+ * This module never exits the process — callers own error presentation.
1977
+ */
1978
+ const HOST_FILE = "host.js";
1979
+ const CONFIG_IMPORT_SUFFIX = "powerhouse.config.json";
1980
+ var HostLoadError = class extends Error {
1981
+ constructor(message, hint) {
1982
+ super(hint ? `${message}\n Hint: ${hint}` : message);
1983
+ this.name = "HostLoadError";
1984
+ }
1985
+ };
1986
+ /** A `hosts/` folder with no `<name>/host.js` inside is "empty" — the guard
1987
+ * state: callers warn loudly and fall back to legacy rather than activating
1988
+ * the new architecture off a stray `mkdir hosts`. */
1989
+ function probeHostsFolder(projectRoot) {
1990
+ const dir = path.join(projectRoot, "hosts");
1991
+ if (!existsSync(dir) || !statSync(dir).isDirectory()) return { kind: "absent" };
1992
+ const hosts = readdirSync(dir, { withFileTypes: true }).filter((entry) => entry.isDirectory() && existsSync(path.join(dir, entry.name, HOST_FILE))).map((entry) => entry.name).sort();
1993
+ return hosts.length === 0 ? {
1994
+ kind: "empty",
1995
+ dir
1996
+ } : {
1997
+ kind: "present",
1998
+ dir,
1999
+ hosts
2000
+ };
2001
+ }
2002
+ /** Sibling imports: `../<host>/host.js` — source material for derived
2003
+ * compositions (full-inclusion wrappers compute over them with plain JS) —
2004
+ * and `../<host>/outputs.js`, the generated `$output` token tree. */
2005
+ const SIBLING_IMPORT = /^\.\.\/([A-Za-z0-9_-]+)\/(host\.js|outputs\.js)$/;
2006
+ /** The generated per-host token tree (`ph generate hosts`). */
2007
+ const OUTPUTS_FILE = "outputs.js";
2008
+ const GENERATE_HINT = "Run `ph generate hosts` to (re)generate hosts/<name>/outputs.js from the producer's runner outputsSchema and declared drives.";
2009
+ /**
2010
+ * One pass over JS source that blanks every comment and, with
2011
+ * `literals: "blank"`, the CONTENTS of string literals and template-literal
2012
+ * text (quotes, backticks and `${`/`}` kept). A template's `${…}` holes are
2013
+ * code: they are scanned like the rest (strings, nested templates and braces
2014
+ * inside them included). Every newline survives, so line-anchored checks and
2015
+ * line numbers still match the original source. Regex literals are not
2016
+ * recognised (host files are data; a regex is not one).
2017
+ */
2018
+ function scanSource(source, literals) {
2019
+ const blank = (text) => text.replace(/[^\n]/g, " ");
2020
+ const literal = (text) => literals === "blank" ? blank(text) : text;
2021
+ let out = "";
2022
+ let i = 0;
2023
+ const holes = [];
2024
+ /** Template text from `i` (just after a backtick or a hole's `}`) up to
2025
+ * and including its closing backtick, or up to and including the next
2026
+ * `${` (pushing a hole). */
2027
+ const templateText = () => {
2028
+ let j = i;
2029
+ while (j < source.length) {
2030
+ const ch = source[j];
2031
+ if (ch === "\\") {
2032
+ j += 2;
2033
+ continue;
2034
+ }
2035
+ if (ch === "`") break;
2036
+ if (ch === "$" && source[j + 1] === "{") break;
2037
+ j++;
2038
+ }
2039
+ out += literal(source.slice(i, Math.min(j, source.length)));
2040
+ if (j >= source.length) i = source.length;
2041
+ else if (source[j] === "`") {
2042
+ out += "`";
2043
+ i = j + 1;
2044
+ } else {
2045
+ out += "${";
2046
+ holes.push(0);
2047
+ i = j + 2;
2048
+ }
2049
+ };
2050
+ while (i < source.length) {
2051
+ const ch = source[i];
2052
+ const next = source[i + 1];
2053
+ if (ch === "/" && next === "/") {
2054
+ const end = source.indexOf("\n", i);
2055
+ const stop = end === -1 ? source.length : end;
2056
+ out += blank(source.slice(i, stop));
2057
+ i = stop;
2058
+ continue;
2059
+ }
2060
+ if (ch === "/" && next === "*") {
2061
+ const end = source.indexOf("*/", i + 2);
2062
+ const stop = end === -1 ? source.length : end + 2;
2063
+ out += blank(source.slice(i, stop));
2064
+ i = stop;
2065
+ continue;
2066
+ }
2067
+ if (ch === "\"" || ch === "'") {
2068
+ let j = i + 1;
2069
+ while (j < source.length && source[j] !== ch && source[j] !== "\n") j += source[j] === "\\" ? 2 : 1;
2070
+ const close = source[j] === ch ? ch : "";
2071
+ out += ch + literal(source.slice(i + 1, Math.min(j, source.length)));
2072
+ out += close;
2073
+ i = close ? j + 1 : j;
2074
+ continue;
2075
+ }
2076
+ if (ch === "`") {
2077
+ out += "`";
2078
+ i++;
2079
+ templateText();
2080
+ continue;
2081
+ }
2082
+ if (holes.length > 0 && ch === "{") holes[holes.length - 1]++;
2083
+ if (holes.length > 0 && ch === "}") {
2084
+ if (holes[holes.length - 1] === 0) {
2085
+ holes.pop();
2086
+ out += "}";
2087
+ i++;
2088
+ templateText();
2089
+ continue;
2090
+ }
2091
+ holes[holes.length - 1]--;
2092
+ }
2093
+ out += ch;
2094
+ i++;
2095
+ }
2096
+ return out;
2097
+ }
2098
+ /** Blank out `//` and block comments, keeping string and template literals
2099
+ * (URLs contain `//`) and every newline, so line-anchored checks still see
2100
+ * the code's own lines. A JSDoc `import("…")` type is a comment, not code. */
2101
+ function stripComments(source) {
2102
+ return scanSource(source, "keep");
2103
+ }
2104
+ /** Blank out comments and the contents of string literals and
2105
+ * template-literal text, so a word inside a string (a URL, a description,
2106
+ * an apostrophe in template text) is neither mistaken for code nor able to
2107
+ * hide code. Template `${…}` holes are code and are kept. */
2108
+ function blankLiterals(source) {
2109
+ return scanSource(source, "blank");
2110
+ }
2111
+ const PROCESS_ACCESS = /(?<![.\w$])process\s*(?:\?\.|\.|\[)/;
2112
+ /** Host files and generated outputs.js are data: reading the environment
2113
+ * through `process.` is banned (typed-host-configs decision 9). Environment
2114
+ * values go through `$env`, which resolves at start in the resolving
2115
+ * process. Comments are already stripped, so a mention there is fine. */
2116
+ function rejectProcessAccess(source, file) {
2117
+ const match = PROCESS_ACCESS.exec(blankLiterals(source));
2118
+ if (!match) return;
2119
+ const line = source.slice(0, match.index).split("\n").length;
2120
+ throw new HostLoadError(`${file}:${line} reads \`process.\` — host files cannot read the environment directly.`, "Use an $env token instead: { $env: \"NAME\" } (fails when unset), or { $env: { name: \"NAME\", optional: true } } as a property value to omit the property when unset. It resolves when the host starts.");
2121
+ }
2122
+ /** Lints a host file and returns what it imports. Rejects every import
2123
+ * except the project's powerhouse.config.json, SIBLING host files (R1:
2124
+ * derived compositions) and sibling generated outputs.js token trees; any
2125
+ * dynamic `import(...)` or `require(...)`; and any `process.` access.
2126
+ * Source-level enforcement: the JSON round trip below is the hard gate; this
2127
+ * one produces the better error. */
2128
+ function scanHostImports(rawSource, file) {
2129
+ const source = stripComments(rawSource);
2130
+ const imports = {
2131
+ hosts: [],
2132
+ outputs: []
2133
+ };
2134
+ for (const match of source.matchAll(/^\s*import\b[^;'"]*?from\s+["']([^"']+)["']/gm)) {
2135
+ const specifier = match[1];
2136
+ if (specifier.endsWith(CONFIG_IMPORT_SUFFIX)) continue;
2137
+ const sibling = SIBLING_IMPORT.exec(specifier);
2138
+ if (sibling) {
2139
+ (sibling[2] === HOST_FILE ? imports.hosts : imports.outputs).push(sibling[1]);
2140
+ continue;
2141
+ }
2142
+ throw new HostLoadError(`${file} imports "${specifier}" — a host file may only import the project's powerhouse.config.json, sibling hosts/<name>/host.js files or generated hosts/<name>/${OUTPUTS_FILE} token trees.`, "Host files are static projections; code belongs in plugins or the runner.");
2143
+ }
2144
+ if (/^\s*import\s+["']/m.test(source)) throw new HostLoadError(`${file} contains a side-effect import — a host file may only import the project's powerhouse.config.json or sibling host files.`);
2145
+ if (/\bimport\s*\(/.test(source) || /\brequire\s*\(/.test(source)) throw new HostLoadError(`${file} uses dynamic import()/require() — host files are static data.`);
2146
+ rejectProcessAccess(source, file);
2147
+ return imports;
2148
+ }
2149
+ /** {@link scanHostImports}, returning only the sibling host names (for cycle
2150
+ * detection). */
2151
+ function lintHostImports(rawSource, file) {
2152
+ return scanHostImports(rawSource, file).hosts;
2153
+ }
2154
+ /** A generated `outputs.js` is plain data: no imports of any kind, no
2155
+ * dynamic import/require, no `process.`. */
2156
+ function lintOutputsFile(rawSource, file) {
2157
+ const source = stripComments(rawSource);
2158
+ if (/^\s*import\b/m.test(source) || /^\s*export\b[^;]*?\bfrom\s+["']/m.test(source) || /\bimport\s*\(/.test(source) || /\brequire\s*\(/.test(source)) throw new HostLoadError(`${file} imports a module — a generated ${OUTPUTS_FILE} is plain data.`, "Regenerate it with `ph generate hosts` instead of editing it.");
2159
+ rejectProcessAccess(source, file);
2160
+ }
2161
+ /** Walks the sibling-import graph from `hostName`, linting every visited file
2162
+ * (and every outputs.js it imports) and failing on a cycle (an ESM circular
2163
+ * would otherwise surface as an undefined default export with no useful
2164
+ * message). Returns the hosts whose outputs.js the graph imports, sorted. */
2165
+ function lintHostImportGraph(hostsDir, hostName) {
2166
+ const state = /* @__PURE__ */ new Map();
2167
+ const producers = /* @__PURE__ */ new Set();
2168
+ const visit = (name, chain) => {
2169
+ const mark = state.get(name);
2170
+ if (mark === "done") return;
2171
+ if (mark === "visiting") throw new HostLoadError(`Host import cycle: ${[...chain, name].map((n) => `hosts/${n}`).join(" -> ")}.`, "Hoist the shared data into one host (or powerhouse.config.json) instead of importing both ways.");
2172
+ const file = path.join(hostsDir, name, HOST_FILE);
2173
+ if (!existsSync(file)) throw new HostLoadError(`hosts/${chain[chain.length - 1] ?? name} imports sibling "hosts/${name}/host.js", which does not exist.`);
2174
+ state.set(name, "visiting");
2175
+ const imports = scanHostImports(readFileSync(file, "utf8"), file);
2176
+ for (const producer of imports.outputs) {
2177
+ if (producers.has(producer)) continue;
2178
+ const outputsFile = path.join(hostsDir, producer, OUTPUTS_FILE);
2179
+ if (!existsSync(outputsFile)) throw new HostLoadError(`hosts/${name}/host.js imports "hosts/${producer}/${OUTPUTS_FILE}", which does not exist.`, GENERATE_HINT);
2180
+ lintOutputsFile(readFileSync(outputsFile, "utf8"), outputsFile);
2181
+ producers.add(producer);
2182
+ }
2183
+ for (const sibling of imports.hosts) visit(sibling, [...chain, name]);
2184
+ state.set(name, "done");
2185
+ };
2186
+ visit(hostName, []);
2187
+ return [...producers].sort();
2188
+ }
2189
+ /** Returns the path of the first value that would not survive a JSON round
2190
+ * trip, or undefined when the object is fully static. */
2191
+ function findNonStaticValue(value, trail = "") {
2192
+ if (value === null) return void 0;
2193
+ const kind = typeof value;
2194
+ if (kind === "string" || kind === "number" || kind === "boolean") return;
2195
+ if (kind !== "object") return `${trail || "<root>"} (${kind})`;
2196
+ if (Array.isArray(value)) {
2197
+ for (let i = 0; i < value.length; i++) {
2198
+ const hit = findNonStaticValue(value[i], `${trail}[${i}]`);
2199
+ if (hit) return hit;
2200
+ }
2201
+ return;
2202
+ }
2203
+ const proto = Object.getPrototypeOf(value);
2204
+ if (proto !== Object.prototype && proto !== null) return `${trail || "<root>"} (non-plain object)`;
2205
+ for (const [key, child] of Object.entries(value)) {
2206
+ const hit = findNonStaticValue(child, trail ? `${trail}.${key}` : key);
2207
+ if (hit) return hit;
2208
+ }
2209
+ }
2210
+ function assertHostShape(host, file) {
2211
+ if (typeof host.name !== "string" || host.name.length === 0) throw new HostLoadError(`${file}: \`name\` must be a non-empty string.`);
2212
+ const runner = host.runner;
2213
+ if (runner === null || typeof runner !== "object" || typeof runner.module !== "string") throw new HostLoadError(`${file}: \`runner\` must be an object with a \`module\` specifier string.`);
2214
+ if (host.reactor !== void 0 && host.children !== void 0) throw new HostLoadError(`${file}: \`reactor\` and \`children\` are mutually exclusive — a host is a reactor runner or a compound runner, never both.`);
2215
+ }
2216
+ async function loadHost(projectRoot, hostName) {
2217
+ return importHost(projectRoot, hostName, true);
2218
+ }
2219
+ async function importHost(projectRoot, hostName, checkOutputs) {
2220
+ const probe = probeHostsFolder(projectRoot);
2221
+ if (probe.kind === "absent") throw new HostLoadError(`No hosts/ folder found in ${projectRoot}.`, "Scaffold one with `ph init --uniform-runners` (or create hosts/<name>/host.js).");
2222
+ if (probe.kind === "empty") throw new HostLoadError(`hosts/ exists at ${probe.dir} but contains no <name>/host.js.`, "An empty hosts/ folder does not activate the uniform-runners architecture; add a host definition or remove the folder.");
2223
+ if (!probe.hosts.includes(hostName)) throw new HostLoadError(`Unknown host "${hostName}". Available hosts: ${probe.hosts.join(", ")}.`);
2224
+ const file = path.join(probe.dir, hostName, HOST_FILE);
2225
+ const producers = lintHostImportGraph(probe.dir, hostName);
2226
+ if (checkOutputs) for (const producer of producers) await assertOutputsFileFresh(projectRoot, probe.dir, hostName, producer);
2227
+ const host = (await import(pathToFileURL(file).href)).default;
2228
+ if (host === null || typeof host !== "object" || Array.isArray(host)) throw new HostLoadError(`${file} must default-export the host object (\`export default { name, runner, ... }\`).`);
2229
+ const nonStatic = findNonStaticValue(host);
2230
+ if (nonStatic) throw new HostLoadError(`${file} exports a non-static value at \`${nonStatic}\` — host files must survive a JSON round trip.`, "Runtime behavior belongs in the runner; host files only carry data.");
2231
+ assertHostShape(host, file);
2232
+ return {
2233
+ name: hostName,
2234
+ dir: path.dirname(file),
2235
+ file,
2236
+ host
2237
+ };
2238
+ }
2239
+ const OUTPUTS_HASH_EXPORT = /^export const outputsHash = "([^"]+)";$/m;
2240
+ /** The hash a generated outputs.js carries, or undefined. */
2241
+ function readOutputsFileHash(source) {
2242
+ return OUTPUTS_HASH_EXPORT.exec(source)?.[1];
2243
+ }
2244
+ function canonicalJson(value) {
2245
+ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
2246
+ if (value !== null && typeof value === "object") return `{${Object.entries(value).filter(([, child]) => child !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, child]) => `${JSON.stringify(key)}:${canonicalJson(child)}`).join(",")}}`;
2247
+ return JSON.stringify(value);
2248
+ }
2249
+ /** sha256 over the canonical JSON of the generator's inputs. The host name
2250
+ * is one: every token in the file carries it, so a copied or renamed host
2251
+ * folder makes its outputs.js stale. */
2252
+ function computeOutputsHash(input) {
2253
+ return `sha256:${createHash("sha256").update(canonicalJson({
2254
+ v: 1,
2255
+ host: input.host,
2256
+ runnerModule: input.runnerModule,
2257
+ outputsSchema: input.outputsSchema,
2258
+ drives: [...new Set(input.drives)].sort()
2259
+ })).digest("hex").slice(0, 32)}`;
2260
+ }
2261
+ function isZodSchema(value) {
2262
+ return value !== null && typeof value === "object" && "_zod" in value;
2263
+ }
2264
+ function isRecord$1(value) {
2265
+ return value !== null && typeof value === "object" && !Array.isArray(value);
2266
+ }
2267
+ /** Local (non-remote) slugs from a drive declaration list. */
2268
+ function localDriveSlugs(drives) {
2269
+ if (!Array.isArray(drives)) return [];
2270
+ return drives.flatMap((drive) => isRecord$1(drive) && typeof drive.slug === "string" && drive.remote === void 0 ? [drive.slug] : []);
2271
+ }
2272
+ /**
2273
+ * Describes the outputs a host's creation produces, for `ph generate hosts`
2274
+ * and the loader's staleness check: the runner's `outputsSchema` as JSON
2275
+ * Schema and the host's declared local drives (the keys `drives.<slug>` of a
2276
+ * switchboard-like runner). Returns undefined when the runner exports no
2277
+ * `outputsSchema` (the host produces nothing a token can reference).
2278
+ *
2279
+ * Plugin-contributed drives are collected across every verb (verb scoping
2280
+ * is ignored: a drive any verb serves is referenceable). Plugins the project
2281
+ * tree cannot resolve contribute nothing, exactly as at boot. The implicit
2282
+ * default drive a switchboard serves when it declares none is NOT a known
2283
+ * key (it is not declared); reach it with a literal `$output` token.
2284
+ */
2285
+ async function describeHostOutputs(projectRoot, hostName) {
2286
+ const { host, file } = await importHost(projectRoot, hostName, false);
2287
+ const runnerModule = host.runner.module;
2288
+ const schema = (await resolveRunnerModule(projectRoot, runnerModule)).outputsSchema;
2289
+ if (!isZodSchema(schema)) return void 0;
2290
+ const { $schema: _dialect, ...outputsSchema } = z.toJSONSchema(schema, {
2291
+ io: "output",
2292
+ unrepresentable: "any"
2293
+ });
2294
+ const reactor = host.reactor;
2295
+ const drives = localDriveSlugs(isRecord$1(reactor) ? reactor.drives : []);
2296
+ const entries = (host.runner.plugins ?? []).map((entry) => typeof entry === "string" ? entry : {
2297
+ ...entry,
2298
+ verbs: "*"
2299
+ });
2300
+ if (entries.length > 0) {
2301
+ const plan = await resolvePluginContributions(projectRoot, "*", entries, path.relative(projectRoot, file));
2302
+ drives.push(...localDriveSlugs(plan.drives.map((drive) => drive.declaration)));
2303
+ }
2304
+ const sortedDrives = [...new Set(drives)].sort();
2305
+ return {
2306
+ host: hostName,
2307
+ runnerModule,
2308
+ outputsSchema,
2309
+ drives: sortedDrives,
2310
+ hash: computeOutputsHash({
2311
+ host: hostName,
2312
+ runnerModule,
2313
+ outputsSchema,
2314
+ drives: sortedDrives
2315
+ })
2316
+ };
2317
+ }
2318
+ async function assertOutputsFileFresh(projectRoot, hostsDir, consumer, producer) {
2319
+ const rel = `hosts/${producer}/${OUTPUTS_FILE}`;
2320
+ const actual = readOutputsFileHash(readFileSync(path.join(hostsDir, producer, OUTPUTS_FILE), "utf8"));
2321
+ if (!existsSync(path.join(hostsDir, producer, HOST_FILE))) throw new HostLoadError(`hosts/${consumer} imports ${rel}, but there is no hosts/${producer}/host.js to produce it.`, "Delete the orphaned outputs.js and fix the import.");
2322
+ const description = await describeHostOutputs(projectRoot, producer);
2323
+ if (!description) throw new HostLoadError(`hosts/${consumer} imports ${rel}, but hosts/${producer}'s runner declares no outputsSchema, so it produces no outputs.`);
2324
+ if (actual !== description.hash) throw new HostLoadError(`${rel} is stale (its producer's outputsSchema or declared drives changed since it was generated); run \`ph generate hosts\`.`, actual === void 0 ? `${rel} carries no outputsHash export; it was not generated by \`ph generate hosts\`.` : `expected ${description.hash}, found ${actual}.`);
2325
+ }
2326
+ //#endregion
2327
+ //#region src/run-record-schema.ts
2328
+ /**
2329
+ * `.ph/run/<host>.json`, version 2 (typed-host-configs 3.6): what a running
2330
+ * host and its members produced. Validated on read; a v1 (or any invalid)
2331
+ * record reads as "not running". `projectName` is kept beyond the plan's
2332
+ * sketch because the live/foreign probe needs it. `host` is the host's
2333
+ * `name` (the file key), not its folder.
2334
+ */
2335
+ const outputsSchema = z.record(z.string(), z.unknown());
2336
+ const runRecordMemberSchema = z.strictObject({
2337
+ /** The member's host folder (`children.<key>.host`). */
2338
+ host: z.string().min(1),
2339
+ runnerModule: z.string().min(1),
2340
+ kind: runnerKindSchema,
2341
+ verb: z.string().min(1),
2342
+ outputs: outputsSchema
2343
+ });
2344
+ const runRecordSchema = z.strictObject({
2345
+ version: z.literal(2),
2346
+ host: z.string().min(1),
2347
+ projectName: z.string(),
2348
+ kind: runnerKindSchema,
2349
+ verb: z.string().min(1),
2350
+ pid: z.number().int(),
2351
+ startedAt: z.string(),
2352
+ /** Standalone hosts: the runner's outputs. */
2353
+ outputs: outputsSchema.optional(),
2354
+ /** Compounds: one entry per started member, keyed by member name. */
2355
+ members: z.record(z.string(), runRecordMemberSchema).optional(),
2356
+ /** Host-specific extras (e.g. mcpUrl) a runner wants in the record. */
2357
+ extra: z.record(z.string(), z.unknown()).optional()
2358
+ });
2359
+ //#endregion
2360
+ //#region src/run-record.ts
2361
+ const runDir = (projectDir) => path.join(resolvePhDir(projectDir), "run");
2362
+ const recordPath = (projectDir, hostName) => path.join(runDir(projectDir), `${hostName}.json`);
2363
+ function readRunRecord(projectDir, hostName) {
2364
+ let raw;
2365
+ try {
2366
+ raw = JSON.parse(fs.readFileSync(recordPath(projectDir, hostName), "utf8"));
2367
+ } catch {
2368
+ return;
2369
+ }
2370
+ const parsed = runRecordSchema.safeParse(raw);
2371
+ return parsed.success ? parsed.data : void 0;
2372
+ }
2373
+ /** Every valid v2 record under `.ph/run/` (invalid and v1 files skipped). */
2374
+ function listRunRecords(projectDir) {
2375
+ let files;
2376
+ try {
2377
+ files = fs.readdirSync(runDir(projectDir));
2378
+ } catch {
2379
+ return [];
2380
+ }
2381
+ return files.filter((file) => file.endsWith(".json")).flatMap((file) => {
2382
+ const record = readRunRecord(projectDir, file.slice(0, -5));
2383
+ return record ? [record] : [];
2384
+ });
2385
+ }
2386
+ /** The project identity the live/foreign probe compares: package.json
2387
+ * `name`, else the folder name. */
2388
+ function readProjectName(projectDir) {
2389
+ try {
2390
+ const pkg = JSON.parse(fs.readFileSync(path.join(projectDir, "package.json"), "utf8"));
2391
+ if (typeof pkg.name === "string" && pkg.name) return pkg.name;
2392
+ } catch {}
2393
+ return path.basename(path.resolve(projectDir));
2394
+ }
2395
+ function writeRunRecord(projectDir, record) {
2396
+ const target = recordPath(projectDir, record.host);
2397
+ const valid = runRecordSchema.parse(record);
2398
+ fs.mkdirSync(path.dirname(target), { recursive: true });
2399
+ fs.writeFileSync(target, `${JSON.stringify(valid, null, 2)}\n`);
2400
+ }
2401
+ function clearRunRecord(projectDir, hostName) {
2402
+ try {
2403
+ fs.rmSync(recordPath(projectDir, hostName));
2404
+ } catch {}
2405
+ }
2406
+ function isPidAlive(pid) {
2407
+ try {
2408
+ process.kill(pid, 0);
2409
+ return true;
2410
+ } catch (error) {
2411
+ return error.code === "EPERM";
2412
+ }
2413
+ }
2414
+ /**
2415
+ * Decide whether the recorded instance is this project's live host.
2416
+ *
2417
+ * pid liveness alone proves nothing (pids are reused), and the recorded
2418
+ * projectName is what separates "my instance" from "a different project that
2419
+ * happens to hold this storage root" — the confusion the vetra lock exists to
2420
+ * prevent. A stale record (dead pid) is reported so the caller can clear it; a
2421
+ * foreign one (live pid, different project) is left alone.
2422
+ */
2423
+ function probeRun(projectDir, hostName, projectName) {
2424
+ const record = readRunRecord(projectDir, hostName);
2425
+ if (!record) return { status: "none" };
2426
+ if (!isPidAlive(record.pid)) return {
2427
+ status: "stale",
2428
+ record
2429
+ };
2430
+ if (record.projectName !== projectName) return {
2431
+ status: "foreign",
2432
+ record
2433
+ };
2434
+ return {
2435
+ status: "live",
2436
+ record
2437
+ };
2438
+ }
2439
+ //#endregion
2440
+ //#region src/placeholders.ts
2441
+ /**
2442
+ * `${userData}` resolution for host files (desktop shape): storage paths in a
2443
+ * host must not derive from the instance name (renames must stay safe), so
2444
+ * the host file writes `${userData}/.ph/reactor-storage` and the RUNNER
2445
+ * resolves it at start. `${userData}` is a PROJECT-SHAPED root: its `.ph`
2446
+ * subtree carries the same names the classic commands use under
2447
+ * `<project>/.ph` (see `resolvePhDir`). In the CLI it IS the project root, so
2448
+ * `ph run desktop` in a project shares the one `.ph` tree `ph vetra` uses;
2449
+ * a shell (Tauri) points it at the OS profile via PH_USER_DATA_DIR, and the
2450
+ * whole `.ph` tree — stores, identity, run records — follows.
2451
+ */
2452
+ function defaultUserDataDir(projectRoot, env = process.env) {
2453
+ return env.PH_USER_DATA_DIR ?? path.resolve(projectRoot);
2454
+ }
2455
+ /** Deep-substitute `${userData}` in every string of a JSON-shaped value.
2456
+ * Non-strings pass through; the input is never mutated. */
2457
+ function resolveUserDataPlaceholders(value, userData) {
2458
+ return substituteBuiltinEnv(value, { userData });
2459
+ }
2460
+ //#endregion
2461
+ //#region src/resolve/node.ts
2462
+ /** Load every producer host a set of refs names (each once). */
2463
+ async function loadProducers(projectRoot, refs) {
2464
+ const producers = /* @__PURE__ */ new Map();
2465
+ for (const { host: folder } of refs) {
2466
+ if (producers.has(folder)) continue;
2467
+ try {
2468
+ const loaded = await loadHost(projectRoot, folder);
2469
+ const specifier = loaded.host.runner.module;
2470
+ producers.set(folder, {
2471
+ folder,
2472
+ name: loaded.host.name,
2473
+ specifier,
2474
+ runner: await resolveRunnerModule(projectRoot, specifier)
2475
+ });
2476
+ } catch (error) {
2477
+ producers.set(folder, { error: `names host "${folder}", which cannot be loaded: ${error instanceof Error ? error.message : String(error)}` });
2478
+ }
2479
+ }
2480
+ return producers;
2481
+ }
2482
+ /** The outputs schema of a runner module, or why it has none. */
2483
+ function runnerOutputsSchema(runner, specifier, label) {
2484
+ const schema = runner.outputsSchema;
2485
+ if (schema === void 0 || schema === null) return { error: `${label} runs "${specifier}", which exports no outputsSchema, so it produces no outputs a token can read.` };
2486
+ return {
2487
+ schema,
2488
+ label: `"${specifier}" (${label})`
2489
+ };
2490
+ }
2491
+ /** Declared-validation lookup for a standalone host's producers. */
2492
+ function producerOutputsSchemas(producers) {
2493
+ return (ref) => {
2494
+ const info = producers.get(ref.host);
2495
+ if (!info) return { error: `names host "${ref.host}", which was not loaded.` };
2496
+ if ("error" in info) return { error: info.error };
2497
+ return runnerOutputsSchema(info.runner, info.specifier, `host "${ref.host}"`);
2498
+ };
2499
+ }
2500
+ /**
2501
+ * Standalone `$output` source: the producer's live v2 run record. Its own
2502
+ * standalone record first (keyed by the producer's `name`); else a live
2503
+ * compound of this project with exactly one member running that host. A
2504
+ * missing, stale, foreign or output-less record means "not running", and the
2505
+ * lookup fails naming the producer and how to start it (no fallback to the
2506
+ * producer's declared config, no waiting).
2507
+ */
2508
+ function runRecordOutputSource(projectRoot, options) {
2509
+ const { consumer, producers, projectName } = options;
2510
+ return { lookup(ref) {
2511
+ const notRunning = `${consumer} needs outputs from host "${ref.host}", which is not running. Start it first: ph run ${ref.host} (or run a compound that includes it).`;
2512
+ const info = producers.get(ref.host);
2513
+ const schema = info && !("error" in info) ? info.runner.outputsSchema : void 0;
2514
+ const withSchema = schema !== void 0 && schema !== null ? { schema } : {};
2515
+ if (ref.member === void 0 && info && !("error" in info)) {
2516
+ const probe = probeRun(projectRoot, info.name, projectName);
2517
+ if (probe.status === "live" && probe.record.outputs) return {
2518
+ status: "available",
2519
+ outputs: probe.record.outputs,
2520
+ ...withSchema
2521
+ };
2522
+ }
2523
+ const members = listRunRecords(projectRoot).filter((record) => record.members !== void 0 && record.projectName === projectName && isPidAlive(record.pid)).flatMap((record) => Object.entries(record.members ?? {}).filter(([key, member]) => member.host === ref.host && (ref.member === void 0 || key === ref.member)).map(([key, member]) => ({
2524
+ compound: record.host,
2525
+ key,
2526
+ member
2527
+ })));
2528
+ if (members.length === 1) return {
2529
+ status: "available",
2530
+ outputs: members[0].member.outputs,
2531
+ ...withSchema
2532
+ };
2533
+ if (members.length > 1) return {
2534
+ status: "unavailable",
2535
+ message: `${consumer} needs outputs from host "${ref.host}", which runs as ${members.map((m) => `member "${m.key}" of "${m.compound}"`).join(" and ")}; stop all but one, or run ${ref.host} on its own.`
2536
+ };
2537
+ return {
2538
+ status: "unavailable",
2539
+ message: notRunning
2540
+ };
2541
+ } };
2542
+ }
2543
+ /** The resolving process's `$env` inputs: its environment plus the
2544
+ * always-resolvable built-ins (`userData` honours PH_USER_DATA_DIR). */
2545
+ function processResolveEnv(projectRoot, env = process.env) {
2546
+ return {
2547
+ env,
2548
+ builtins: {
2549
+ userData: defaultUserDataDir(projectRoot, env),
2550
+ projectRoot: path.resolve(projectRoot)
2551
+ }
2552
+ };
2553
+ }
2554
+ //#endregion
2555
+ //#region src/resolve/sources.ts
2556
+ /**
2557
+ * The compound output source: a member's `$output` tokens read the live
2558
+ * `RunnerHandle.outputs` of the members started before it. `schemas` (member
2559
+ * key → its runner's `outputsSchema`) lets an absent optional output field
2560
+ * omit the consuming property. Pure (the run-record source for standalone
2561
+ * hosts is node: ./node.ts).
2562
+ */
2563
+ function compoundOutputSource(members, started, compound, schemas) {
2564
+ return { lookup(ref) {
2565
+ const target = memberForRef(ref, members);
2566
+ if ("error" in target) return {
2567
+ status: "unavailable",
2568
+ message: `compound "${compound}": a token ${target.error}`
2569
+ };
2570
+ if (!started.has(target.key)) return {
2571
+ status: "unavailable",
2572
+ message: `compound "${compound}": member "${target.key}" (host "${ref.host}") has not started yet; a producer must start before its consumers.`
2573
+ };
2574
+ const schema = schemas?.get(target.key);
2575
+ return {
2576
+ status: "available",
2577
+ outputs: started.get(target.key),
2578
+ ...schema !== void 0 ? { schema } : {}
2579
+ };
2580
+ } };
2581
+ }
2582
+ //#endregion
2583
+ //#region src/runner-handle.ts
2584
+ /** The data half of a handle, validated by the compound. `ready`/`shutdown`
2585
+ * are functions and promises, so they are checked as TS fields, not here. */
2586
+ const runnerHandleSchema = z.looseObject({ outputs: z.record(z.string(), z.unknown()).optional() });
2587
+ function isRecord(value) {
2588
+ return typeof value === "object" && value !== null;
2589
+ }
2590
+ function isPromiseLike(value) {
2591
+ return isRecord(value) && typeof value.then === "function";
2592
+ }
2593
+ function isCallable(value) {
2594
+ return typeof value === "function";
2595
+ }
2596
+ /** Normalize what a verb returned. `undefined` (a self-sustaining bridge)
2597
+ * is an empty handle; anything else must match runnerHandleSchema. */
2598
+ function toStartedHandle(value, where) {
2599
+ if (value === void 0 || value === null) return { outputs: {} };
2600
+ const parsed = runnerHandleSchema.safeParse(value);
2601
+ if (!parsed.success) throw new Error(`${where} returned an invalid runner handle:\n${z.prettifyError(parsed.error)}`);
2602
+ const live = isRecord(value) ? value : {};
2603
+ const shutdown = live.shutdown;
2604
+ return {
2605
+ ...parsed.data,
2606
+ outputs: parsed.data.outputs ?? {},
2607
+ ...isPromiseLike(live.ready) ? { ready: live.ready } : {},
2608
+ ...isCallable(shutdown) ? { shutdown: () => shutdown.call(value) } : {}
2609
+ };
2610
+ }
2611
+ //#endregion
2612
+ //#region src/compound.ts
2613
+ /** Build the member host object the member runner sees: the member's own
2614
+ * host.js with the wrapper applied. A wrapper SECTION is a FULL STATEMENT —
2615
+ * `reactor` and `config`, when present on the wrapper, replace the member's
2616
+ * wholesale; `runner` key-merges (wrappers override port, host, plugins…). */
2617
+ async function memberDraft(projectRoot, member) {
2618
+ const base = (await loadHost(projectRoot, member.host)).host;
2619
+ const reactor = member.reactor ?? base.reactor;
2620
+ const config = member.config ?? base.config;
2621
+ return {
2622
+ ...base,
2623
+ runner: {
2624
+ ...base.runner,
2625
+ ...member.runner
2626
+ },
2627
+ ...config !== void 0 ? { config } : {},
2628
+ ...reactor !== void 0 ? { reactor } : {}
2629
+ };
2630
+ }
2631
+ /** Whether a member receives the compound's `cspRegistrySync` wiring (as
2632
+ * `runner.cspRegistrySync`): its runner declares that option (any specifier
2633
+ * that reaches the Connect runner), or it names the Connect runner. A
2634
+ * member's role is its runner, not its folder. */
2635
+ function takesCspRegistrySync(m) {
2636
+ return m.specifier === "@powerhousedao/ph-cli/runners/connect" || declaresKey(m.runner.hostSchema, ["runner"], "cspRegistrySync");
2637
+ }
2638
+ /** At compound verb "run" each member runs its own (merged) defaultVerb —
2639
+ * what lets a desktop compound pair a switchboard at `run` with a connect at
2640
+ * `serve`. An explicit forwarded verb stays uniform across members. */
2641
+ function memberVerbOf(compoundVerb, runner) {
2642
+ return compoundVerb === "run" ? runner.defaultVerb ?? "run" : compoundVerb;
2643
+ }
2644
+ async function runCompound(hostInput, ctx, options) {
2645
+ const compoundFile = `hosts/${hostInput.name}`;
2646
+ const removed = findRemovedForms(hostInput);
2647
+ if (removed.length > 0) throw new RunnerError(`${compoundFile}: removed form:\n${removed.map((r) => ` - ${r.path}: ${r.message}`).join("\n")}`);
2648
+ const parsed = declaredGenericCompoundHostSchema.safeParse(hostInput);
2649
+ if (!parsed.success) throw new Error(`${compoundFile}: invalid compound host:\n${z.prettifyError(parsed.error)}`);
2650
+ const host = parsed.data;
2651
+ const projectRoot = ctx.projectRoot;
2652
+ const wiring = host.config ?? {};
2653
+ const verb = ctx.verb;
2654
+ const oneShotCompound = ONE_SHOT_VERBS.has(verb);
2655
+ const keepsRecord = wiring.runtimeRecord !== false && !oneShotCompound;
2656
+ const probe = oneShotCompound ? void 0 : probeRun(projectRoot, host.name, options.projectName);
2657
+ if (probe?.status === "live") throw new Error(`${host.name} is already running for this project (pid ${probe.record.pid}). Stop it before starting another.`);
2658
+ if (probe?.status === "foreign") throw new Error(`.ph/run/${host.name}.json describes a live "${probe.record.projectName}", but this project is "${options.projectName}". Refusing to start a second instance.`);
2659
+ const prepared = await prepareMembers(projectRoot, host.children);
2660
+ const plan = planCompound(prepared.map((m) => ({
2661
+ key: m.key,
2662
+ host: m.member.host,
2663
+ refs: outputSitesOf(m.draft).map(({ ref, path }) => ({
2664
+ ref,
2665
+ path
2666
+ }))
2667
+ })), wiring.startOrder);
2668
+ const byKey = new Map(prepared.map((m) => [m.key, m]));
2669
+ const members = prepared.map((m) => ({
2670
+ key: m.key,
2671
+ host: m.member.host
2672
+ }));
2673
+ for (const m of prepared) validateDeclaredHost(m.runner, m.specifier, m.draft, m.file, { outputsSchemaOf: (ref) => {
2674
+ const target = memberForRef(ref, members);
2675
+ if ("error" in target) return { error: target.error };
2676
+ const producer = byKey.get(target.key);
2677
+ return producer ? runnerOutputsSchema(producer.runner, producer.specifier, `member "${target.key}"`) : { error: `names member "${target.key}", which was not prepared.` };
2678
+ } });
2679
+ if (wiring.cspRegistrySync && !prepared.some(takesCspRegistrySync)) console.warn(`${compoundFile}: config.cspRegistrySync is set, but no member's runner declares runner.cspRegistrySync (members run: ${prepared.map((m) => m.specifier).join(", ")}); the baked Connect CSP is not patched for the runtime registry.`);
2680
+ const started = [];
2681
+ const liveOutputs = /* @__PURE__ */ new Map();
2682
+ const outputs = compoundOutputSource(members, liveOutputs, host.name, new Map(prepared.map((m) => [m.key, m.runner.outputsSchema])));
2683
+ const resolveEnv = processResolveEnv(projectRoot, ctx.env);
2684
+ let stopping;
2685
+ const shutdown = () => stopping ??= (async () => {
2686
+ for (const m of [...started].reverse()) try {
2687
+ await m.handle.shutdown?.();
2688
+ } catch {}
2689
+ if (keepsRecord) clearRunRecord(projectRoot, host.name);
2690
+ })();
2691
+ try {
2692
+ for (const name of plan.order) {
2693
+ const m = byKey.get(name);
2694
+ if (!m) continue;
2695
+ const memberVerb = memberVerbOf(verb, m.draft.runner);
2696
+ const oneShot = ONE_SHOT_VERBS.has(memberVerb);
2697
+ const resolved = oneShot ? substituteBuiltinEnv(m.draft, resolveEnv.builtins ?? {}) : resolveHostOutputs(m.draft, {
2698
+ outputs,
2699
+ ...resolveEnv,
2700
+ where: m.file
2701
+ });
2702
+ if (wiring.cspRegistrySync && takesCspRegistrySync(m)) resolved.runner = {
2703
+ ...resolved.runner,
2704
+ cspRegistrySync: true
2705
+ };
2706
+ const validated = validateHost(m.runner, m.specifier, resolved, m.file, oneShot ? { tokens: "allow" } : {});
2707
+ const fn = getVerb(m.runner, m.specifier, memberVerb);
2708
+ const where = `${name} (${m.specifier} ${memberVerb})`;
2709
+ const handle = toStartedHandle(await fn(validated, {
2710
+ projectRoot,
2711
+ env: ctx.env,
2712
+ verb: memberVerb,
2713
+ parent: {
2714
+ host: host.name,
2715
+ verb
2716
+ }
2717
+ }), where);
2718
+ started.push({
2719
+ name,
2720
+ member: m.member,
2721
+ specifier: m.specifier,
2722
+ kind: m.runner.kind,
2723
+ verb: memberVerb,
2724
+ handle,
2725
+ outputs: handle.outputs
2726
+ });
2727
+ if (handle.ready) await handle.ready;
2728
+ let memberOutputs = handle.outputs;
2729
+ if (!oneShot && isSchemaLike(m.runner.outputsSchema)) {
2730
+ const checked = m.runner.outputsSchema.safeParse(handle.outputs);
2731
+ if (!checked.success) throw new Error(`${where} reported outputs that fail its outputsSchema:\n${checked.error.issues.map((i) => ` - ${i.path.map(String).join(".") || "<root>"}: ${i.message}`).join("\n")}`);
2732
+ if (!isPlainObject(checked.data)) throw new Error(`${where}: its outputsSchema parsed the outputs to ${JSON.stringify(checked.data)}, not an object.`);
2733
+ memberOutputs = checked.data;
2734
+ }
2735
+ started[started.length - 1].outputs = memberOutputs;
2736
+ liveOutputs.set(name, memberOutputs);
2737
+ }
2738
+ } catch (error) {
2739
+ await shutdown();
2740
+ throw error;
2741
+ }
2742
+ if (keepsRecord) {
2743
+ const recordMembers = {};
2744
+ for (const m of started) recordMembers[m.name] = {
2745
+ host: m.member.host,
2746
+ runnerModule: m.specifier,
2747
+ kind: m.kind,
2748
+ verb: m.verb,
2749
+ outputs: m.outputs
2750
+ };
2751
+ writeRunRecord(projectRoot, {
2752
+ version: 2,
2753
+ host: host.name,
2754
+ projectName: options.projectName,
2755
+ kind: "compound",
2756
+ verb,
2757
+ pid: process.pid,
2758
+ startedAt: (/* @__PURE__ */ new Date()).toISOString(),
2759
+ members: recordMembers,
2760
+ ...options.recordExtra ? { extra: options.recordExtra } : {}
2761
+ });
2762
+ }
2763
+ const exit = options.exit ?? ((code) => process.exit(code));
2764
+ let signalled;
2765
+ const handleSignal = (signal) => {
2766
+ if (signalled) return signalled;
2767
+ const code = signal === "SIGINT" ? 130 : 143;
2768
+ signalled = shutdown().finally(() => exit(code));
2769
+ return signalled;
2770
+ };
2771
+ if (options.installSignalHandlers !== false) {
2772
+ process.on("exit", () => {
2773
+ if (keepsRecord) clearRunRecord(projectRoot, host.name);
2774
+ });
2775
+ process.on("SIGINT", () => void handleSignal("SIGINT"));
2776
+ process.on("SIGTERM", () => void handleSignal("SIGTERM"));
2777
+ }
2778
+ return {
2779
+ started,
2780
+ shutdown,
2781
+ handleSignal
2782
+ };
2783
+ }
2784
+ /** Load every member's draft and runner, in declaration order. */
2785
+ async function prepareMembers(projectRoot, children) {
2786
+ const out = [];
2787
+ for (const [key, member] of Object.entries(children)) {
2788
+ const draft = await memberDraft(projectRoot, member);
2789
+ const specifier = draft.runner.module;
2790
+ out.push({
2791
+ key,
2792
+ member,
2793
+ draft,
2794
+ specifier,
2795
+ runner: await resolveRunnerModule(projectRoot, specifier),
2796
+ file: `hosts/${member.host}/host.js`
2797
+ });
2798
+ }
2799
+ return out;
2800
+ }
2801
+ //#endregion
2802
+ export { envSitesOf as $, PluginError as $t, probeHostsFolder as A, driveDeclarationSchema as At, resolveRunnerModule as B, isToken as Bt, computeOutputsHash as C, reactorHostSchema as Ct, lintHostImports as D, runnerBaseSchema as Dt, lintHostImportGraph as E, refineStartOrder as Et, ONE_SHOT_VERBS as F, concatTokenSchema as Ft, resolveHostOutputs as G, ref as Gt, validateHost as H, keyTokenSchema as Ht, RunnerError as I, envTokenSchema as It, planCompound as J, tokenable as Jt, PlanError as K, tokenKeyOf as Kt, getVerb as L, envTokenable as Lt, scanHostImports as M, projectDriveIdWith as Mt, stripComments as N, TOKEN_ESCAPE_KEY as Nt, lintOutputsFile as O, runnerKindSchema as Ot, CONNECT_RUNNER as P, TOKEN_KEYS as Pt, checkTokenSites as Q, resolvePluginContributions as Qt, isSchemaLike as R, findToken as Rt, OUTPUTS_FILE as S, reactorBackendSchema as St, findNonStaticValue as T, reactorSchema as Tt, TokenResolutionError as U, mapTokenSchema as Ut, validateDeclaredHost as V, itemTokenSchema as Vt, describeMapElements as W, outputTokenSchema as Wt, findRemovedForms as X, findDeadConnectConfig as Xt, substituteBuiltinEnv as Y, CONNECT_PLUGIN_OWNED_SLICES as Yt, checkOutputPaths as Z, resolveHostPlugins as Zt, readRunRecord as _, emittedHostSchemas as _t, loadProducers as a, pluginEntryObjectSchema as an, describeToken as at, runRecordSchema as b, profileSchema as bt, runRecordOutputSource as c, resolveOrder as cn, unwrapEscapes as ct, resolveUserDataPlaceholders as d, runProvideHook as dn, compoundHostSchema as dt, entryActiveForVerb as en, outputRefsOf as et, clearRunRecord as f, runTransformHook as fn, compoundWiringSchema as ft, readProjectName as g, emitHostJsonSchema as gt, probeRun as h, defineHostSchemas as ht, compoundOutputSource as i, normalizePluginEntry as in, collectTokenSites as it, readOutputsFileHash as j, drivesSchema as jt, loadHost as k, buildDriveDeclarationSchema as kt, runnerOutputsSchema as l, runObserveHook as ln, childWrapperSchema as lt, listRunRecords as m, declaredHostSchemas as mt, runnerHandleSchema as n, mergeContributions as nn, refKey as nt, processResolveEnv as o, pluginEntrySchema as on, formatPath as ot, isPidAlive as p, declaredGenericCompoundHostSchema as pt, memberForRef as q, tokenSchema as qt, toStartedHandle as r, normalizePluginEntries as rn, schemaAtPath as rt, producerOutputsSchemas as s, registerHostType as sn, renderTokens as st, runCompound as t, hostTypeSatisfies as tn, outputSitesOf as tt, defaultUserDataDir as u, runObserveHookSequential as un, childrenSchema as ut, writeRunRecord as v, genericCompoundHostSchema as vt, describeHostOutputs as w, reactorProtocolSchema as wt, HostLoadError as x, reactorBackendKindSchema as xt, runRecordMemberSchema as y, makeHostSchemas as yt, listVerbs as z, forbidRef as zt };
2803
+
2804
+ //# sourceMappingURL=compound-B6RZMA0Y.mjs.map