@powerhousedao/host-core 6.3.0-dev.9 → 6.4.0-next.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{compound-CBqPgk38.d.mts → compound-D2dh2VUh.d.mts} +332 -22
- package/dist/compound-D2dh2VUh.d.mts.map +1 -0
- package/dist/{compound-DKi56SSx.mjs → compound-n-bO0qKh.mjs} +1616 -487
- package/dist/compound-n-bO0qKh.mjs.map +1 -0
- package/dist/{env-substitution-C_fVirPh.d.mts → env-substitution-Ct39KFvA.d.mts} +7 -3
- package/dist/env-substitution-Ct39KFvA.d.mts.map +1 -0
- package/dist/{env-substitution-BXGohOGN.mjs → env-substitution-FJ5Nua4M.mjs} +29 -10
- package/dist/env-substitution-FJ5Nua4M.mjs.map +1 -0
- package/dist/{host-schemas-BM7F21lf.d.mts → host-schemas-B6_-P11_.d.mts} +52 -19
- package/dist/host-schemas-B6_-P11_.d.mts.map +1 -0
- package/dist/index.d.mts +194 -129
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +51 -355
- package/dist/index.mjs.map +1 -1
- package/dist/kill-tree.d.mts +8 -0
- package/dist/kill-tree.d.mts.map +1 -0
- package/dist/kill-tree.mjs +73 -0
- package/dist/kill-tree.mjs.map +1 -0
- package/dist/plugins-DP3YlIWx.mjs +309 -0
- package/dist/plugins-DP3YlIWx.mjs.map +1 -0
- package/dist/{plugins-Uk84BRay.d.mts → plugins-Dsmfhbn7.d.mts} +53 -3
- package/dist/plugins-Dsmfhbn7.d.mts.map +1 -0
- package/dist/plugins.d.mts +2 -2
- package/dist/plugins.mjs +2 -174
- package/dist/projection.d.mts +12 -18
- package/dist/projection.d.mts.map +1 -1
- package/dist/projection.mjs +17 -10
- package/dist/projection.mjs.map +1 -1
- package/dist/runners/compound.d.mts +9 -3
- package/dist/runners/compound.d.mts.map +1 -1
- package/dist/runners/compound.mjs +1 -1
- package/dist/schema.d.mts +6 -4
- package/dist/schema.d.mts.map +1 -1
- package/dist/schema.mjs +5 -4
- package/dist/schema.mjs.map +1 -1
- package/package.json +9 -3
- package/dist/compound-CBqPgk38.d.mts.map +0 -1
- package/dist/compound-DKi56SSx.mjs.map +0 -1
- package/dist/env-substitution-BXGohOGN.mjs.map +0 -1
- package/dist/env-substitution-C_fVirPh.d.mts.map +0 -1
- package/dist/host-schemas-BM7F21lf.d.mts.map +0 -1
- package/dist/plugins-Uk84BRay.d.mts.map +0 -1
- package/dist/plugins.mjs.map +0 -1
|
@@ -1,273 +1,60 @@
|
|
|
1
|
+
import { killTree } from "./kill-tree.mjs";
|
|
1
2
|
import { createRequire } from "node:module";
|
|
2
3
|
import { createHash } from "node:crypto";
|
|
3
|
-
import fs, { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
|
|
4
|
+
import fs, { existsSync, readFileSync, readdirSync, realpathSync, statSync } from "node:fs";
|
|
4
5
|
import path from "node:path";
|
|
5
6
|
import { pathToFileURL } from "node:url";
|
|
7
|
+
import { Worker } from "node:worker_threads";
|
|
6
8
|
import { z } from "zod";
|
|
7
9
|
import { TOKEN_ESCAPE_KEY, TOKEN_KEYS, concatTokenSchema, envTokenSchema, envTokenable, findToken, forbidRef, isToken, itemTokenSchema, keyTokenSchema, mapTokenSchema, outputTokenSchema, ref, switchboardOfDrive, tokenKeyOf, tokenSchema, tokenable } from "@powerhousedao/shared/host-tokens";
|
|
8
10
|
import { isOriginPlaceholderUrl } from "@powerhousedao/shared/connect/origin-placeholder";
|
|
9
11
|
import { resolvePhDir } from "@powerhousedao/shared/clis/ph-dir";
|
|
10
|
-
import { execFileSync } from "node:child_process";
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
* R1 — the host plugin framework (bridge-runners-to-plugins plan,
|
|
14
|
-
* customization-references/host-core as the blueprint).
|
|
15
|
-
*
|
|
16
|
-
* A plugin is hooks + contributions; hooks are boot wiring (main realm only),
|
|
17
|
-
* contributions are declarative, serializable surface. Host RUNTIMES define
|
|
18
|
-
* the hook vocabulary and interleave their own wiring between stages — they
|
|
19
|
-
* are never plugins themselves.
|
|
20
|
-
*
|
|
21
|
-
* host.js carries the COMPOSITION as `runner.plugins` entries:
|
|
22
|
-
* string | { module, enabled?, verbs?, config? }
|
|
23
|
-
* Presence is activation (enabled defaults true); `verbs` scopes an entry to
|
|
24
|
-
* matching run verbs; `config` is validated against the plugin's declared
|
|
25
|
-
* zod schema. Entries resolve from the PROJECT's dependency tree exactly
|
|
26
|
-
* like runner modules.
|
|
27
|
-
*/
|
|
28
|
-
var PluginError = class extends Error {
|
|
29
|
-
constructor(message, hint) {
|
|
30
|
-
super(hint ? `${message}\n Hint: ${hint}` : message);
|
|
31
|
-
this.name = "PluginError";
|
|
32
|
-
}
|
|
33
|
-
};
|
|
34
|
-
const pluginEntryObjectSchema = z.strictObject({
|
|
35
|
-
module: z.string().min(1),
|
|
36
|
-
/** Presence is activation BY DEFAULT; false is the explicit off-switch. */
|
|
37
|
-
enabled: z.boolean().optional(),
|
|
38
|
-
/** "*" (default) or the run verbs this entry is active for. */
|
|
39
|
-
verbs: z.union([z.literal("*"), z.array(z.string().min(1)).min(1)]).optional(),
|
|
40
|
-
/** Validated against the plugin's declared configSchema at resolution. */
|
|
41
|
-
config: z.record(z.string(), z.unknown()).optional()
|
|
42
|
-
});
|
|
43
|
-
const pluginEntrySchema = z.union([z.string().min(1), pluginEntryObjectSchema]);
|
|
44
|
-
function normalizePluginEntry(entry) {
|
|
45
|
-
if (typeof entry === "string") return {
|
|
46
|
-
module: entry,
|
|
47
|
-
enabled: true,
|
|
48
|
-
verbs: "*",
|
|
49
|
-
config: {}
|
|
50
|
-
};
|
|
51
|
-
return {
|
|
52
|
-
module: entry.module,
|
|
53
|
-
enabled: entry.enabled ?? true,
|
|
54
|
-
verbs: entry.verbs ?? "*",
|
|
55
|
-
config: entry.config ?? {}
|
|
56
|
-
};
|
|
57
|
-
}
|
|
58
|
-
/** Module is the identity key: a duplicate makes override targeting and
|
|
59
|
-
* ordering ambiguous, so it fails loudly. */
|
|
60
|
-
function normalizePluginEntries(entries, where) {
|
|
61
|
-
const normalized = entries.map(normalizePluginEntry);
|
|
62
|
-
const seen = /* @__PURE__ */ new Set();
|
|
63
|
-
for (const entry of normalized) {
|
|
64
|
-
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.");
|
|
65
|
-
seen.add(entry.module);
|
|
66
|
-
}
|
|
67
|
-
return normalized;
|
|
68
|
-
}
|
|
69
|
-
function entryActiveForVerb(entry, verb) {
|
|
70
|
-
if (!entry.enabled) return false;
|
|
71
|
-
return entry.verbs === "*" || entry.verbs.includes(verb);
|
|
72
|
-
}
|
|
12
|
+
import { execFileSync, spawn } from "node:child_process";
|
|
13
|
+
import net from "node:net";
|
|
14
|
+
//#region src/drive-schema.ts
|
|
73
15
|
/**
|
|
74
|
-
* The
|
|
75
|
-
*
|
|
76
|
-
*
|
|
77
|
-
* the
|
|
16
|
+
* The schema half of drives.ts, zod only so `./schema` stays neutral.
|
|
17
|
+
* - slug: the SEEDING KEY (idempotence); id optional (stable identity).
|
|
18
|
+
* - preferredEditor: stored at header.meta.preferredEditor; Connect config's
|
|
19
|
+
* `app` is the legacy alias.
|
|
20
|
+
* - remote.url: a drive served elsewhere; local fields are ignored for it.
|
|
21
|
+
* Token-able (`$output` on a producer's `drives.<slug>.url`).
|
|
78
22
|
*/
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
pre: [],
|
|
103
|
-
normal: [],
|
|
104
|
-
post: []
|
|
105
|
-
};
|
|
106
|
-
for (const plugin of plugins) buckets[plugin.enforce ?? "normal"].push(plugin);
|
|
107
|
-
const bucketed = [
|
|
108
|
-
...buckets.pre,
|
|
109
|
-
...buckets.normal,
|
|
110
|
-
...buckets.post
|
|
111
|
-
];
|
|
112
|
-
const byName = new Map(bucketed.map((p) => [p.name, p]));
|
|
113
|
-
for (const plugin of bucketed) for (const dep of plugin.dependsOn ?? []) if (!byName.has(dep)) throw new PluginError(`Plugin "${plugin.name}" depends on missing plugin "${dep}".`, "dependsOn names PLUGINS only — the host runtime is implied and never named.");
|
|
114
|
-
const ordered = [];
|
|
115
|
-
const state = /* @__PURE__ */ new Map();
|
|
116
|
-
const visit = (plugin, chain) => {
|
|
117
|
-
const mark = state.get(plugin.name);
|
|
118
|
-
if (mark === "done") return;
|
|
119
|
-
if (mark === "visiting") throw new PluginError(`Plugin dependency cycle: ${[...chain, plugin.name].join(" -> ")}.`);
|
|
120
|
-
state.set(plugin.name, "visiting");
|
|
121
|
-
for (const dep of plugin.dependsOn ?? []) visit(byName.get(dep), [...chain, plugin.name]);
|
|
122
|
-
state.set(plugin.name, "done");
|
|
123
|
-
ordered.push(plugin);
|
|
124
|
-
};
|
|
125
|
-
for (const plugin of bucketed) visit(plugin, []);
|
|
126
|
-
return ordered;
|
|
127
|
-
}
|
|
128
|
-
async function runProvideHook(name, plugins, ctx) {
|
|
129
|
-
const impls = plugins.filter((p) => typeof p.hooks?.[name] === "function");
|
|
130
|
-
if (impls.length > 1) throw new PluginError(`Hook "${name}" is provided by ${impls.map((p) => `"${p.name}"`).join(" and ")} — provide hooks have one winner.`);
|
|
131
|
-
const impl = impls[0]?.hooks?.[name];
|
|
132
|
-
return impl ? await impl(ctx) : void 0;
|
|
133
|
-
}
|
|
134
|
-
async function runTransformHook(name, plugins, ctx, seed) {
|
|
135
|
-
let value = seed;
|
|
136
|
-
for (const plugin of plugins) {
|
|
137
|
-
const impl = plugin.hooks?.[name];
|
|
138
|
-
if (typeof impl === "function") value = await impl(value, ctx);
|
|
139
|
-
}
|
|
140
|
-
return value;
|
|
141
|
-
}
|
|
142
|
-
/** Sequential observe, in plugin order — for lifecycle moments whose order
|
|
143
|
-
* is load-bearing (teardown: the switchboard stops privacy before workflows
|
|
144
|
-
* before the api, per the carve map). */
|
|
145
|
-
async function runObserveHookSequential(name, plugins, ctx) {
|
|
146
|
-
for (const plugin of plugins) {
|
|
147
|
-
const impl = plugin.hooks?.[name];
|
|
148
|
-
if (typeof impl === "function") await impl(ctx);
|
|
149
|
-
}
|
|
150
|
-
}
|
|
151
|
-
async function runObserveHook(name, plugins, ctx) {
|
|
152
|
-
await Promise.all(plugins.map(async (plugin) => {
|
|
153
|
-
const impl = plugin.hooks?.[name];
|
|
154
|
-
if (typeof impl === "function") await impl(ctx);
|
|
155
|
-
}));
|
|
23
|
+
function buildDriveDeclarationSchema(urlField) {
|
|
24
|
+
return z.strictObject({
|
|
25
|
+
slug: z.string().min(1),
|
|
26
|
+
id: z.string().min(1).optional(),
|
|
27
|
+
/** Derive the id from the project path (`<slug>-<hash of the path>`) — the
|
|
28
|
+
* same ids classic `ph vetra` produced. `true` serves the drive under the
|
|
29
|
+
* hashed slug too (the vetra drive's slug IS its hashed id); `"id"` hashes
|
|
30
|
+
* only the id and keeps the declared slug (the classic Workflows drive:
|
|
31
|
+
* `/d/workflows`, id `workflows-<hash>`). */
|
|
32
|
+
projectHash: z.union([z.boolean(), z.literal("id")]).optional(),
|
|
33
|
+
/** What a missing drive is created as. Default powerhouse/document-drive. */
|
|
34
|
+
documentType: z.enum(["powerhouse/document-drive", "powerhouse/reactor-drive"]).optional(),
|
|
35
|
+
name: z.string().min(1).optional(),
|
|
36
|
+
icon: z.string().optional(),
|
|
37
|
+
preferredEditor: z.string().optional(),
|
|
38
|
+
sharingType: z.enum([
|
|
39
|
+
"public",
|
|
40
|
+
"private",
|
|
41
|
+
"shared"
|
|
42
|
+
]).optional(),
|
|
43
|
+
availableOffline: z.boolean().optional(),
|
|
44
|
+
remote: z.strictObject({ url: urlField(z.string().min(1)) }).optional()
|
|
45
|
+
});
|
|
156
46
|
}
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
}
|
|
165
|
-
const sorted = [...resolved].sort((a, b) => rank[a.provenance] - rank[b.provenance]);
|
|
166
|
-
const merged = {};
|
|
167
|
-
for (const { plugin, provenance } of sorted) for (const [kind, values] of Object.entries(plugin.contributions ?? {})) {
|
|
168
|
-
if (!values) continue;
|
|
169
|
-
const bucket = merged[kind] ??= [];
|
|
170
|
-
for (const value of values) bucket.push({
|
|
171
|
-
value,
|
|
172
|
-
source: {
|
|
173
|
-
pluginName: plugin.name,
|
|
174
|
-
provenance
|
|
175
|
-
}
|
|
176
|
-
});
|
|
177
|
-
}
|
|
178
|
-
return merged;
|
|
47
|
+
const driveDeclarationSchema = buildDriveDeclarationSchema(tokenable);
|
|
48
|
+
const drivesSchema = z.array(driveDeclarationSchema);
|
|
49
|
+
/** The project-hashed drive id (`${slug}-${sha256(projectRoot)[0..8]}`) with
|
|
50
|
+
* the hash function injected, so neutral consumers (a browser monitor) can
|
|
51
|
+
* pass `crypto.subtle`-derived or precomputed hex. drives.ts binds it to
|
|
52
|
+
* node:crypto as `projectDriveId`. */
|
|
53
|
+
function projectDriveIdWith(sha256Hex, projectRoot, slug) {
|
|
54
|
+
return `${slug}-${sha256Hex(projectRoot).substring(0, 8)}`;
|
|
179
55
|
}
|
|
180
56
|
//#endregion
|
|
181
|
-
//#region src/
|
|
182
|
-
/**
|
|
183
|
-
* NODE-ONLY plugin resolution (split from plugins.ts so the pure runner core
|
|
184
|
-
* stays browser-safe for ConnectCore — R3). Resolves host.js entries from the
|
|
185
|
-
* PROJECT dependency tree, exactly like runner modules.
|
|
186
|
-
*/
|
|
187
|
-
function isHostPluginShape(value) {
|
|
188
|
-
return value !== null && typeof value === "object" && typeof value.name === "string";
|
|
189
|
-
}
|
|
190
|
-
/**
|
|
191
|
-
* Resolve host.js plugin entries into live plugins for one host boot:
|
|
192
|
-
* verb-filter → module resolution from the project tree (default condition,
|
|
193
|
-
* like runners) → factory/object contract → config validation → appliesTo.
|
|
194
|
-
*/
|
|
195
|
-
async function resolveHostPlugins(projectRoot, hostType, verb, entries, where) {
|
|
196
|
-
const normalized = normalizePluginEntries(entries, where);
|
|
197
|
-
const projectRequire = createRequire(pathToFileURL(path.join(projectRoot, "package.json")).href);
|
|
198
|
-
const resolved = [];
|
|
199
|
-
for (const entry of normalized) {
|
|
200
|
-
if (!entryActiveForVerb(entry, verb)) continue;
|
|
201
|
-
let file;
|
|
202
|
-
try {
|
|
203
|
-
file = projectRequire.resolve(entry.module);
|
|
204
|
-
} catch {
|
|
205
|
-
throw new PluginError(`${where}: cannot resolve plugin "${entry.module}" from ${projectRoot}.`, "Plugins resolve from the project dependency tree, exactly like runner modules.");
|
|
206
|
-
}
|
|
207
|
-
const exported = (await import(pathToFileURL(file).href)).default;
|
|
208
|
-
let plugin;
|
|
209
|
-
if (typeof exported === "function") plugin = exported(entry.config);
|
|
210
|
-
else if (isHostPluginShape(exported)) {
|
|
211
|
-
if (Object.keys(entry.config).length > 0 && !exported.configSchema) throw new PluginError(`${where}: plugin "${entry.module}" takes no config, but the entry passes one.`);
|
|
212
|
-
plugin = exported;
|
|
213
|
-
} else throw new PluginError(`${where}: "${entry.module}" does not default-export a plugin object or factory.`, "Export `{ name, hooks?, contributions? }` or `(config) => plugin`.");
|
|
214
|
-
if (plugin.configSchema) {
|
|
215
|
-
const parsed = plugin.configSchema.safeParse(entry.config);
|
|
216
|
-
if (!parsed.success) throw new PluginError(`${where}: config for plugin "${plugin.name}" is invalid:\n` + z.prettifyError(parsed.error));
|
|
217
|
-
}
|
|
218
|
-
const appliesTo = plugin.appliesTo ?? "reactor";
|
|
219
|
-
if (!hostTypeSatisfies(hostType, appliesTo)) throw new PluginError(`${where}: plugin "${plugin.name}" applies to "${appliesTo}" hosts, but this host is "${hostType}".`);
|
|
220
|
-
resolved.push({
|
|
221
|
-
entry,
|
|
222
|
-
plugin,
|
|
223
|
-
provenance: "dependency"
|
|
224
|
-
});
|
|
225
|
-
}
|
|
226
|
-
return resolved;
|
|
227
|
-
}
|
|
228
|
-
/**
|
|
229
|
-
* LENIENT resolution for diagnostics (`ph run <host> --explain drives`):
|
|
230
|
-
* collects the drive contributions of the entries active for `verb`. Unlike
|
|
231
|
-
* resolveHostPlugins it does not know the host type (so appliesTo is not
|
|
232
|
-
* checked) and does not fail on a specifier the project tree cannot resolve
|
|
233
|
-
* — the entry is listed under `unresolved` instead. Config is still validated
|
|
234
|
-
* against the plugin's schema, so a bad entry surfaces here too.
|
|
235
|
-
*/
|
|
236
|
-
async function resolvePluginContributions(projectRoot, verb, entries, where) {
|
|
237
|
-
const normalized = normalizePluginEntries(entries, where);
|
|
238
|
-
const projectRequire = createRequire(pathToFileURL(path.join(projectRoot, "package.json")).href);
|
|
239
|
-
const plan = {
|
|
240
|
-
drives: [],
|
|
241
|
-
unresolved: []
|
|
242
|
-
};
|
|
243
|
-
for (const entry of normalized) {
|
|
244
|
-
if (!entryActiveForVerb(entry, verb)) continue;
|
|
245
|
-
let file;
|
|
246
|
-
try {
|
|
247
|
-
file = projectRequire.resolve(entry.module);
|
|
248
|
-
} catch {
|
|
249
|
-
plan.unresolved.push(entry.module);
|
|
250
|
-
continue;
|
|
251
|
-
}
|
|
252
|
-
const exported = (await import(pathToFileURL(file).href)).default;
|
|
253
|
-
let plugin;
|
|
254
|
-
if (typeof exported === "function") plugin = exported(entry.config);
|
|
255
|
-
else if (isHostPluginShape(exported)) plugin = exported;
|
|
256
|
-
else {
|
|
257
|
-
plan.unresolved.push(entry.module);
|
|
258
|
-
continue;
|
|
259
|
-
}
|
|
260
|
-
if (plugin.configSchema) {
|
|
261
|
-
const parsed = plugin.configSchema.safeParse(entry.config);
|
|
262
|
-
if (!parsed.success) throw new PluginError(`${where}: config for plugin "${plugin.name}" is invalid:\n` + z.prettifyError(parsed.error));
|
|
263
|
-
}
|
|
264
|
-
for (const declaration of plugin.contributions?.drives ?? []) plan.drives.push({
|
|
265
|
-
declaration,
|
|
266
|
-
source: plugin.name
|
|
267
|
-
});
|
|
268
|
-
}
|
|
269
|
-
return plan;
|
|
270
|
-
}
|
|
57
|
+
//#region src/connect-composition.ts
|
|
271
58
|
/**
|
|
272
59
|
* The connect config slices each built-in Connect plugin owns, by specifier
|
|
273
60
|
* (typed-host-configs 1.6). Under a declared composition Connect zeroes a
|
|
@@ -369,9 +156,9 @@ function alreadyServed(authored, served) {
|
|
|
369
156
|
return Object.keys(want).every((key) => alreadyServed(want[key], have[key]));
|
|
370
157
|
}
|
|
371
158
|
/**
|
|
372
|
-
* The composition that serves `config` as
|
|
373
|
-
*
|
|
374
|
-
*
|
|
159
|
+
* The composition that serves `config` as it is written, for a host that
|
|
160
|
+
* declares no `runner.plugins`. `config` is the connect block Connect is
|
|
161
|
+
* served without a composition.
|
|
375
162
|
*
|
|
376
163
|
* A built-in configured through its entry is always in it, its entry holding
|
|
377
164
|
* the values `config` has at the slices it owns: composed in, the plugin
|
|
@@ -401,85 +188,175 @@ function defaultConnectComposition(config) {
|
|
|
401
188
|
}
|
|
402
189
|
return composition;
|
|
403
190
|
}
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
*
|
|
408
|
-
*
|
|
409
|
-
*
|
|
410
|
-
*
|
|
411
|
-
*
|
|
412
|
-
*
|
|
413
|
-
*
|
|
414
|
-
*
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
191
|
+
//#endregion
|
|
192
|
+
//#region src/plugins.ts
|
|
193
|
+
/**
|
|
194
|
+
* R1 — the host plugin framework (bridge-runners-to-plugins plan,
|
|
195
|
+
* customization-references/host-core as the blueprint).
|
|
196
|
+
*
|
|
197
|
+
* A plugin is hooks + contributions; hooks are boot wiring (main realm only),
|
|
198
|
+
* contributions are declarative, serializable surface. Host RUNTIMES define
|
|
199
|
+
* the hook vocabulary and interleave their own wiring between stages — they
|
|
200
|
+
* are never plugins themselves.
|
|
201
|
+
*
|
|
202
|
+
* host.js carries the COMPOSITION as `runner.plugins` entries:
|
|
203
|
+
* string | { module, enabled?, verbs?, config? }
|
|
204
|
+
* Presence is activation (enabled defaults true); `verbs` scopes an entry to
|
|
205
|
+
* matching run verbs; `config` is validated against the plugin's declared
|
|
206
|
+
* zod schema. Entries resolve from the PROJECT's dependency tree exactly
|
|
207
|
+
* like runner modules.
|
|
208
|
+
*/
|
|
209
|
+
var PluginError = class extends Error {
|
|
210
|
+
constructor(message, hint) {
|
|
211
|
+
super(hint ? `${message}\n Hint: ${hint}` : message);
|
|
212
|
+
this.name = "PluginError";
|
|
213
|
+
}
|
|
214
|
+
};
|
|
215
|
+
const pluginEntryObjectSchema = z.strictObject({
|
|
216
|
+
module: z.string().min(1),
|
|
217
|
+
/** Presence is activation BY DEFAULT; false is the explicit off-switch. */
|
|
218
|
+
enabled: z.boolean().optional(),
|
|
219
|
+
/** "*" (default) or the run verbs this entry is active for. */
|
|
220
|
+
verbs: z.union([z.literal("*"), z.array(z.string().min(1)).min(1)]).optional(),
|
|
221
|
+
/** Validated against the plugin's declared configSchema at resolution. */
|
|
222
|
+
config: z.record(z.string(), z.unknown()).optional()
|
|
223
|
+
});
|
|
224
|
+
const pluginEntrySchema = z.union([z.string().min(1), pluginEntryObjectSchema]);
|
|
225
|
+
function normalizePluginEntry(entry) {
|
|
226
|
+
if (typeof entry === "string") return {
|
|
227
|
+
module: entry,
|
|
228
|
+
enabled: true,
|
|
229
|
+
verbs: "*",
|
|
230
|
+
config: {}
|
|
231
|
+
};
|
|
232
|
+
return {
|
|
233
|
+
module: entry.module,
|
|
234
|
+
enabled: entry.enabled ?? true,
|
|
235
|
+
verbs: entry.verbs ?? "*",
|
|
236
|
+
config: entry.config ?? {}
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
/** Module is the identity key: a duplicate makes override targeting and
|
|
240
|
+
* ordering ambiguous, so it fails loudly. */
|
|
241
|
+
function normalizePluginEntries(entries, where) {
|
|
242
|
+
const normalized = entries.map(normalizePluginEntry);
|
|
243
|
+
const seen = /* @__PURE__ */ new Set();
|
|
244
|
+
for (const entry of normalized) {
|
|
245
|
+
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.");
|
|
246
|
+
seen.add(entry.module);
|
|
247
|
+
}
|
|
248
|
+
return normalized;
|
|
249
|
+
}
|
|
250
|
+
function entryActiveForVerb(entry, verb) {
|
|
251
|
+
if (!entry.enabled) return false;
|
|
252
|
+
return entry.verbs === "*" || entry.verbs.includes(verb);
|
|
253
|
+
}
|
|
254
|
+
/**
|
|
255
|
+
* The appliesTo hierarchy. "reactor" is the base every reactor host extends;
|
|
256
|
+
* "compound" is its own branch (plugins over the member set — e.g. the clint
|
|
257
|
+
* proxy). Host runtimes register their id with a parent; compatibility walks
|
|
258
|
+
* the parent chain.
|
|
259
|
+
*/
|
|
260
|
+
const HOST_TYPE_PARENTS = {
|
|
261
|
+
reactor: null,
|
|
262
|
+
compound: null,
|
|
263
|
+
connect: "reactor",
|
|
264
|
+
switchboard: "reactor",
|
|
265
|
+
mastra: "reactor"
|
|
266
|
+
};
|
|
267
|
+
function registerHostType(id, parent) {
|
|
268
|
+
if (id in HOST_TYPE_PARENTS && HOST_TYPE_PARENTS[id] !== parent) throw new PluginError(`Host type "${id}" is already registered with parent "${String(HOST_TYPE_PARENTS[id])}".`);
|
|
269
|
+
HOST_TYPE_PARENTS[id] = parent;
|
|
270
|
+
}
|
|
271
|
+
function hostTypeSatisfies(hostType, appliesTo) {
|
|
272
|
+
let current = hostType;
|
|
273
|
+
while (current !== null) {
|
|
274
|
+
if (current === appliesTo) return true;
|
|
275
|
+
current = current in HOST_TYPE_PARENTS ? HOST_TYPE_PARENTS[current] : null;
|
|
276
|
+
}
|
|
277
|
+
return false;
|
|
278
|
+
}
|
|
279
|
+
/** Registration order, bucketed pre → normal → post (stable within buckets),
|
|
280
|
+
* then dependsOn topo-sorted within the bucketed order. */
|
|
281
|
+
function resolveOrder(plugins) {
|
|
282
|
+
const buckets = {
|
|
283
|
+
pre: [],
|
|
284
|
+
normal: [],
|
|
285
|
+
post: []
|
|
286
|
+
};
|
|
287
|
+
for (const plugin of plugins) buckets[plugin.enforce ?? "normal"].push(plugin);
|
|
288
|
+
const bucketed = [
|
|
289
|
+
...buckets.pre,
|
|
290
|
+
...buckets.normal,
|
|
291
|
+
...buckets.post
|
|
292
|
+
];
|
|
293
|
+
const byName = new Map(bucketed.map((p) => [p.name, p]));
|
|
294
|
+
for (const plugin of bucketed) for (const dep of plugin.dependsOn ?? []) if (!byName.has(dep)) throw new PluginError(`Plugin "${plugin.name}" depends on missing plugin "${dep}".`, "dependsOn names PLUGINS only — the host runtime is implied and never named.");
|
|
295
|
+
const ordered = [];
|
|
296
|
+
const state = /* @__PURE__ */ new Map();
|
|
297
|
+
const visit = (plugin, chain) => {
|
|
298
|
+
const mark = state.get(plugin.name);
|
|
299
|
+
if (mark === "done") return;
|
|
300
|
+
if (mark === "visiting") throw new PluginError(`Plugin dependency cycle: ${[...chain, plugin.name].join(" -> ")}.`);
|
|
301
|
+
state.set(plugin.name, "visiting");
|
|
302
|
+
for (const dep of plugin.dependsOn ?? []) visit(byName.get(dep), [...chain, plugin.name]);
|
|
303
|
+
state.set(plugin.name, "done");
|
|
304
|
+
ordered.push(plugin);
|
|
305
|
+
};
|
|
306
|
+
for (const plugin of bucketed) visit(plugin, []);
|
|
307
|
+
return ordered;
|
|
308
|
+
}
|
|
309
|
+
async function runProvideHook(name, plugins, ctx) {
|
|
310
|
+
const impls = plugins.filter((p) => typeof p.hooks?.[name] === "function");
|
|
311
|
+
if (impls.length > 1) throw new PluginError(`Hook "${name}" is provided by ${impls.map((p) => `"${p.name}"`).join(" and ")} — provide hooks have one winner.`);
|
|
312
|
+
const impl = impls[0]?.hooks?.[name];
|
|
313
|
+
return impl ? await impl(ctx) : void 0;
|
|
314
|
+
}
|
|
315
|
+
async function runTransformHook(name, plugins, ctx, seed) {
|
|
316
|
+
let value = seed;
|
|
317
|
+
for (const plugin of plugins) {
|
|
318
|
+
const impl = plugin.hooks?.[name];
|
|
319
|
+
if (typeof impl === "function") value = await impl(value, ctx);
|
|
320
|
+
}
|
|
321
|
+
return value;
|
|
322
|
+
}
|
|
323
|
+
/** Sequential observe, in plugin order — for lifecycle moments whose order
|
|
324
|
+
* is load-bearing (teardown: the switchboard stops privacy before workflows
|
|
325
|
+
* before the api, per the carve map). */
|
|
326
|
+
async function runObserveHookSequential(name, plugins, ctx) {
|
|
327
|
+
for (const plugin of plugins) {
|
|
328
|
+
const impl = plugin.hooks?.[name];
|
|
329
|
+
if (typeof impl === "function") await impl(ctx);
|
|
438
330
|
}
|
|
439
|
-
return warnings;
|
|
440
331
|
}
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
* - preferredEditor: stored at header.meta.preferredEditor; Connect config's
|
|
447
|
-
* `app` is the legacy alias.
|
|
448
|
-
* - remote.url: a drive served elsewhere; local fields are ignored for it.
|
|
449
|
-
* Token-able (`$output` on a producer's `drives.<slug>.url`).
|
|
450
|
-
*/
|
|
451
|
-
function buildDriveDeclarationSchema(urlField) {
|
|
452
|
-
return z.strictObject({
|
|
453
|
-
slug: z.string().min(1),
|
|
454
|
-
id: z.string().min(1).optional(),
|
|
455
|
-
/** Derive the id from the project path, like generateProjectDriveId — the
|
|
456
|
-
* same ids classic `ph vetra` produces. `true` serves the drive under the
|
|
457
|
-
* hashed slug too (the vetra drive's slug IS its hashed id); `"id"` hashes
|
|
458
|
-
* only the id and keeps the declared slug (the classic Workflows drive:
|
|
459
|
-
* `/d/workflows`, id `workflows-<hash>`). */
|
|
460
|
-
projectHash: z.union([z.boolean(), z.literal("id")]).optional(),
|
|
461
|
-
/** What a missing drive is created as. Default powerhouse/document-drive. */
|
|
462
|
-
documentType: z.enum(["powerhouse/document-drive", "powerhouse/reactor-drive"]).optional(),
|
|
463
|
-
name: z.string().min(1).optional(),
|
|
464
|
-
icon: z.string().optional(),
|
|
465
|
-
preferredEditor: z.string().optional(),
|
|
466
|
-
sharingType: z.enum([
|
|
467
|
-
"public",
|
|
468
|
-
"private",
|
|
469
|
-
"shared"
|
|
470
|
-
]).optional(),
|
|
471
|
-
availableOffline: z.boolean().optional(),
|
|
472
|
-
remote: z.strictObject({ url: urlField(z.string().min(1)) }).optional()
|
|
473
|
-
});
|
|
332
|
+
async function runObserveHook(name, plugins, ctx) {
|
|
333
|
+
await Promise.all(plugins.map(async (plugin) => {
|
|
334
|
+
const impl = plugin.hooks?.[name];
|
|
335
|
+
if (typeof impl === "function") await impl(ctx);
|
|
336
|
+
}));
|
|
474
337
|
}
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
338
|
+
/** Array kinds concatenate in provenance-then-order sequence (built-in first,
|
|
339
|
+
* so later sources read as overrides where consumers want last-wins). */
|
|
340
|
+
function mergeContributions(resolved) {
|
|
341
|
+
const rank = {
|
|
342
|
+
"built-in": 0,
|
|
343
|
+
local: 1,
|
|
344
|
+
dependency: 2
|
|
345
|
+
};
|
|
346
|
+
const sorted = [...resolved].sort((a, b) => rank[a.provenance] - rank[b.provenance]);
|
|
347
|
+
const merged = {};
|
|
348
|
+
for (const { plugin, provenance } of sorted) for (const [kind, values] of Object.entries(plugin.contributions ?? {})) {
|
|
349
|
+
if (!values) continue;
|
|
350
|
+
const bucket = merged[kind] ??= [];
|
|
351
|
+
for (const value of values) bucket.push({
|
|
352
|
+
value,
|
|
353
|
+
source: {
|
|
354
|
+
pluginName: plugin.name,
|
|
355
|
+
provenance
|
|
356
|
+
}
|
|
357
|
+
});
|
|
358
|
+
}
|
|
359
|
+
return merged;
|
|
483
360
|
}
|
|
484
361
|
//#endregion
|
|
485
362
|
//#region src/host-schemas.ts
|
|
@@ -500,6 +377,16 @@ const HOST_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
|
|
|
500
377
|
const HOST_NAME_MAX_LENGTH = 128;
|
|
501
378
|
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.";
|
|
502
379
|
const hostNameSchema = z.string().min(1).max(128, HOST_NAME_MESSAGE).regex(HOST_NAME_PATTERN, HOST_NAME_MESSAGE);
|
|
380
|
+
/** An npm package name, as `<package>/<host>` names a package that supplies
|
|
381
|
+
* hosts: `name` or `@scope/name`, each part letters, digits, '-', '.', '_'
|
|
382
|
+
* and '~', not starting with '.' or '_'. Each part is one folder name, the
|
|
383
|
+
* one the package has under node_modules. */
|
|
384
|
+
const PACKAGE_NAME_PATTERN = /^(?:@[A-Za-z0-9~-][A-Za-z0-9._~-]*\/)?[A-Za-z0-9~-][A-Za-z0-9._~-]*$/;
|
|
385
|
+
/** How a compound names a member's host: its folder under the project's
|
|
386
|
+
* `hosts/` (or, in a package's compound, the package's first), or
|
|
387
|
+
* `<package>/<host>` for one an installed package supplies. */
|
|
388
|
+
const HOST_REF_PATTERN = new RegExp(`^(?:${PACKAGE_NAME_PATTERN.source.slice(1, -1)}/)?${HOST_NAME_PATTERN.source.slice(1, -1)}$`);
|
|
389
|
+
const HOST_REF_MESSAGE = "A member's host is a host folder (`switchboard`), or `<package>/<host>` (`@acme/tools/studio`) for one an installed package supplies.";
|
|
503
390
|
/**
|
|
504
391
|
* A URL, or one written against the page origin (`${origin}/graphql`): the
|
|
505
392
|
* browser resolves the placeholder when it loads Connect's config, for a
|
|
@@ -524,6 +411,8 @@ const reactorProtocolSchema = z.strictObject({
|
|
|
524
411
|
unsupportedStoredDocuments: z.enum(["refuse", "read-only"]).optional()
|
|
525
412
|
});
|
|
526
413
|
const runnerKindSchema = z.enum(["reactor", "compound"]);
|
|
414
|
+
/** A compound member's process: its own, or the compound's (`shared`). */
|
|
415
|
+
const memberProcessSchema = z.enum(["own", "shared"]);
|
|
527
416
|
const reactorBackendKindSchema = z.enum([
|
|
528
417
|
"in-process",
|
|
529
418
|
"worker",
|
|
@@ -877,8 +766,6 @@ function buildHostSchemas(tokenField) {
|
|
|
877
766
|
provisionalRouteMs: z.number().int().nonnegative().optional()
|
|
878
767
|
}).optional(),
|
|
879
768
|
protocol: reactorProtocolSchema.optional(),
|
|
880
|
-
/** DEPRECATED (dies in R2): workflows become a listed plugin. */
|
|
881
|
-
workflows: z.boolean().optional(),
|
|
882
769
|
renown: z.strictObject({
|
|
883
770
|
url: z.string().optional(),
|
|
884
771
|
networkId: z.string().optional(),
|
|
@@ -922,10 +809,15 @@ function buildHostSchemas(tokenField) {
|
|
|
922
809
|
* which key-merges over the member's own. Plugins live in `runner.plugins`
|
|
923
810
|
* (as on a standalone host); there is no wrapper-level `plugins`. */
|
|
924
811
|
const childWrapperSchema = z.strictObject({
|
|
925
|
-
host: z.string().min(1),
|
|
812
|
+
host: z.string().min(1).regex(HOST_REF_PATTERN, HOST_REF_MESSAGE),
|
|
926
813
|
runner: runnerBaseSchema.partial().extend({ port: z.number().int().min(0).max(65535).optional() }).optional(),
|
|
927
814
|
config: z.looseObject({}).optional(),
|
|
928
|
-
reactor: reactorSchema.optional()
|
|
815
|
+
reactor: reactorSchema.optional(),
|
|
816
|
+
/** Where the member runs: `own`, a child process of the compound
|
|
817
|
+
* (`ph run <host>`), stopped through its stdin; `shared`, in the
|
|
818
|
+
* compound's own process. Default: `own` next to a foreground member
|
|
819
|
+
* (the Cli runner), `shared` otherwise. */
|
|
820
|
+
process: memberProcessSchema.optional()
|
|
929
821
|
});
|
|
930
822
|
const childrenSchema = z.record(z.string(), childWrapperSchema);
|
|
931
823
|
return {
|
|
@@ -1066,6 +958,255 @@ function emittedHostSchemas() {
|
|
|
1066
958
|
};
|
|
1067
959
|
}
|
|
1068
960
|
//#endregion
|
|
961
|
+
//#region src/host-ref.ts
|
|
962
|
+
/**
|
|
963
|
+
* How a host is addressed (decision D5). A bare name (`switchboard`) is the
|
|
964
|
+
* project's own host, `<project>/hosts/switchboard/`, always: a package
|
|
965
|
+
* cannot shadow it. `<package>/<host>` (`@powerhousedao/vetra-cli/studio`,
|
|
966
|
+
* `tools/studio`) is a host an installed package supplies, in the `hosts/`
|
|
967
|
+
* folder it ships: `<package>/hosts/studio/`. The host is the last segment,
|
|
968
|
+
* so a host name has no `/`. Only inside a package's compound does a bare
|
|
969
|
+
* member name look in that package first (`locateHost`'s `scope`).
|
|
970
|
+
*/
|
|
971
|
+
var HostLoadError = class extends Error {
|
|
972
|
+
constructor(message, hint) {
|
|
973
|
+
super(hint ? `${message}\n Hint: ${hint}` : message);
|
|
974
|
+
this.name = "HostLoadError";
|
|
975
|
+
}
|
|
976
|
+
};
|
|
977
|
+
/** Splits a ref at its last `/`; refuses what names no host. */
|
|
978
|
+
function parseHostRef(ref) {
|
|
979
|
+
const slash = ref.lastIndexOf("/");
|
|
980
|
+
if (slash === -1) return { host: ref };
|
|
981
|
+
const pkg = ref.slice(0, slash);
|
|
982
|
+
const host = ref.slice(slash + 1);
|
|
983
|
+
if (/^@[^/]*$/.test(pkg) || ref.startsWith("@") && host === "") throw new HostLoadError(`"${ref}" names a package, not a host.`, `A package's host is <package>/<host>, e.g. \`ph run ${ref.replace(/\/$/, "")}/<host>\`.`);
|
|
984
|
+
if (!PACKAGE_NAME_PATTERN.test(pkg)) throw new HostLoadError(`"${ref}" names no host: a host is <host> (the project's) or <package>/<host>, a host name has no "/", and "${pkg}" is no package name.`);
|
|
985
|
+
if (host === "") throw new HostLoadError(`"${ref}" names package "${pkg}" but no host.`, `Write ${pkg}/<host>.`);
|
|
986
|
+
return {
|
|
987
|
+
package: pkg,
|
|
988
|
+
host
|
|
989
|
+
};
|
|
990
|
+
}
|
|
991
|
+
function formatHostRef(ref) {
|
|
992
|
+
return ref.package === void 0 ? ref.host : `${ref.package}/${ref.host}`;
|
|
993
|
+
}
|
|
994
|
+
/** Where messages point for a host file: `hosts/<host>/host.js`, behind its
|
|
995
|
+
* package for a package's (`@acme/tools/hosts/studio/host.js`). */
|
|
996
|
+
function hostFileLabel(folder, hostPackage) {
|
|
997
|
+
const file = `hosts/${folder}/host.js`;
|
|
998
|
+
return hostPackage ? `${hostPackage.name}/${file}` : file;
|
|
999
|
+
}
|
|
1000
|
+
function packageJsonName(dir) {
|
|
1001
|
+
try {
|
|
1002
|
+
const name = JSON.parse(readFileSync(path.join(dir, "package.json"), "utf8")).name;
|
|
1003
|
+
return typeof name === "string" ? name : void 0;
|
|
1004
|
+
} catch {
|
|
1005
|
+
return;
|
|
1006
|
+
}
|
|
1007
|
+
}
|
|
1008
|
+
/**
|
|
1009
|
+
* The real folder of the installed package `name`, found from `fromRoot` as
|
|
1010
|
+
* Node finds it: the first `<dir>/node_modules/<name>/package.json` on the
|
|
1011
|
+
* lookup paths of `<fromRoot>/package.json`, by its real path (a pnpm link
|
|
1012
|
+
* leads to the package's own folder, whose dependencies are its own). Not
|
|
1013
|
+
* through `exports`, which may not list `package.json`. Undefined when it is
|
|
1014
|
+
* not installed there.
|
|
1015
|
+
*/
|
|
1016
|
+
function resolvePackageRoot(fromRoot, name) {
|
|
1017
|
+
const root = path.resolve(fromRoot);
|
|
1018
|
+
const lookup = createRequire(pathToFileURL(path.join(root, "package.json")).href).resolve.paths(name) ?? [];
|
|
1019
|
+
for (const dir of lookup) {
|
|
1020
|
+
const candidate = path.join(dir, name);
|
|
1021
|
+
if (existsSync(path.join(candidate, "package.json"))) return realpathSync(candidate);
|
|
1022
|
+
}
|
|
1023
|
+
}
|
|
1024
|
+
/** The installed package `name`, found from the project root
|
|
1025
|
+
* (resolvePackageRoot). */
|
|
1026
|
+
function findHostPackage(projectRoot, name, host) {
|
|
1027
|
+
const root = path.resolve(projectRoot);
|
|
1028
|
+
if (packageJsonName(root) === name) throw new HostLoadError(`"${name}/${host}": "${name}" is this project's own package.`, `Run the project's own host by its bare name: \`ph run ${host}\`.`);
|
|
1029
|
+
const found = resolvePackageRoot(root, name);
|
|
1030
|
+
if (found !== void 0) return {
|
|
1031
|
+
name,
|
|
1032
|
+
root: found
|
|
1033
|
+
};
|
|
1034
|
+
throw new HostLoadError(`Package "${name}" is not installed in this project, so it supplies no host "${host}".`, `Add ${name} as a dependency of the project (looked up from ${root}).`);
|
|
1035
|
+
}
|
|
1036
|
+
/** The `<name>/host.js` folders under `<root>/hosts`, sorted; undefined
|
|
1037
|
+
* when there is no hosts/ folder. */
|
|
1038
|
+
function hostFolders(root) {
|
|
1039
|
+
const dir = path.join(root, "hosts");
|
|
1040
|
+
if (!existsSync(dir) || !statSync(dir).isDirectory()) return void 0;
|
|
1041
|
+
return readdirSync(dir, { withFileTypes: true }).filter((entry) => entry.isDirectory() && existsSync(path.join(dir, entry.name, "host.js"))).map((entry) => entry.name).sort();
|
|
1042
|
+
}
|
|
1043
|
+
/** A package's host, or why the package has none by that name. */
|
|
1044
|
+
function packageHostLocation(pkg, host) {
|
|
1045
|
+
const folders = hostFolders(pkg.root);
|
|
1046
|
+
if (folders === void 0 || folders.length === 0) throw new HostLoadError(`Package "${pkg.name}" supplies no hosts: ${pkg.root} has no hosts/<name>/host.js, so "${pkg.name}/${host}" cannot run.`);
|
|
1047
|
+
if (!folders.includes(host)) throw new HostLoadError(`Package "${pkg.name}" supplies no host "${host}". Its hosts: ${folders.join(", ")}.`);
|
|
1048
|
+
return {
|
|
1049
|
+
ref: formatHostRef({
|
|
1050
|
+
package: pkg.name,
|
|
1051
|
+
host
|
|
1052
|
+
}),
|
|
1053
|
+
folder: host,
|
|
1054
|
+
hostsDir: path.join(pkg.root, "hosts"),
|
|
1055
|
+
package: pkg
|
|
1056
|
+
};
|
|
1057
|
+
}
|
|
1058
|
+
/**
|
|
1059
|
+
* Where `ref` is. `<package>/<host>` is always the installed package's,
|
|
1060
|
+
* found from the project root (also when a package's compound writes it). A
|
|
1061
|
+
* bare name is the project's, except in a package's compound (`scope`): there
|
|
1062
|
+
* the package's own host of that name comes first. Throws a HostLoadError
|
|
1063
|
+
* naming the package and the host. A bare name the project lacks is left to
|
|
1064
|
+
* the loader's own message (undefined `package`, project `hostsDir`).
|
|
1065
|
+
*/
|
|
1066
|
+
function locateHost(projectRoot, ref, scope) {
|
|
1067
|
+
const parsed = parseHostRef(ref);
|
|
1068
|
+
if (parsed.package !== void 0) return packageHostLocation(findHostPackage(projectRoot, parsed.package, parsed.host), parsed.host);
|
|
1069
|
+
const own = {
|
|
1070
|
+
ref: parsed.host,
|
|
1071
|
+
folder: parsed.host,
|
|
1072
|
+
hostsDir: path.join(projectRoot, "hosts")
|
|
1073
|
+
};
|
|
1074
|
+
if (!scope) return own;
|
|
1075
|
+
const supplied = hostFolders(scope.root) ?? [];
|
|
1076
|
+
if (supplied.includes(parsed.host)) return packageHostLocation(scope, parsed.host);
|
|
1077
|
+
const projects = hostFolders(projectRoot) ?? [];
|
|
1078
|
+
if (projects.includes(parsed.host)) return own;
|
|
1079
|
+
throw new HostLoadError(`Unknown host "${parsed.host}": package "${scope.name}" supplies none (its hosts: ${supplied.join(", ") || "none"}), and neither does the project (its hosts: ${projects.join(", ") || "none"}).`);
|
|
1080
|
+
}
|
|
1081
|
+
//#endregion
|
|
1082
|
+
//#region src/plugins-resolve.ts
|
|
1083
|
+
/**
|
|
1084
|
+
* NODE-ONLY plugin resolution (split from plugins.ts so the pure runner core
|
|
1085
|
+
* stays browser-safe for ConnectCore — R3). Resolves host.js entries from the
|
|
1086
|
+
* PROJECT dependency tree, exactly like runner modules.
|
|
1087
|
+
*/
|
|
1088
|
+
function isHostPluginShape(value) {
|
|
1089
|
+
return value !== null && typeof value === "object" && typeof value.name === "string";
|
|
1090
|
+
}
|
|
1091
|
+
/**
|
|
1092
|
+
* Resolve host.js plugin entries into live plugins for one host boot:
|
|
1093
|
+
* verb-filter → module resolution from the project tree (default condition,
|
|
1094
|
+
* like runners) → factory/object contract → config validation → appliesTo.
|
|
1095
|
+
*/
|
|
1096
|
+
async function resolveHostPlugins(projectRoot, hostType, verb, entries, where) {
|
|
1097
|
+
const normalized = normalizePluginEntries(entries, where);
|
|
1098
|
+
const projectRequire = createRequire(pathToFileURL(path.join(projectRoot, "package.json")).href);
|
|
1099
|
+
const resolved = [];
|
|
1100
|
+
for (const entry of normalized) {
|
|
1101
|
+
if (!entryActiveForVerb(entry, verb)) continue;
|
|
1102
|
+
let file;
|
|
1103
|
+
try {
|
|
1104
|
+
file = projectRequire.resolve(entry.module);
|
|
1105
|
+
} catch {
|
|
1106
|
+
throw new PluginError(`${where}: cannot resolve plugin "${entry.module}" from ${projectRoot}.`, "Plugins resolve from the project dependency tree, exactly like runner modules.");
|
|
1107
|
+
}
|
|
1108
|
+
const exported = (await import(pathToFileURL(file).href)).default;
|
|
1109
|
+
let plugin;
|
|
1110
|
+
if (typeof exported === "function") plugin = exported(entry.config);
|
|
1111
|
+
else if (isHostPluginShape(exported)) {
|
|
1112
|
+
if (Object.keys(entry.config).length > 0 && !exported.configSchema) throw new PluginError(`${where}: plugin "${entry.module}" takes no config, but the entry passes one.`);
|
|
1113
|
+
plugin = exported;
|
|
1114
|
+
} else throw new PluginError(`${where}: "${entry.module}" does not default-export a plugin object or factory.`, "Export `{ name, hooks?, contributions? }` or `(config) => plugin`.");
|
|
1115
|
+
if (plugin.configSchema) {
|
|
1116
|
+
const parsed = plugin.configSchema.safeParse(entry.config);
|
|
1117
|
+
if (!parsed.success) throw new PluginError(`${where}: config for plugin "${plugin.name}" is invalid:\n` + z.prettifyError(parsed.error));
|
|
1118
|
+
}
|
|
1119
|
+
const appliesTo = plugin.appliesTo ?? "reactor";
|
|
1120
|
+
if (!hostTypeSatisfies(hostType, appliesTo)) throw new PluginError(`${where}: plugin "${plugin.name}" applies to "${appliesTo}" hosts, but this host is "${hostType}".`);
|
|
1121
|
+
resolved.push({
|
|
1122
|
+
entry,
|
|
1123
|
+
plugin,
|
|
1124
|
+
provenance: "dependency"
|
|
1125
|
+
});
|
|
1126
|
+
}
|
|
1127
|
+
return resolved;
|
|
1128
|
+
}
|
|
1129
|
+
/**
|
|
1130
|
+
* LENIENT resolution for diagnostics (`ph run <host> --explain drives`):
|
|
1131
|
+
* collects the drive contributions of the entries active for `verb`. Unlike
|
|
1132
|
+
* resolveHostPlugins it does not know the host type (so appliesTo is not
|
|
1133
|
+
* checked) and does not fail on a specifier the project tree cannot resolve
|
|
1134
|
+
* — the entry is listed under `unresolved` instead. Config is still validated
|
|
1135
|
+
* against the plugin's schema, so a bad entry surfaces here too.
|
|
1136
|
+
*/
|
|
1137
|
+
async function resolvePluginContributions(projectRoot, verb, entries, where) {
|
|
1138
|
+
const normalized = normalizePluginEntries(entries, where);
|
|
1139
|
+
const projectRequire = createRequire(pathToFileURL(path.join(projectRoot, "package.json")).href);
|
|
1140
|
+
const plan = {
|
|
1141
|
+
drives: [],
|
|
1142
|
+
unresolved: []
|
|
1143
|
+
};
|
|
1144
|
+
for (const entry of normalized) {
|
|
1145
|
+
if (!entryActiveForVerb(entry, verb)) continue;
|
|
1146
|
+
let file;
|
|
1147
|
+
try {
|
|
1148
|
+
file = projectRequire.resolve(entry.module);
|
|
1149
|
+
} catch {
|
|
1150
|
+
plan.unresolved.push(entry.module);
|
|
1151
|
+
continue;
|
|
1152
|
+
}
|
|
1153
|
+
const exported = (await import(pathToFileURL(file).href)).default;
|
|
1154
|
+
let plugin;
|
|
1155
|
+
if (typeof exported === "function") plugin = exported(entry.config);
|
|
1156
|
+
else if (isHostPluginShape(exported)) plugin = exported;
|
|
1157
|
+
else {
|
|
1158
|
+
plan.unresolved.push(entry.module);
|
|
1159
|
+
continue;
|
|
1160
|
+
}
|
|
1161
|
+
if (plugin.configSchema) {
|
|
1162
|
+
const parsed = plugin.configSchema.safeParse(entry.config);
|
|
1163
|
+
if (!parsed.success) throw new PluginError(`${where}: config for plugin "${plugin.name}" is invalid:\n` + z.prettifyError(parsed.error));
|
|
1164
|
+
}
|
|
1165
|
+
for (const declaration of plugin.contributions?.drives ?? []) plan.drives.push({
|
|
1166
|
+
declaration,
|
|
1167
|
+
source: plugin.name
|
|
1168
|
+
});
|
|
1169
|
+
}
|
|
1170
|
+
return plan;
|
|
1171
|
+
}
|
|
1172
|
+
/**
|
|
1173
|
+
* Dead-config warnings for a Connect host (typed-host-configs 1.6): an
|
|
1174
|
+
* authored connect config value whose owning plugin is not in the
|
|
1175
|
+
* composition active for `verb`. Connect zeroes such a slice, so the value
|
|
1176
|
+
* has no effect — e.g. Sektar's `connect.drives.allowAddDrive: true` without
|
|
1177
|
+
* the generic plugin.
|
|
1178
|
+
*
|
|
1179
|
+
* Nothing is reported when the host declares no composition
|
|
1180
|
+
* (`runner.plugins` absent: the default composition serves the config as is), or
|
|
1181
|
+
* when Connect already serves every leaf of the authored value. Warnings, not
|
|
1182
|
+
* errors: the host still boots, it just does not do what the value says.
|
|
1183
|
+
*/
|
|
1184
|
+
function findDeadConnectConfig(config, entries, verb, where) {
|
|
1185
|
+
if (!config || entries === void 0) return [];
|
|
1186
|
+
const active = new Set(normalizePluginEntries(entries, where).filter((entry) => entryActiveForVerb(entry, verb)).map((entry) => entry.module));
|
|
1187
|
+
const warnings = [];
|
|
1188
|
+
for (const [owner, { slices, inertUnless }] of Object.entries(CONNECT_PLUGIN_OWNED_SLICES)) {
|
|
1189
|
+
if (active.has(owner)) continue;
|
|
1190
|
+
if (inertUnless !== void 0) {
|
|
1191
|
+
const gate = slices.find((slice) => slice.path === inertUnless);
|
|
1192
|
+
if (alreadyServed(valueAt$1(config, inertUnless), gate?.absent)) continue;
|
|
1193
|
+
}
|
|
1194
|
+
for (const { path: slicePath, absent, entryKey } of slices) {
|
|
1195
|
+
const value = valueAt$1(config, slicePath);
|
|
1196
|
+
if (alreadyServed(value, absent)) continue;
|
|
1197
|
+
const move = entryKey === void 0 ? `compose "${owner}" (presence is the switch)` : `compose "${owner}" and set \`${entryKey}\` in its entry config`;
|
|
1198
|
+
warnings.push({
|
|
1199
|
+
path: slicePath,
|
|
1200
|
+
value,
|
|
1201
|
+
served: absent,
|
|
1202
|
+
owner,
|
|
1203
|
+
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.`
|
|
1204
|
+
});
|
|
1205
|
+
}
|
|
1206
|
+
}
|
|
1207
|
+
return warnings;
|
|
1208
|
+
}
|
|
1209
|
+
//#endregion
|
|
1069
1210
|
//#region src/resolve/walk.ts
|
|
1070
1211
|
function isPlainObject(value) {
|
|
1071
1212
|
if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
|
|
@@ -1651,7 +1792,12 @@ function isDriveReference(value) {
|
|
|
1651
1792
|
return keys.length === 2 && keys[0] === "from" && keys[1] === "slug" && typeof value.from === "string" && typeof value.slug === "string";
|
|
1652
1793
|
}
|
|
1653
1794
|
function checkReactor(reactor, base, found) {
|
|
1654
|
-
if (!isPlainObject(reactor)
|
|
1795
|
+
if (!isPlainObject(reactor)) return;
|
|
1796
|
+
if (reactor.workflows !== void 0) found.push({
|
|
1797
|
+
path: `${base}reactor.workflows`,
|
|
1798
|
+
message: "reactor.workflows was removed in 6.4; the workflows plugin under runner.plugins decides: list it to run workflows, leave it out to run none. On a switchboard, PH_WORKFLOWS_ENABLED=0 still switches them off."
|
|
1799
|
+
});
|
|
1800
|
+
if (!isPlainObject(reactor.backends)) return;
|
|
1655
1801
|
for (const [name, backend] of Object.entries(reactor.backends)) {
|
|
1656
1802
|
if (!isPlainObject(backend) || !isPlainObject(backend.remote)) continue;
|
|
1657
1803
|
const host = backend.remote.host;
|
|
@@ -1717,7 +1863,11 @@ function findRemovedForms(host) {
|
|
|
1717
1863
|
//#endregion
|
|
1718
1864
|
//#region src/env-substitution.ts
|
|
1719
1865
|
/** The always-resolvable `$env` names (also the `"${name}"` sugar). */
|
|
1720
|
-
const BUILTIN_ENV_NAMES = [
|
|
1866
|
+
const BUILTIN_ENV_NAMES = [
|
|
1867
|
+
"userData",
|
|
1868
|
+
"projectRoot",
|
|
1869
|
+
"package"
|
|
1870
|
+
];
|
|
1721
1871
|
function isBuiltinEnvName(name) {
|
|
1722
1872
|
return BUILTIN_ENV_NAMES.includes(name);
|
|
1723
1873
|
}
|
|
@@ -2227,7 +2377,9 @@ function setAt(root, trail, value, omit) {
|
|
|
2227
2377
|
/**
|
|
2228
2378
|
* Resolves a host's `runner.module` specifier from the PROJECT's dependency
|
|
2229
2379
|
* tree (not ph-cli's), imports it, and checks the runner-module contract:
|
|
2230
|
-
* `{ run, hostSchema, kind, outputsSchema?, verbs?, ...optionalVerbs }`.
|
|
2380
|
+
* `{ run, hostSchema, kind, outputsSchema?, verbs?, ...optionalVerbs }`. For
|
|
2381
|
+
* a host an installed package supplies, the caller passes the package's
|
|
2382
|
+
* folder as the root (`moduleRootOf`).
|
|
2231
2383
|
*/
|
|
2232
2384
|
var RunnerError = class extends Error {
|
|
2233
2385
|
constructor(message, hint) {
|
|
@@ -2251,6 +2403,7 @@ const NON_VERB_EXPORTS = /* @__PURE__ */ new Set([
|
|
|
2251
2403
|
"verbs",
|
|
2252
2404
|
"argsSchema",
|
|
2253
2405
|
"kind",
|
|
2406
|
+
"foreground",
|
|
2254
2407
|
"checkBoot",
|
|
2255
2408
|
"default"
|
|
2256
2409
|
]);
|
|
@@ -2276,7 +2429,7 @@ async function resolveRunnerModule(projectRoot, specifier) {
|
|
|
2276
2429
|
const fallback = runnerFallback(specifier);
|
|
2277
2430
|
resolved = resolveFirst(fallback ? [specifier, fallback] : [specifier]);
|
|
2278
2431
|
} catch {
|
|
2279
|
-
throw new RunnerError(`Cannot resolve runner module "${specifier}" from ${projectRoot}.`, "The runner must be a dependency of the project (install it, then retry).");
|
|
2432
|
+
throw new RunnerError(`Cannot resolve runner module "${specifier}" from ${projectRoot}.`, "The runner must be a dependency of the project, or of the package that supplies the host (install it, then retry).");
|
|
2280
2433
|
}
|
|
2281
2434
|
const module = await import(pathToFileURL(resolved).href);
|
|
2282
2435
|
if (typeof module.run !== "function") throw new RunnerError(`Runner "${specifier}" does not export a \`run\` function (required verb).`);
|
|
@@ -2285,6 +2438,7 @@ async function resolveRunnerModule(projectRoot, specifier) {
|
|
|
2285
2438
|
const declared = module.declaredHostSchema;
|
|
2286
2439
|
if (declared !== void 0 && typeof declared.safeParse !== "function") throw new RunnerError(`Runner "${specifier}" exports a \`declaredHostSchema\` without safeParse.`);
|
|
2287
2440
|
if (module.checkBoot !== void 0 && typeof module.checkBoot !== "function") throw new RunnerError(`Runner "${specifier}" exports a \`checkBoot\` that is not a function.`);
|
|
2441
|
+
if (module.foreground !== void 0 && typeof module.foreground !== "boolean") throw new RunnerError(`Runner "${specifier}" exports a \`foreground\` that is not a boolean.`);
|
|
2288
2442
|
const verbs = module.verbs;
|
|
2289
2443
|
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.`);
|
|
2290
2444
|
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").`);
|
|
@@ -2296,6 +2450,18 @@ async function resolveRunnerModule(projectRoot, specifier) {
|
|
|
2296
2450
|
* the declared host (tokens may remain in token-able fields; a `$map` is
|
|
2297
2451
|
* the empty collection, see `emptyMaps`). */
|
|
2298
2452
|
const ONE_SHOT_VERBS = /* @__PURE__ */ new Set(["build"]);
|
|
2453
|
+
/** Why a one-shot verb (build) does not run on a host an installed package
|
|
2454
|
+
* supplies (`ref`, as the project addresses it): the package ships its hosts
|
|
2455
|
+
* built, and a build here would write into the installed package (a
|
|
2456
|
+
* Connect's outDir) or build the project in its name. The package's own
|
|
2457
|
+
* repository builds them, where they are project hosts. */
|
|
2458
|
+
function packageBuildRefusal(ref, hostPackage, verb) {
|
|
2459
|
+
return {
|
|
2460
|
+
path: "",
|
|
2461
|
+
message: `${ref} is a host ${hostPackage.name} supplies, and a package's hosts are built by the package: "${verb}" does not run on it.`,
|
|
2462
|
+
hint: `${hostPackage.name} ships them built; its own repository builds them, where they are project hosts. Build this project's own hosts by their bare names.`
|
|
2463
|
+
};
|
|
2464
|
+
}
|
|
2299
2465
|
/** Verbs that work on a host's stores and start nothing (`migrate`,
|
|
2300
2466
|
* `migrate-status`, `reset`). Their host is resolved as for `run`, so they
|
|
2301
2467
|
* address the stores `run` opens; they take no lock and return nothing, so
|
|
@@ -2314,7 +2480,7 @@ function getVerb(runner, specifier, verb) {
|
|
|
2314
2480
|
if (typeof candidate !== "function" || !listVerbs(runner).includes(verb)) throw new RunnerError(`Runner "${specifier}" does not support the verb "${verb}". Supported verbs: ${listVerbs(runner).join(", ")}.`);
|
|
2315
2481
|
return candidate;
|
|
2316
2482
|
}
|
|
2317
|
-
function isRecord$
|
|
2483
|
+
function isRecord$3(value) {
|
|
2318
2484
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2319
2485
|
}
|
|
2320
2486
|
/** reactor XOR children, decided by the runner's declared `kind`. */
|
|
@@ -2339,7 +2505,7 @@ function assertKindShape(kind, specifier, host, file) {
|
|
|
2339
2505
|
* this runner exports. */
|
|
2340
2506
|
function knownVerbIssues(runner, specifier, host) {
|
|
2341
2507
|
const options = host.runner;
|
|
2342
|
-
if (!isRecord$
|
|
2508
|
+
if (!isRecord$3(options)) return [];
|
|
2343
2509
|
const verbs = listVerbs(runner);
|
|
2344
2510
|
const unknownVerb = (verb) => typeof verb === "string" && !verbs.includes(verb);
|
|
2345
2511
|
const issues = [];
|
|
@@ -2348,7 +2514,7 @@ function knownVerbIssues(runner, specifier, host) {
|
|
|
2348
2514
|
message: `runner.defaultVerb "${options.defaultVerb}" is not a verb of "${specifier}". Supported verbs: ${verbs.join(", ")}.`
|
|
2349
2515
|
});
|
|
2350
2516
|
(Array.isArray(options.plugins) ? options.plugins : []).forEach((entry, index) => {
|
|
2351
|
-
if (!isRecord$
|
|
2517
|
+
if (!isRecord$3(entry) || !Array.isArray(entry.verbs)) return;
|
|
2352
2518
|
const scoped = entry.verbs;
|
|
2353
2519
|
for (const bad of scoped.filter(unknownVerb)) issues.push({
|
|
2354
2520
|
path: `runner.plugins[${index}].verbs`,
|
|
@@ -2363,7 +2529,7 @@ function formatIssues(issues) {
|
|
|
2363
2529
|
function valueAt(host, path) {
|
|
2364
2530
|
let current = host;
|
|
2365
2531
|
for (const key of path) if (Array.isArray(current) && typeof key === "number") current = current[key];
|
|
2366
|
-
else if (isRecord$
|
|
2532
|
+
else if (isRecord$3(current) && typeof key === "string") current = current[key];
|
|
2367
2533
|
else return;
|
|
2368
2534
|
return current;
|
|
2369
2535
|
}
|
|
@@ -2379,7 +2545,7 @@ function validateHost(runner, specifier, host, file, options = {}) {
|
|
|
2379
2545
|
/** What `validateHost` checks, as data: nothing throws. */
|
|
2380
2546
|
function hostSchemaIssues(runner, schema, specifier, host, options = {}) {
|
|
2381
2547
|
const issues = [];
|
|
2382
|
-
if (isRecord$
|
|
2548
|
+
if (isRecord$3(host)) {
|
|
2383
2549
|
issues.push(...kindShapeIssues(runner.kind, specifier, host));
|
|
2384
2550
|
if (options.tokens !== "allow") {
|
|
2385
2551
|
const token = findToken(host);
|
|
@@ -2431,14 +2597,15 @@ function validateDeclaredHost(runner, specifier, host, file, options = {}) {
|
|
|
2431
2597
|
const issues = checkTokenSites(host);
|
|
2432
2598
|
if (options.outputsSchemaOf) issues.push(...checkOutputPaths(host, options.outputsSchemaOf));
|
|
2433
2599
|
if (issues.length > 0) throw new RunnerError(`${file}: invalid output token:\n${formatIssues(issues)}`);
|
|
2434
|
-
if (isRecord$
|
|
2600
|
+
if (isRecord$3(host)) assertKindShape(runner.kind, specifier, host, file);
|
|
2435
2601
|
if (!runner.declaredHostSchema) return;
|
|
2436
2602
|
parseHost(runner, runner.declaredHostSchema, specifier, host, file, { tokens: "allow" });
|
|
2437
2603
|
}
|
|
2438
2604
|
//#endregion
|
|
2439
2605
|
//#region src/host-loader.ts
|
|
2440
2606
|
/**
|
|
2441
|
-
* Loads and pre-validates a `hosts/<name>/host.js` definition
|
|
2607
|
+
* Loads and pre-validates a `hosts/<name>/host.js` definition: the project's
|
|
2608
|
+
* own, or one an installed package supplies (`<package>/<host>`, host-ref.ts).
|
|
2442
2609
|
*
|
|
2443
2610
|
* A host file is a static PROJECTION of powerhouse.config.json: plain ESM,
|
|
2444
2611
|
* default-exporting a data object. Three gates run before any runner sees it:
|
|
@@ -2458,19 +2625,13 @@ function validateDeclaredHost(runner, specifier, host, file, options = {}) {
|
|
|
2458
2625
|
*/
|
|
2459
2626
|
const HOST_FILE = "host.js";
|
|
2460
2627
|
const CONFIG_IMPORT_SUFFIX = "powerhouse.config.json";
|
|
2461
|
-
|
|
2462
|
-
|
|
2463
|
-
|
|
2464
|
-
this.name = "HostLoadError";
|
|
2465
|
-
}
|
|
2466
|
-
};
|
|
2467
|
-
/** A `hosts/` folder with no `<name>/host.js` inside is "empty" — the guard
|
|
2468
|
-
* state: callers warn loudly and fall back to legacy rather than activating
|
|
2469
|
-
* the new architecture off a stray `mkdir hosts`. */
|
|
2628
|
+
/** A `hosts/` folder with no `<name>/host.js` inside is "empty": it defines
|
|
2629
|
+
* no host, so nothing runs from it, as from an absent one
|
|
2630
|
+
* ({@link withoutHostsMessage}). */
|
|
2470
2631
|
function probeHostsFolder(projectRoot) {
|
|
2471
2632
|
const dir = path.join(projectRoot, "hosts");
|
|
2472
|
-
|
|
2473
|
-
|
|
2633
|
+
const hosts = hostFolders(projectRoot);
|
|
2634
|
+
if (hosts === void 0) return { kind: "absent" };
|
|
2474
2635
|
return hosts.length === 0 ? {
|
|
2475
2636
|
kind: "empty",
|
|
2476
2637
|
dir
|
|
@@ -2480,6 +2641,14 @@ function probeHostsFolder(projectRoot) {
|
|
|
2480
2641
|
hosts
|
|
2481
2642
|
};
|
|
2482
2643
|
}
|
|
2644
|
+
/**
|
|
2645
|
+
* Why `subject` cannot run in a project whose hosts/ folder is absent or
|
|
2646
|
+
* empty, and what adds the host files. One wording, for `ph run <host>` and
|
|
2647
|
+
* for the `ph vetra`, `ph connect` and `ph switchboard` sugar.
|
|
2648
|
+
*/
|
|
2649
|
+
function withoutHostsMessage(probe, subject) {
|
|
2650
|
+
return `${probe.kind === "empty" ? `hosts/ exists at ${probe.dir} but contains no <name>/host.js` : "This project has no hosts/ folder"}, so ${subject} cannot run. Run \`ph migrate\` to add the host files.`;
|
|
2651
|
+
}
|
|
2483
2652
|
/** Sibling imports: `../<host>/host.js` — source material for derived
|
|
2484
2653
|
* compositions (full-inclusion wrappers compute over them with plain JS) —
|
|
2485
2654
|
* and `../<host>/outputs.js`, the generated `$output` token tree. */
|
|
@@ -2688,33 +2857,91 @@ function findNonStaticValue(value, trail = "") {
|
|
|
2688
2857
|
if (hit) return hit;
|
|
2689
2858
|
}
|
|
2690
2859
|
}
|
|
2860
|
+
/** Where a loaded host's module specifiers resolve from: its package's
|
|
2861
|
+
* folder, else the project root. */
|
|
2862
|
+
function moduleRootOf(projectRoot, loaded) {
|
|
2863
|
+
return loaded.package?.root ?? projectRoot;
|
|
2864
|
+
}
|
|
2691
2865
|
function assertHostShape(host, file) {
|
|
2692
2866
|
if (typeof host.name !== "string" || host.name.length === 0) throw new HostLoadError(`${file}: \`name\` must be a non-empty string.`);
|
|
2693
2867
|
const runner = host.runner;
|
|
2694
2868
|
if (runner === null || typeof runner !== "object" || typeof runner.module !== "string") throw new HostLoadError(`${file}: \`runner\` must be an object with a \`module\` specifier string.`);
|
|
2695
2869
|
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.`);
|
|
2696
2870
|
}
|
|
2697
|
-
|
|
2698
|
-
|
|
2871
|
+
/** `hostName` is a ref: the project's folder name, or `<package>/<host>`. */
|
|
2872
|
+
async function loadHost(projectRoot, hostName, options = {}) {
|
|
2873
|
+
return importHost(projectRoot, hostName, true, false, options.scope);
|
|
2874
|
+
}
|
|
2875
|
+
/**
|
|
2876
|
+
* `loadHost`, evaluated again: the host file and what it imports are read as
|
|
2877
|
+
* they are on disk now. A process keeps the first evaluation of a module, so
|
|
2878
|
+
* `loadHost` returns the host as it was when the process first loaded it; a
|
|
2879
|
+
* dev server that follows powerhouse.config.json asks for this one.
|
|
2880
|
+
*/
|
|
2881
|
+
async function loadHostFresh(projectRoot, hostName, options = {}) {
|
|
2882
|
+
return importHost(projectRoot, hostName, true, true, options.scope);
|
|
2883
|
+
}
|
|
2884
|
+
const FRESH_IMPORT_WORKER = `
|
|
2885
|
+
const { parentPort, workerData } = require("node:worker_threads");
|
|
2886
|
+
import(workerData.url).then(
|
|
2887
|
+
(module) => {
|
|
2888
|
+
try {
|
|
2889
|
+
parentPort.postMessage({ host: module.default });
|
|
2890
|
+
} catch (error) {
|
|
2891
|
+
parentPort.postMessage({ error: String(error) });
|
|
2892
|
+
}
|
|
2893
|
+
},
|
|
2894
|
+
(error) => parentPort.postMessage({ error: String(error) }),
|
|
2895
|
+
);
|
|
2896
|
+
`;
|
|
2897
|
+
/** The default export of a module, evaluated in a worker: a worker has its
|
|
2898
|
+
* own module graph, so the file and its imports are read again. Host files
|
|
2899
|
+
* export data, which is what reaches this thread. */
|
|
2900
|
+
function importDefaultFresh(url, file) {
|
|
2901
|
+
return new Promise((resolve, reject) => {
|
|
2902
|
+
const worker = new Worker(FRESH_IMPORT_WORKER, {
|
|
2903
|
+
eval: true,
|
|
2904
|
+
workerData: { url }
|
|
2905
|
+
});
|
|
2906
|
+
const fail = (reason) => reject(new HostLoadError(`${file} could not be read again: ${reason}`));
|
|
2907
|
+
worker.once("message", (message) => {
|
|
2908
|
+
if (message.error !== void 0) fail(message.error);
|
|
2909
|
+
else resolve(message.host);
|
|
2910
|
+
worker.terminate();
|
|
2911
|
+
});
|
|
2912
|
+
worker.once("error", (error) => fail(String(error)));
|
|
2913
|
+
worker.once("exit", () => fail("its worker exited without an answer"));
|
|
2914
|
+
});
|
|
2699
2915
|
}
|
|
2700
|
-
|
|
2916
|
+
/** Where `ref` is; for the project's own host, the loader's messages when
|
|
2917
|
+
* its hosts/ folder lacks it. */
|
|
2918
|
+
function locateLoadable(projectRoot, ref, scope) {
|
|
2919
|
+
const location = locateHost(projectRoot, ref, scope);
|
|
2920
|
+
if (location.package) return location;
|
|
2701
2921
|
const probe = probeHostsFolder(projectRoot);
|
|
2702
|
-
if (probe.kind
|
|
2703
|
-
if (probe.
|
|
2704
|
-
|
|
2705
|
-
|
|
2706
|
-
|
|
2707
|
-
|
|
2708
|
-
const
|
|
2922
|
+
if (probe.kind !== "present") throw new HostLoadError(withoutHostsMessage(probe, `the host "${ref}"`));
|
|
2923
|
+
if (!probe.hosts.includes(location.folder)) throw new HostLoadError(`Unknown host "${ref}". Available hosts: ${probe.hosts.join(", ")}.`);
|
|
2924
|
+
return location;
|
|
2925
|
+
}
|
|
2926
|
+
async function importHost(projectRoot, hostName, checkOutputs, fresh = false, scope) {
|
|
2927
|
+
const location = locateLoadable(projectRoot, hostName, scope);
|
|
2928
|
+
const { folder, hostsDir } = location;
|
|
2929
|
+
const file = path.join(hostsDir, folder, HOST_FILE);
|
|
2930
|
+
const producers = lintHostImportGraph(hostsDir, folder);
|
|
2931
|
+
if (checkOutputs) for (const producer of producers) await assertOutputsFileFresh(projectRoot, location, producer);
|
|
2932
|
+
const url = pathToFileURL(file).href;
|
|
2933
|
+
const host = fresh ? await importDefaultFresh(url, file) : (await import(url)).default;
|
|
2709
2934
|
if (host === null || typeof host !== "object" || Array.isArray(host)) throw new HostLoadError(`${file} must default-export the host object (\`export default { name, runner, ... }\`).`);
|
|
2710
2935
|
const nonStatic = findNonStaticValue(host);
|
|
2711
2936
|
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.");
|
|
2712
2937
|
assertHostShape(host, file);
|
|
2713
2938
|
return {
|
|
2714
|
-
name:
|
|
2939
|
+
name: folder,
|
|
2715
2940
|
dir: path.dirname(file),
|
|
2716
2941
|
file,
|
|
2717
|
-
host
|
|
2942
|
+
host,
|
|
2943
|
+
ref: location.ref,
|
|
2944
|
+
...location.package ? { package: location.package } : {}
|
|
2718
2945
|
};
|
|
2719
2946
|
}
|
|
2720
2947
|
const OUTPUTS_HASH_EXPORT = /^export const outputsHash = "([^"]+)";$/m;
|
|
@@ -2742,13 +2969,13 @@ function computeOutputsHash(input) {
|
|
|
2742
2969
|
function isZodSchema(value) {
|
|
2743
2970
|
return value !== null && typeof value === "object" && "_zod" in value;
|
|
2744
2971
|
}
|
|
2745
|
-
function isRecord$
|
|
2972
|
+
function isRecord$2(value) {
|
|
2746
2973
|
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
2747
2974
|
}
|
|
2748
2975
|
/** Local (non-remote) slugs from a drive declaration list. */
|
|
2749
2976
|
function localDriveSlugs(drives) {
|
|
2750
2977
|
if (!Array.isArray(drives)) return [];
|
|
2751
|
-
return drives.flatMap((drive) => isRecord$
|
|
2978
|
+
return drives.flatMap((drive) => isRecord$2(drive) && typeof drive.slug === "string" && drive.remote === void 0 ? [drive.slug] : []);
|
|
2752
2979
|
}
|
|
2753
2980
|
/**
|
|
2754
2981
|
* Describes the outputs a host's creation produces, for `ph generate hosts`
|
|
@@ -2764,45 +2991,53 @@ function localDriveSlugs(drives) {
|
|
|
2764
2991
|
* key (it is not declared); reach it with a literal `$output` token.
|
|
2765
2992
|
*/
|
|
2766
2993
|
async function describeHostOutputs(projectRoot, hostName) {
|
|
2767
|
-
const
|
|
2994
|
+
const loaded = await importHost(projectRoot, hostName, false);
|
|
2995
|
+
const { host, file } = loaded;
|
|
2996
|
+
const moduleRoot = moduleRootOf(projectRoot, loaded);
|
|
2768
2997
|
const runnerModule = host.runner.module;
|
|
2769
|
-
const schema = (await resolveRunnerModule(
|
|
2998
|
+
const schema = (await resolveRunnerModule(moduleRoot, runnerModule)).outputsSchema;
|
|
2770
2999
|
if (!isZodSchema(schema)) return void 0;
|
|
2771
3000
|
const { $schema: _dialect, ...outputsSchema } = z.toJSONSchema(schema, {
|
|
2772
3001
|
io: "output",
|
|
2773
3002
|
unrepresentable: "any"
|
|
2774
3003
|
});
|
|
2775
3004
|
const reactor = host.reactor;
|
|
2776
|
-
const drives = localDriveSlugs(isRecord$
|
|
3005
|
+
const drives = localDriveSlugs(isRecord$2(reactor) ? reactor.drives : []);
|
|
2777
3006
|
const entries = (host.runner.plugins ?? []).map((entry) => typeof entry === "string" ? entry : {
|
|
2778
3007
|
...entry,
|
|
2779
3008
|
verbs: "*"
|
|
2780
3009
|
});
|
|
2781
3010
|
if (entries.length > 0) {
|
|
2782
|
-
const plan = await resolvePluginContributions(
|
|
3011
|
+
const plan = await resolvePluginContributions(moduleRoot, "*", entries, path.relative(projectRoot, file));
|
|
2783
3012
|
drives.push(...localDriveSlugs(plan.drives.map((drive) => drive.declaration)));
|
|
2784
3013
|
}
|
|
2785
3014
|
const sortedDrives = [...new Set(drives)].sort();
|
|
3015
|
+
const folder = loaded.name;
|
|
2786
3016
|
return {
|
|
2787
|
-
host:
|
|
3017
|
+
host: folder,
|
|
2788
3018
|
runnerModule,
|
|
2789
3019
|
outputsSchema,
|
|
2790
3020
|
drives: sortedDrives,
|
|
2791
3021
|
hash: computeOutputsHash({
|
|
2792
|
-
host:
|
|
3022
|
+
host: folder,
|
|
2793
3023
|
runnerModule,
|
|
2794
3024
|
outputsSchema,
|
|
2795
3025
|
drives: sortedDrives
|
|
2796
3026
|
})
|
|
2797
3027
|
};
|
|
2798
3028
|
}
|
|
2799
|
-
async function assertOutputsFileFresh(projectRoot,
|
|
2800
|
-
const
|
|
3029
|
+
async function assertOutputsFileFresh(projectRoot, consumer, producer) {
|
|
3030
|
+
const { hostsDir } = consumer;
|
|
3031
|
+
const where = consumer.package ? `${consumer.package.name}/` : "";
|
|
3032
|
+
const rel = `${where}hosts/${producer}/${OUTPUTS_FILE}`;
|
|
2801
3033
|
const actual = readOutputsFileHash(readFileSync(path.join(hostsDir, producer, OUTPUTS_FILE), "utf8"));
|
|
2802
|
-
if (!existsSync(path.join(hostsDir, producer, HOST_FILE))) throw new HostLoadError(
|
|
2803
|
-
const description = await describeHostOutputs(projectRoot,
|
|
2804
|
-
|
|
2805
|
-
|
|
3034
|
+
if (!existsSync(path.join(hostsDir, producer, HOST_FILE))) throw new HostLoadError(`${where}hosts/${consumer.folder} imports ${rel}, but there is no ${hostFileLabel(producer, consumer.package)} to produce it.`, "Delete the orphaned outputs.js and fix the import.");
|
|
3035
|
+
const description = await describeHostOutputs(projectRoot, formatHostRef({
|
|
3036
|
+
package: consumer.package?.name,
|
|
3037
|
+
host: producer
|
|
3038
|
+
}));
|
|
3039
|
+
if (!description) throw new HostLoadError(`${where}hosts/${consumer.folder} imports ${rel}, but ${where}hosts/${producer}'s runner declares no outputsSchema, so it produces no outputs.`);
|
|
3040
|
+
if (actual !== description.hash) throw new HostLoadError(consumer.package ? `${rel} is stale against the runner this project resolves for it (its outputsSchema or declared drives differ from those it was generated from): package "${consumer.package.name}" was built against another version of "${description.runnerModule}".` : `${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}.`);
|
|
2806
3041
|
}
|
|
2807
3042
|
//#endregion
|
|
2808
3043
|
//#region src/runner-args.ts
|
|
@@ -2811,7 +3046,7 @@ const isStringRecord = (value) => typeof value === "object" && value !== null &&
|
|
|
2811
3046
|
function isRunnerArgsSchema(value) {
|
|
2812
3047
|
if (typeof value !== "object" || value === null) return false;
|
|
2813
3048
|
const schema = value;
|
|
2814
|
-
return isStrings(schema.options) && isStrings(schema.flags) && (schema.memberOptions === void 0 || isStringRecord(schema.memberOptions)) && (schema.retired === void 0 || isStringRecord(schema.retired));
|
|
3049
|
+
return isStrings(schema.options) && isStrings(schema.flags) && (schema.memberOptions === void 0 || isStringRecord(schema.memberOptions)) && (schema.retired === void 0 || isStringRecord(schema.retired)) && (schema.passthrough === void 0 || typeof schema.passthrough === "boolean");
|
|
2815
3050
|
}
|
|
2816
3051
|
const OWN_FLAGS = /* @__PURE__ */ new Set([
|
|
2817
3052
|
"--debug",
|
|
@@ -2876,13 +3111,15 @@ const acceptedBy = (schema) => [...schema.options, ...schema.flags];
|
|
|
2876
3111
|
* The arguments a standalone runner receives as `ctx.argv`: `argv` checked
|
|
2877
3112
|
* against the runner's schema, retired switches warned about and dropped.
|
|
2878
3113
|
* Nothing is dropped silently: an argument the runner does not accept, or any
|
|
2879
|
-
* argument for a runner without a schema, fails.
|
|
3114
|
+
* argument for a runner without a schema, fails. A `passthrough` runner gets
|
|
3115
|
+
* them all, in order.
|
|
2880
3116
|
*/
|
|
2881
3117
|
function checkRunnerArgv(argv, target) {
|
|
2882
3118
|
if (argv.length === 0) return [];
|
|
2883
3119
|
const where = `hosts/${target.host}`;
|
|
2884
3120
|
const schema = target.schema;
|
|
2885
3121
|
if (!isRunnerArgsSchema(schema)) throw new RunnerError(`${where}: its runner ${target.runner} accepts no arguments, but got: ${argv.join(" ")}`, "Set these in the host file instead.");
|
|
3122
|
+
if (schema.passthrough) return [...argv];
|
|
2886
3123
|
const options = new Set(schema.options);
|
|
2887
3124
|
const accepted = new Set(acceptedBy(schema));
|
|
2888
3125
|
const kept = [];
|
|
@@ -2902,8 +3139,13 @@ function checkRunnerArgv(argv, target) {
|
|
|
2902
3139
|
* (`--switchboard-port 4001` reaches that member as `--port 4001`). An
|
|
2903
3140
|
* argument no member accepts fails, as does one that would set the same
|
|
2904
3141
|
* option on several members.
|
|
3142
|
+
*
|
|
3143
|
+
* With a `foreground` member (the one that owns the terminal) the members
|
|
3144
|
+
* take only their member-named options, at the front; the first other
|
|
3145
|
+
* argument, or a literal `--`, starts the foreground member's own, checked
|
|
3146
|
+
* against its runner's schema (a passthrough runner takes them as typed).
|
|
2905
3147
|
*/
|
|
2906
|
-
function splitCompoundArgv(argv, host, members) {
|
|
3148
|
+
function splitCompoundArgv(argv, host, members, foreground) {
|
|
2907
3149
|
const perMember = new Map(members.map((m) => [m.key, []]));
|
|
2908
3150
|
if (argv.length === 0) return perMember;
|
|
2909
3151
|
const where = `hosts/${host}`;
|
|
@@ -2911,6 +3153,36 @@ function splitCompoundArgv(argv, host, members) {
|
|
|
2911
3153
|
key: m.key,
|
|
2912
3154
|
schema: m.schema
|
|
2913
3155
|
}] : []);
|
|
3156
|
+
const owner = members.find((m) => m.key === foreground);
|
|
3157
|
+
if (owner) {
|
|
3158
|
+
let i = 0;
|
|
3159
|
+
for (; i < argv.length; i++) {
|
|
3160
|
+
const token = argv[i];
|
|
3161
|
+
if (token === "--") {
|
|
3162
|
+
i++;
|
|
3163
|
+
break;
|
|
3164
|
+
}
|
|
3165
|
+
const equals = token.startsWith("-") ? token.indexOf("=") : -1;
|
|
3166
|
+
const name = equals === -1 ? token : token.slice(0, equals);
|
|
3167
|
+
const named = schemas.filter(({ key, schema }) => key !== owner.key && schema.memberOptions?.[name] !== void 0);
|
|
3168
|
+
if (named.length === 0) break;
|
|
3169
|
+
if (named.length > 1) throw new RunnerError(`${where}: ${name} matches the members ${named.map((m) => m.key).join(", ")}.`, "Set the option in each member's host file instead.");
|
|
3170
|
+
const { key, schema } = named[0];
|
|
3171
|
+
const option = schema.memberOptions?.[name] ?? name;
|
|
3172
|
+
if (equals !== -1) perMember.get(key)?.push(option + token.slice(name.length));
|
|
3173
|
+
else if (i + 1 >= argv.length) throw new RunnerError(`${where}: ${name} needs a value.`);
|
|
3174
|
+
else {
|
|
3175
|
+
perMember.get(key)?.push(option, argv[i + 1]);
|
|
3176
|
+
i++;
|
|
3177
|
+
}
|
|
3178
|
+
}
|
|
3179
|
+
perMember.set(owner.key, checkRunnerArgv(argv.slice(i), {
|
|
3180
|
+
host,
|
|
3181
|
+
runner: owner.runner,
|
|
3182
|
+
schema: owner.schema
|
|
3183
|
+
}));
|
|
3184
|
+
return perMember;
|
|
3185
|
+
}
|
|
2914
3186
|
const memberNames = /* @__PURE__ */ new Map();
|
|
2915
3187
|
for (const { schema } of schemas) for (const [alias, option] of Object.entries(schema.memberOptions ?? {})) {
|
|
2916
3188
|
const aliases = memberNames.get(option) ?? [];
|
|
@@ -2966,11 +3238,14 @@ function splitCompoundArgv(argv, host, members) {
|
|
|
2966
3238
|
* host and its members produced. Validated on read; a v1 (or any invalid)
|
|
2967
3239
|
* record reads as "not running". `projectName` is kept beyond the plan's
|
|
2968
3240
|
* sketch because the live/foreign probe needs it. `host` is the host's
|
|
2969
|
-
* `name` (the file key), not its folder.
|
|
3241
|
+
* `name` (the file key), not its folder. A host an installed package
|
|
3242
|
+
* supplies has its record in a folder named after the package,
|
|
3243
|
+
* `.ph/run/<package>/<host>.json`, and says which in `package`.
|
|
2970
3244
|
*/
|
|
2971
3245
|
const outputsSchema = z.record(z.string(), z.unknown());
|
|
2972
3246
|
const runRecordMemberSchema = z.strictObject({
|
|
2973
|
-
/** The member's host folder
|
|
3247
|
+
/** The member's host as the project addresses it: its folder, or
|
|
3248
|
+
* `<package>/<host>` for one a package supplies. */
|
|
2974
3249
|
host: z.string().min(1),
|
|
2975
3250
|
runnerModule: z.string().min(1),
|
|
2976
3251
|
kind: runnerKindSchema,
|
|
@@ -2980,6 +3255,9 @@ const runRecordMemberSchema = z.strictObject({
|
|
|
2980
3255
|
const runRecordSchema = z.strictObject({
|
|
2981
3256
|
version: z.literal(2),
|
|
2982
3257
|
host: hostNameSchema,
|
|
3258
|
+
/** The installed package that supplies the host; absent for the
|
|
3259
|
+
* project's own. */
|
|
3260
|
+
package: z.string().regex(PACKAGE_NAME_PATTERN).optional(),
|
|
2983
3261
|
projectName: z.string(),
|
|
2984
3262
|
kind: runnerKindSchema,
|
|
2985
3263
|
verb: z.string().min(1),
|
|
@@ -2994,13 +3272,53 @@ const runRecordSchema = z.strictObject({
|
|
|
2994
3272
|
});
|
|
2995
3273
|
//#endregion
|
|
2996
3274
|
//#region src/run-record.ts
|
|
3275
|
+
/** The key a host's record is filed under: its `name`, behind the package
|
|
3276
|
+
* that supplies it when it is not the project's own (`@acme/tools/studio`),
|
|
3277
|
+
* as `ph run` addresses the host. */
|
|
3278
|
+
function runRecordKey(name, hostPackage) {
|
|
3279
|
+
return hostPackage === void 0 ? name : `${hostPackage}/${name}`;
|
|
3280
|
+
}
|
|
3281
|
+
/** The key of a record as read: where it is filed. */
|
|
3282
|
+
function recordKeyOf(record) {
|
|
3283
|
+
return runRecordKey(record.host, record.package);
|
|
3284
|
+
}
|
|
2997
3285
|
const runDir = (projectDir, env = process.env) => path.join(resolvePhDir(projectDir, env), "run");
|
|
2998
|
-
function recordPath(projectDir,
|
|
3286
|
+
function recordPath(projectDir, key, env) {
|
|
2999
3287
|
const dir = runDir(projectDir, env);
|
|
3000
|
-
const
|
|
3001
|
-
|
|
3288
|
+
const slash = key.lastIndexOf("/");
|
|
3289
|
+
const hostName = key.slice(slash + 1);
|
|
3290
|
+
const pkg = slash === -1 ? void 0 : key.slice(0, slash);
|
|
3291
|
+
const folder = pkg === void 0 ? path.resolve(dir) : path.resolve(dir, ...pkg.split("/"));
|
|
3292
|
+
const file = path.resolve(folder, `${hostName}.json`);
|
|
3293
|
+
if (!hostNameSchema.safeParse(hostName).success || pkg !== void 0 && !PACKAGE_NAME_PATTERN.test(pkg) || path.dirname(file) !== folder) throw new Error(`"${key}" can't name a run record. ${HOST_NAME_MESSAGE}`);
|
|
3002
3294
|
return file;
|
|
3003
3295
|
}
|
|
3296
|
+
/** The record keys under `.ph/run/`: `<name>.json` files, and those in a
|
|
3297
|
+
* package's folder (`<pkg>/` or `@scope/<pkg>/`). */
|
|
3298
|
+
function recordKeys(dir) {
|
|
3299
|
+
const entries = (at) => {
|
|
3300
|
+
try {
|
|
3301
|
+
return fs.readdirSync(at, { withFileTypes: true });
|
|
3302
|
+
} catch {
|
|
3303
|
+
return [];
|
|
3304
|
+
}
|
|
3305
|
+
};
|
|
3306
|
+
const records = (at, prefix) => entries(at).filter((entry) => entry.isFile() && entry.name.endsWith(".json")).map((entry) => `${prefix}${entry.name.slice(0, -5)}`);
|
|
3307
|
+
const keys = records(dir, "");
|
|
3308
|
+
for (const entry of entries(dir)) {
|
|
3309
|
+
if (!entry.isDirectory()) continue;
|
|
3310
|
+
const at = path.join(dir, entry.name);
|
|
3311
|
+
if (!entry.name.startsWith("@")) {
|
|
3312
|
+
keys.push(...records(at, `${entry.name}/`));
|
|
3313
|
+
continue;
|
|
3314
|
+
}
|
|
3315
|
+
for (const inner of entries(at)) {
|
|
3316
|
+
if (!inner.isDirectory()) continue;
|
|
3317
|
+
keys.push(...records(path.join(at, inner.name), `${entry.name}/${inner.name}/`));
|
|
3318
|
+
}
|
|
3319
|
+
}
|
|
3320
|
+
return keys;
|
|
3321
|
+
}
|
|
3004
3322
|
function readRunRecord(projectDir, hostName, env = process.env) {
|
|
3005
3323
|
let raw;
|
|
3006
3324
|
try {
|
|
@@ -3011,16 +3329,11 @@ function readRunRecord(projectDir, hostName, env = process.env) {
|
|
|
3011
3329
|
const parsed = runRecordSchema.safeParse(raw);
|
|
3012
3330
|
return parsed.success ? parsed.data : void 0;
|
|
3013
3331
|
}
|
|
3014
|
-
/** Every valid v2 record under `.ph/run
|
|
3332
|
+
/** Every valid v2 record under `.ph/run/`, package hosts' included (invalid
|
|
3333
|
+
* and v1 files skipped). */
|
|
3015
3334
|
function listRunRecords(projectDir, env = process.env) {
|
|
3016
|
-
|
|
3017
|
-
|
|
3018
|
-
files = fs.readdirSync(runDir(projectDir, env));
|
|
3019
|
-
} catch {
|
|
3020
|
-
return [];
|
|
3021
|
-
}
|
|
3022
|
-
return files.filter((file) => file.endsWith(".json")).flatMap((file) => {
|
|
3023
|
-
const record = readRunRecord(projectDir, file.slice(0, -5), env);
|
|
3335
|
+
return recordKeys(runDir(projectDir, env)).flatMap((key) => {
|
|
3336
|
+
const record = readRunRecord(projectDir, key, env);
|
|
3024
3337
|
return record ? [record] : [];
|
|
3025
3338
|
});
|
|
3026
3339
|
}
|
|
@@ -3034,7 +3347,7 @@ function readProjectName(projectDir) {
|
|
|
3034
3347
|
return path.basename(path.resolve(projectDir));
|
|
3035
3348
|
}
|
|
3036
3349
|
function writeRunRecord(projectDir, record) {
|
|
3037
|
-
const target = recordPath(projectDir, record
|
|
3350
|
+
const target = recordPath(projectDir, recordKeyOf(record));
|
|
3038
3351
|
const valid = runRecordSchema.parse(record);
|
|
3039
3352
|
fs.mkdirSync(path.dirname(target), { recursive: true });
|
|
3040
3353
|
fs.writeFileSync(target, `${JSON.stringify(valid, null, 2)}\n`);
|
|
@@ -3137,6 +3450,513 @@ function probeRun(projectDir, hostName, projectName, env = process.env) {
|
|
|
3137
3450
|
};
|
|
3138
3451
|
}
|
|
3139
3452
|
//#endregion
|
|
3453
|
+
//#region src/stop-channel.ts
|
|
3454
|
+
/** Set by a supervisor that holds this process's stdin. */
|
|
3455
|
+
const STOP_ON_STDIN_ENV = "PH_STOP_ON_STDIN";
|
|
3456
|
+
/**
|
|
3457
|
+
* Windows has no SIGTERM: `process.kill(pid, "SIGTERM")` ends the process at
|
|
3458
|
+
* once, so no handler runs and a stack's stores are left as a crash leaves
|
|
3459
|
+
* them. A started host therefore listens on a pipe named after its pid, and
|
|
3460
|
+
* a connection to it is delivered as the SIGTERM it stands for. Elsewhere
|
|
3461
|
+
* the signal itself does this, and there is no channel.
|
|
3462
|
+
*/
|
|
3463
|
+
function stopChannelPath(pid, platform = process.platform) {
|
|
3464
|
+
return platform === "win32" ? `\\\\.\\pipe\\ph-stop-${pid}` : void 0;
|
|
3465
|
+
}
|
|
3466
|
+
/** Calls `onStop` for each connection to `channel`. The server holds no
|
|
3467
|
+
* process open, and one that cannot listen leaves the host running without
|
|
3468
|
+
* a channel rather than not running. */
|
|
3469
|
+
function listenForStop(channel, onStop) {
|
|
3470
|
+
const server = net.createServer((socket) => {
|
|
3471
|
+
socket.on("error", () => void 0);
|
|
3472
|
+
socket.end();
|
|
3473
|
+
onStop();
|
|
3474
|
+
});
|
|
3475
|
+
server.on("error", () => void 0);
|
|
3476
|
+
server.listen(channel);
|
|
3477
|
+
server.unref();
|
|
3478
|
+
return server;
|
|
3479
|
+
}
|
|
3480
|
+
let installed = false;
|
|
3481
|
+
/** What a host's process calls once before it starts anything: from then on
|
|
3482
|
+
* {@link requestStop} reaches its SIGTERM handlers on every platform. */
|
|
3483
|
+
function installStopChannel() {
|
|
3484
|
+
const channel = stopChannelPath(process.pid);
|
|
3485
|
+
if (!channel || installed) return;
|
|
3486
|
+
installed = true;
|
|
3487
|
+
listenForStop(channel, () => {
|
|
3488
|
+
if (!process.emit("SIGTERM", "SIGTERM")) process.exit(143);
|
|
3489
|
+
});
|
|
3490
|
+
}
|
|
3491
|
+
const ASK_TIMEOUT_MS = 2e3;
|
|
3492
|
+
/** Connects to a stop channel; true once the listener took the request. */
|
|
3493
|
+
function askToStop(channel, timeoutMs = ASK_TIMEOUT_MS) {
|
|
3494
|
+
return new Promise((resolve) => {
|
|
3495
|
+
let connected = false;
|
|
3496
|
+
const socket = net.connect(channel);
|
|
3497
|
+
socket.setTimeout(timeoutMs, () => socket.destroy());
|
|
3498
|
+
socket.once("connect", () => connected = true);
|
|
3499
|
+
socket.on("error", () => void 0);
|
|
3500
|
+
socket.once("close", () => resolve(connected));
|
|
3501
|
+
socket.resume();
|
|
3502
|
+
});
|
|
3503
|
+
}
|
|
3504
|
+
/**
|
|
3505
|
+
* Asks the process to stop as SIGTERM would. False when it could not be
|
|
3506
|
+
* asked: on Windows a process without a stop channel (started by an older
|
|
3507
|
+
* version, or not a host), which only a kill ends.
|
|
3508
|
+
*/
|
|
3509
|
+
async function requestStop(pid, platform = process.platform) {
|
|
3510
|
+
const channel = stopChannelPath(pid, platform);
|
|
3511
|
+
if (channel) return askToStop(channel);
|
|
3512
|
+
try {
|
|
3513
|
+
process.kill(pid, "SIGTERM");
|
|
3514
|
+
} catch {}
|
|
3515
|
+
return true;
|
|
3516
|
+
}
|
|
3517
|
+
const STOP_RUN_TIMEOUT_MS = 6e4;
|
|
3518
|
+
/** Asks the project's running `hostName` to stop and waits until its process
|
|
3519
|
+
* is gone. It never kills: a host that does not answer keeps running. */
|
|
3520
|
+
async function stopRun(projectDir, hostName, options = {}) {
|
|
3521
|
+
const env = options.env ?? process.env;
|
|
3522
|
+
const probe = probeRun(projectDir, hostName, readProjectName(projectDir), env);
|
|
3523
|
+
if (probe.status === "none" || probe.status === "stale") return { status: "none" };
|
|
3524
|
+
const { pid } = probe.record;
|
|
3525
|
+
if (probe.status === "foreign") return {
|
|
3526
|
+
status: "foreign",
|
|
3527
|
+
pid,
|
|
3528
|
+
projectName: probe.record.projectName
|
|
3529
|
+
};
|
|
3530
|
+
if (!await requestStop(pid)) return {
|
|
3531
|
+
status: "unreachable",
|
|
3532
|
+
pid
|
|
3533
|
+
};
|
|
3534
|
+
const deadline = Date.now() + (options.timeoutMs ?? 6e4);
|
|
3535
|
+
while (isPidAlive(pid)) {
|
|
3536
|
+
if (Date.now() >= deadline) return {
|
|
3537
|
+
status: "timeout",
|
|
3538
|
+
pid
|
|
3539
|
+
};
|
|
3540
|
+
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
3541
|
+
}
|
|
3542
|
+
if (readRunRecord(projectDir, hostName, env)?.pid === pid) clearRunRecord(projectDir, hostName, env);
|
|
3543
|
+
return {
|
|
3544
|
+
status: "stopped",
|
|
3545
|
+
pid
|
|
3546
|
+
};
|
|
3547
|
+
}
|
|
3548
|
+
//#endregion
|
|
3549
|
+
//#region src/compound-member.ts
|
|
3550
|
+
/**
|
|
3551
|
+
* How a compound hands an own-process member its host. The member's
|
|
3552
|
+
* `host.js` alone is not the member: the compound's wrapper (reactor, config
|
|
3553
|
+
* and runner overrides) and its resolved tokens are. So the compound
|
|
3554
|
+
* resolves the member as it would in its own process and the child's
|
|
3555
|
+
* `ph run <folder>` runs that host instead of reading the file.
|
|
3556
|
+
*/
|
|
3557
|
+
/** Carries a {@link CompoundMemberHost} as JSON to the child's `ph run`. */
|
|
3558
|
+
const COMPOUND_MEMBER_ENV = "PH_COMPOUND_MEMBER";
|
|
3559
|
+
/** The most an environment variable holds on Windows, in characters; counted
|
|
3560
|
+
* here with its name and `=`, and kept on every platform, so a stack that
|
|
3561
|
+
* starts on one starts on all. */
|
|
3562
|
+
const ENV_VALUE_LIMIT = 32767;
|
|
3563
|
+
const isRecord$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
3564
|
+
/**
|
|
3565
|
+
* The first value in `value` that a JSON round trip drops or changes: a
|
|
3566
|
+
* function, symbol or bigint, `undefined` or an empty slot in an array, a
|
|
3567
|
+
* number that is not finite, an instance of a class (a Date, a Map, …) or
|
|
3568
|
+
* any object with `toJSON`, a symbol key, a cycle. An object property that
|
|
3569
|
+
* is `undefined` is fine: JSON drops it, and an absent key reads the same.
|
|
3570
|
+
*/
|
|
3571
|
+
function jsonChange(value) {
|
|
3572
|
+
const ancestors = /* @__PURE__ */ new Set();
|
|
3573
|
+
const walk = (item, path) => {
|
|
3574
|
+
switch (typeof item) {
|
|
3575
|
+
case "string":
|
|
3576
|
+
case "boolean": return;
|
|
3577
|
+
case "number": return Number.isFinite(item) ? void 0 : {
|
|
3578
|
+
path,
|
|
3579
|
+
what: `the number ${item}, which JSON writes as null`
|
|
3580
|
+
};
|
|
3581
|
+
case "undefined": return {
|
|
3582
|
+
path,
|
|
3583
|
+
what: "undefined, which JSON writes as null here"
|
|
3584
|
+
};
|
|
3585
|
+
case "function": return {
|
|
3586
|
+
path,
|
|
3587
|
+
what: "a function, which JSON drops"
|
|
3588
|
+
};
|
|
3589
|
+
case "symbol": return {
|
|
3590
|
+
path,
|
|
3591
|
+
what: "a symbol, which JSON drops"
|
|
3592
|
+
};
|
|
3593
|
+
case "bigint": return {
|
|
3594
|
+
path,
|
|
3595
|
+
what: "a bigint, which JSON cannot write"
|
|
3596
|
+
};
|
|
3597
|
+
}
|
|
3598
|
+
if (item === null) return void 0;
|
|
3599
|
+
const object = item;
|
|
3600
|
+
if (ancestors.has(object)) return {
|
|
3601
|
+
path,
|
|
3602
|
+
what: "a cycle, which JSON cannot write"
|
|
3603
|
+
};
|
|
3604
|
+
const prototype = Object.getPrototypeOf(object);
|
|
3605
|
+
if (Array.isArray(object) && prototype === Array.prototype) {
|
|
3606
|
+
ancestors.add(object);
|
|
3607
|
+
try {
|
|
3608
|
+
for (let i = 0; i < object.length; i++) {
|
|
3609
|
+
if (!(i in object)) return {
|
|
3610
|
+
path: [...path, i],
|
|
3611
|
+
what: "an empty slot, which JSON writes as null"
|
|
3612
|
+
};
|
|
3613
|
+
const found = walk(object[i], [...path, i]);
|
|
3614
|
+
if (found) return found;
|
|
3615
|
+
}
|
|
3616
|
+
return;
|
|
3617
|
+
} finally {
|
|
3618
|
+
ancestors.delete(object);
|
|
3619
|
+
}
|
|
3620
|
+
}
|
|
3621
|
+
if (object instanceof Date) return {
|
|
3622
|
+
path,
|
|
3623
|
+
what: "a Date, which JSON writes as a string"
|
|
3624
|
+
};
|
|
3625
|
+
if (prototype !== Object.prototype && prototype !== null) {
|
|
3626
|
+
const name = object.constructor?.name;
|
|
3627
|
+
return {
|
|
3628
|
+
path,
|
|
3629
|
+
what: `${typeof name === "string" && name ? `a ${name}` : "an instance of a class"}, which JSON writes as a plain object`
|
|
3630
|
+
};
|
|
3631
|
+
}
|
|
3632
|
+
if (typeof object.toJSON === "function") return {
|
|
3633
|
+
path,
|
|
3634
|
+
what: "an object with toJSON, which JSON replaces"
|
|
3635
|
+
};
|
|
3636
|
+
if (Object.getOwnPropertySymbols(object).length > 0) return {
|
|
3637
|
+
path,
|
|
3638
|
+
what: "a symbol-keyed property, which JSON drops"
|
|
3639
|
+
};
|
|
3640
|
+
ancestors.add(object);
|
|
3641
|
+
try {
|
|
3642
|
+
for (const [key, entry] of Object.entries(object)) {
|
|
3643
|
+
if (entry === void 0) continue;
|
|
3644
|
+
const found = walk(entry, [...path, key]);
|
|
3645
|
+
if (found) return found;
|
|
3646
|
+
}
|
|
3647
|
+
return;
|
|
3648
|
+
} finally {
|
|
3649
|
+
ancestors.delete(object);
|
|
3650
|
+
}
|
|
3651
|
+
};
|
|
3652
|
+
return walk(value, []);
|
|
3653
|
+
}
|
|
3654
|
+
/**
|
|
3655
|
+
* The member's host as the JSON its child reads from COMPOUND_MEMBER_ENV.
|
|
3656
|
+
* Refuses one JSON would change, or too long for an environment variable,
|
|
3657
|
+
* naming the member, the value and the way out: the member runs in the
|
|
3658
|
+
* compound's process, where nothing is copied.
|
|
3659
|
+
*/
|
|
3660
|
+
function encodeCompoundMember(member) {
|
|
3661
|
+
const where = `hosts/${member.compound}: member "${member.member}" cannot run in its own process`;
|
|
3662
|
+
const hint = `Run it in the compound's process: children.${member.member}.process: "shared".`;
|
|
3663
|
+
const change = jsonChange(member.host);
|
|
3664
|
+
if (change) throw new RunnerError(`${where}: its host holds ${change.what}, at ${formatPath(change.path)}; the child gets its host as JSON.`, hint);
|
|
3665
|
+
const json = JSON.stringify(member);
|
|
3666
|
+
if (19 + json.length > 32767) throw new RunnerError(`${where}: its host is ${json.length} characters as JSON, and the child gets it in an environment variable, which holds at most ${ENV_VALUE_LIMIT} on Windows.`, hint);
|
|
3667
|
+
return json;
|
|
3668
|
+
}
|
|
3669
|
+
/**
|
|
3670
|
+
* The member host a compound handed this process for `folder`, taken out of
|
|
3671
|
+
* `env` so nothing this process starts inherits it. Undefined when there is
|
|
3672
|
+
* none; throws when it is malformed or names another folder.
|
|
3673
|
+
*/
|
|
3674
|
+
function takeCompoundMember(env, folder) {
|
|
3675
|
+
const raw = env[COMPOUND_MEMBER_ENV];
|
|
3676
|
+
if (raw === void 0) return void 0;
|
|
3677
|
+
delete env[COMPOUND_MEMBER_ENV];
|
|
3678
|
+
let parsed;
|
|
3679
|
+
try {
|
|
3680
|
+
parsed = JSON.parse(raw);
|
|
3681
|
+
} catch {
|
|
3682
|
+
parsed = void 0;
|
|
3683
|
+
}
|
|
3684
|
+
if (!isRecord$1(parsed) || typeof parsed.compound !== "string" || typeof parsed.member !== "string" || typeof parsed.folder !== "string" || !isRecord$1(parsed.host)) throw new Error(`${COMPOUND_MEMBER_ENV} does not hold a compound member's host.`);
|
|
3685
|
+
if (parsed.folder !== folder) throw new Error(`${COMPOUND_MEMBER_ENV} holds member "${parsed.member}" (hosts/${parsed.folder}) of compound "${parsed.compound}", not hosts/${folder}.`);
|
|
3686
|
+
return parsed;
|
|
3687
|
+
}
|
|
3688
|
+
//#endregion
|
|
3689
|
+
//#region src/spawn-host.ts
|
|
3690
|
+
/** The tail line before which a timed-out or aborted run's output is its own. */
|
|
3691
|
+
const SPAWN_STOPPING_NOTE = "spawnHost: stopping it";
|
|
3692
|
+
var SpawnHostError = class extends Error {
|
|
3693
|
+
phase;
|
|
3694
|
+
outputTail;
|
|
3695
|
+
exit;
|
|
3696
|
+
constructor(message, phase, outputTail, exit) {
|
|
3697
|
+
super(outputTail ? `${message}\n--- output tail ---\n${outputTail}` : message);
|
|
3698
|
+
this.phase = phase;
|
|
3699
|
+
this.outputTail = outputTail;
|
|
3700
|
+
this.exit = exit;
|
|
3701
|
+
this.name = "SpawnHostError";
|
|
3702
|
+
}
|
|
3703
|
+
};
|
|
3704
|
+
const READY_TIMEOUT_MS = 12e4;
|
|
3705
|
+
const STOP_TIMEOUT_MS = 3e4;
|
|
3706
|
+
const POLL_MS = 100;
|
|
3707
|
+
const CLOSE_WAIT_MS = 1e3;
|
|
3708
|
+
const BASE_ENV_KEYS = [
|
|
3709
|
+
"PATH",
|
|
3710
|
+
"HOME",
|
|
3711
|
+
"TMPDIR"
|
|
3712
|
+
];
|
|
3713
|
+
const WIN32_ENV_KEYS = [
|
|
3714
|
+
"SystemRoot",
|
|
3715
|
+
"USERPROFILE",
|
|
3716
|
+
"APPDATA",
|
|
3717
|
+
"LOCALAPPDATA",
|
|
3718
|
+
"TEMP",
|
|
3719
|
+
"TMP",
|
|
3720
|
+
"ComSpec",
|
|
3721
|
+
"PATHEXT"
|
|
3722
|
+
];
|
|
3723
|
+
/** The child's whole env: without a `baseEnv`, no other `process.env` key
|
|
3724
|
+
* reaches it. */
|
|
3725
|
+
function childEnv(dataDir, env = {}, baseEnv) {
|
|
3726
|
+
if ("PH_USER_DATA_DIR" in env) throw new Error("spawnHost: set the data dir with `dataDir`, not env.PH_USER_DATA_DIR.");
|
|
3727
|
+
if (baseEnv) {
|
|
3728
|
+
const base = {};
|
|
3729
|
+
for (const [key, value] of Object.entries(baseEnv)) if (value !== void 0) base[key] = value;
|
|
3730
|
+
return {
|
|
3731
|
+
...base,
|
|
3732
|
+
PH_USER_DATA_DIR: dataDir,
|
|
3733
|
+
...env
|
|
3734
|
+
};
|
|
3735
|
+
}
|
|
3736
|
+
const keys = process.platform === "win32" ? [...BASE_ENV_KEYS, ...WIN32_ENV_KEYS] : BASE_ENV_KEYS;
|
|
3737
|
+
const base = {};
|
|
3738
|
+
for (const key of keys) {
|
|
3739
|
+
const value = process.env[key];
|
|
3740
|
+
if (value !== void 0) base[key] = value;
|
|
3741
|
+
}
|
|
3742
|
+
return {
|
|
3743
|
+
...base,
|
|
3744
|
+
PH_USER_DATA_DIR: dataDir,
|
|
3745
|
+
PH_NO_TELEMETRY: "1",
|
|
3746
|
+
PH_NO_DOTENV: "1",
|
|
3747
|
+
...env
|
|
3748
|
+
};
|
|
3749
|
+
}
|
|
3750
|
+
/** The project's ph-cli, else its ph-run (a packaged app has only that). */
|
|
3751
|
+
function resolvePhCliEntry(projectRoot) {
|
|
3752
|
+
const require_ = createRequire(pathToFileURL(path.join(projectRoot, "package.json")).href);
|
|
3753
|
+
let pkgPath;
|
|
3754
|
+
try {
|
|
3755
|
+
pkgPath = require_.resolve("@powerhousedao/ph-cli/package.json");
|
|
3756
|
+
} catch (error) {
|
|
3757
|
+
try {
|
|
3758
|
+
pkgPath = require_.resolve("@powerhousedao/ph-run/package.json");
|
|
3759
|
+
} catch {
|
|
3760
|
+
throw error;
|
|
3761
|
+
}
|
|
3762
|
+
}
|
|
3763
|
+
return path.join(path.dirname(pkgPath), "dist", "cli.mjs");
|
|
3764
|
+
}
|
|
3765
|
+
/** Readiness waits for a record; refuse a host/verb that writes none. */
|
|
3766
|
+
async function assertWritesRecord(projectRoot, host, verb, definition) {
|
|
3767
|
+
if (verb !== void 0 && (ONE_SHOT_VERBS.has(verb) || STORE_VERBS.has(verb))) throw new Error(`spawnHost: "${verb}" is a one-shot verb; it writes no run record to wait for.`);
|
|
3768
|
+
const declared = definition ?? (await loadHost(projectRoot, host)).host;
|
|
3769
|
+
const specifier = declared.runner.module;
|
|
3770
|
+
const supplier = locateHost(projectRoot, host).package;
|
|
3771
|
+
const runner = await resolveRunnerModule(supplier?.root ?? projectRoot, specifier);
|
|
3772
|
+
if (runner.kind === "compound") {
|
|
3773
|
+
if (declared.config?.runtimeRecord === false) throw new Error(`spawnHost: hosts/${host} sets config.runtimeRecord: false, so it writes no run record to wait for.`);
|
|
3774
|
+
return;
|
|
3775
|
+
}
|
|
3776
|
+
if (!isSchemaLike(runner.outputsSchema)) throw new Error(`spawnHost: hosts/${host} runs "${specifier}", which exports no outputsSchema, so it writes no run record to wait for.`);
|
|
3777
|
+
}
|
|
3778
|
+
const sleep = (ms) => new Promise((resolve) => {
|
|
3779
|
+
setTimeout(resolve, ms).unref();
|
|
3780
|
+
});
|
|
3781
|
+
const live = /* @__PURE__ */ new Set();
|
|
3782
|
+
let exitHookInstalled = false;
|
|
3783
|
+
function track(child) {
|
|
3784
|
+
live.add(child);
|
|
3785
|
+
child.once("exit", () => live.delete(child));
|
|
3786
|
+
if (exitHookInstalled) return;
|
|
3787
|
+
exitHookInstalled = true;
|
|
3788
|
+
process.once("exit", () => {
|
|
3789
|
+
for (const running of live) running.kill("SIGTERM");
|
|
3790
|
+
});
|
|
3791
|
+
}
|
|
3792
|
+
/**
|
|
3793
|
+
* `ph run <host> [verb]` as a child; ready when its run record appears.
|
|
3794
|
+
*
|
|
3795
|
+
* The child shares this process's group, so a terminal Ctrl-C reaches both.
|
|
3796
|
+
* It runs the project's own ph-cli (else its ph-run): one older than
|
|
3797
|
+
* PH_NO_DOTENV reads the project's `.env` anyway.
|
|
3798
|
+
*/
|
|
3799
|
+
async function spawnHost(options) {
|
|
3800
|
+
const projectRoot = path.resolve(options.projectRoot);
|
|
3801
|
+
const dataDir = path.resolve(options.dataDir);
|
|
3802
|
+
const member = options.definition ? encodeCompoundMember({
|
|
3803
|
+
...options.definition,
|
|
3804
|
+
folder: options.host
|
|
3805
|
+
}) : void 0;
|
|
3806
|
+
const env = childEnv(dataDir, {
|
|
3807
|
+
...options.env,
|
|
3808
|
+
...options.stopOnStdin ? { [STOP_ON_STDIN_ENV]: "1" } : {},
|
|
3809
|
+
...member === void 0 ? {} : { [COMPOUND_MEMBER_ENV]: member }
|
|
3810
|
+
}, options.baseEnv);
|
|
3811
|
+
const readerEnv = { PH_USER_DATA_DIR: dataDir };
|
|
3812
|
+
const readyTimeoutMs = options.readyTimeoutMs ?? READY_TIMEOUT_MS;
|
|
3813
|
+
const stopTimeoutMs = options.stopTimeoutMs ?? STOP_TIMEOUT_MS;
|
|
3814
|
+
const { signal, stopOnStdin = false } = options;
|
|
3815
|
+
if (signal?.aborted) throw new SpawnHostError("spawnHost: aborted before start.", "aborted", "");
|
|
3816
|
+
await assertWritesRecord(projectRoot, options.host, options.verb, options.definition?.host);
|
|
3817
|
+
const cli = options.cli ?? resolvePhCliEntry(projectRoot);
|
|
3818
|
+
fs.mkdirSync(dataDir, { recursive: true });
|
|
3819
|
+
const log = options.logFile ? fs.createWriteStream(options.logFile, { flags: "a" }) : void 0;
|
|
3820
|
+
let tail = "";
|
|
3821
|
+
log?.on("error", (error) => {
|
|
3822
|
+
tail = (tail + `logFile: ${error.message}\n`).slice(-8192);
|
|
3823
|
+
});
|
|
3824
|
+
const args = [
|
|
3825
|
+
cli,
|
|
3826
|
+
"run",
|
|
3827
|
+
options.host
|
|
3828
|
+
];
|
|
3829
|
+
if (options.verb !== void 0) args.push(options.verb);
|
|
3830
|
+
if (options.argv && options.argv.length > 0) args.push("--", ...options.argv);
|
|
3831
|
+
const child = spawn(process.execPath, args, {
|
|
3832
|
+
cwd: projectRoot,
|
|
3833
|
+
env,
|
|
3834
|
+
stdio: [
|
|
3835
|
+
stopOnStdin ? "pipe" : "ignore",
|
|
3836
|
+
"pipe",
|
|
3837
|
+
"pipe"
|
|
3838
|
+
],
|
|
3839
|
+
windowsHide: true
|
|
3840
|
+
});
|
|
3841
|
+
child.stdin?.on("error", () => void 0);
|
|
3842
|
+
if (!stopOnStdin) track(child);
|
|
3843
|
+
const { stdout, stderr } = child;
|
|
3844
|
+
if (!stdout || !stderr) throw new Error("spawnHost: the child has no pipes.");
|
|
3845
|
+
const onChunk = (stream) => (chunk) => {
|
|
3846
|
+
tail = (tail + chunk).slice(-8192);
|
|
3847
|
+
log?.write(chunk);
|
|
3848
|
+
try {
|
|
3849
|
+
options.onOutput?.(stream, chunk);
|
|
3850
|
+
} catch (error) {
|
|
3851
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
3852
|
+
tail = (tail + `onOutput: ${message}\n`).slice(-8192);
|
|
3853
|
+
}
|
|
3854
|
+
};
|
|
3855
|
+
stdout.setEncoding("utf8").on("data", onChunk("stdout"));
|
|
3856
|
+
stderr.setEncoding("utf8").on("data", onChunk("stderr"));
|
|
3857
|
+
let forced = false;
|
|
3858
|
+
let exit;
|
|
3859
|
+
const exited = new Promise((resolve) => {
|
|
3860
|
+
const done = (code, sig) => {
|
|
3861
|
+
if (exit) return;
|
|
3862
|
+
exit = {
|
|
3863
|
+
code,
|
|
3864
|
+
signal: sig,
|
|
3865
|
+
forced
|
|
3866
|
+
};
|
|
3867
|
+
signal?.removeEventListener("abort", onAbort);
|
|
3868
|
+
resolve(exit);
|
|
3869
|
+
};
|
|
3870
|
+
child.once("exit", done);
|
|
3871
|
+
child.once("error", (error) => {
|
|
3872
|
+
tail = (tail + `${error.message}\n`).slice(-8192);
|
|
3873
|
+
if (child.pid === void 0) done(null, null);
|
|
3874
|
+
});
|
|
3875
|
+
});
|
|
3876
|
+
const closed = new Promise((resolve) => {
|
|
3877
|
+
child.once("close", () => {
|
|
3878
|
+
log?.end();
|
|
3879
|
+
resolve();
|
|
3880
|
+
});
|
|
3881
|
+
});
|
|
3882
|
+
const pid = child.pid;
|
|
3883
|
+
const ownRecords = () => pid === void 0 ? [] : listRunRecords(projectRoot, readerEnv).filter((r) => r.pid === pid);
|
|
3884
|
+
const kill = (sig) => {
|
|
3885
|
+
if (pid === void 0) return;
|
|
3886
|
+
try {
|
|
3887
|
+
process.kill(pid, sig);
|
|
3888
|
+
} catch {}
|
|
3889
|
+
};
|
|
3890
|
+
const clearOwnRecords = () => {
|
|
3891
|
+
for (const record of ownRecords()) clearRunRecord(projectRoot, recordKeyOf(record), readerEnv);
|
|
3892
|
+
};
|
|
3893
|
+
let stopping;
|
|
3894
|
+
const stop = () => {
|
|
3895
|
+
stopping ??= (async () => {
|
|
3896
|
+
if (!exit) {
|
|
3897
|
+
if (stopOnStdin) child.stdin?.end();
|
|
3898
|
+
else kill("SIGTERM");
|
|
3899
|
+
let timer;
|
|
3900
|
+
const timedOut = await Promise.race([exited.then(() => false), new Promise((resolve) => {
|
|
3901
|
+
timer = setTimeout(() => resolve(true), stopTimeoutMs);
|
|
3902
|
+
})]);
|
|
3903
|
+
clearTimeout(timer);
|
|
3904
|
+
if (timedOut) {
|
|
3905
|
+
forced = true;
|
|
3906
|
+
if (stopOnStdin && pid !== void 0) killTree(pid, "SIGKILL");
|
|
3907
|
+
else kill("SIGKILL");
|
|
3908
|
+
}
|
|
3909
|
+
}
|
|
3910
|
+
const result = await exited;
|
|
3911
|
+
clearOwnRecords();
|
|
3912
|
+
return result;
|
|
3913
|
+
})();
|
|
3914
|
+
return stopping;
|
|
3915
|
+
};
|
|
3916
|
+
function onAbort() {
|
|
3917
|
+
stop();
|
|
3918
|
+
}
|
|
3919
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
3920
|
+
const deadline = Date.now() + readyTimeoutMs;
|
|
3921
|
+
for (;;) {
|
|
3922
|
+
const aborted = signal?.aborted ?? false;
|
|
3923
|
+
if (exit && !aborted) {
|
|
3924
|
+
clearOwnRecords();
|
|
3925
|
+
let timer;
|
|
3926
|
+
await Promise.race([closed, new Promise((resolve) => {
|
|
3927
|
+
timer = setTimeout(resolve, CLOSE_WAIT_MS);
|
|
3928
|
+
})]);
|
|
3929
|
+
clearTimeout(timer);
|
|
3930
|
+
const how = exit.signal !== null ? `signal ${exit.signal}` : `code ${exit.code}`;
|
|
3931
|
+
throw new SpawnHostError(`spawnHost: ph run ${options.host} exited (${how}) before writing its run record.`, "exited", tail, exit);
|
|
3932
|
+
}
|
|
3933
|
+
const record = aborted ? void 0 : ownRecords().at(0);
|
|
3934
|
+
if (record) return {
|
|
3935
|
+
pid: record.pid,
|
|
3936
|
+
dataDir,
|
|
3937
|
+
record,
|
|
3938
|
+
outputs: record.outputs,
|
|
3939
|
+
members: record.members,
|
|
3940
|
+
exited,
|
|
3941
|
+
stop
|
|
3942
|
+
};
|
|
3943
|
+
if (aborted || Date.now() >= deadline) {
|
|
3944
|
+
const phase = aborted ? "aborted" : "timeout";
|
|
3945
|
+
const ended = tail === "" || tail.endsWith("\n") ? "" : "\n";
|
|
3946
|
+
const ran = `${tail}${ended}${SPAWN_STOPPING_NOTE}\n`;
|
|
3947
|
+
tail = "";
|
|
3948
|
+
const stopped = await stop();
|
|
3949
|
+
let timer;
|
|
3950
|
+
await Promise.race([closed, new Promise((resolve) => {
|
|
3951
|
+
timer = setTimeout(resolve, CLOSE_WAIT_MS);
|
|
3952
|
+
})]);
|
|
3953
|
+
clearTimeout(timer);
|
|
3954
|
+
throw new SpawnHostError(phase === "aborted" ? `spawnHost: aborted before ph run ${options.host} was ready.` : `spawnHost: ph run ${options.host} wrote no run record within ${readyTimeoutMs} ms.`, phase, ran + tail, stopped);
|
|
3955
|
+
}
|
|
3956
|
+
await Promise.race([sleep(POLL_MS), exited]);
|
|
3957
|
+
}
|
|
3958
|
+
}
|
|
3959
|
+
//#endregion
|
|
3140
3960
|
//#region src/child-wrapper.ts
|
|
3141
3961
|
/** Generic compound rule: `reactor`/`config` replace, `runner` key-merges. */
|
|
3142
3962
|
function applyChildWrapper(base, wrapper) {
|
|
@@ -3175,19 +3995,22 @@ function resolveUserDataPlaceholders(value, userData) {
|
|
|
3175
3995
|
}
|
|
3176
3996
|
//#endregion
|
|
3177
3997
|
//#region src/resolve/node.ts
|
|
3178
|
-
/** Load every producer host a set of refs names (each once).
|
|
3179
|
-
|
|
3998
|
+
/** Load every producer host a set of refs names (each once). In a host a
|
|
3999
|
+
* package supplies (`scope`), a bare name is that package's host first. */
|
|
4000
|
+
async function loadProducers(projectRoot, refs, scope) {
|
|
3180
4001
|
const producers = /* @__PURE__ */ new Map();
|
|
3181
4002
|
for (const { host: folder } of refs) {
|
|
3182
4003
|
if (producers.has(folder)) continue;
|
|
3183
4004
|
try {
|
|
3184
|
-
const loaded = await loadHost(projectRoot, folder);
|
|
4005
|
+
const loaded = await loadHost(projectRoot, folder, { scope });
|
|
3185
4006
|
const specifier = loaded.host.runner.module;
|
|
3186
4007
|
producers.set(folder, {
|
|
3187
4008
|
folder,
|
|
3188
4009
|
name: loaded.host.name,
|
|
4010
|
+
...loaded.ref !== void 0 ? { ref: loaded.ref } : {},
|
|
4011
|
+
...loaded.package ? { package: loaded.package } : {},
|
|
3189
4012
|
specifier,
|
|
3190
|
-
runner: await resolveRunnerModule(projectRoot, specifier)
|
|
4013
|
+
runner: await resolveRunnerModule(moduleRootOf(projectRoot, loaded), specifier)
|
|
3191
4014
|
});
|
|
3192
4015
|
} catch (error) {
|
|
3193
4016
|
producers.set(folder, { error: `names host "${folder}", which cannot be loaded: ${error instanceof Error ? error.message : String(error)}` });
|
|
@@ -3237,28 +4060,31 @@ function runRecordOutputSource(projectRoot, options) {
|
|
|
3237
4060
|
const env = options.env ?? process.env;
|
|
3238
4061
|
const siblings = siblingEnvs(projectRoot, env);
|
|
3239
4062
|
return { lookup(ref) {
|
|
3240
|
-
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).`;
|
|
3241
4063
|
const info = producers.get(ref.host);
|
|
3242
|
-
const
|
|
4064
|
+
const loaded = info && !("error" in info) ? info : void 0;
|
|
4065
|
+
const address = loaded?.ref ?? ref.host;
|
|
4066
|
+
const notRunning = `${consumer} needs outputs from host "${address}", which is not running. Start it first: ph run ${address} (or run a compound that includes it).`;
|
|
4067
|
+
const schema = loaded?.runner.outputsSchema;
|
|
3243
4068
|
const withSchema = schema !== void 0 && schema !== null ? { schema } : {};
|
|
3244
4069
|
const standalone = [];
|
|
3245
|
-
if (ref.member === void 0 &&
|
|
3246
|
-
const
|
|
4070
|
+
if (ref.member === void 0 && loaded) {
|
|
4071
|
+
const key = runRecordKey(loaded.name, loaded.package?.name);
|
|
4072
|
+
const probe = probeRun(projectRoot, key, projectName, env);
|
|
3247
4073
|
if (probe.status === "live" && probe.record.outputs) return {
|
|
3248
4074
|
status: "available",
|
|
3249
4075
|
outputs: probe.record.outputs,
|
|
3250
4076
|
...withSchema
|
|
3251
4077
|
};
|
|
3252
4078
|
for (const sibling of siblings) {
|
|
3253
|
-
const other = probeRun(projectRoot,
|
|
4079
|
+
const other = probeRun(projectRoot, key, projectName, sibling);
|
|
3254
4080
|
if (other.status === "live" && other.record.outputs) standalone.push({
|
|
3255
|
-
label: `"${
|
|
4081
|
+
label: `"${loaded.name}" (pid ${other.record.pid})`,
|
|
3256
4082
|
outputs: other.record.outputs
|
|
3257
4083
|
});
|
|
3258
4084
|
}
|
|
3259
4085
|
}
|
|
3260
|
-
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 ===
|
|
3261
|
-
label: `member "${key}" of "${record.host}"`,
|
|
4086
|
+
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 === address && (ref.member === void 0 || key === ref.member)).map(([key, member]) => ({
|
|
4087
|
+
label: `member "${key}" of "${runRecordKey(record.host, record.package)}"`,
|
|
3262
4088
|
outputs: member.outputs
|
|
3263
4089
|
})));
|
|
3264
4090
|
const found = [...standalone, ...members];
|
|
@@ -3269,7 +4095,7 @@ function runRecordOutputSource(projectRoot, options) {
|
|
|
3269
4095
|
};
|
|
3270
4096
|
if (found.length > 1) return {
|
|
3271
4097
|
status: "unavailable",
|
|
3272
|
-
message: `${consumer} needs outputs from host "${
|
|
4098
|
+
message: `${consumer} needs outputs from host "${address}", which runs as ${found.map((m) => m.label).join(" and ")}; stop all but one, or run ${address} on its own.`
|
|
3273
4099
|
};
|
|
3274
4100
|
return {
|
|
3275
4101
|
status: "unavailable",
|
|
@@ -3278,13 +4104,16 @@ function runRecordOutputSource(projectRoot, options) {
|
|
|
3278
4104
|
} };
|
|
3279
4105
|
}
|
|
3280
4106
|
/** The resolving process's `$env` inputs: its environment plus the
|
|
3281
|
-
* always-resolvable built-ins (`userData` honours PH_USER_DATA_DIR).
|
|
3282
|
-
|
|
4107
|
+
* always-resolvable built-ins (`userData` honours PH_USER_DATA_DIR).
|
|
4108
|
+
* `package` is the root of the package that supplies the host being
|
|
4109
|
+
* resolved (`hostPackage`), else the project root. */
|
|
4110
|
+
function processResolveEnv(projectRoot, env = process.env, hostPackage) {
|
|
3283
4111
|
return {
|
|
3284
4112
|
env,
|
|
3285
4113
|
builtins: {
|
|
3286
4114
|
userData: defaultUserDataDir(projectRoot, env),
|
|
3287
|
-
projectRoot: path.resolve(projectRoot)
|
|
4115
|
+
projectRoot: path.resolve(projectRoot),
|
|
4116
|
+
package: hostPackage?.root ?? path.resolve(projectRoot)
|
|
3288
4117
|
}
|
|
3289
4118
|
};
|
|
3290
4119
|
}
|
|
@@ -3342,14 +4171,12 @@ function toStartedHandle(value, where) {
|
|
|
3342
4171
|
...parsed.data,
|
|
3343
4172
|
outputs: parsed.data.outputs ?? {},
|
|
3344
4173
|
...isPromiseLike(live.ready) ? { ready: live.ready } : {},
|
|
3345
|
-
...isCallable(shutdown) ? { shutdown: () => shutdown.call(value) } : {}
|
|
4174
|
+
...isCallable(shutdown) ? { shutdown: () => shutdown.call(value) } : {},
|
|
4175
|
+
...isPromiseLike(live.exited) ? { exited: live.exited } : {}
|
|
3346
4176
|
};
|
|
3347
4177
|
}
|
|
3348
4178
|
//#endregion
|
|
3349
4179
|
//#region src/compound.ts
|
|
3350
|
-
async function memberDraft(projectRoot, member) {
|
|
3351
|
-
return applyChildWrapper((await loadHost(projectRoot, member.host)).host, member);
|
|
3352
|
-
}
|
|
3353
4180
|
/** Whether a member receives the compound's `cspRegistrySync` wiring (as
|
|
3354
4181
|
* `runner.cspRegistrySync`): its runner declares that option (any specifier
|
|
3355
4182
|
* that reaches the Connect runner), or it names the Connect runner. A
|
|
@@ -3357,6 +4184,8 @@ async function memberDraft(projectRoot, member) {
|
|
|
3357
4184
|
function takesCspRegistrySync(m) {
|
|
3358
4185
|
return m.specifier === "@powerhousedao/ph-cli/runners/connect" || declaresKey(m.runner.hostSchema, ["runner"], "cspRegistrySync");
|
|
3359
4186
|
}
|
|
4187
|
+
/** Past the shell's own limit: this only matters when no shell is left. */
|
|
4188
|
+
const STOP_STREAM_LIMIT_MS = 15e3;
|
|
3360
4189
|
/**
|
|
3361
4190
|
* Windows has no SIGTERM, so a supervisor asks a stack to stop through its
|
|
3362
4191
|
* stdin: a line, or the pipe closing, which also covers the supervisor dying.
|
|
@@ -3380,6 +4209,126 @@ function whenStreamStops(stream, stop) {
|
|
|
3380
4209
|
]) stream.once(event, once);
|
|
3381
4210
|
stream.resume();
|
|
3382
4211
|
}
|
|
4212
|
+
/**
|
|
4213
|
+
* A standalone host's stop through its supervisor's stream (stdin, under
|
|
4214
|
+
* {@link STOP_ON_STDIN_ENV}): a line or the end of it is delivered as the
|
|
4215
|
+
* stop channel delivers a request, to the SIGTERM handlers, else as exit
|
|
4216
|
+
* 143. Held until `started()`: a stop while the verb starts takes effect
|
|
4217
|
+
* once it has, so a store is never left half-opened.
|
|
4218
|
+
*/
|
|
4219
|
+
function holdStopRequests(stream, options = {}) {
|
|
4220
|
+
const exit = options.exit ?? ((code) => process.exit(code));
|
|
4221
|
+
const signal = options.signal ?? (() => process.emit("SIGTERM", "SIGTERM"));
|
|
4222
|
+
let asked = false;
|
|
4223
|
+
let up = false;
|
|
4224
|
+
const deliver = () => {
|
|
4225
|
+
const limit = options.limitMs ?? 15e3;
|
|
4226
|
+
setTimeout(() => exit(143), limit).unref();
|
|
4227
|
+
if (!signal()) exit(143);
|
|
4228
|
+
};
|
|
4229
|
+
whenStreamStops(stream, () => {
|
|
4230
|
+
asked = true;
|
|
4231
|
+
if (up) deliver();
|
|
4232
|
+
});
|
|
4233
|
+
for (const output of options.outputs ?? [process.stdout, process.stderr]) output.on("error", () => void 0);
|
|
4234
|
+
return { started() {
|
|
4235
|
+
if (up) return;
|
|
4236
|
+
up = true;
|
|
4237
|
+
if (asked) deliver();
|
|
4238
|
+
} };
|
|
4239
|
+
}
|
|
4240
|
+
/** How long an own-process member may take to write its run record: a
|
|
4241
|
+
* store's first boot can be slow, and an in-process member has no limit. */
|
|
4242
|
+
const MEMBER_READY_TIMEOUT_MS = 6e5;
|
|
4243
|
+
/** An id as a file name (the services manager's rule: `:` is no file name
|
|
4244
|
+
* on NTFS). */
|
|
4245
|
+
const fileSafe = (id) => id.replace(/[<>:"/\\|?*]/g, "+");
|
|
4246
|
+
/**
|
|
4247
|
+
* A fresh log file for this run of an own-process member, named as the
|
|
4248
|
+
* services manager names a service's: `<phDir>/services/<member>/
|
|
4249
|
+
* <member>.<runId>.log`, or `<phDir>/services/<package>/<member>/…` for a
|
|
4250
|
+
* compound the package `hostPackage` supplies. Older runs beyond the newest
|
|
4251
|
+
* few are removed.
|
|
4252
|
+
*/
|
|
4253
|
+
function memberLogFile(projectRoot, env, member, hostPackage) {
|
|
4254
|
+
const safe = fileSafe(member);
|
|
4255
|
+
const dir = path.join(resolvePhDir(projectRoot, env), "services", ...hostPackage === void 0 ? [] : hostPackage.split("/"), safe);
|
|
4256
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
4257
|
+
const escaped = safe.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
4258
|
+
const pattern = new RegExp(`^${escaped}\\.(\\d+)\\.log$`);
|
|
4259
|
+
const runId = (name) => Number(pattern.exec(name)?.[1]);
|
|
4260
|
+
const runs = fs.readdirSync(dir).filter((name) => pattern.test(name)).sort((a, b) => runId(b) - runId(a));
|
|
4261
|
+
for (const old of runs.slice(4)) try {
|
|
4262
|
+
fs.rmSync(path.join(dir, old));
|
|
4263
|
+
} catch {}
|
|
4264
|
+
let id = Math.max(Date.now(), runs.length > 0 ? runId(runs[0]) + 1 : 0);
|
|
4265
|
+
while (fs.existsSync(path.join(dir, `${safe}.${id}.log`))) id += 1;
|
|
4266
|
+
return path.join(dir, `${safe}.${id}.log`);
|
|
4267
|
+
}
|
|
4268
|
+
/** Every URL among a member's outputs, by dotted path. */
|
|
4269
|
+
function urlEndpoints(outputs) {
|
|
4270
|
+
const found = {};
|
|
4271
|
+
const walk = (value, at) => {
|
|
4272
|
+
if (typeof value === "string") {
|
|
4273
|
+
if (/^[a-z][a-z\d+.-]*:\/\//i.test(value)) found[at] = value;
|
|
4274
|
+
} else if (Array.isArray(value)) value.forEach((item, i) => walk(item, at ? `${at}.${i}` : String(i)));
|
|
4275
|
+
else if (isPlainObject(value)) for (const [key, item] of Object.entries(value)) walk(item, at ? `${at}.${key}` : key);
|
|
4276
|
+
};
|
|
4277
|
+
walk(outputs, "");
|
|
4278
|
+
return found;
|
|
4279
|
+
}
|
|
4280
|
+
/**
|
|
4281
|
+
* The member whose runner owns the terminal (`foreground: true`) and the
|
|
4282
|
+
* order the compound starts its members in. Its rules: one such member at
|
|
4283
|
+
* most, in the compound's process, and last, so no member reads its outputs
|
|
4284
|
+
* and a `startOrder` that names it puts it at the end. `runCompound` refuses
|
|
4285
|
+
* the first broken one; `ph host check` reports them all.
|
|
4286
|
+
*/
|
|
4287
|
+
function planForeground(members, plan, wiring) {
|
|
4288
|
+
const owners = members.filter((m) => m.runner.foreground === true);
|
|
4289
|
+
if (owners.length === 0) return {
|
|
4290
|
+
order: plan.order,
|
|
4291
|
+
issues: []
|
|
4292
|
+
};
|
|
4293
|
+
if (owners.length > 1) return {
|
|
4294
|
+
order: plan.order,
|
|
4295
|
+
issues: [{
|
|
4296
|
+
path: "children",
|
|
4297
|
+
message: `members ${owners.map((m) => `"${m.key}"`).join(", ")} each run a runner that owns the terminal; a compound has one.`
|
|
4298
|
+
}]
|
|
4299
|
+
};
|
|
4300
|
+
const [owner] = owners;
|
|
4301
|
+
const where = `member "${owner.key}" (${owner.specifier})`;
|
|
4302
|
+
const issues = [];
|
|
4303
|
+
if (owner.member.process === "own") issues.push({
|
|
4304
|
+
path: `children.${owner.key}.process`,
|
|
4305
|
+
message: `${where} owns the terminal, so it runs in the compound's process, not its own.`,
|
|
4306
|
+
hint: `Remove children.${owner.key}.process.`
|
|
4307
|
+
});
|
|
4308
|
+
const readers = plan.edges.filter((edge) => edge.producer === owner.key);
|
|
4309
|
+
if (readers.length > 0) issues.push({
|
|
4310
|
+
path: "children",
|
|
4311
|
+
message: `${readers.map((edge) => `${edge.consumer}.${edge.path}`).join(", ")} read the outputs of ${where}, which owns the terminal and starts last.`
|
|
4312
|
+
});
|
|
4313
|
+
const named = wiring.startOrder;
|
|
4314
|
+
if (named?.includes(owner.key) && named.at(-1) !== owner.key) issues.push({
|
|
4315
|
+
path: "config.startOrder",
|
|
4316
|
+
message: `config.startOrder starts ${where} before ${named.slice(named.indexOf(owner.key) + 1).join(", ")}, but it owns the terminal and starts last.`,
|
|
4317
|
+
hint: "Put it last in startOrder, or leave it out."
|
|
4318
|
+
});
|
|
4319
|
+
return {
|
|
4320
|
+
foreground: owner.key,
|
|
4321
|
+
order: [...plan.order.filter((key) => key !== owner.key), owner.key],
|
|
4322
|
+
issues
|
|
4323
|
+
};
|
|
4324
|
+
}
|
|
4325
|
+
/** Where a member runs: `own` (a child process) or `shared` (the
|
|
4326
|
+
* compound's). The foreground member and every member at a one-shot verb
|
|
4327
|
+
* share the compound's; next to a foreground member the default is `own`. */
|
|
4328
|
+
function memberProcessOf(member, options) {
|
|
4329
|
+
if (options.foreground || options.oneShot) return "shared";
|
|
4330
|
+
return member.process ?? (options.besideForeground ? "own" : "shared");
|
|
4331
|
+
}
|
|
3383
4332
|
/** The verb the generic compound starts its members at for its own `verb`:
|
|
3384
4333
|
* `run` follows the compound's defaultVerb. */
|
|
3385
4334
|
function compoundStartVerb(verb, runner) {
|
|
@@ -3392,7 +4341,8 @@ function memberVerbOf(compoundVerb, runner) {
|
|
|
3392
4341
|
return compoundVerb === "run" ? runner.defaultVerb ?? "run" : compoundVerb;
|
|
3393
4342
|
}
|
|
3394
4343
|
async function runCompound(hostInput, ctx, options) {
|
|
3395
|
-
const
|
|
4344
|
+
const scope = ctx.hostPackage;
|
|
4345
|
+
const compoundFile = scope ? `${scope.name}/hosts/${hostInput.name}` : `hosts/${hostInput.name}`;
|
|
3396
4346
|
const removed = findRemovedForms(hostInput);
|
|
3397
4347
|
if (removed.length > 0) throw new RunnerError(`${compoundFile}: removed form:\n${removed.map((r) => ` - ${r.path}: ${r.message}`).join("\n")}`);
|
|
3398
4348
|
const parsed = declaredGenericCompoundHostSchema.safeParse(hostInput);
|
|
@@ -3402,7 +4352,6 @@ async function runCompound(hostInput, ctx, options) {
|
|
|
3402
4352
|
const wiring = host.config ?? {};
|
|
3403
4353
|
const verb = ctx.verb;
|
|
3404
4354
|
const oneShotCompound = ONE_SHOT_VERBS.has(verb);
|
|
3405
|
-
const keepsRecord = wiring.runtimeRecord !== false && !oneShotCompound;
|
|
3406
4355
|
let stopRequested = false;
|
|
3407
4356
|
let stopFromStream = () => {
|
|
3408
4357
|
stopRequested = true;
|
|
@@ -3412,52 +4361,115 @@ async function runCompound(hostInput, ctx, options) {
|
|
|
3412
4361
|
const outputs = options.supervisedOutputs ?? [process.stdout, process.stderr];
|
|
3413
4362
|
for (const output of outputs) output.on("error", () => void 0);
|
|
3414
4363
|
}
|
|
3415
|
-
const
|
|
3416
|
-
|
|
3417
|
-
|
|
3418
|
-
const
|
|
3419
|
-
|
|
3420
|
-
|
|
3421
|
-
|
|
3422
|
-
|
|
3423
|
-
|
|
3424
|
-
|
|
3425
|
-
|
|
3426
|
-
|
|
3427
|
-
|
|
4364
|
+
const recordKey = runRecordKey(host.name, scope?.name);
|
|
4365
|
+
const probe = oneShotCompound ? void 0 : probeRun(projectRoot, recordKey, options.projectName);
|
|
4366
|
+
const live = probe?.status === "live" ? probe.record : void 0;
|
|
4367
|
+
const running = live ? /* @__PURE__ */ new Error(`${recordKey} is already running for this project (pid ${live.pid}). Stop it before starting another.`) : void 0;
|
|
4368
|
+
if (running && (ctx.argv ?? []).length === 0) throw running;
|
|
4369
|
+
if (probe?.status === "foreign") throw new Error(`.ph/run/${recordKey}.json describes a live "${probe.record.projectName}", but this project is "${options.projectName}". Refusing to start a second instance.`);
|
|
4370
|
+
let prepared;
|
|
4371
|
+
let order;
|
|
4372
|
+
let foreground;
|
|
4373
|
+
let memberArgv;
|
|
4374
|
+
const byKey = /* @__PURE__ */ new Map();
|
|
4375
|
+
try {
|
|
4376
|
+
prepared = await prepareMembers(projectRoot, host.children, scope);
|
|
4377
|
+
const cycle = await memberCycle(projectRoot, prepared);
|
|
4378
|
+
if (cycle) throw new RunnerError(`${compoundFile}: compound member cycle: ${cycle.join(" -> ")}.`, "A compound cannot run itself, directly or through another compound.");
|
|
4379
|
+
const plan = planCompound(prepared.map((m) => ({
|
|
4380
|
+
key: m.key,
|
|
4381
|
+
host: m.member.host,
|
|
4382
|
+
refs: outputSitesOf(m.draft).map(({ ref, path }) => ({
|
|
4383
|
+
ref,
|
|
4384
|
+
path
|
|
4385
|
+
}))
|
|
4386
|
+
})), wiring.startOrder);
|
|
4387
|
+
for (const m of prepared) byKey.set(m.key, m);
|
|
4388
|
+
const declared = prepared.map((m) => ({
|
|
4389
|
+
key: m.key,
|
|
4390
|
+
host: m.member.host
|
|
4391
|
+
}));
|
|
4392
|
+
for (const m of prepared) validateDeclaredHost(m.runner, m.specifier, m.draft, m.file, { outputsSchemaOf: (ref) => {
|
|
4393
|
+
const target = memberForRef(ref, declared);
|
|
4394
|
+
if ("error" in target) return { error: target.error };
|
|
4395
|
+
const producer = byKey.get(target.key);
|
|
4396
|
+
return producer ? runnerOutputsSchema(producer.runner, producer.specifier, `member "${target.key}"`) : { error: `names member "${target.key}", which was not prepared.` };
|
|
4397
|
+
} });
|
|
4398
|
+
const planned = planForeground(prepared, plan, wiring);
|
|
4399
|
+
const broken = planned.issues.at(0);
|
|
4400
|
+
if (broken) throw new RunnerError(`${compoundFile}: ${broken.message}`, broken.hint);
|
|
4401
|
+
foreground = planned.foreground;
|
|
4402
|
+
order = planned.order;
|
|
4403
|
+
if (oneShotCompound) {
|
|
4404
|
+
const [first] = scope ? [{
|
|
4405
|
+
ref: recordKey,
|
|
4406
|
+
hostPackage: scope,
|
|
4407
|
+
where: compoundFile
|
|
4408
|
+
}] : prepared.flatMap((m) => m.hostPackage && m.key !== foreground ? [{
|
|
4409
|
+
ref: m.ref,
|
|
4410
|
+
hostPackage: m.hostPackage,
|
|
4411
|
+
where: `${compoundFile} (member "${m.key}")`
|
|
4412
|
+
}] : []);
|
|
4413
|
+
if (first) {
|
|
4414
|
+
const refusal = packageBuildRefusal(first.ref, first.hostPackage, verb);
|
|
4415
|
+
throw new RunnerError(`${first.where}: ${refusal.message}`, refusal.hint);
|
|
4416
|
+
}
|
|
4417
|
+
}
|
|
4418
|
+
memberArgv = splitCompoundArgv(ctx.argv ?? [], hostInput.name, prepared.map((m) => ({
|
|
4419
|
+
key: m.key,
|
|
4420
|
+
runner: m.specifier,
|
|
4421
|
+
schema: m.runner.argsSchema
|
|
4422
|
+
})), foreground);
|
|
4423
|
+
} catch (error) {
|
|
4424
|
+
throw running ?? error;
|
|
4425
|
+
}
|
|
4426
|
+
const beside = running !== void 0;
|
|
4427
|
+
if (running && (foreground === void 0 || (memberArgv.get(foreground) ?? []).length === 0)) throw running;
|
|
4428
|
+
const keepsRecord = wiring.runtimeRecord !== false && !oneShotCompound && !beside;
|
|
3428
4429
|
const members = prepared.map((m) => ({
|
|
3429
4430
|
key: m.key,
|
|
3430
4431
|
host: m.member.host
|
|
3431
4432
|
}));
|
|
3432
|
-
for (const m of prepared) validateDeclaredHost(m.runner, m.specifier, m.draft, m.file, { outputsSchemaOf: (ref) => {
|
|
3433
|
-
const target = memberForRef(ref, members);
|
|
3434
|
-
if ("error" in target) return { error: target.error };
|
|
3435
|
-
const producer = byKey.get(target.key);
|
|
3436
|
-
return producer ? runnerOutputsSchema(producer.runner, producer.specifier, `member "${target.key}"`) : { error: `names member "${target.key}", which was not prepared.` };
|
|
3437
|
-
} });
|
|
3438
|
-
const memberArgv = splitCompoundArgv(ctx.argv ?? [], hostInput.name, prepared.map((m) => ({
|
|
3439
|
-
key: m.key,
|
|
3440
|
-
runner: m.specifier,
|
|
3441
|
-
schema: m.runner.argsSchema
|
|
3442
|
-
})));
|
|
3443
4433
|
if (wiring.cspRegistrySync && !prepared.some(takesCspRegistrySync)) console.warn(`${compoundFile}: config.cspRegistrySync is set, but no member's runner declares runner.cspRegistrySync (members run: ${prepared.map((m) => m.specifier).join(", ")}); the baked Connect CSP is not patched for the runtime registry.`);
|
|
3444
4434
|
const started = [];
|
|
3445
4435
|
const liveOutputs = /* @__PURE__ */ new Map();
|
|
4436
|
+
for (const [key, member] of Object.entries(live?.members ?? {})) liveOutputs.set(key, member.outputs);
|
|
3446
4437
|
const outputs = compoundOutputSource(members, liveOutputs, host.name, new Map(prepared.map((m) => [m.key, m.runner.outputsSchema])));
|
|
3447
|
-
const
|
|
4438
|
+
const resolveEnvOf = (m) => processResolveEnv(projectRoot, ctx.env, m.hostPackage);
|
|
4439
|
+
const statuses = /* @__PURE__ */ new Map();
|
|
4440
|
+
const othersSeen = () => [...statuses.values()].filter((status) => status.name !== foreground).map((status) => ({
|
|
4441
|
+
...status,
|
|
4442
|
+
endpoints: { ...status.endpoints }
|
|
4443
|
+
}));
|
|
3448
4444
|
let stopping;
|
|
3449
4445
|
const shutdown = () => stopping ??= (async () => {
|
|
3450
|
-
for (const m of [...started].reverse())
|
|
3451
|
-
|
|
3452
|
-
|
|
3453
|
-
|
|
4446
|
+
for (const m of [...started].reverse()) {
|
|
4447
|
+
const status = statuses.get(m.name);
|
|
4448
|
+
if (status?.status === "starting" || status?.status === "ready") status.status = "stopping";
|
|
4449
|
+
try {
|
|
4450
|
+
await m.handle.shutdown?.();
|
|
4451
|
+
} catch {}
|
|
4452
|
+
if (status?.status === "stopping") status.status = "stopped";
|
|
4453
|
+
}
|
|
4454
|
+
if (keepsRecord) clearRunRecord(projectRoot, recordKey);
|
|
3454
4455
|
})();
|
|
4456
|
+
const death = {};
|
|
3455
4457
|
try {
|
|
3456
|
-
for (const name of
|
|
4458
|
+
for (const name of order) {
|
|
4459
|
+
if (death.message) throw new Error(death.message);
|
|
3457
4460
|
const m = byKey.get(name);
|
|
3458
4461
|
if (!m) continue;
|
|
3459
|
-
const
|
|
4462
|
+
const isForeground = name === foreground;
|
|
4463
|
+
if (beside && !isForeground) continue;
|
|
4464
|
+
if (isForeground && oneShotCompound) continue;
|
|
4465
|
+
const memberVerb = isForeground ? m.draft.runner.defaultVerb ?? "run" : memberVerbOf(verb, m.draft.runner);
|
|
3460
4466
|
const oneShot = ONE_SHOT_VERBS.has(memberVerb);
|
|
4467
|
+
const memberProcess = memberProcessOf(m.member, {
|
|
4468
|
+
foreground: isForeground,
|
|
4469
|
+
besideForeground: foreground !== void 0,
|
|
4470
|
+
oneShot
|
|
4471
|
+
});
|
|
4472
|
+
const resolveEnv = resolveEnvOf(m);
|
|
3461
4473
|
const resolved = oneShot ? substituteBuiltinEnv(m.draft, resolveEnv.builtins ?? {}) : resolveHostOutputs(m.draft, {
|
|
3462
4474
|
outputs,
|
|
3463
4475
|
...resolveEnv,
|
|
@@ -3471,19 +4483,61 @@ async function runCompound(hostInput, ctx, options) {
|
|
|
3471
4483
|
const fn = getVerb(m.runner, m.specifier, memberVerb);
|
|
3472
4484
|
const where = `${name} (${m.specifier} ${memberVerb})`;
|
|
3473
4485
|
const argv = memberArgv.get(name) ?? [];
|
|
3474
|
-
const
|
|
3475
|
-
|
|
3476
|
-
|
|
3477
|
-
|
|
3478
|
-
|
|
3479
|
-
|
|
3480
|
-
|
|
3481
|
-
|
|
3482
|
-
|
|
3483
|
-
|
|
4486
|
+
const status = {
|
|
4487
|
+
name,
|
|
4488
|
+
host: m.ref,
|
|
4489
|
+
process: memberProcess,
|
|
4490
|
+
status: "starting",
|
|
4491
|
+
endpoints: {}
|
|
4492
|
+
};
|
|
4493
|
+
statuses.set(name, status);
|
|
4494
|
+
let handle;
|
|
4495
|
+
if (memberProcess === "own") {
|
|
4496
|
+
const own = await startOwnProcess({
|
|
4497
|
+
projectRoot,
|
|
4498
|
+
compound: host.name,
|
|
4499
|
+
member: name,
|
|
4500
|
+
folder: m.ref,
|
|
4501
|
+
verb: memberVerb,
|
|
4502
|
+
argv,
|
|
4503
|
+
env: ctx.env,
|
|
4504
|
+
host: resolved,
|
|
4505
|
+
echo: foreground === void 0,
|
|
4506
|
+
...scope ? { logPackage: scope.name } : {}
|
|
4507
|
+
});
|
|
4508
|
+
handle = own.handle;
|
|
4509
|
+
status.pid = own.pid;
|
|
4510
|
+
status.logFile = own.logFile;
|
|
4511
|
+
own.exited.then((exit) => {
|
|
4512
|
+
if (status.status !== "starting" && status.status !== "ready") return;
|
|
4513
|
+
status.status = exit.code === 0 ? "stopped" : "failed";
|
|
4514
|
+
const how = exit.signal !== null ? `signal ${exit.signal}` : `code ${exit.code}`;
|
|
4515
|
+
status.error = `exited (${how}) while the stack runs; its log: ${own.logFile}`;
|
|
4516
|
+
death.message ??= `${compoundFile}: member "${name}" ${status.error}`;
|
|
4517
|
+
death.ends?.();
|
|
4518
|
+
});
|
|
4519
|
+
} else {
|
|
4520
|
+
handle = toStartedHandle(await fn(oneShot ? emptyMaps(validated, resolved) : validated, {
|
|
4521
|
+
projectRoot,
|
|
4522
|
+
...m.hostPackage ? { hostPackage: m.hostPackage } : {},
|
|
4523
|
+
env: ctx.env,
|
|
4524
|
+
verb: memberVerb,
|
|
4525
|
+
parent: {
|
|
4526
|
+
host: host.name,
|
|
4527
|
+
verb
|
|
4528
|
+
},
|
|
4529
|
+
...argv.length > 0 ? { argv } : {},
|
|
4530
|
+
...isForeground ? { foreground: {
|
|
4531
|
+
members: othersSeen,
|
|
4532
|
+
beside
|
|
4533
|
+
} } : {}
|
|
4534
|
+
}), where);
|
|
4535
|
+
status.pid = process.pid;
|
|
4536
|
+
}
|
|
3484
4537
|
started.push({
|
|
3485
4538
|
name,
|
|
3486
4539
|
member: m.member,
|
|
4540
|
+
ref: m.ref,
|
|
3487
4541
|
specifier: m.specifier,
|
|
3488
4542
|
kind: m.runner.kind,
|
|
3489
4543
|
verb: memberVerb,
|
|
@@ -3500,7 +4554,10 @@ async function runCompound(hostInput, ctx, options) {
|
|
|
3500
4554
|
}
|
|
3501
4555
|
started[started.length - 1].outputs = memberOutputs;
|
|
3502
4556
|
liveOutputs.set(name, memberOutputs);
|
|
4557
|
+
if (status.status === "starting") status.status = "ready";
|
|
4558
|
+
status.endpoints = urlEndpoints(memberOutputs);
|
|
3503
4559
|
}
|
|
4560
|
+
if (death.message) throw new Error(death.message);
|
|
3504
4561
|
} catch (error) {
|
|
3505
4562
|
await shutdown();
|
|
3506
4563
|
throw error;
|
|
@@ -3508,7 +4565,7 @@ async function runCompound(hostInput, ctx, options) {
|
|
|
3508
4565
|
if (keepsRecord) {
|
|
3509
4566
|
const recordMembers = {};
|
|
3510
4567
|
for (const m of started) recordMembers[m.name] = {
|
|
3511
|
-
host: m.
|
|
4568
|
+
host: m.ref,
|
|
3512
4569
|
runnerModule: m.specifier,
|
|
3513
4570
|
kind: m.kind,
|
|
3514
4571
|
verb: m.verb,
|
|
@@ -3517,6 +4574,7 @@ async function runCompound(hostInput, ctx, options) {
|
|
|
3517
4574
|
writeRunRecord(projectRoot, {
|
|
3518
4575
|
version: 2,
|
|
3519
4576
|
host: host.name,
|
|
4577
|
+
...scope ? { package: scope.name } : {},
|
|
3520
4578
|
projectName: options.projectName,
|
|
3521
4579
|
kind: "compound",
|
|
3522
4580
|
verb,
|
|
@@ -3527,16 +4585,15 @@ async function runCompound(hostInput, ctx, options) {
|
|
|
3527
4585
|
});
|
|
3528
4586
|
}
|
|
3529
4587
|
const exit = options.exit ?? ((code) => process.exit(code));
|
|
3530
|
-
let
|
|
3531
|
-
const
|
|
3532
|
-
|
|
3533
|
-
|
|
3534
|
-
|
|
3535
|
-
|
|
3536
|
-
};
|
|
4588
|
+
let ending;
|
|
4589
|
+
const end = (code, afterStop) => ending ??= shutdown().finally(() => {
|
|
4590
|
+
afterStop?.();
|
|
4591
|
+
exit(code);
|
|
4592
|
+
});
|
|
4593
|
+
const handleSignal = (signal) => end(signal === "SIGINT" ? 130 : 143);
|
|
3537
4594
|
if (options.installSignalHandlers !== false) {
|
|
3538
4595
|
process.on("exit", () => {
|
|
3539
|
-
if (keepsRecord) clearRunRecord(projectRoot,
|
|
4596
|
+
if (keepsRecord) clearRunRecord(projectRoot, recordKey);
|
|
3540
4597
|
});
|
|
3541
4598
|
process.on("SIGINT", () => void handleSignal("SIGINT"));
|
|
3542
4599
|
process.on("SIGTERM", () => void handleSignal("SIGTERM"));
|
|
@@ -3547,32 +4604,104 @@ async function runCompound(hostInput, ctx, options) {
|
|
|
3547
4604
|
handleSignal("SIGTERM");
|
|
3548
4605
|
};
|
|
3549
4606
|
if (stopRequested) stopFromStream();
|
|
4607
|
+
death.ends = () => void end(1, () => console.error(death.message));
|
|
4608
|
+
if (death.message) death.ends();
|
|
4609
|
+
const exited = started.find((m) => m.name === foreground)?.handle.exited;
|
|
4610
|
+
if (exited) Promise.resolve(exited).then((code) => void end(typeof code === "number" ? code : 0), () => void end(1));
|
|
3550
4611
|
return {
|
|
3551
4612
|
started,
|
|
3552
4613
|
shutdown,
|
|
3553
4614
|
handleSignal
|
|
3554
4615
|
};
|
|
3555
4616
|
}
|
|
4617
|
+
/**
|
|
4618
|
+
* An own-process member: `ph run <folder> <verb> -- <argv>` as an attached,
|
|
4619
|
+
* hidden child (spawnHost) with the compound's env, its resolved host and a
|
|
4620
|
+
* stdin it stops on; its output in this run's log file. Resolves once its
|
|
4621
|
+
* run record is written, which its `ph run` does after `ready`.
|
|
4622
|
+
*/
|
|
4623
|
+
async function startOwnProcess(start) {
|
|
4624
|
+
const logFile = memberLogFile(start.projectRoot, start.env, start.member, start.logPackage);
|
|
4625
|
+
const spawned = await spawnHost({
|
|
4626
|
+
projectRoot: start.projectRoot,
|
|
4627
|
+
host: start.folder,
|
|
4628
|
+
dataDir: defaultUserDataDir(start.projectRoot, start.env),
|
|
4629
|
+
verb: start.verb,
|
|
4630
|
+
argv: start.argv,
|
|
4631
|
+
baseEnv: start.env,
|
|
4632
|
+
definition: {
|
|
4633
|
+
compound: start.compound,
|
|
4634
|
+
member: start.member,
|
|
4635
|
+
host: start.host
|
|
4636
|
+
},
|
|
4637
|
+
stopOnStdin: true,
|
|
4638
|
+
logFile,
|
|
4639
|
+
readyTimeoutMs: MEMBER_READY_TIMEOUT_MS,
|
|
4640
|
+
...start.echo ? { onOutput: (stream, chunk) => {
|
|
4641
|
+
process[stream].write(chunk);
|
|
4642
|
+
} } : {}
|
|
4643
|
+
});
|
|
4644
|
+
return {
|
|
4645
|
+
handle: {
|
|
4646
|
+
outputs: spawned.outputs ?? {},
|
|
4647
|
+
shutdown: () => spawned.stop()
|
|
4648
|
+
},
|
|
4649
|
+
pid: spawned.pid,
|
|
4650
|
+
logFile,
|
|
4651
|
+
exited: spawned.exited
|
|
4652
|
+
};
|
|
4653
|
+
}
|
|
3556
4654
|
/** Load every member's draft and runner, in declaration order. */
|
|
3557
|
-
async function prepareMembers(projectRoot, children) {
|
|
4655
|
+
async function prepareMembers(projectRoot, children, scope) {
|
|
3558
4656
|
const out = [];
|
|
3559
|
-
for (const [key, member] of Object.entries(children)) out.push(await prepareMember(projectRoot, key, member));
|
|
4657
|
+
for (const [key, member] of Object.entries(children)) out.push(await prepareMember(projectRoot, key, member, scope));
|
|
3560
4658
|
return out;
|
|
3561
4659
|
}
|
|
3562
|
-
/** One member's draft and runner.
|
|
3563
|
-
|
|
3564
|
-
|
|
4660
|
+
/** One member's draft and runner. `scope`: the package whose compound names
|
|
4661
|
+
* the member, where a bare member host is looked up first; the runner
|
|
4662
|
+
* resolves from the package that supplies the member's host. */
|
|
4663
|
+
async function prepareMember(projectRoot, key, member, scope) {
|
|
4664
|
+
const loaded = await loadHost(projectRoot, member.host, { scope });
|
|
4665
|
+
const draft = applyChildWrapper(loaded.host, member);
|
|
3565
4666
|
const specifier = draft.runner.module;
|
|
3566
4667
|
return {
|
|
3567
4668
|
key,
|
|
3568
4669
|
member,
|
|
3569
4670
|
draft,
|
|
3570
4671
|
specifier,
|
|
3571
|
-
runner: await resolveRunnerModule(projectRoot, specifier),
|
|
3572
|
-
file:
|
|
4672
|
+
runner: await resolveRunnerModule(moduleRootOf(projectRoot, loaded), specifier),
|
|
4673
|
+
file: hostFileLabel(loaded.name, loaded.package),
|
|
4674
|
+
ref: loaded.ref ?? member.host,
|
|
4675
|
+
...loaded.package ? { hostPackage: loaded.package } : {}
|
|
4676
|
+
};
|
|
4677
|
+
}
|
|
4678
|
+
/**
|
|
4679
|
+
* A compound that is, through its compound members, a member of itself
|
|
4680
|
+
* would start itself without end: the chain of hosts, as the project
|
|
4681
|
+
* addresses them, when there is one. Each compound member's own members are
|
|
4682
|
+
* looked up as it looks them up (its package first, for a package's). A
|
|
4683
|
+
* reactor member ends a chain.
|
|
4684
|
+
*/
|
|
4685
|
+
async function memberCycle(projectRoot, prepared) {
|
|
4686
|
+
const walk = async (chain, children, scope) => {
|
|
4687
|
+
for (const member of Object.values(children)) {
|
|
4688
|
+
const loaded = await loadHost(projectRoot, member.host, { scope });
|
|
4689
|
+
const ref = loaded.ref ?? member.host;
|
|
4690
|
+
if (chain.includes(ref)) return [...chain, ref];
|
|
4691
|
+
const nested = loaded.host.children;
|
|
4692
|
+
if (!isPlainObject(nested)) continue;
|
|
4693
|
+
const found = await walk([...chain, ref], nested, loaded.package);
|
|
4694
|
+
if (found) return found;
|
|
4695
|
+
}
|
|
3573
4696
|
};
|
|
4697
|
+
for (const m of prepared) {
|
|
4698
|
+
const nested = m.draft.children;
|
|
4699
|
+
if (!isPlainObject(nested)) continue;
|
|
4700
|
+
const found = await walk([m.ref], nested, m.hostPackage);
|
|
4701
|
+
if (found) return found;
|
|
4702
|
+
}
|
|
3574
4703
|
}
|
|
3575
4704
|
//#endregion
|
|
3576
|
-
export {
|
|
4705
|
+
export { computeOutputsHash as $, runProvideHook as $n, resolveHostPlugins as $t, STOP_RUN_TIMEOUT_MS as A, placementKeyIssues as An, resolveHostOutputs as At, probeRun as B, runnerKindSchema as Bn, checkTokenSites as Bt, applyChildWrapper as C, emitHostJsonSchema as Cn, packageBuildRefusal as Ct, COMPOUND_MEMBER_ENV as D, makeHostSchemas as Dn, TokenResolutionError as Dt, spawnHost as E, hostNameSchema as En, validateHost as Et, stopChannelPath as F, reactorProtocolSchema as Fn, BUILTIN_ENV_NAMES as Ft, writeRunRecord as G, normalizePluginEntries as Gn, schemaAtPath as Gt, readRunRecord as H, entryActiveForVerb as Hn, outputRefsOf as Ht, stopRun as I, reactorSchema as In, isBuiltinEnvName as It, checkRunnerArgv as J, pluginEntrySchema as Jn, formatPath as Jt, runRecordMemberSchema as K, normalizePluginEntry as Kn, collectTokenSites as Kt, clearRunRecord as L, refineConnectReactor as Ln, substituteBuiltinEnv as Lt, installStopChannel as M, reactorBackendKindSchema as Mn, PlanError as Mt, listenForStop as N, reactorBackendSchema as Nn, memberForRef as Nt, takeCompoundMember as O, memberProcessSchema as On, describeMapElements as Ot, requestStop as P, reactorHostSchema as Pn, planCompound as Pt, OUTPUTS_FILE as Q, runObserveHookSequential as Qn, findDeadConnectConfig as Qt, isPidAlive as R, refineStartOrder as Rn, findRemovedForms as Rt, resolveUserDataPlaceholders as S, defineHostSchemas as Sn, tokenable as Sr, listVerbs as St, SpawnHostError as T, genericCompoundHostSchema as Tn, validateDeclaredHost as Tt, recordKeyOf as U, hostTypeSatisfies as Un, outputSitesOf as Ut, readProjectName as V, PluginError as Vn, envSitesOf as Vt, runRecordKey as W, mergeContributions as Wn, refKey as Wt, splitCompoundArgv as X, resolveOrder as Xn, renderTokens as Xt, isRunnerArgsSchema as Y, registerHostType as Yn, isPlainObject as Yt, splitRunArgv as Z, runObserveHook as Zn, unwrapEscapes as Zt, processResolveEnv as _, compoundHostSchema as _n, mapTokenSchema as _r, getVerb as _t, memberProcessOf as a, locateHost as an, drivesSchema as ar, loadHost as at, runnerOutputsSchema as b, declaredGenericCompoundHostSchema as bn, tokenKeyOf as br, kindShapeIssues as bt, prepareMember as c, CONNECT_PRIMARY_MESSAGE as cn, TOKEN_KEYS as cr, probeHostsFolder as ct, takesCspRegistrySync as d, HOST_NAME_PATTERN as dn, envTokenable as dr, stripComments as dt, resolvePluginContributions as en, runTransformHook as er, describeHostOutputs as et, runnerHandleSchema as f, HOST_REF_MESSAGE as fn, findToken as fr, withoutHostsMessage as ft, loadProducers as g, childrenSchema as gn, keyTokenSchema as gr, STORE_VERBS as gt, OUTPUT_DATA_DIRS_ENV as h, childWrapperSchema as hn, itemTokenSchema as hr, RunnerError as ht, memberCycle as i, hostFileLabel as in, driveDeclarationSchema as ir, lintOutputsFile as it, askToStop as j, profileSchema as jn, unsetEnvMessage as jt, STOP_ON_STDIN_ENV as k, originOrUrlSchema as kn, emptyMaps as kt, runCompound as l, HOST_NAME_MAX_LENGTH as ln, concatTokenSchema as lr, readOutputsFileHash as lt, compoundOutputSource as m, PACKAGE_NAME_PATTERN as mn, isToken as mr, ONE_SHOT_VERBS as mt, compoundStartVerb as n, findHostPackage as nn, defaultConnectComposition as nr, lintHostImportGraph as nt, memberVerbOf as o, parseHostRef as on, projectDriveIdWith as or, loadHostFresh as ot, toStartedHandle as p, HOST_REF_PATTERN as pn, forbidRef as pr, CONNECT_RUNNER as pt, runRecordSchema as q, pluginEntryObjectSchema as qn, describeToken as qt, holdStopRequests as r, formatHostRef as rn, buildDriveDeclarationSchema as rr, lintHostImports as rt, planForeground as s, resolvePackageRoot as sn, TOKEN_ESCAPE_KEY as sr, moduleRootOf as st, STOP_STREAM_LIMIT_MS as t, HostLoadError as tn, CONNECT_PLUGIN_OWNED_SLICES as tr, findNonStaticValue as tt, stopStreamOf as u, HOST_NAME_MESSAGE as un, envTokenSchema as ur, scanHostImports as ut, producerOutputsSchemas as v, compoundWiringSchema as vn, outputTokenSchema as vr, hostSchemaIssues as vt, SPAWN_STOPPING_NOTE as w, emittedHostSchemas as wn, resolveRunnerModule as wt, defaultUserDataDir as x, declaredHostSchemas as xn, tokenSchema as xr, knownVerbIssues as xt, runRecordOutputSource as y, connectReactorIssues as yn, ref as yr, isSchemaLike as yt, listRunRecords as z, runnerBaseSchema as zn, checkOutputPaths as zt };
|
|
3577
4706
|
|
|
3578
|
-
//# sourceMappingURL=compound-
|
|
4707
|
+
//# sourceMappingURL=compound-n-bO0qKh.mjs.map
|