@powerhousedao/ph-cli 6.2.3-dev.10 → 6.2.3-dev.101

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