@powerhousedao/host-core 6.2.3-dev.55
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/LICENSE +661 -0
- package/dist/compound-9--OujO-.d.mts +155 -0
- package/dist/compound-9--OujO-.d.mts.map +1 -0
- package/dist/host-schemas-B0-Vk8vP.mjs +512 -0
- package/dist/host-schemas-B0-Vk8vP.mjs.map +1 -0
- package/dist/index.d.mts +431 -0
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +142 -0
- package/dist/index.mjs.map +1 -0
- package/dist/runners/compound.d.mts +95 -0
- package/dist/runners/compound.d.mts.map +1 -0
- package/dist/runners/compound.mjs +47 -0
- package/dist/runners/compound.mjs.map +1 -0
- package/package.json +49 -0
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
//#region src/host-loader.d.ts
|
|
2
|
+
declare class HostLoadError extends Error {
|
|
3
|
+
constructor(message: string, hint?: string);
|
|
4
|
+
}
|
|
5
|
+
type HostsFolderStatus = {
|
|
6
|
+
kind: "absent";
|
|
7
|
+
} | {
|
|
8
|
+
kind: "empty";
|
|
9
|
+
dir: string;
|
|
10
|
+
} | {
|
|
11
|
+
kind: "present";
|
|
12
|
+
dir: string;
|
|
13
|
+
hosts: string[];
|
|
14
|
+
};
|
|
15
|
+
/** A `hosts/` folder with no `<name>/host.js` inside is "empty" — the guard
|
|
16
|
+
* state: callers warn loudly and fall back to legacy rather than activating
|
|
17
|
+
* the new architecture off a stray `mkdir hosts`. */
|
|
18
|
+
declare function probeHostsFolder(projectRoot: string): HostsFolderStatus;
|
|
19
|
+
/** Rejects every import except the project's powerhouse.config.json, plus any
|
|
20
|
+
* dynamic `import(...)` or `require(...)`. Source-level enforcement: the JSON
|
|
21
|
+
* round trip below is the hard gate; this one produces the better error. */
|
|
22
|
+
declare function lintHostImports(source: string, file: string): void;
|
|
23
|
+
/** Returns the path of the first value that would not survive a JSON round
|
|
24
|
+
* trip, or undefined when the object is fully static. */
|
|
25
|
+
declare function findNonStaticValue(value: unknown, trail?: string): string | undefined;
|
|
26
|
+
interface HostDefinition {
|
|
27
|
+
name: string;
|
|
28
|
+
runner: {
|
|
29
|
+
module: string;
|
|
30
|
+
} & Record<string, unknown>;
|
|
31
|
+
config?: Record<string, unknown>;
|
|
32
|
+
profile?: Record<string, unknown>;
|
|
33
|
+
reactor?: Record<string, unknown>;
|
|
34
|
+
children?: Record<string, unknown>;
|
|
35
|
+
}
|
|
36
|
+
interface LoadedHost {
|
|
37
|
+
name: string;
|
|
38
|
+
dir: string;
|
|
39
|
+
file: string;
|
|
40
|
+
host: HostDefinition;
|
|
41
|
+
}
|
|
42
|
+
declare function loadHost(projectRoot: string, hostName: string): Promise<LoadedHost>;
|
|
43
|
+
//#endregion
|
|
44
|
+
//#region src/runner-resolver.d.ts
|
|
45
|
+
/**
|
|
46
|
+
* Resolves a host's `runner.module` specifier from the PROJECT's dependency
|
|
47
|
+
* tree (not ph-cli's), imports it, and checks the runner-module contract:
|
|
48
|
+
* `{ run, hostSchema, kind, ...optionalVerbs }`. Phase-0 home is ph-cli; the
|
|
49
|
+
* uniform-runners plan moves this into @powerhousedao/host-core with the
|
|
50
|
+
* generic compound (phase 1).
|
|
51
|
+
*/
|
|
52
|
+
declare class RunnerError extends Error {
|
|
53
|
+
constructor(message: string, hint?: string);
|
|
54
|
+
}
|
|
55
|
+
interface RunnerContext {
|
|
56
|
+
projectRoot: string;
|
|
57
|
+
verb: string;
|
|
58
|
+
env: Record<string, string | undefined>;
|
|
59
|
+
}
|
|
60
|
+
type RunnerVerb = (host: HostDefinition, ctx: RunnerContext) => Promise<unknown>;
|
|
61
|
+
/** zod-shaped structurally, so this module needs no zod dependency. */
|
|
62
|
+
interface HostSchemaLike {
|
|
63
|
+
safeParse(host: unknown): {
|
|
64
|
+
success: boolean;
|
|
65
|
+
error?: {
|
|
66
|
+
issues?: {
|
|
67
|
+
path: (string | number)[];
|
|
68
|
+
message: string;
|
|
69
|
+
}[];
|
|
70
|
+
};
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
interface RunnerModule {
|
|
74
|
+
run: RunnerVerb;
|
|
75
|
+
hostSchema: HostSchemaLike;
|
|
76
|
+
kind: string;
|
|
77
|
+
[key: string]: unknown;
|
|
78
|
+
}
|
|
79
|
+
declare function resolveRunnerModule(projectRoot: string, specifier: string): Promise<RunnerModule>;
|
|
80
|
+
declare function listVerbs(runner: RunnerModule): string[];
|
|
81
|
+
declare function getVerb(runner: RunnerModule, specifier: string, verb: string): RunnerVerb;
|
|
82
|
+
declare function validateHost(runner: RunnerModule, specifier: string, host: HostDefinition, file: string): void;
|
|
83
|
+
//#endregion
|
|
84
|
+
//#region src/compound.d.ts
|
|
85
|
+
/**
|
|
86
|
+
* The generic compound runner: supervises the members a compound host
|
|
87
|
+
* declares, each started via its OWN declared runner at the compound's member
|
|
88
|
+
* verb. It projects a reactor member's created drives into a connect member's
|
|
89
|
+
* config, writes a .ph/run/<host>.json record, holds a per-project lock, and
|
|
90
|
+
* tears members down in reverse order on shutdown.
|
|
91
|
+
*
|
|
92
|
+
* Phase-1 model is ATTACHED and in-process: member runner verbs start their
|
|
93
|
+
* servers (which hold the event loop) and return a handle of facts; the
|
|
94
|
+
* compound stays alive as long as they do. Detached supervision is phase 5.
|
|
95
|
+
*/
|
|
96
|
+
/** Facts a member runner verb returns so the compound can project and tear
|
|
97
|
+
* down. All optional: a void-returning verb is treated as "started, no facts,
|
|
98
|
+
* self-sustaining" (the phase-0 bridges). */
|
|
99
|
+
interface RunnerHandle {
|
|
100
|
+
/** Port the member bound. */
|
|
101
|
+
port?: number;
|
|
102
|
+
/** Drive URLs a reactor member created, in display order — projected into a
|
|
103
|
+
* connect member's defaultDrives. */
|
|
104
|
+
driveUrls?: (string | null | undefined)[];
|
|
105
|
+
/** Named endpoints (graphql, mcp, …) for the run record / diagnostics. */
|
|
106
|
+
endpoints?: Record<string, string>;
|
|
107
|
+
/** Resolves when the member is serving; the compound awaits it before the
|
|
108
|
+
* next member when ordering requires readiness. */
|
|
109
|
+
ready?: Promise<void>;
|
|
110
|
+
/** Reverse-order teardown. */
|
|
111
|
+
shutdown?: () => void | Promise<void>;
|
|
112
|
+
}
|
|
113
|
+
interface CompoundMember {
|
|
114
|
+
host: string;
|
|
115
|
+
plugins?: string[];
|
|
116
|
+
runner?: {
|
|
117
|
+
port?: number;
|
|
118
|
+
} & Record<string, unknown>;
|
|
119
|
+
config?: Record<string, unknown>;
|
|
120
|
+
reactor?: Record<string, unknown>;
|
|
121
|
+
}
|
|
122
|
+
interface CompoundWiring {
|
|
123
|
+
/** Project the reactor member's created drives into the connect member. */
|
|
124
|
+
projectDrivesIntoConnect?: boolean;
|
|
125
|
+
/** --drives-public-base equivalent. */
|
|
126
|
+
drivesPublicBase?: string | null;
|
|
127
|
+
/** Member start order; defaults to declaration order. */
|
|
128
|
+
startOrder?: string[];
|
|
129
|
+
/** Write .ph/run/<host>.json (default true). */
|
|
130
|
+
runtimeRecord?: boolean;
|
|
131
|
+
/** Patch the baked CSP for the runtime registry on a served connect member
|
|
132
|
+
* (forwarded to the connect runner as a runner option). */
|
|
133
|
+
cspRegistrySync?: boolean;
|
|
134
|
+
}
|
|
135
|
+
interface StartedMember {
|
|
136
|
+
name: string;
|
|
137
|
+
handle: RunnerHandle;
|
|
138
|
+
}
|
|
139
|
+
interface RunCompoundOptions {
|
|
140
|
+
/** Project identity for the lock (defaults read from package.json by the CLI). */
|
|
141
|
+
projectName: string;
|
|
142
|
+
/** Extra record fields (e.g. mcpUrl). */
|
|
143
|
+
recordExtra?: Record<string, unknown>;
|
|
144
|
+
/** Registers signal handlers for teardown (default true; tests pass false). */
|
|
145
|
+
installSignalHandlers?: boolean;
|
|
146
|
+
}
|
|
147
|
+
interface RunCompoundResult {
|
|
148
|
+
started: StartedMember[];
|
|
149
|
+
shutdown: () => Promise<void>;
|
|
150
|
+
}
|
|
151
|
+
declare function runCompound(host: HostDefinition, ctx: RunnerContext, options: RunCompoundOptions): Promise<RunCompoundResult>;
|
|
152
|
+
//#endregion
|
|
153
|
+
export { probeHostsFolder as C, loadHost as S, HostLoadError as _, RunnerHandle as a, findNonStaticValue as b, RunnerContext as c, RunnerVerb as d, getVerb as f, HostDefinition as g, validateHost as h, RunCompoundResult as i, RunnerError as l, resolveRunnerModule as m, CompoundWiring as n, runCompound as o, listVerbs as p, RunCompoundOptions as r, HostSchemaLike as s, CompoundMember as t, RunnerModule as u, HostsFolderStatus as v, lintHostImports as x, LoadedHost as y };
|
|
154
|
+
export {};
|
|
155
|
+
//# sourceMappingURL=compound-9--OujO-.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"compound-9--OujO-.d.mts","names":[],"sources":["../src/host-loader.ts","../src/runner-resolver.ts","../src/compound.ts"],"mappings":";cAuBa,sBAAsB;EACjC,YAAY,iBAAiB;;KAMnB;EACN;;EACA;EAAe;;EACf;EAAiB;EAAa;;;;;iBAKpB,iBAAiB,sBAAsB;;;;iBAqBvC,gBAAgB,gBAAgB;;;iBA0BhC,mBACd,gBACA;UA4Be;EACf;EACA;IAAU;MAAmB;EAC7B,SAAS;EACT,UAAU;EACV,UAAU;EACV,WAAW;;UAGI;EACf;EACA;EACA;EACA,MAAM;;iBA2Bc,SACpB,qBACA,mBACC,QAAQ;;;;;;;;;;cCjJE,oBAAoB;EAC/B,YAAY,iBAAiB;;UAMd;EACf;EACA;EACA,KAAK;;KAGK,cACV,MAAM,gBACN,KAAK,kBACF;;UAGY;EACf,UAAU;IACR;IACA;MAAU;QAAW;QAA2B;;;;;UAInC;EACf,KAAK;EACL,YAAY;EACZ;GACC;;iBAMmB,oBACpB,qBACA,oBACC,QAAQ;iBAsCK,UAAU,QAAQ;iBAUlB,QACd,QAAQ,cACR,mBACA,eACC;iBAYa,aACd,QAAQ,cACR,mBACA,MAAM,gBACN;;;;;;;;;;;;;;;;;UCrFe;;EAEf;;;EAGA;;EAEA,YAAY;;;EAGZ,QAAQ;;EAER,wBAAwB;;UAGT;EACf;EACA;EACA;IAAW;MAAkB;EAC7B,SAAS;EACT,UAAU;;UAGK;;EAEf;;EAEA;;EAEA;;EAEA;;;EAGA;;UAGQ;EACR;EACA,QAAQ;;UA+DO;;EAEf;;EAEA,cAAc;;EAEd;;UAGe;EACf,SAAS;EACT,gBAAgB;;iBAGI,YACpB,MAAM,gBACN,KAAK,eACL,SAAS,qBACR,QAAQ"}
|
|
@@ -0,0 +1,512 @@
|
|
|
1
|
+
import { createRequire } from "node:module";
|
|
2
|
+
import fs, { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { pathToFileURL } from "node:url";
|
|
5
|
+
import { z } from "zod";
|
|
6
|
+
//#region src/connect-projection.ts
|
|
7
|
+
/**
|
|
8
|
+
* Instance-fact projection for compound hosts: the drives a compound's
|
|
9
|
+
* reactor member created, projected into the Connect member's runtime-config
|
|
10
|
+
* override. Pure functions, moved from ph-cli's vetra service so the generic
|
|
11
|
+
* compound and the classic path share one implementation.
|
|
12
|
+
*/
|
|
13
|
+
function isLocalDrive(drive) {
|
|
14
|
+
return "local" in drive;
|
|
15
|
+
}
|
|
16
|
+
const driveKey = (drive) => isLocalDrive(drive) ? `local:${drive.id}` : drive.url;
|
|
17
|
+
/**
|
|
18
|
+
* Concatenate groups of `connect.drives.defaultDrives` in the order given,
|
|
19
|
+
* de-duplicating by drive identity (URL for remote entries, id for local
|
|
20
|
+
* ones). The first occurrence of a drive wins, so earlier groups keep their
|
|
21
|
+
* position and metadata — e.g. the Vetra drive `ph vetra` starts stays first
|
|
22
|
+
* even when the project's `powerhouse.config.json` lists the same drive.
|
|
23
|
+
*/
|
|
24
|
+
function mergeDefaultDrives(...groups) {
|
|
25
|
+
const seen = /* @__PURE__ */ new Set();
|
|
26
|
+
const out = [];
|
|
27
|
+
for (const group of groups) for (const drive of group) {
|
|
28
|
+
const key = driveKey(drive);
|
|
29
|
+
if (seen.has(key)) continue;
|
|
30
|
+
seen.add(key);
|
|
31
|
+
out.push(drive);
|
|
32
|
+
}
|
|
33
|
+
return out;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Rebase a local drive URL onto a public base: keeps the /d/<slug> path,
|
|
37
|
+
* swaps the loopback origin for the public base. Browser clients behind a
|
|
38
|
+
* reverse proxy can't reach http://localhost:<port>. Non-loopback URLs
|
|
39
|
+
* (e.g. a remote drive) are already public and pass through unchanged, as do
|
|
40
|
+
* unparseable ones.
|
|
41
|
+
*/
|
|
42
|
+
function rebaseDriveUrl(driveUrl, publicBase) {
|
|
43
|
+
let url;
|
|
44
|
+
try {
|
|
45
|
+
url = new URL(driveUrl);
|
|
46
|
+
} catch {
|
|
47
|
+
return driveUrl;
|
|
48
|
+
}
|
|
49
|
+
if (![
|
|
50
|
+
"localhost",
|
|
51
|
+
"127.0.0.1",
|
|
52
|
+
"[::1]"
|
|
53
|
+
].includes(url.hostname)) return driveUrl;
|
|
54
|
+
return `${publicBase.replace(/\/+$/, "")}${url.pathname}`;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* The compound's drives projection: created drives first (rebased onto the
|
|
58
|
+
* public base when given), then the project's configured drives, de-duplicated
|
|
59
|
+
* — and `preserve-all`, because compound-injected drive lists change per
|
|
60
|
+
* launch context and must never detach drives the user added by hand.
|
|
61
|
+
*/
|
|
62
|
+
function projectDrivesIntoConnect(input) {
|
|
63
|
+
return { drives: {
|
|
64
|
+
defaultDrives: mergeDefaultDrives(input.createdDriveUrls.filter((url) => typeof url === "string" && url.length > 0).map((url) => ({
|
|
65
|
+
url: input.publicBase ? rebaseDriveUrl(url, input.publicBase) : url,
|
|
66
|
+
name: null,
|
|
67
|
+
icon: null
|
|
68
|
+
})), input.configuredDefaultDrives ?? []),
|
|
69
|
+
preserveStrategy: "preserve-all"
|
|
70
|
+
} };
|
|
71
|
+
}
|
|
72
|
+
//#endregion
|
|
73
|
+
//#region src/host-loader.ts
|
|
74
|
+
/**
|
|
75
|
+
* Loads and pre-validates a `hosts/<name>/host.js` definition.
|
|
76
|
+
*
|
|
77
|
+
* A host file is a static PROJECTION of powerhouse.config.json: plain ESM,
|
|
78
|
+
* default-exporting a data object. Three gates run before any runner sees it:
|
|
79
|
+
* 1. import lint — the only legal import is the project's
|
|
80
|
+
* powerhouse.config.json (host files are data, not programs);
|
|
81
|
+
* 2. static check — the exported object must survive a JSON round trip
|
|
82
|
+
* (functions, undefined, class instances, Dates etc. are rejected,
|
|
83
|
+
* reporting the offending path);
|
|
84
|
+
* 3. shape pre-check — `name`, `runner.module`, and the reactor XOR children
|
|
85
|
+
* rule. Full validation is the runner's `hostSchema` (phase 2).
|
|
86
|
+
*
|
|
87
|
+
* This module never exits the process — callers own error presentation.
|
|
88
|
+
*/
|
|
89
|
+
const HOST_FILE = "host.js";
|
|
90
|
+
const CONFIG_IMPORT_SUFFIX = "powerhouse.config.json";
|
|
91
|
+
var HostLoadError = class extends Error {
|
|
92
|
+
constructor(message, hint) {
|
|
93
|
+
super(hint ? `${message}\n Hint: ${hint}` : message);
|
|
94
|
+
this.name = "HostLoadError";
|
|
95
|
+
}
|
|
96
|
+
};
|
|
97
|
+
/** A `hosts/` folder with no `<name>/host.js` inside is "empty" — the guard
|
|
98
|
+
* state: callers warn loudly and fall back to legacy rather than activating
|
|
99
|
+
* the new architecture off a stray `mkdir hosts`. */
|
|
100
|
+
function probeHostsFolder(projectRoot) {
|
|
101
|
+
const dir = path.join(projectRoot, "hosts");
|
|
102
|
+
if (!existsSync(dir) || !statSync(dir).isDirectory()) return { kind: "absent" };
|
|
103
|
+
const hosts = readdirSync(dir, { withFileTypes: true }).filter((entry) => entry.isDirectory() && existsSync(path.join(dir, entry.name, HOST_FILE))).map((entry) => entry.name).sort();
|
|
104
|
+
return hosts.length === 0 ? {
|
|
105
|
+
kind: "empty",
|
|
106
|
+
dir
|
|
107
|
+
} : {
|
|
108
|
+
kind: "present",
|
|
109
|
+
dir,
|
|
110
|
+
hosts
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
/** Rejects every import except the project's powerhouse.config.json, plus any
|
|
114
|
+
* dynamic `import(...)` or `require(...)`. Source-level enforcement: the JSON
|
|
115
|
+
* round trip below is the hard gate; this one produces the better error. */
|
|
116
|
+
function lintHostImports(source, file) {
|
|
117
|
+
for (const match of source.matchAll(/^\s*import\b[^;'"]*?from\s+["']([^"']+)["']/gm)) {
|
|
118
|
+
const specifier = match[1];
|
|
119
|
+
if (!specifier.endsWith(CONFIG_IMPORT_SUFFIX)) throw new HostLoadError(`${file} imports "${specifier}" — a host file may only import the project's powerhouse.config.json.`, "Host files are static projections; code belongs in plugins.js or the runner.");
|
|
120
|
+
}
|
|
121
|
+
if (/^\s*import\s+["']/m.test(source)) throw new HostLoadError(`${file} contains a side-effect import — a host file may only import the project's powerhouse.config.json.`);
|
|
122
|
+
if (/\bimport\s*\(/.test(source) || /\brequire\s*\(/.test(source)) throw new HostLoadError(`${file} uses dynamic import()/require() — host files are static data.`);
|
|
123
|
+
}
|
|
124
|
+
/** Returns the path of the first value that would not survive a JSON round
|
|
125
|
+
* trip, or undefined when the object is fully static. */
|
|
126
|
+
function findNonStaticValue(value, trail = "") {
|
|
127
|
+
if (value === null) return void 0;
|
|
128
|
+
const kind = typeof value;
|
|
129
|
+
if (kind === "string" || kind === "number" || kind === "boolean") return;
|
|
130
|
+
if (kind !== "object") return `${trail || "<root>"} (${kind})`;
|
|
131
|
+
if (Array.isArray(value)) {
|
|
132
|
+
for (let i = 0; i < value.length; i++) {
|
|
133
|
+
const hit = findNonStaticValue(value[i], `${trail}[${i}]`);
|
|
134
|
+
if (hit) return hit;
|
|
135
|
+
}
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
138
|
+
const proto = Object.getPrototypeOf(value);
|
|
139
|
+
if (proto !== Object.prototype && proto !== null) return `${trail || "<root>"} (non-plain object)`;
|
|
140
|
+
for (const [key, child] of Object.entries(value)) {
|
|
141
|
+
const hit = findNonStaticValue(child, trail ? `${trail}.${key}` : key);
|
|
142
|
+
if (hit) return hit;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
function assertHostShape(host, file) {
|
|
146
|
+
if (typeof host.name !== "string" || host.name.length === 0) throw new HostLoadError(`${file}: \`name\` must be a non-empty string.`);
|
|
147
|
+
const runner = host.runner;
|
|
148
|
+
if (runner === null || typeof runner !== "object" || typeof runner.module !== "string") throw new HostLoadError(`${file}: \`runner\` must be an object with a \`module\` specifier string.`);
|
|
149
|
+
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.`);
|
|
150
|
+
}
|
|
151
|
+
async function loadHost(projectRoot, hostName) {
|
|
152
|
+
const probe = probeHostsFolder(projectRoot);
|
|
153
|
+
if (probe.kind === "absent") throw new HostLoadError(`No hosts/ folder found in ${projectRoot}.`, "Scaffold one with `ph init --uniform-runners` (or create hosts/<name>/host.js).");
|
|
154
|
+
if (probe.kind === "empty") throw new HostLoadError(`hosts/ exists at ${probe.dir} but contains no <name>/host.js.`, "An empty hosts/ folder does not activate the uniform-runners architecture; add a host definition or remove the folder.");
|
|
155
|
+
if (!probe.hosts.includes(hostName)) throw new HostLoadError(`Unknown host "${hostName}". Available hosts: ${probe.hosts.join(", ")}.`);
|
|
156
|
+
const file = path.join(probe.dir, hostName, HOST_FILE);
|
|
157
|
+
lintHostImports(readFileSync(file, "utf8"), file);
|
|
158
|
+
const host = (await import(pathToFileURL(file).href)).default;
|
|
159
|
+
if (host === null || typeof host !== "object" || Array.isArray(host)) throw new HostLoadError(`${file} must default-export the host object (\`export default { name, runner, ... }\`).`);
|
|
160
|
+
const nonStatic = findNonStaticValue(host);
|
|
161
|
+
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.");
|
|
162
|
+
assertHostShape(host, file);
|
|
163
|
+
return {
|
|
164
|
+
name: hostName,
|
|
165
|
+
dir: path.dirname(file),
|
|
166
|
+
file,
|
|
167
|
+
host
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
//#endregion
|
|
171
|
+
//#region src/runner-resolver.ts
|
|
172
|
+
/**
|
|
173
|
+
* Resolves a host's `runner.module` specifier from the PROJECT's dependency
|
|
174
|
+
* tree (not ph-cli's), imports it, and checks the runner-module contract:
|
|
175
|
+
* `{ run, hostSchema, kind, ...optionalVerbs }`. Phase-0 home is ph-cli; the
|
|
176
|
+
* uniform-runners plan moves this into @powerhousedao/host-core with the
|
|
177
|
+
* generic compound (phase 1).
|
|
178
|
+
*/
|
|
179
|
+
var RunnerError = class extends Error {
|
|
180
|
+
constructor(message, hint) {
|
|
181
|
+
super(hint ? `${message}\n Hint: ${hint}` : message);
|
|
182
|
+
this.name = "RunnerError";
|
|
183
|
+
}
|
|
184
|
+
};
|
|
185
|
+
/** Exports that are part of the contract but are not verbs. */
|
|
186
|
+
const NON_VERB_EXPORTS = /* @__PURE__ */ new Set([
|
|
187
|
+
"hostSchema",
|
|
188
|
+
"kind",
|
|
189
|
+
"default"
|
|
190
|
+
]);
|
|
191
|
+
async function resolveRunnerModule(projectRoot, specifier) {
|
|
192
|
+
const projectRequire = createRequire(pathToFileURL(path.join(projectRoot, "package.json")).href);
|
|
193
|
+
let resolved;
|
|
194
|
+
try {
|
|
195
|
+
resolved = projectRequire.resolve(specifier);
|
|
196
|
+
} catch {
|
|
197
|
+
throw new RunnerError(`Cannot resolve runner module "${specifier}" from ${projectRoot}.`, "The runner must be a dependency of the project (install it, then retry).");
|
|
198
|
+
}
|
|
199
|
+
const module = await import(pathToFileURL(resolved).href);
|
|
200
|
+
if (typeof module.run !== "function") throw new RunnerError(`Runner "${specifier}" does not export a \`run\` function (required verb).`);
|
|
201
|
+
const hostSchema = module.hostSchema;
|
|
202
|
+
if (!hostSchema || typeof hostSchema.safeParse !== "function") throw new RunnerError(`Runner "${specifier}" does not export a \`hostSchema\` — runners validate their own host shape.`);
|
|
203
|
+
if (typeof module.kind !== "string") throw new RunnerError(`Runner "${specifier}" does not export \`kind\` (e.g. "reactor" | "compound").`);
|
|
204
|
+
return module;
|
|
205
|
+
}
|
|
206
|
+
function listVerbs(runner) {
|
|
207
|
+
return Object.entries(runner).filter(([name, value]) => typeof value === "function" && !NON_VERB_EXPORTS.has(name)).map(([name]) => name).sort();
|
|
208
|
+
}
|
|
209
|
+
function getVerb(runner, specifier, verb) {
|
|
210
|
+
const candidate = runner[verb];
|
|
211
|
+
if (typeof candidate !== "function" || NON_VERB_EXPORTS.has(verb)) throw new RunnerError(`Runner "${specifier}" does not support the verb "${verb}". Supported verbs: ${listVerbs(runner).join(", ")}.`);
|
|
212
|
+
return candidate;
|
|
213
|
+
}
|
|
214
|
+
function validateHost(runner, specifier, host, file) {
|
|
215
|
+
const result = runner.hostSchema.safeParse(host);
|
|
216
|
+
if (!result.success) throw new RunnerError(`${file} failed validation against the hostSchema of "${specifier}":\n${(result.error?.issues ?? []).map((issue) => ` - ${issue.path.join(".") || "<root>"}: ${issue.message}`).join("\n") || " (no details reported)"}`);
|
|
217
|
+
}
|
|
218
|
+
//#endregion
|
|
219
|
+
//#region src/run-record.ts
|
|
220
|
+
const runDir = (projectDir) => path.join(projectDir, ".ph", "run");
|
|
221
|
+
const recordPath = (projectDir, hostName) => path.join(runDir(projectDir), `${hostName}.json`);
|
|
222
|
+
function readRunRecord(projectDir, hostName) {
|
|
223
|
+
try {
|
|
224
|
+
return JSON.parse(fs.readFileSync(recordPath(projectDir, hostName), "utf8"));
|
|
225
|
+
} catch {
|
|
226
|
+
return;
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
function writeRunRecord(projectDir, record) {
|
|
230
|
+
const target = recordPath(projectDir, record.hostName);
|
|
231
|
+
fs.mkdirSync(path.dirname(target), { recursive: true });
|
|
232
|
+
fs.writeFileSync(target, `${JSON.stringify(record, null, 2)}\n`);
|
|
233
|
+
}
|
|
234
|
+
function clearRunRecord(projectDir, hostName) {
|
|
235
|
+
try {
|
|
236
|
+
fs.rmSync(recordPath(projectDir, hostName));
|
|
237
|
+
} catch {}
|
|
238
|
+
}
|
|
239
|
+
function isPidAlive(pid) {
|
|
240
|
+
try {
|
|
241
|
+
process.kill(pid, 0);
|
|
242
|
+
return true;
|
|
243
|
+
} catch (error) {
|
|
244
|
+
return error.code === "EPERM";
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
/**
|
|
248
|
+
* Decide whether the recorded instance is this project's live host.
|
|
249
|
+
*
|
|
250
|
+
* pid liveness alone proves nothing (pids are reused), and the recorded
|
|
251
|
+
* projectName is what separates "my instance" from "a different project that
|
|
252
|
+
* happens to hold this storage root" — the confusion the vetra lock exists to
|
|
253
|
+
* prevent. A stale record (dead pid) is reported so the caller can clear it; a
|
|
254
|
+
* foreign one (live pid, different project) is left alone.
|
|
255
|
+
*/
|
|
256
|
+
function probeRun(projectDir, hostName, projectName) {
|
|
257
|
+
const record = readRunRecord(projectDir, hostName);
|
|
258
|
+
if (!record) return { status: "none" };
|
|
259
|
+
if (!isPidAlive(record.pid)) return {
|
|
260
|
+
status: "stale",
|
|
261
|
+
record
|
|
262
|
+
};
|
|
263
|
+
if (record.projectName !== projectName) return {
|
|
264
|
+
status: "foreign",
|
|
265
|
+
record
|
|
266
|
+
};
|
|
267
|
+
return {
|
|
268
|
+
status: "live",
|
|
269
|
+
record
|
|
270
|
+
};
|
|
271
|
+
}
|
|
272
|
+
//#endregion
|
|
273
|
+
//#region src/placeholders.ts
|
|
274
|
+
/**
|
|
275
|
+
* `${userData}` resolution for host files (desktop shape): storage paths in a
|
|
276
|
+
* host must not derive from the instance name (renames must stay safe), so
|
|
277
|
+
* the host file writes `${userData}/pglite` and the RUNNER resolves it at
|
|
278
|
+
* start. In the CLI the default userData is `<projectRoot>/.ph/user-data`;
|
|
279
|
+
* a shell (Tauri) overrides it via PH_USER_DATA_DIR to the OS profile dir.
|
|
280
|
+
*/
|
|
281
|
+
function defaultUserDataDir(projectRoot, env = process.env) {
|
|
282
|
+
return env.PH_USER_DATA_DIR ?? path.join(projectRoot, ".ph", "user-data");
|
|
283
|
+
}
|
|
284
|
+
const PLACEHOLDER = /\$\{userData\}/g;
|
|
285
|
+
/** Deep-substitute `${userData}` in every string of a JSON-shaped value.
|
|
286
|
+
* Non-strings pass through; the input is never mutated. */
|
|
287
|
+
function resolveUserDataPlaceholders(value, userData) {
|
|
288
|
+
if (typeof value === "string") return value.replace(PLACEHOLDER, userData);
|
|
289
|
+
if (Array.isArray(value)) return value.map((v) => resolveUserDataPlaceholders(v, userData));
|
|
290
|
+
if (value !== null && typeof value === "object") {
|
|
291
|
+
const out = {};
|
|
292
|
+
for (const [k, v] of Object.entries(value)) out[k] = resolveUserDataPlaceholders(v, userData);
|
|
293
|
+
return out;
|
|
294
|
+
}
|
|
295
|
+
return value;
|
|
296
|
+
}
|
|
297
|
+
//#endregion
|
|
298
|
+
//#region src/compound.ts
|
|
299
|
+
function memberEntries(host) {
|
|
300
|
+
const children = host.children ?? {};
|
|
301
|
+
return Object.entries(children);
|
|
302
|
+
}
|
|
303
|
+
function orderedMembers(host, wiring) {
|
|
304
|
+
const entries = memberEntries(host);
|
|
305
|
+
if (!wiring.startOrder) return entries;
|
|
306
|
+
const byName = new Map(entries);
|
|
307
|
+
const out = [];
|
|
308
|
+
for (const name of wiring.startOrder) {
|
|
309
|
+
const m = byName.get(name);
|
|
310
|
+
if (m) {
|
|
311
|
+
out.push([name, m]);
|
|
312
|
+
byName.delete(name);
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
for (const [name, m] of entries) if (byName.has(name)) out.push([name, m]);
|
|
316
|
+
return out;
|
|
317
|
+
}
|
|
318
|
+
/** Build the member host object the member runner sees: the member's own
|
|
319
|
+
* host.js, with the wrapper's runner/config/reactor overrides applied
|
|
320
|
+
* (wrapper wins), and any compound-computed config patch merged in. */
|
|
321
|
+
async function resolveMemberHost(projectRoot, member, userData, configPatch) {
|
|
322
|
+
const base = (await loadHost(projectRoot, member.host)).host;
|
|
323
|
+
return resolveUserDataPlaceholders({
|
|
324
|
+
...base,
|
|
325
|
+
runner: {
|
|
326
|
+
...base.runner,
|
|
327
|
+
...member.runner ?? {}
|
|
328
|
+
},
|
|
329
|
+
config: {
|
|
330
|
+
...base.config ?? {},
|
|
331
|
+
...member.config ?? {},
|
|
332
|
+
...configPatch ?? {}
|
|
333
|
+
},
|
|
334
|
+
reactor: {
|
|
335
|
+
...base.reactor ?? {},
|
|
336
|
+
...member.reactor ?? {}
|
|
337
|
+
}
|
|
338
|
+
}, userData);
|
|
339
|
+
}
|
|
340
|
+
function isConnectMember(member) {
|
|
341
|
+
return member.host === "connect";
|
|
342
|
+
}
|
|
343
|
+
function isReactorFactMember(member) {
|
|
344
|
+
return member.host === "switchboard";
|
|
345
|
+
}
|
|
346
|
+
async function runCompound(host, ctx, options) {
|
|
347
|
+
const projectRoot = ctx.projectRoot;
|
|
348
|
+
const wiring = host.config ?? {};
|
|
349
|
+
const verb = ctx.verb;
|
|
350
|
+
const probe = probeRun(projectRoot, host.name, options.projectName);
|
|
351
|
+
if (probe.status === "live") throw new Error(`${host.name} is already running for this project (pid ${probe.record.pid}). Stop it before starting another.`);
|
|
352
|
+
if (probe.status === "foreign") throw new Error(`.ph/run/${host.name}.json describes a live "${probe.record.projectName}", but this project is "${options.projectName}". Refusing to start a second instance.`);
|
|
353
|
+
const userData = defaultUserDataDir(projectRoot, ctx.env);
|
|
354
|
+
const started = [];
|
|
355
|
+
const reactorFacts = { driveUrls: [] };
|
|
356
|
+
const shutdown = async () => {
|
|
357
|
+
for (const m of [...started].reverse()) try {
|
|
358
|
+
await m.handle.shutdown?.();
|
|
359
|
+
} catch {}
|
|
360
|
+
if (wiring.runtimeRecord !== false) clearRunRecord(projectRoot, host.name);
|
|
361
|
+
};
|
|
362
|
+
for (const [name, member] of orderedMembers(host, wiring)) {
|
|
363
|
+
let configPatch;
|
|
364
|
+
if (isConnectMember(member) && wiring.projectDrivesIntoConnect && reactorFacts.driveUrls.length > 0) {
|
|
365
|
+
const configuredDefaultDrives = (member.config?.drives)?.defaultDrives;
|
|
366
|
+
configPatch = projectDrivesIntoConnect({
|
|
367
|
+
createdDriveUrls: reactorFacts.driveUrls,
|
|
368
|
+
configuredDefaultDrives,
|
|
369
|
+
publicBase: wiring.drivesPublicBase
|
|
370
|
+
});
|
|
371
|
+
}
|
|
372
|
+
const memberHost = await resolveMemberHost(projectRoot, member, userData, configPatch);
|
|
373
|
+
if (isConnectMember(member) && wiring.cspRegistrySync) memberHost.runner = {
|
|
374
|
+
...memberHost.runner,
|
|
375
|
+
cspRegistrySync: true
|
|
376
|
+
};
|
|
377
|
+
const specifier = memberHost.runner.module;
|
|
378
|
+
const runner = await resolveRunnerModule(projectRoot, specifier);
|
|
379
|
+
validateHost(runner, specifier, memberHost, `hosts/${member.host}/host.js`);
|
|
380
|
+
const handle = await getVerb(runner, specifier, verb === "run" ? memberHost.runner.defaultVerb ?? "run" : verb)(memberHost, ctx) ?? {};
|
|
381
|
+
if (handle.ready) await handle.ready;
|
|
382
|
+
started.push({
|
|
383
|
+
name,
|
|
384
|
+
handle
|
|
385
|
+
});
|
|
386
|
+
if (isReactorFactMember(member) && handle.driveUrls) reactorFacts.driveUrls.push(...handle.driveUrls);
|
|
387
|
+
}
|
|
388
|
+
if (wiring.runtimeRecord !== false) {
|
|
389
|
+
const members = {};
|
|
390
|
+
for (const m of started) members[m.name] = {
|
|
391
|
+
port: m.handle.port,
|
|
392
|
+
url: m.handle.endpoints?.graphql ?? m.handle.endpoints?.connect
|
|
393
|
+
};
|
|
394
|
+
writeRunRecord(projectRoot, {
|
|
395
|
+
pid: process.pid,
|
|
396
|
+
hostName: host.name,
|
|
397
|
+
projectName: options.projectName,
|
|
398
|
+
startedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
399
|
+
members,
|
|
400
|
+
extra: options.recordExtra
|
|
401
|
+
});
|
|
402
|
+
}
|
|
403
|
+
if (options.installSignalHandlers !== false) {
|
|
404
|
+
const onSignal = (code) => {
|
|
405
|
+
shutdown().finally(() => process.exit(code));
|
|
406
|
+
};
|
|
407
|
+
process.on("exit", () => {
|
|
408
|
+
if (wiring.runtimeRecord !== false) clearRunRecord(projectRoot, host.name);
|
|
409
|
+
});
|
|
410
|
+
process.on("SIGINT", () => onSignal(130));
|
|
411
|
+
process.on("SIGTERM", () => onSignal(143));
|
|
412
|
+
}
|
|
413
|
+
return {
|
|
414
|
+
started,
|
|
415
|
+
shutdown
|
|
416
|
+
};
|
|
417
|
+
}
|
|
418
|
+
//#endregion
|
|
419
|
+
//#region src/host-schemas.ts
|
|
420
|
+
/**
|
|
421
|
+
* The shared zod schemas for host.js blocks (D2.a). The `reactor` block
|
|
422
|
+
* validates STRICTLY (D2.d — phase 0's tolerated-unknown-keys notice ends
|
|
423
|
+
* here): a typo'd protocol key must fail, not silently not-apply, because
|
|
424
|
+
* these are fleet-consensus settings. `config` stays loose — it is
|
|
425
|
+
* runner-defined by design.
|
|
426
|
+
*/
|
|
427
|
+
const profileSchema = z.strictObject({
|
|
428
|
+
appId: z.string().min(1).optional(),
|
|
429
|
+
name: z.string().min(1).optional(),
|
|
430
|
+
description: z.string().optional(),
|
|
431
|
+
icon: z.string().optional()
|
|
432
|
+
}).optional();
|
|
433
|
+
const reactorProtocolSchema = z.strictObject({
|
|
434
|
+
featureFlags: z.strictObject({
|
|
435
|
+
documentDecisions: z.boolean().optional(),
|
|
436
|
+
authEnforcement: z.boolean().optional(),
|
|
437
|
+
authGroups: z.boolean().optional(),
|
|
438
|
+
authConditions: z.boolean().optional()
|
|
439
|
+
}).optional(),
|
|
440
|
+
createSignaturePolicy: z.enum(["legacy", "v2-required"]).optional(),
|
|
441
|
+
unsupportedStoredDocuments: z.enum(["refuse", "read-only"]).optional()
|
|
442
|
+
});
|
|
443
|
+
const reactorBackendSchema = z.strictObject({
|
|
444
|
+
kind: z.enum([
|
|
445
|
+
"in-process",
|
|
446
|
+
"worker",
|
|
447
|
+
"remote"
|
|
448
|
+
]).optional(),
|
|
449
|
+
storage: z.strictObject({
|
|
450
|
+
kind: z.enum([
|
|
451
|
+
"idb",
|
|
452
|
+
"memory",
|
|
453
|
+
"path",
|
|
454
|
+
"postgres"
|
|
455
|
+
]),
|
|
456
|
+
dataDir: z.string().optional(),
|
|
457
|
+
url: z.string().optional()
|
|
458
|
+
}).optional(),
|
|
459
|
+
readModel: z.strictObject({ url: z.string().optional() }).optional(),
|
|
460
|
+
packages: z.strictObject({
|
|
461
|
+
cdnUrl: z.string().optional(),
|
|
462
|
+
specs: z.array(z.string()).optional(),
|
|
463
|
+
dynamic: z.boolean().optional()
|
|
464
|
+
}).optional(),
|
|
465
|
+
remote: z.strictObject({
|
|
466
|
+
host: z.string().optional(),
|
|
467
|
+
url: z.string().optional()
|
|
468
|
+
}).optional()
|
|
469
|
+
});
|
|
470
|
+
const reactorSchema = z.strictObject({
|
|
471
|
+
backends: z.record(z.string(), reactorBackendSchema).optional(),
|
|
472
|
+
placement: z.strictObject({
|
|
473
|
+
primary: z.string().optional(),
|
|
474
|
+
default: z.looseObject({}).optional()
|
|
475
|
+
}).optional(),
|
|
476
|
+
workflows: z.boolean().optional(),
|
|
477
|
+
protocol: reactorProtocolSchema.optional()
|
|
478
|
+
});
|
|
479
|
+
/** Common runner options every host.runner carries; runner modules extend it
|
|
480
|
+
* loosely with their own process options. */
|
|
481
|
+
const runnerBaseSchema = z.looseObject({
|
|
482
|
+
module: z.string().min(1),
|
|
483
|
+
defaultVerb: z.string().optional(),
|
|
484
|
+
port: z.number().int().positive().optional()
|
|
485
|
+
});
|
|
486
|
+
/** A compound's children map (mutually exclusive with `reactor` — the XOR is
|
|
487
|
+
* structural, enforced by the loader; schemas validate each side's shape). */
|
|
488
|
+
const childrenSchema = z.record(z.string(), z.strictObject({
|
|
489
|
+
host: z.string().min(1),
|
|
490
|
+
plugins: z.array(z.string()).optional(),
|
|
491
|
+
runner: z.looseObject({}).optional(),
|
|
492
|
+
config: z.looseObject({}).optional(),
|
|
493
|
+
reactor: reactorSchema.optional()
|
|
494
|
+
}));
|
|
495
|
+
z.looseObject({
|
|
496
|
+
name: z.string().min(1),
|
|
497
|
+
runner: runnerBaseSchema,
|
|
498
|
+
config: z.looseObject({}).optional(),
|
|
499
|
+
profile: profileSchema,
|
|
500
|
+
reactor: reactorSchema.optional()
|
|
501
|
+
});
|
|
502
|
+
const compoundHostSchema = z.looseObject({
|
|
503
|
+
name: z.string().min(1),
|
|
504
|
+
runner: runnerBaseSchema,
|
|
505
|
+
children: childrenSchema,
|
|
506
|
+
config: z.looseObject({}).optional(),
|
|
507
|
+
profile: profileSchema
|
|
508
|
+
});
|
|
509
|
+
//#endregion
|
|
510
|
+
export { lintHostImports as C, projectDrivesIntoConnect as D, mergeDefaultDrives as E, rebaseDriveUrl as O, findNonStaticValue as S, probeHostsFolder as T, getVerb as _, reactorProtocolSchema as a, validateHost as b, runCompound as c, clearRunRecord as d, isPidAlive as f, RunnerError as g, writeRunRecord as h, reactorBackendSchema as i, defaultUserDataDir as l, readRunRecord as m, compoundHostSchema as n, reactorSchema as o, probeRun as p, profileSchema as r, runnerBaseSchema as s, childrenSchema as t, resolveUserDataPlaceholders as u, listVerbs as v, loadHost as w, HostLoadError as x, resolveRunnerModule as y };
|
|
511
|
+
|
|
512
|
+
//# sourceMappingURL=host-schemas-B0-Vk8vP.mjs.map
|