@powerhousedao/ph-cli 6.2.3 → 6.3.0-dev.2

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