@powerhousedao/host-core 6.2.3-dev.100

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs ADDED
@@ -0,0 +1,1181 @@
1
+ import { $ as TokenResolutionError, $t as driveDeclarationSchema, A as computeOutputsHash, An as registerHostType, At as compoundWiringSchema, B as stripComments, Bt as originOrUrlSchema, C as readProjectName, Cn as entryActiveForVerb, Ct as CONNECT_PRIMARY_MESSAGE, D as runRecordSchema, Dn as normalizePluginEntry, Dt as childWrapperSchema, E as runRecordMemberSchema, En as normalizePluginEntries, Et as HOST_NAME_PATTERN, F as lintOutputsFile, Fn as runTransformHook, Ft as emitHostJsonSchema, G as hostSchemaIssues, Gt as reactorHostSchema, H as ONE_SHOT_VERBS, Ht as profileSchema, I as loadHost, It as emittedHostSchemas, J as knownVerbIssues, Jt as refineConnectReactor, K as isSchemaLike, Kt as reactorProtocolSchema, L as probeHostsFolder, Lt as genericCompoundHostSchema, M as findNonStaticValue, Mn as runObserveHook, Mt as declaredGenericCompoundHostSchema, N as lintHostImportGraph, Nn as runObserveHookSequential, Nt as declaredHostSchemas, O as HostLoadError, On as pluginEntryObjectSchema, Ot as childrenSchema, P as lintHostImports, Pn as runProvideHook, Pt as defineHostSchemas, Q as validateHost, Qt as buildDriveDeclarationSchema, R as readOutputsFileHash, Rt as hostNameSchema, S as probeRun, Sn as PluginError, St as unwrapEscapes, T as writeRunRecord, Tn as mergeContributions, Tt as HOST_NAME_MESSAGE, U as RunnerError, Ut as reactorBackendKindSchema, V as CONNECT_RUNNER, Vt as placementKeyIssues, W as getVerb, Wt as reactorBackendSchema, X as resolveRunnerModule, Xt as runnerBaseSchema, Y as listVerbs, Yt as refineStartOrder, Z as validateDeclaredHost, Zt as runnerKindSchema, _ as resolveUserDataPlaceholders, _n as tokenable, _t as collectTokenSites, an as envTokenSchema, at as planCompound, b as isPidAlive, bn as resolveHostPlugins, bt as isPlainObject, c as toStartedHandle, cn as forbidRef, ct as substituteBuiltinEnv, d as loadProducers, dn as keyTokenSchema, dt as checkTokenSites, en as drivesSchema, et as describeMapElements, f as processResolveEnv, fn as mapTokenSchema, ft as envSitesOf, g as defaultUserDataDir, gn as tokenSchema, gt as schemaAtPath, h as runnerOutputsSchema, hn as tokenKeyOf, ht as refKey, i as runCompound, in as concatTokenSchema, it as memberForRef, j as describeHostOutputs, jn as resolveOrder, jt as connectReactorIssues, k as OUTPUTS_FILE, kn as pluginEntrySchema, kt as compoundHostSchema, l as compoundOutputSource, ln as isToken, lt as findRemovedForms, m as runRecordOutputSource, mn as ref, mt as outputSitesOf, n as memberVerbOf, nn as TOKEN_ESCAPE_KEY, nt as unsetEnvMessage, o as takesCspRegistrySync, on as envTokenable, ot as BUILTIN_ENV_NAMES, p as producerOutputsSchemas, pn as outputTokenSchema, pt as outputRefsOf, q as kindShapeIssues, qt as reactorSchema, r as prepareMember, rn as TOKEN_KEYS, rt as PlanError, s as runnerHandleSchema, sn as findToken, st as isBuiltinEnvName, t as compoundStartVerb, tn as projectDriveIdWith, tt as resolveHostOutputs, u as OUTPUT_DATA_DIRS_ENV, un as itemTokenSchema, ut as checkOutputPaths, v as applyChildWrapper, vn as CONNECT_PLUGIN_OWNED_SLICES, vt as describeToken, w as readRunRecord, wn as hostTypeSatisfies, wt as HOST_NAME_MAX_LENGTH, x as listRunRecords, xn as resolvePluginContributions, xt as renderTokens, y as clearRunRecord, yn as findDeadConnectConfig, yt as formatPath, z as scanHostImports, zt as makeHostSchemas } from "./compound-DO_mvh0O.mjs";
2
+ import { createRequire } from "node:module";
3
+ import crypto from "node:crypto";
4
+ import fs from "node:fs";
5
+ import path from "node:path";
6
+ import { pathToFileURL } from "node:url";
7
+ import { z } from "zod";
8
+ import { driveAddressMessage, switchboardOfDrive, switchboardOfDrive as switchboardOfDrive$1 } from "@powerhousedao/shared/host-tokens";
9
+ import { ORIGIN_PLACEHOLDER, SWITCHBOARD_PROXY_PATHS, isHtmlNavigation, isOriginPlaceholderUrl, isSwitchboardProxyPath, resolveOriginPlaceholders, toOriginPlaceholder, withOriginPlaceholders } from "@powerhousedao/shared/connect/origin-placeholder";
10
+ import { spawn } from "node:child_process";
11
+ import { DEFAULT_CONNECT_STUDIO_PORT, DEFAULT_SWITCHBOARD_PORT } from "@powerhousedao/shared/clis/constants";
12
+ import { DRIVE_ICON_MAX_BYTES, resolveImageRef } from "@powerhousedao/shared/connect/image-ref";
13
+ //#region src/spawn-host.ts
14
+ /** The tail line before which a timed-out or aborted run's output is its own. */
15
+ const SPAWN_STOPPING_NOTE = "spawnHost: stopping it";
16
+ var SpawnHostError = class extends Error {
17
+ phase;
18
+ outputTail;
19
+ exit;
20
+ constructor(message, phase, outputTail, exit) {
21
+ super(outputTail ? `${message}\n--- output tail ---\n${outputTail}` : message);
22
+ this.phase = phase;
23
+ this.outputTail = outputTail;
24
+ this.exit = exit;
25
+ this.name = "SpawnHostError";
26
+ }
27
+ };
28
+ const READY_TIMEOUT_MS = 12e4;
29
+ const STOP_TIMEOUT_MS = 3e4;
30
+ const POLL_MS = 100;
31
+ const CLOSE_WAIT_MS = 1e3;
32
+ const BASE_ENV_KEYS = [
33
+ "PATH",
34
+ "HOME",
35
+ "TMPDIR"
36
+ ];
37
+ const WIN32_ENV_KEYS = [
38
+ "SystemRoot",
39
+ "USERPROFILE",
40
+ "APPDATA",
41
+ "LOCALAPPDATA",
42
+ "TEMP",
43
+ "TMP",
44
+ "ComSpec",
45
+ "PATHEXT"
46
+ ];
47
+ /** The child's whole env: no other `process.env` key reaches it. */
48
+ function childEnv(dataDir, env = {}) {
49
+ if ("PH_USER_DATA_DIR" in env) throw new Error("spawnHost: set the data dir with `dataDir`, not env.PH_USER_DATA_DIR.");
50
+ const keys = process.platform === "win32" ? [...BASE_ENV_KEYS, ...WIN32_ENV_KEYS] : BASE_ENV_KEYS;
51
+ const base = {};
52
+ for (const key of keys) {
53
+ const value = process.env[key];
54
+ if (value !== void 0) base[key] = value;
55
+ }
56
+ return {
57
+ ...base,
58
+ FEATURE_UNIFORM_RUNNERS_ENABLED: "1",
59
+ PH_USER_DATA_DIR: dataDir,
60
+ PH_NO_TELEMETRY: "1",
61
+ PH_NO_DOTENV: "1",
62
+ ...env
63
+ };
64
+ }
65
+ function resolvePhCliEntry(projectRoot) {
66
+ const pkgPath = createRequire(pathToFileURL(path.join(projectRoot, "package.json")).href).resolve("@powerhousedao/ph-cli/package.json");
67
+ return path.join(path.dirname(pkgPath), "dist", "cli.mjs");
68
+ }
69
+ /** Readiness waits for a record; refuse a host/verb that writes none. */
70
+ async function assertWritesRecord(projectRoot, host, verb) {
71
+ if (verb !== void 0 && ONE_SHOT_VERBS.has(verb)) throw new Error(`spawnHost: "${verb}" is a one-shot verb; it writes no run record to wait for.`);
72
+ const loaded = await loadHost(projectRoot, host);
73
+ const specifier = loaded.host.runner.module;
74
+ const runner = await resolveRunnerModule(projectRoot, specifier);
75
+ if (runner.kind === "compound") {
76
+ if (loaded.host.config?.runtimeRecord === false) throw new Error(`spawnHost: hosts/${host} sets config.runtimeRecord: false, so it writes no run record to wait for.`);
77
+ return;
78
+ }
79
+ if (!isSchemaLike(runner.outputsSchema)) throw new Error(`spawnHost: hosts/${host} runs "${specifier}", which exports no outputsSchema, so it writes no run record to wait for.`);
80
+ }
81
+ const sleep = (ms) => new Promise((resolve) => {
82
+ setTimeout(resolve, ms).unref();
83
+ });
84
+ const live = /* @__PURE__ */ new Set();
85
+ let exitHookInstalled = false;
86
+ function track(child) {
87
+ live.add(child);
88
+ child.once("exit", () => live.delete(child));
89
+ if (exitHookInstalled) return;
90
+ exitHookInstalled = true;
91
+ process.once("exit", () => {
92
+ for (const running of live) running.kill("SIGTERM");
93
+ });
94
+ }
95
+ /**
96
+ * `ph run <host> [verb]` as a child; ready when its run record appears.
97
+ *
98
+ * The child shares this process's group, so a terminal Ctrl-C reaches both.
99
+ * It runs the project's own ph-cli: one older than PH_NO_DOTENV reads the
100
+ * project's `.env` anyway.
101
+ */
102
+ async function spawnHost(options) {
103
+ const projectRoot = path.resolve(options.projectRoot);
104
+ const dataDir = path.resolve(options.dataDir);
105
+ const env = childEnv(dataDir, options.env);
106
+ const readerEnv = { PH_USER_DATA_DIR: dataDir };
107
+ const readyTimeoutMs = options.readyTimeoutMs ?? READY_TIMEOUT_MS;
108
+ const stopTimeoutMs = options.stopTimeoutMs ?? STOP_TIMEOUT_MS;
109
+ const { signal } = options;
110
+ if (signal?.aborted) throw new SpawnHostError("spawnHost: aborted before start.", "aborted", "");
111
+ await assertWritesRecord(projectRoot, options.host, options.verb);
112
+ const cli = options.cli ?? resolvePhCliEntry(projectRoot);
113
+ fs.mkdirSync(dataDir, { recursive: true });
114
+ const log = options.logFile ? fs.createWriteStream(options.logFile, { flags: "a" }) : void 0;
115
+ let tail = "";
116
+ log?.on("error", (error) => {
117
+ tail = (tail + `logFile: ${error.message}\n`).slice(-8192);
118
+ });
119
+ const args = [
120
+ cli,
121
+ "run",
122
+ options.host
123
+ ];
124
+ if (options.verb !== void 0) args.push(options.verb);
125
+ const child = spawn(process.execPath, args, {
126
+ cwd: projectRoot,
127
+ env,
128
+ stdio: [
129
+ "ignore",
130
+ "pipe",
131
+ "pipe"
132
+ ],
133
+ windowsHide: true
134
+ });
135
+ track(child);
136
+ const onChunk = (stream) => (chunk) => {
137
+ tail = (tail + chunk).slice(-8192);
138
+ log?.write(chunk);
139
+ try {
140
+ options.onOutput?.(stream, chunk);
141
+ } catch (error) {
142
+ const message = error instanceof Error ? error.message : String(error);
143
+ tail = (tail + `onOutput: ${message}\n`).slice(-8192);
144
+ }
145
+ };
146
+ child.stdout.setEncoding("utf8").on("data", onChunk("stdout"));
147
+ child.stderr.setEncoding("utf8").on("data", onChunk("stderr"));
148
+ let forced = false;
149
+ let exit;
150
+ const exited = new Promise((resolve) => {
151
+ const done = (code, sig) => {
152
+ if (exit) return;
153
+ exit = {
154
+ code,
155
+ signal: sig,
156
+ forced
157
+ };
158
+ signal?.removeEventListener("abort", onAbort);
159
+ resolve(exit);
160
+ };
161
+ child.once("exit", done);
162
+ child.once("error", (error) => {
163
+ tail = (tail + `${error.message}\n`).slice(-8192);
164
+ if (child.pid === void 0) done(null, null);
165
+ });
166
+ });
167
+ const closed = new Promise((resolve) => {
168
+ child.once("close", () => {
169
+ log?.end();
170
+ resolve();
171
+ });
172
+ });
173
+ const pid = child.pid;
174
+ const ownRecords = () => pid === void 0 ? [] : listRunRecords(projectRoot, readerEnv).filter((r) => r.pid === pid);
175
+ const kill = (sig) => {
176
+ if (pid === void 0) return;
177
+ try {
178
+ process.kill(pid, sig);
179
+ } catch {}
180
+ };
181
+ const clearOwnRecords = () => {
182
+ for (const record of ownRecords()) clearRunRecord(projectRoot, record.host, readerEnv);
183
+ };
184
+ let stopping;
185
+ const stop = () => {
186
+ stopping ??= (async () => {
187
+ if (!exit) {
188
+ kill("SIGTERM");
189
+ let timer;
190
+ const timedOut = await Promise.race([exited.then(() => false), new Promise((resolve) => {
191
+ timer = setTimeout(() => resolve(true), stopTimeoutMs);
192
+ })]);
193
+ clearTimeout(timer);
194
+ if (timedOut) {
195
+ forced = true;
196
+ kill("SIGKILL");
197
+ }
198
+ }
199
+ const result = await exited;
200
+ clearOwnRecords();
201
+ return result;
202
+ })();
203
+ return stopping;
204
+ };
205
+ function onAbort() {
206
+ stop();
207
+ }
208
+ signal?.addEventListener("abort", onAbort, { once: true });
209
+ const deadline = Date.now() + readyTimeoutMs;
210
+ for (;;) {
211
+ const aborted = signal?.aborted ?? false;
212
+ if (exit && !aborted) {
213
+ clearOwnRecords();
214
+ let timer;
215
+ await Promise.race([closed, new Promise((resolve) => {
216
+ timer = setTimeout(resolve, CLOSE_WAIT_MS);
217
+ })]);
218
+ clearTimeout(timer);
219
+ const how = exit.signal !== null ? `signal ${exit.signal}` : `code ${exit.code}`;
220
+ throw new SpawnHostError(`spawnHost: ph run ${options.host} exited (${how}) before writing its run record.`, "exited", tail, exit);
221
+ }
222
+ const record = aborted ? void 0 : ownRecords().at(0);
223
+ if (record) return {
224
+ pid: record.pid,
225
+ dataDir,
226
+ record,
227
+ outputs: record.outputs,
228
+ members: record.members,
229
+ exited,
230
+ stop
231
+ };
232
+ if (aborted || Date.now() >= deadline) {
233
+ const phase = aborted ? "aborted" : "timeout";
234
+ const ended = tail === "" || tail.endsWith("\n") ? "" : "\n";
235
+ const ran = `${tail}${ended}${SPAWN_STOPPING_NOTE}\n`;
236
+ tail = "";
237
+ const stopped = await stop();
238
+ let timer;
239
+ await Promise.race([closed, new Promise((resolve) => {
240
+ timer = setTimeout(resolve, CLOSE_WAIT_MS);
241
+ })]);
242
+ clearTimeout(timer);
243
+ throw new SpawnHostError(phase === "aborted" ? `spawnHost: aborted before ph run ${options.host} was ready.` : `spawnHost: ph run ${options.host} wrote no run record within ${readyTimeoutMs} ms.`, phase, ran + tail, stopped);
244
+ }
245
+ await Promise.race([sleep(POLL_MS), exited]);
246
+ }
247
+ }
248
+ //#endregion
249
+ //#region src/check-host.ts
250
+ /** The `ph run` pipeline up to the verb, collecting every issue; starts nothing. */
251
+ async function checkHost(name, options) {
252
+ const result = {
253
+ issues: [],
254
+ warnings: [],
255
+ deferred: []
256
+ };
257
+ const file = `hosts/${name}/host.js`;
258
+ const issue = issuer(result, file);
259
+ const verb = options.verb ?? "run";
260
+ let host;
261
+ let runner;
262
+ try {
263
+ host = (await loadHost(options.projectRoot, name)).host;
264
+ runner = await resolveRunnerModule(options.projectRoot, host.runner.module);
265
+ } catch (error) {
266
+ issue("load", "", error);
267
+ return result;
268
+ }
269
+ const specifier = host.runner.module;
270
+ if (runner.kind === "compound") {
271
+ await checkCompound(result, options, {
272
+ file,
273
+ host,
274
+ runner,
275
+ specifier,
276
+ verb
277
+ });
278
+ return result;
279
+ }
280
+ const refs = outputRefsOf(host);
281
+ const producers = await loadProducers(options.projectRoot, refs);
282
+ await checkSubject(result, options, {
283
+ file,
284
+ host,
285
+ runner,
286
+ specifier,
287
+ verb,
288
+ outputsSchemaOf: producerOutputsSchemas(producers),
289
+ self: "outputs"
290
+ });
291
+ return result;
292
+ }
293
+ /** Declared validation; returns whether its tokens and its shape passed. */
294
+ function checkDeclared(result, subject, outputsSchemaOf) {
295
+ const issue = issuer(result, subject.file);
296
+ const { host, runner, specifier } = subject;
297
+ try {
298
+ getVerb(runner, specifier, subject.verb);
299
+ } catch (error) {
300
+ issue("declared", "", error);
301
+ }
302
+ const tokenIssues = [
303
+ ...findRemovedForms(host),
304
+ ...checkTokenSites(host),
305
+ ...outputsSchemaOf ? checkOutputPaths(host, outputsSchemaOf) : []
306
+ ];
307
+ for (const i of tokenIssues) issue("declared", i);
308
+ const shapeIssues = runner.declaredHostSchema ? schemaIssuesOf(runner, runner.declaredHostSchema, specifier, host, true) : kindShapeIssues(runner.kind, specifier, host);
309
+ for (const i of shapeIssues) issue("declared", i);
310
+ return {
311
+ tokens: tokenIssues.length === 0,
312
+ shape: shapeIssues.length === 0
313
+ };
314
+ }
315
+ function schemaIssuesOf(runner, schema, specifier, host, allowTokens) {
316
+ const checked = hostSchemaIssues(runner, schema, specifier, host, { tokens: allowTokens ? "allow" : "forbid" });
317
+ return [...checked.issues, ...checked.schemaIssues ?? []];
318
+ }
319
+ async function checkSubject(result, options, subject) {
320
+ const issue = issuer(result, subject.file);
321
+ const { runner, specifier, file } = subject;
322
+ const declared = checkDeclared(result, subject, subject.outputsSchemaOf);
323
+ const resolveEnv = processResolveEnv(options.projectRoot, options.env);
324
+ const patch = subject.patch ?? ((host) => host);
325
+ if (ONE_SHOT_VERBS.has(subject.verb)) {
326
+ if (!declared.tokens || !declared.shape) return;
327
+ const host = patch(substituteBuiltinEnv(subject.host, resolveEnv.builtins ?? {}));
328
+ const schema = runner.declaredHostSchema ?? runner.hostSchema;
329
+ for (const i of schemaIssuesOf(runner, schema, specifier, host, true)) issue("resolved", i);
330
+ return;
331
+ }
332
+ const unset = envSitesOf(subject.host).filter((site) => !site.optional && !isBuiltinEnvName(site.name) && options.env[site.name] === void 0);
333
+ for (const site of unset) issue("resolve", {
334
+ path: site.path,
335
+ message: unsetEnvMessage(site.name)
336
+ });
337
+ if (!declared.tokens || unset.length > 0) return;
338
+ let resolved;
339
+ let deferred = [];
340
+ try {
341
+ if (options.outputs) resolved = resolveHostOutputs(subject.host, {
342
+ outputs: options.outputs,
343
+ ...resolveEnv
344
+ });
345
+ else {
346
+ const partial = resolveHostOutputs(subject.host, resolveEnv, { deferSelf: subject.self });
347
+ resolved = partial.host;
348
+ deferred = partial.deferred;
349
+ }
350
+ } catch (error) {
351
+ if (error instanceof TokenResolutionError && error.detail) issue("resolve", {
352
+ path: error.detail.path,
353
+ message: error.detail.reason
354
+ });
355
+ else issue("resolve", "", error);
356
+ return;
357
+ }
358
+ result.deferred.push(...deferred.map((d) => ({
359
+ ...d,
360
+ file
361
+ })));
362
+ if (!declared.shape) return;
363
+ const allow = deferred.length > 0;
364
+ const schema = allow ? runner.declaredHostSchema ?? runner.hostSchema : runner.hostSchema;
365
+ const checked = hostSchemaIssues(runner, schema, specifier, patch(resolved), { tokens: allow ? "allow" : "forbid" });
366
+ const resolvedIssues = [...checked.issues, ...checked.schemaIssues ?? []];
367
+ for (const i of resolvedIssues) issue("resolved", i);
368
+ if (resolvedIssues.length > 0 || !runner.checkBoot) return;
369
+ try {
370
+ const boot = await runner.checkBoot(checked.data, {
371
+ projectRoot: options.projectRoot,
372
+ verb: subject.verb,
373
+ env: options.env,
374
+ file
375
+ });
376
+ for (const i of boot) issue("boot", {
377
+ ...i,
378
+ path: i.path ?? ""
379
+ });
380
+ } catch (error) {
381
+ issue("boot", "", error);
382
+ }
383
+ }
384
+ async function checkCompound(result, options, subject) {
385
+ const issue = issuer(result, subject.file);
386
+ const { host, runner, specifier } = subject;
387
+ const declared = checkDeclared(result, subject);
388
+ if (!declared.tokens || !declared.shape) return;
389
+ if (!runner.declaredHostSchema) {
390
+ const own = schemaIssuesOf(runner, runner.hostSchema, specifier, host, true);
391
+ for (const i of own) issue("resolved", i);
392
+ if (own.length > 0) return;
393
+ }
394
+ const children = isPlainObject(host.children) ? host.children : {};
395
+ const wiring = isPlainObject(host.config) ? host.config : {};
396
+ const verb = compoundStartVerb(subject.verb, host.runner);
397
+ const prepared = [];
398
+ for (const [key, member] of Object.entries(children)) try {
399
+ prepared.push(await prepareMember(options.projectRoot, key, member));
400
+ } catch (error) {
401
+ issuer(result, `hosts/${member.host}/host.js`)("load", "", error);
402
+ }
403
+ const members = Object.entries(children).map(([key, m]) => ({
404
+ key,
405
+ host: m.host
406
+ }));
407
+ if (prepared.length === members.length) try {
408
+ planCompound(prepared.map((m) => ({
409
+ key: m.key,
410
+ host: m.member.host,
411
+ refs: outputSitesOf(m.draft).map(({ ref, path }) => ({
412
+ ref,
413
+ path
414
+ }))
415
+ })), wiring.startOrder);
416
+ } catch (error) {
417
+ issue("declared", "", error);
418
+ }
419
+ result.warnings.push(...sharedPortWarnings(subject.file, prepared));
420
+ const byKey = new Map(prepared.map((m) => [m.key, m]));
421
+ const outputsSchemaOf = (ref) => {
422
+ const target = memberForRef(ref, members);
423
+ if ("error" in target) return { error: target.error };
424
+ const producer = byKey.get(target.key);
425
+ return producer ? runnerOutputsSchema(producer.runner, producer.specifier, `member "${target.key}"`) : { error: `names member "${target.key}", which was not prepared.` };
426
+ };
427
+ for (const m of prepared) {
428
+ const csp = wiring.cspRegistrySync === true && takesCspRegistrySync(m);
429
+ await checkSubject(result, options, {
430
+ file: m.file,
431
+ host: m.draft,
432
+ runner: m.runner,
433
+ specifier: m.specifier,
434
+ verb: memberVerbOf(verb, m.draft.runner),
435
+ outputsSchemaOf,
436
+ self: { members },
437
+ ...csp ? { patch: (resolved) => ({
438
+ ...resolved,
439
+ runner: {
440
+ ...resolved.runner,
441
+ cspRegistrySync: true
442
+ }
443
+ }) } : {}
444
+ });
445
+ }
446
+ }
447
+ const SWITCHBOARD_RUNNER = "@powerhousedao/ph-cli/runners/switchboard";
448
+ /** The port a member binds: its own literal, else its ph-cli runner's default. */
449
+ function boundPortOf(m) {
450
+ const port = m.draft.runner.port;
451
+ if (port === void 0) {
452
+ if (m.specifier === "@powerhousedao/ph-cli/runners/connect") return DEFAULT_CONNECT_STUDIO_PORT;
453
+ if (m.specifier === SWITCHBOARD_RUNNER) return DEFAULT_SWITCHBOARD_PORT;
454
+ return;
455
+ }
456
+ return typeof port === "number" && Number.isInteger(port) && port > 0 ? port : void 0;
457
+ }
458
+ /** Members binding one port: under `ph run` the later one moves or fails. */
459
+ function sharedPortWarnings(file, prepared) {
460
+ const owners = /* @__PURE__ */ new Map();
461
+ const warnings = [];
462
+ for (const m of prepared) {
463
+ const port = boundPortOf(m);
464
+ if (port === void 0) continue;
465
+ const other = owners.get(port);
466
+ if (!other) {
467
+ owners.set(port, m);
468
+ continue;
469
+ }
470
+ const connects = m.specifier === "@powerhousedao/ph-cli/runners/connect" && other.specifier === "@powerhousedao/ph-cli/runners/connect";
471
+ warnings.push({
472
+ stage: "declared",
473
+ file,
474
+ path: `children.${m.key}.runner.port`,
475
+ message: connects ? `${other.key} and ${m.key} both use port ${port}. One will move to the next free port and lose its browser data.` : `${other.key} and ${m.key} both use port ${port}. One will move to the next free port or fail to start.`
476
+ });
477
+ }
478
+ return warnings;
479
+ }
480
+ function issuer(result, file) {
481
+ return (stage, found, error) => {
482
+ if (typeof found !== "string") {
483
+ const { path, message, hint } = found;
484
+ result.issues.push({
485
+ stage,
486
+ file,
487
+ path,
488
+ message,
489
+ ...hint ? { hint } : {}
490
+ });
491
+ return;
492
+ }
493
+ const [message, hint] = (error instanceof Error ? error.message : String(error)).split("\n Hint: ");
494
+ result.issues.push({
495
+ stage,
496
+ file,
497
+ path: found,
498
+ message,
499
+ ...hint ? { hint } : {}
500
+ });
501
+ };
502
+ }
503
+ //#endregion
504
+ //#region src/host-export-schema.ts
505
+ function isRecord$1(value) {
506
+ return typeof value === "object" && value !== null && !Array.isArray(value);
507
+ }
508
+ function childFolders$1(host) {
509
+ if (!isRecord$1(host) || !isRecord$1(host.children)) return [];
510
+ return Object.entries(host.children).flatMap(([key, child]) => isRecord$1(child) && typeof child.host === "string" ? [[key, child.host]] : []);
511
+ }
512
+ const declaredHostSchema = z.custom().superRefine((host, ctx) => {
513
+ const result = (isRecord$1(host) && "children" in host ? declaredHostSchemas.compoundHostSchema : declaredHostSchemas.reactorHostSchema).safeParse(host);
514
+ if (result.success) return;
515
+ for (const issue of result.error.issues) ctx.addIssue({
516
+ code: "custom",
517
+ message: issue.message,
518
+ path: issue.path
519
+ });
520
+ });
521
+ /** `ph host export`: a declared host plus its members, keyed by folder. */
522
+ const hostExportSchema = z.strictObject({
523
+ format: z.literal("ph-host-export"),
524
+ version: z.literal(1),
525
+ project: z.strictObject({
526
+ name: z.string().min(1),
527
+ root: z.string().min(1)
528
+ }),
529
+ name: z.string().min(1),
530
+ host: declaredHostSchema,
531
+ members: z.record(z.string(), declaredHostSchema)
532
+ }).superRefine((value, ctx) => {
533
+ const reached = /* @__PURE__ */ new Set();
534
+ const pending = [[["host"], value.host]];
535
+ for (let next = pending.shift(); next; next = pending.shift()) {
536
+ const [at, host] = next;
537
+ for (const [key, folder] of childFolders$1(host)) {
538
+ if (!(folder in value.members)) {
539
+ ctx.addIssue({
540
+ code: "custom",
541
+ path: [
542
+ ...at,
543
+ "children",
544
+ key,
545
+ "host"
546
+ ],
547
+ message: `Member folder "${folder}" is missing from members.`
548
+ });
549
+ continue;
550
+ }
551
+ if (reached.has(folder)) continue;
552
+ reached.add(folder);
553
+ pending.push([["members", folder], value.members[folder]]);
554
+ }
555
+ }
556
+ for (const folder of Object.keys(value.members)) {
557
+ if (reached.has(folder)) continue;
558
+ ctx.addIssue({
559
+ code: "custom",
560
+ path: ["members", folder],
561
+ message: `Member "${folder}" is not reached from the host's children.`
562
+ });
563
+ }
564
+ });
565
+ //#endregion
566
+ //#region src/host-export.ts
567
+ function checkHint(name) {
568
+ return `Run \`ph host check ${name}\`.`;
569
+ }
570
+ function childFolders(host, name) {
571
+ if (!("children" in host)) return [];
572
+ const parsed = declaredHostSchemas.childrenSchema.safeParse(host.children);
573
+ if (!parsed.success) throw new HostLoadError(`hosts/${name}/host.js: invalid \`children\`:\n${z.prettifyError(parsed.error)}`, checkHint(name));
574
+ return Object.values(parsed.data).map((child) => child.host);
575
+ }
576
+ /** A host as declared and every member it reaches, raw `loadHost` bodies. */
577
+ async function exportHost(projectRoot, name) {
578
+ const root = path.resolve(projectRoot);
579
+ const { host } = await loadHost(root, name);
580
+ const members = {};
581
+ const visit = async (folders) => {
582
+ for (const folder of folders) {
583
+ if (folder in members) continue;
584
+ const member = (await loadHost(root, folder)).host;
585
+ members[folder] = member;
586
+ await visit(childFolders(member, folder));
587
+ }
588
+ };
589
+ await visit(childFolders(host, name));
590
+ const envelope = {
591
+ format: "ph-host-export",
592
+ version: 1,
593
+ project: {
594
+ name: readProjectName(root),
595
+ root
596
+ },
597
+ name,
598
+ host,
599
+ members
600
+ };
601
+ const parsed = hostExportSchema.safeParse(JSON.parse(JSON.stringify(envelope)));
602
+ if (!parsed.success) throw new HostLoadError(`hosts/${name}/host.js: the export is not a valid host export:\n${z.prettifyError(parsed.error)}`, checkHint(name));
603
+ return envelope;
604
+ }
605
+ //#endregion
606
+ //#region src/drives.ts
607
+ const sha256Hex = (input) => crypto.createHash("sha256").update(input).digest("hex");
608
+ function projectDriveId(projectRoot, slug) {
609
+ return projectDriveIdWith(sha256Hex, projectRoot, slug);
610
+ }
611
+ function resolveDriveDeclaration(projectRoot, decl) {
612
+ const id = decl.projectHash ? projectDriveId(projectRoot, decl.slug) : decl.id;
613
+ const slug = decl.projectHash === true ? id : decl.slug;
614
+ if (decl.remote) return {
615
+ kind: "remote",
616
+ id,
617
+ slug,
618
+ name: decl.name ?? decl.slug,
619
+ remoteUrl: decl.remote.url,
620
+ sharingType: decl.sharingType ?? "public",
621
+ availableOffline: decl.availableOffline ?? true
622
+ };
623
+ return {
624
+ kind: "local",
625
+ id,
626
+ slug,
627
+ documentType: decl.documentType,
628
+ name: decl.name ?? decl.slug,
629
+ icon: resolveImageRef(projectRoot, decl.icon, {
630
+ maxBytes: DRIVE_ICON_MAX_BYTES,
631
+ warn: (m) => console.warn(m)
632
+ }),
633
+ preferredEditor: decl.preferredEditor,
634
+ sharingType: decl.sharingType ?? "public",
635
+ availableOffline: decl.availableOffline ?? true
636
+ };
637
+ }
638
+ /** Idempotent, slug-keyed: an existing slug is left untouched (never
639
+ * recreated, never mutated — preserveStrategy refinements live here later). */
640
+ async function seedDrives(client, drives) {
641
+ const result = {
642
+ created: [],
643
+ existing: [],
644
+ attached: []
645
+ };
646
+ for (const drive of drives) {
647
+ if (drive.kind === "remote") {
648
+ await client.attachRemoteDrive(drive.remoteUrl);
649
+ result.attached.push(drive.slug);
650
+ continue;
651
+ }
652
+ if (await client.findDriveBySlug(drive.slug) !== void 0) {
653
+ result.existing.push(drive.slug);
654
+ continue;
655
+ }
656
+ await client.createDrive(drive);
657
+ result.created.push(drive.slug);
658
+ }
659
+ return result;
660
+ }
661
+ /** Merge host-declared drives with plugin contributions, slug-keyed — the
662
+ * host file wins on conflicts (it is the most explicit source). */
663
+ function mergeDrivePlan(projectRoot, hostDeclared, contributed) {
664
+ const plan = /* @__PURE__ */ new Map();
665
+ for (const { declaration, source } of contributed) {
666
+ const drive = resolveDriveDeclaration(projectRoot, declaration);
667
+ plan.set(drive.slug, {
668
+ drive,
669
+ source
670
+ });
671
+ }
672
+ for (const declaration of hostDeclared) {
673
+ const drive = resolveDriveDeclaration(projectRoot, declaration);
674
+ plan.set(drive.slug, {
675
+ drive,
676
+ source: "host"
677
+ });
678
+ }
679
+ return [...plan.values()];
680
+ }
681
+ function explainDrivePlan(plan) {
682
+ if (plan.length === 0) return "(no drives declared)";
683
+ return ["drives:", ...plan.map(({ drive, source }) => {
684
+ const kind = drive.kind === "remote" ? `remote ${drive.remoteUrl}` : "local";
685
+ const editor = drive.preferredEditor ? ` editor=${drive.preferredEditor}` : "";
686
+ const id = drive.id ?? "generated";
687
+ return ` ${drive.slug} (${kind}, id=${id}${editor}) [${source}]`;
688
+ })].join("\n");
689
+ }
690
+ //#endregion
691
+ //#region src/backend-projection.ts
692
+ function projectStorage(name, storage) {
693
+ switch (storage.kind) {
694
+ case "idb": return { kind: "idb" };
695
+ case "memory": return { kind: "memory" };
696
+ case "path":
697
+ if (!storage.dataDir) throw new Error(`Backend "${name}": storage kind "path" requires dataDir.`);
698
+ return {
699
+ kind: "path",
700
+ dataDir: storage.dataDir
701
+ };
702
+ case "postgres": throw new Error(`Backend "${name}": storage kind "postgres" is server-side only — a provisioned (in-process/worker) reactor cannot use it. Point a "remote" backend at the switchboard that owns that database instead.`);
703
+ }
704
+ }
705
+ /** One backend → one descriptor. The protocol's featureFlags ride every
706
+ * descriptor (they are fleet consensus, not per-backend). A remote backend
707
+ * must carry remote.url — provision() requires it. */
708
+ function backendToDescriptor(name, backend, protocol) {
709
+ const descriptor = {
710
+ kind: backend.kind,
711
+ name
712
+ };
713
+ if (descriptor.kind === "remote") {
714
+ const url = backend.remote?.url;
715
+ if (!url) throw new Error(`Backend "${name}" is kind "remote" but has no remote.url — a remote descriptor attaches to an already-running reactor by URL.`);
716
+ descriptor.remote = { url };
717
+ return descriptor;
718
+ }
719
+ if (backend.storage) descriptor.storage = projectStorage(name, backend.storage);
720
+ if (backend.packages) descriptor.packages = backend.packages;
721
+ if (protocol?.featureFlags) descriptor.featureFlags = protocol.featureFlags;
722
+ return descriptor;
723
+ }
724
+ /** All named backends, in placement-primary-first order (the order a
725
+ * createReactorClients step would provision them). */
726
+ function backendsToDescriptors(reactor) {
727
+ const backends = reactor?.backends;
728
+ if (!backends) return [];
729
+ const names = Object.keys(backends);
730
+ const primary = reactor.placement?.primary;
731
+ return (primary && names.includes(primary) ? [primary, ...names.filter((n) => n !== primary)] : names).map((name) => backendToDescriptor(name, backends[name], reactor.protocol));
732
+ }
733
+ const LOCAL_KINDS = /* @__PURE__ */ new Set(["in-process", "worker"]);
734
+ /**
735
+ * Structural multi-reactor (phase 4): true when the block names BOTH a local
736
+ * backend (in-process/worker — the tab's own reactor) and a remote one. This
737
+ * is the shape Connect's routing client serves; a lone remote backend is an
738
+ * attach-only host (assistant/agent shape), not a routed tab.
739
+ */
740
+ function isStructuralMultiReactor(reactor) {
741
+ const backends = reactor?.backends;
742
+ if (!backends) return false;
743
+ const kinds = Object.values(backends).map((b) => b.kind);
744
+ return kinds.some((k) => LOCAL_KINDS.has(k)) && kinds.some((k) => k === "remote");
745
+ }
746
+ /** The remote backends' drive addresses, placement order. */
747
+ function remoteBackendUrls(reactor) {
748
+ return backendsToDescriptors(reactor).filter((d) => d.kind === "remote").map((d) => d.remote?.url).filter((u) => typeof u === "string");
749
+ }
750
+ /**
751
+ * The remote backends by host key, placement order, each with the
752
+ * connection settings it sets. A url that is not a string yet (an output
753
+ * token, unresolved when a host builds) is skipped, as in remoteBackendUrls.
754
+ */
755
+ function remoteBackends(reactor) {
756
+ return backendsToDescriptors(reactor).flatMap((d) => {
757
+ const remote = reactor?.backends?.[d.name]?.remote;
758
+ if (d.kind !== "remote" || typeof d.remote?.url !== "string" || !remote) return [];
759
+ const { requestTimeoutMs, breaker, realtime } = remote;
760
+ return [{
761
+ name: d.name,
762
+ url: d.remote.url,
763
+ ...requestTimeoutMs !== void 0 ? { requestTimeoutMs } : {},
764
+ ...breaker !== void 0 ? { breaker } : {},
765
+ ...realtime !== void 0 ? { realtime } : {}
766
+ }];
767
+ });
768
+ }
769
+ //#endregion
770
+ //#region src/reactor-config.ts
771
+ /**
772
+ * The shared `reactor` host-config block and its projections onto the
773
+ * Switchboard config / Connect runtime config. Phase 2 of uniform-runners: makes
774
+ * the reactor block live through the bridge runners, BEFORE track R replaces
775
+ * the projection with reactor-monitor's provision(). The headline is
776
+ * single-sourced `reactor.protocol` — both projections read the same block, so
777
+ * client and server cannot diverge, and a contradicting pre-set env fails boot.
778
+ */
779
+ /** A switchboard host's own store. Prefers placement.primary, else
780
+ * "main"/"local", else the first. Connect refuses placement.primary: its
781
+ * reactor is {@link browserBackend}. */
782
+ function primaryBackend(reactor) {
783
+ const backends = reactor?.backends;
784
+ if (!backends) return void 0;
785
+ const names = Object.keys(backends);
786
+ if (names.length === 0) return void 0;
787
+ return backends[reactor.placement?.primary ?? (names.includes("main") ? "main" : names.includes("local") ? "local" : names[0])];
788
+ }
789
+ const FLAG_ENV = {
790
+ documentDecisions: "REACTOR_DOCUMENT_DECISIONS",
791
+ authEnforcement: "REACTOR_AUTH_ENFORCEMENT",
792
+ authGroups: "REACTOR_AUTH_GROUPS",
793
+ authConditions: "REACTOR_AUTH_CONDITIONS",
794
+ undoV3: "REACTOR_UNDO_V3"
795
+ };
796
+ /** The env vars a protocol block maps onto, with their string values. Only
797
+ * keys the block actually sets appear. */
798
+ function protocolEnv(protocol) {
799
+ const env = {};
800
+ if (!protocol) return env;
801
+ for (const [key, varName] of Object.entries(FLAG_ENV)) {
802
+ const value = protocol.featureFlags?.[key];
803
+ if (value !== void 0) env[varName] = value ? "true" : "false";
804
+ }
805
+ if (protocol.createSignaturePolicy !== void 0) env.CREATE_SIGNATURE_POLICY = protocol.createSignaturePolicy;
806
+ if (protocol.unsupportedStoredDocuments !== void 0) env.REACTOR_UNSUPPORTED_STORED_DOCUMENTS = protocol.unsupportedStoredDocuments;
807
+ return env;
808
+ }
809
+ /** The reactor block as a switchboard config layer. The reactor store and the
810
+ * read model are separate fields: `readModel.url` never moves the reactor. */
811
+ function reactorBlockToSwitchboardConfig(reactor) {
812
+ const layer = {};
813
+ const backend = primaryBackend(reactor);
814
+ const storage = backend?.storage;
815
+ const reactorUrl = storage?.kind === "postgres" ? storage.url : storage?.dataDir;
816
+ const readModelUrl = backend?.readModel?.url;
817
+ if (reactorUrl || readModelUrl) layer.storage = {
818
+ ...reactorUrl ? { reactor: { url: reactorUrl } } : {},
819
+ ...readModelUrl ? { readModel: { url: readModelUrl } } : {}
820
+ };
821
+ if (reactor?.protocol) layer.protocol = reactor.protocol;
822
+ if (backend?.packages?.dynamic) layer.packages = { dynamic: true };
823
+ if (reactor?.workflows !== void 0) layer.features = { workflows: reactor.workflows };
824
+ return layer;
825
+ }
826
+ const LOCAL_BACKEND_KINDS = /* @__PURE__ */ new Set(["in-process", "worker"]);
827
+ /** Connect's browser reactor: its first in-process or worker backend. */
828
+ function browserBackend(reactor) {
829
+ const entry = Object.entries(reactor?.backends ?? {}).find(([, backend]) => LOCAL_BACKEND_KINDS.has(backend.kind));
830
+ return entry ? {
831
+ ...entry[1],
832
+ name: entry[0]
833
+ } : void 0;
834
+ }
835
+ /**
836
+ * Which reactor client the backend topology asks for:
837
+ * - local (in-process/worker) AND remote backends -> `router`
838
+ * - remote backend(s) only -> `remote`
839
+ * - a worker backend -> `worker`
840
+ * - anything else local -> `in-process`
841
+ * `undefined` when no backends are declared — the caller then keeps the
842
+ * legacy reactorWorker/multiReactor behaviour untouched.
843
+ */
844
+ function reactorClientMode(reactor) {
845
+ const backends = reactor?.backends;
846
+ if (!backends) return void 0;
847
+ const kinds = Object.values(backends).map((b) => b.kind);
848
+ if (kinds.length === 0) return void 0;
849
+ const hasLocal = kinds.some((k) => LOCAL_BACKEND_KINDS.has(k));
850
+ const hasRemote = kinds.some((k) => k === "remote");
851
+ if (hasLocal && hasRemote) return "router";
852
+ if (hasRemote) return "remote";
853
+ return browserBackend(reactor)?.kind === "worker" ? "worker" : "in-process";
854
+ }
855
+ /** Served only when `newDrives` names a served remote backend: a local one
856
+ * is the default, and Connect refuses one it has no address for. */
857
+ function connectRouterSettings(reactor, served) {
858
+ const newDrives = reactor?.placement?.newDrives;
859
+ const { probeTimeoutMs, provisionalRouteMs } = reactor?.router ?? {};
860
+ const router = {
861
+ ...newDrives !== void 0 && served.some((remote) => remote.name === newDrives) ? { newDrives } : {},
862
+ ...probeTimeoutMs !== void 0 ? { probeTimeoutMs } : {},
863
+ ...provisionalRouteMs !== void 0 ? { provisionalRouteMs } : {}
864
+ };
865
+ return Object.keys(router).length > 0 ? router : void 0;
866
+ }
867
+ function connectStorage(backend) {
868
+ const kind = backend?.storage?.kind;
869
+ return kind === "idb" || kind === "memory" ? kind : void 0;
870
+ }
871
+ /** Why the browser reactor's declared store can't be served: Connect keeps
872
+ * IndexedDB instead of a folder or Postgres. */
873
+ function unservedConnectStorage(reactor) {
874
+ const browser = browserBackend(reactor);
875
+ const kind = browser?.storage?.kind;
876
+ if (!browser || !kind || connectStorage(browser)) return void 0;
877
+ return `reactor.backends.${browser.name}.storage "${kind}": Connect's browser reactor can't use it and keeps IndexedDB instead.`;
878
+ }
879
+ /** Project the reactor block onto the Connect runtime config: protocol →
880
+ * connect.reactor (same shape), backend topology → instance.reactorWorker
881
+ * (the browser reactor's kind), instance.reactorClient, instance.storage
882
+ * (the browser reactor's store), and with a
883
+ * switchboard instance.remoteBackends and instance.router, workflows →
884
+ * app.workflowsEnabled. */
885
+ function projectReactorToConnect(reactor) {
886
+ const connect = {};
887
+ if (reactor?.protocol) connect.reactor = reactor.protocol;
888
+ const mode = reactorClientMode(reactor);
889
+ if (mode !== void 0) {
890
+ const routed = mode === "router" || mode === "remote";
891
+ const served = routed ? remoteBackends(reactor) : [];
892
+ const router = routed ? connectRouterSettings(reactor, served) : void 0;
893
+ const browser = browserBackend(reactor);
894
+ const storage = connectStorage(browser);
895
+ connect.instance = {
896
+ reactorWorker: browser?.kind === "worker",
897
+ reactorClient: mode,
898
+ ...storage ? { storage } : {},
899
+ ...routed ? { remoteBackends: served } : {},
900
+ ...router ? { router } : {}
901
+ };
902
+ }
903
+ if (reactor?.workflows !== void 0) connect.app = { workflowsEnabled: reactor.workflows };
904
+ return { connect };
905
+ }
906
+ /** Whether an env value means what the host's value does. The switchboard
907
+ * reads REACTOR_UNDO_V3 as on unless it is exactly "false". */
908
+ function protocolEnvAgrees(varName, envValue, hostValue) {
909
+ if (varName === FLAG_ENV.undoV3) return envValue !== "false" === (hostValue === "true");
910
+ return envValue === hostValue;
911
+ }
912
+ /** Each pre-set env var that CONTRADICTS the host's protocol block, as a
913
+ * message naming the var, the host value and the env value. An env var that
914
+ * merely matches, or is unset, is fine. */
915
+ function protocolConflicts(protocol, env, hostFile = "the host file") {
916
+ if (!protocol) return [];
917
+ return Object.entries(protocolEnv(protocol)).flatMap(([varName, hostValue]) => {
918
+ const envValue = env[varName];
919
+ if (envValue === void 0 || protocolEnvAgrees(varName, envValue, hostValue)) return [];
920
+ return [`reactor.protocol conflict: ${varName} is "${envValue}" in the environment but "${hostValue}" in ${hostFile}. These are fleet-consensus settings — a mismatch would diverge replay. Remove the env override or align the host.`];
921
+ });
922
+ }
923
+ /**
924
+ * The enforcement teeth of single-sourcing: if a pre-set env var CONTRADICTS
925
+ * the host's protocol block, fail loudly naming the var, the host value, and
926
+ * the env value (phase-2 transition keeps an operator's explicit env as an
927
+ * escape hatch unless it disagrees with the protocol — see the WBS
928
+ * precedence note).
929
+ */
930
+ function assertProtocolConsistency(protocol, env, hostFile = "the host file") {
931
+ const conflict = protocolConflicts(protocol, env, hostFile).at(0);
932
+ if (conflict) throw new Error(conflict);
933
+ }
934
+ //#endregion
935
+ //#region src/connect-projection.ts
936
+ /**
937
+ * Instance-fact projection for compound hosts: the drives a compound's
938
+ * reactor member created, projected into the Connect member's runtime-config
939
+ * override. Pure functions, moved from ph-cli's vetra service so the generic
940
+ * compound and the classic path share one implementation.
941
+ */
942
+ function isLocalDrive(drive) {
943
+ return "local" in drive;
944
+ }
945
+ const driveKey = (drive) => isLocalDrive(drive) ? `local:${drive.id}` : drive.url;
946
+ /**
947
+ * Concatenate groups of `connect.drives.defaultDrives` in the order given,
948
+ * de-duplicating by drive identity (URL for remote entries, id for local
949
+ * ones). The first occurrence of a drive wins, so earlier groups keep their
950
+ * position and metadata — e.g. the Vetra drive `ph vetra` starts stays first
951
+ * even when the project's `powerhouse.config.json` lists the same drive.
952
+ */
953
+ function mergeDefaultDrives(...groups) {
954
+ const seen = /* @__PURE__ */ new Set();
955
+ const out = [];
956
+ for (const group of groups) for (const drive of group) {
957
+ const key = driveKey(drive);
958
+ if (seen.has(key)) continue;
959
+ seen.add(key);
960
+ out.push(drive);
961
+ }
962
+ return out;
963
+ }
964
+ /**
965
+ * Rebase a local drive URL onto a public base: keeps the /d/<slug> path,
966
+ * swaps the loopback origin for the public base. Browser clients behind a
967
+ * reverse proxy can't reach http://localhost:<port>. Non-loopback URLs
968
+ * (e.g. a remote drive) are already public and pass through unchanged, as do
969
+ * unparseable ones.
970
+ */
971
+ function rebaseDriveUrl(driveUrl, publicBase) {
972
+ let url;
973
+ try {
974
+ url = new URL(driveUrl);
975
+ } catch {
976
+ return driveUrl;
977
+ }
978
+ if (![
979
+ "localhost",
980
+ "127.0.0.1",
981
+ "[::1]"
982
+ ].includes(url.hostname)) return driveUrl;
983
+ return `${publicBase.replace(/\/+$/, "")}${url.pathname}`;
984
+ }
985
+ /**
986
+ * The compound's drives projection: created drives first (rebased onto the
987
+ * public base when given), then the project's configured drives, de-duplicated
988
+ * — and `preserve-all`, because compound-injected drive lists change per
989
+ * launch context and must never detach drives the user added by hand.
990
+ */
991
+ function projectDrivesIntoConnect(input) {
992
+ return { drives: {
993
+ defaultDrives: mergeDefaultDrives(input.createdDriveUrls.filter((url) => typeof url === "string" && url.length > 0).map((url) => ({
994
+ url: input.publicBase ? rebaseDriveUrl(url, input.publicBase) : url,
995
+ name: null,
996
+ icon: null
997
+ })), input.configuredDefaultDrives ?? []),
998
+ preserveStrategy: "preserve-all"
999
+ } };
1000
+ }
1001
+ /** A served slug names a declared one as is, or hashed (`<slug>-<8 hex>`). */
1002
+ function servesSlug(declared, served) {
1003
+ return served === declared || served.startsWith(`${declared}-`) && /^[0-9a-f]{8}$/.test(served.slice(declared.length + 1));
1004
+ }
1005
+ /** Annotates remote default drives with their backend (`sync: false` when placed on it); other remote placements become collections. */
1006
+ function placeConnectDrives(reactor, defaultDrives) {
1007
+ const remotes = remoteBackends(reactor).flatMap(({ name, url }) => {
1008
+ const at = switchboardOfDrive$1(url);
1009
+ return at ? [{
1010
+ name,
1011
+ base: at.base
1012
+ }] : [];
1013
+ });
1014
+ if (remotes.length === 0) return { defaultDrives: [...defaultDrives] };
1015
+ const placement = Object.entries(reactor?.placement?.drives ?? {});
1016
+ const matched = /* @__PURE__ */ new Set();
1017
+ const placed = defaultDrives.map((drive) => {
1018
+ if (!("url" in drive)) return drive;
1019
+ const at = switchboardOfDrive$1(drive.url);
1020
+ const backend = remotes.find((remote) => remote.base === at?.base)?.name;
1021
+ if (!at || !backend) return drive;
1022
+ const entry = placement.find(([slug]) => servesSlug(slug, at.slug));
1023
+ if (entry) matched.add(entry[0]);
1024
+ return entry?.[1] === backend ? {
1025
+ ...drive,
1026
+ backend,
1027
+ sync: false
1028
+ } : {
1029
+ ...drive,
1030
+ backend
1031
+ };
1032
+ });
1033
+ const names = new Set(remotes.map((remote) => remote.name));
1034
+ const collections = Object.fromEntries(placement.filter(([slug, backend]) => !matched.has(slug) && names.has(backend)).map(([slug, backend]) => [slug, {
1035
+ backend,
1036
+ sync: false
1037
+ }]));
1038
+ return Object.keys(collections).length > 0 ? {
1039
+ defaultDrives: placed,
1040
+ collections
1041
+ } : { defaultDrives: placed };
1042
+ }
1043
+ //#endregion
1044
+ //#region src/expect-host.ts
1045
+ function isRecord(value) {
1046
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1047
+ }
1048
+ function runnerOf(host) {
1049
+ return isRecord(host.runner) ? host.runner : {};
1050
+ }
1051
+ function defaultVerbOf(host) {
1052
+ const verb = runnerOf(host).defaultVerb;
1053
+ return typeof verb === "string" ? verb : void 0;
1054
+ }
1055
+ /** At compound verb "run" each member runs its own defaultVerb; any other
1056
+ * compound verb is forwarded uniformly (compound.ts `memberVerbOf`). */
1057
+ function memberVerb(compoundVerb, member) {
1058
+ return compoundVerb === "run" ? defaultVerbOf(member) ?? "run" : compoundVerb;
1059
+ }
1060
+ /** Backend names, placement-primary first (`backendsToDescriptors` order). */
1061
+ function orderedBackends(reactor) {
1062
+ const backends = Object.entries(reactor.backends ?? {});
1063
+ const primary = reactor.placement?.primary;
1064
+ return [...backends.filter(([name]) => name === primary), ...backends.filter(([name]) => name !== primary)];
1065
+ }
1066
+ function expectBackend(name, backend, reactor) {
1067
+ const out = {
1068
+ name,
1069
+ kind: backend.kind
1070
+ };
1071
+ if (backend.storage) out.storage = backend.storage.kind;
1072
+ if (typeof backend.storage?.dataDir === "string") out.dataDir = backend.storage.dataDir;
1073
+ try {
1074
+ backendToDescriptor(name, backend, reactor.protocol);
1075
+ } catch (error) {
1076
+ out.provisionError = error instanceof Error ? error.message : String(error);
1077
+ }
1078
+ return out;
1079
+ }
1080
+ function expectDrive(declaration, source) {
1081
+ if (typeof declaration.slug !== "string") return void 0;
1082
+ const remote = isRecord(declaration.remote) ? declaration.remote : void 0;
1083
+ const drive = {
1084
+ slug: declaration.slug,
1085
+ kind: remote ? "remote" : "local",
1086
+ source
1087
+ };
1088
+ if (remote && typeof remote.url === "string") drive.url = remote.url;
1089
+ if (typeof declaration.id === "string") drive.id = declaration.id;
1090
+ const projectHash = declaration.projectHash;
1091
+ if (typeof projectHash === "boolean" || projectHash === "id") drive.projectHash = projectHash;
1092
+ return drive;
1093
+ }
1094
+ /** The key `mergeDrivePlan` merges on: the SERVED slug, which for
1095
+ * `projectHash: true` is the hashed id (never equal to a plain slug). */
1096
+ function servedSlugKey(drive) {
1097
+ return drive.projectHash === true ? `${drive.slug}\0hashed` : drive.slug;
1098
+ }
1099
+ /** Contributions first, then host declarations; keyed by served slug, the
1100
+ * host wins (and keeps the contribution's position), like `mergeDrivePlan`. */
1101
+ function drivePlan(reactor, contributed) {
1102
+ const plan = /* @__PURE__ */ new Map();
1103
+ for (const { declaration, source } of contributed) {
1104
+ const drive = expectDrive(declaration, source);
1105
+ if (drive) plan.set(servedSlugKey(drive), drive);
1106
+ }
1107
+ for (const declaration of reactor?.drives ?? []) {
1108
+ const drive = expectDrive(declaration, "host");
1109
+ if (drive) plan.set(servedSlugKey(drive), drive);
1110
+ }
1111
+ return [...plan.values()];
1112
+ }
1113
+ /** Token facts of the host's OWN fields (a compound's `children` are its
1114
+ * members' own). */
1115
+ function tokenFacts(declared, kind) {
1116
+ const own = kind === "compound" ? Object.fromEntries(Object.entries(declared).filter(([key]) => key !== "children")) : declared;
1117
+ const sites = outputSitesOf(own);
1118
+ const consumes = sites.map(({ path, ref, outputPath }) => ({
1119
+ at: path,
1120
+ host: ref.host,
1121
+ ...ref.member !== void 0 ? { member: ref.member } : {},
1122
+ path: outputPath
1123
+ }));
1124
+ return {
1125
+ dependsOn: [...new Set(sites.map(({ ref }) => refKey(ref)))].sort(),
1126
+ consumes,
1127
+ env: [...new Set(envSitesOf(own).map(({ name }) => name))].sort()
1128
+ };
1129
+ }
1130
+ function expectOwn(input, verb) {
1131
+ const resolved = input.resolved ?? input.declared;
1132
+ const expectation = {
1133
+ name: typeof resolved.name === "string" ? resolved.name : "",
1134
+ kind: input.kind,
1135
+ verb,
1136
+ ...tokenFacts(input.declared, input.kind)
1137
+ };
1138
+ if (input.kind !== "reactor") return expectation;
1139
+ const reactor = isRecord(resolved.reactor) ? resolved.reactor : void 0;
1140
+ const mode = reactorClientMode(reactor);
1141
+ if (mode !== void 0) expectation.clientMode = mode;
1142
+ expectation.multiReactor = isStructuralMultiReactor(reactor);
1143
+ const backends = reactor ? orderedBackends(reactor) : [];
1144
+ if (reactor && backends.length > 0) {
1145
+ expectation.backends = backends.map(([name, backend]) => expectBackend(name, backend, reactor));
1146
+ expectation.remotes = backends.flatMap(([, backend]) => backend.kind === "remote" && typeof backend.remote?.url === "string" ? [backend.remote.url] : []);
1147
+ }
1148
+ expectation.drives = drivePlan(reactor, input.contributed ?? []);
1149
+ return expectation;
1150
+ }
1151
+ /**
1152
+ * The expectation for one host. A reactor host's comes from its resolved
1153
+ * reactor block and contributed drives; a compound's lists its members in
1154
+ * plan order, each with the verb it runs at under the compound's own verb
1155
+ * and the members it starts after.
1156
+ */
1157
+ function expectHost(input) {
1158
+ const verb = defaultVerbOf(input.declared) ?? "run";
1159
+ const expectation = expectOwn(input, verb);
1160
+ if (input.kind !== "compound" || !input.members) return expectation;
1161
+ const order = input.plan?.order ?? input.members.map((m) => m.key);
1162
+ const edges = input.plan?.edges ?? [];
1163
+ const byKey = new Map(input.members.map((m) => [m.key, m]));
1164
+ const members = {};
1165
+ for (const key of order) {
1166
+ const member = byKey.get(key);
1167
+ if (!member) continue;
1168
+ members[key] = {
1169
+ host: member.host,
1170
+ ...expectOwn(member, memberVerb(verb, member.declared)),
1171
+ after: [...new Set(edges.filter((e) => e.consumer === key).map((e) => e.producer))].sort()
1172
+ };
1173
+ }
1174
+ expectation.startOrder = order.filter((key) => byKey.has(key));
1175
+ expectation.members = members;
1176
+ return expectation;
1177
+ }
1178
+ //#endregion
1179
+ export { BUILTIN_ENV_NAMES, CONNECT_PLUGIN_OWNED_SLICES, CONNECT_PRIMARY_MESSAGE, CONNECT_RUNNER, HOST_NAME_MAX_LENGTH, HOST_NAME_MESSAGE, HOST_NAME_PATTERN, HostLoadError, ONE_SHOT_VERBS, ORIGIN_PLACEHOLDER, OUTPUTS_FILE, OUTPUT_DATA_DIRS_ENV, PlanError, PluginError, RunnerError, SPAWN_STOPPING_NOTE, SWITCHBOARD_PROXY_PATHS, SpawnHostError, TOKEN_ESCAPE_KEY, TOKEN_KEYS, TokenResolutionError, applyChildWrapper, assertProtocolConsistency, backendToDescriptor, backendsToDescriptors, browserBackend, buildDriveDeclarationSchema, checkHost, checkOutputPaths, checkTokenSites, childWrapperSchema, childrenSchema, clearRunRecord, collectTokenSites, compoundHostSchema, compoundOutputSource, compoundWiringSchema, computeOutputsHash, concatTokenSchema, connectReactorIssues, declaredGenericCompoundHostSchema, declaredHostSchemas, defaultUserDataDir, defineHostSchemas, describeHostOutputs, describeMapElements, describeToken, driveAddressMessage, driveDeclarationSchema, drivesSchema, emitHostJsonSchema, emittedHostSchemas, entryActiveForVerb, envSitesOf, envTokenSchema, envTokenable, expectHost, explainDrivePlan, exportHost, findDeadConnectConfig, findNonStaticValue, findRemovedForms, findToken, forbidRef, formatPath, genericCompoundHostSchema, getVerb, hostExportSchema, hostNameSchema, hostSchemaIssues, hostTypeSatisfies, isBuiltinEnvName, isHtmlNavigation, isOriginPlaceholderUrl, isPidAlive, isSchemaLike, isStructuralMultiReactor, isSwitchboardProxyPath, isToken, itemTokenSchema, keyTokenSchema, kindShapeIssues, knownVerbIssues, lintHostImportGraph, lintHostImports, lintOutputsFile, listRunRecords, listVerbs, loadHost, loadProducers, makeHostSchemas, mapTokenSchema, memberForRef, mergeContributions, mergeDefaultDrives, mergeDrivePlan, normalizePluginEntries, normalizePluginEntry, originOrUrlSchema, outputRefsOf, outputSitesOf, outputTokenSchema, placeConnectDrives, placementKeyIssues, planCompound, pluginEntryObjectSchema, pluginEntrySchema, primaryBackend, probeHostsFolder, probeRun, processResolveEnv, producerOutputsSchemas, profileSchema, projectDriveId, projectDriveIdWith, projectDrivesIntoConnect, projectReactorToConnect, protocolConflicts, protocolEnv, protocolEnvAgrees, reactorBackendKindSchema, reactorBackendSchema, reactorBlockToSwitchboardConfig, reactorClientMode, reactorHostSchema, reactorProtocolSchema, reactorSchema, readOutputsFileHash, readProjectName, readRunRecord, rebaseDriveUrl, ref, refKey, refineConnectReactor, refineStartOrder, registerHostType, remoteBackendUrls, remoteBackends, renderTokens, resolveDriveDeclaration, resolveHostOutputs, resolveHostPlugins, resolveOrder, resolveOriginPlaceholders, resolvePluginContributions, resolveRunnerModule, resolveUserDataPlaceholders, runCompound, runObserveHook, runObserveHookSequential, runProvideHook, runRecordMemberSchema, runRecordOutputSource, runRecordSchema, runTransformHook, runnerBaseSchema, runnerHandleSchema, runnerKindSchema, runnerOutputsSchema, scanHostImports, schemaAtPath, seedDrives, spawnHost, stripComments, substituteBuiltinEnv, switchboardOfDrive, toOriginPlaceholder, toStartedHandle, tokenKeyOf, tokenSchema, tokenable, unservedConnectStorage, unwrapEscapes, validateDeclaredHost, validateHost, withOriginPlaceholders, writeRunRecord };
1180
+
1181
+ //# sourceMappingURL=index.mjs.map