@powerhousedao/host-core 6.4.0-next.3 → 6.4.0-next.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/dist/{compound-L62ALvYc.d.mts → compound-BLhEewO6.d.mts} +8 -2
  2. package/dist/compound-BLhEewO6.d.mts.map +1 -0
  3. package/dist/{compound-Q9sZSEZF.mjs → compound-g6x_KkWp.mjs} +133 -1208
  4. package/dist/compound-g6x_KkWp.mjs.map +1 -0
  5. package/dist/control-channel-DVn4dvfQ.d.mts +206 -0
  6. package/dist/control-channel-DVn4dvfQ.d.mts.map +1 -0
  7. package/dist/control-channel.d.mts +2 -2
  8. package/dist/control-channel.mjs +358 -47
  9. package/dist/control-channel.mjs.map +1 -1
  10. package/dist/host-entry-B8n_590_.mjs +188 -0
  11. package/dist/host-entry-B8n_590_.mjs.map +1 -0
  12. package/dist/index.d.mts +68 -102
  13. package/dist/index.d.mts.map +1 -1
  14. package/dist/index.mjs +6 -3
  15. package/dist/index.mjs.map +1 -1
  16. package/dist/instance-C6uugZ32.d.mts +165 -0
  17. package/dist/instance-C6uugZ32.d.mts.map +1 -0
  18. package/dist/instance.d.mts +3 -0
  19. package/dist/instance.mjs +145 -0
  20. package/dist/instance.mjs.map +1 -0
  21. package/dist/kill-tree.d.mts +2 -0
  22. package/dist/kill-tree.d.mts.map +1 -1
  23. package/dist/kill-tree.mjs +1 -1
  24. package/dist/kill-tree.mjs.map +1 -1
  25. package/dist/run-record-C6oTZF_C.mjs +1077 -0
  26. package/dist/run-record-C6oTZF_C.mjs.map +1 -0
  27. package/dist/runners/compound.d.mts +1 -1
  28. package/dist/runners/compound.mjs +2 -1
  29. package/dist/runners/compound.mjs.map +1 -1
  30. package/dist/spawn-host-DWroRe1S.d.mts +107 -0
  31. package/dist/spawn-host-DWroRe1S.d.mts.map +1 -0
  32. package/dist/supervisor-record.d.mts +88 -0
  33. package/dist/supervisor-record.d.mts.map +1 -0
  34. package/dist/supervisor-record.mjs +127 -0
  35. package/dist/supervisor-record.mjs.map +1 -0
  36. package/dist/supervisor.d.mts +205 -0
  37. package/dist/supervisor.d.mts.map +1 -0
  38. package/dist/supervisor.mjs +905 -0
  39. package/dist/supervisor.mjs.map +1 -0
  40. package/package.json +21 -3
  41. package/dist/compound-L62ALvYc.d.mts.map +0 -1
  42. package/dist/compound-Q9sZSEZF.mjs.map +0 -1
  43. package/dist/control-channel-eqvyUF03.d.mts +0 -123
  44. package/dist/control-channel-eqvyUF03.d.mts.map +0 -1
@@ -0,0 +1,165 @@
1
+ import { l as ControlRecord, w as RunRecord } from "./control-channel-DVn4dvfQ.mjs";
2
+ //#region src/instance-key.d.ts
3
+ type Env$1 = Readonly<Record<string, string | undefined>>;
4
+ /**
5
+ * What names one running instance at every layer (host runs, Cli services,
6
+ * the desktop shell): a host and a data folder. The same key asked twice is
7
+ * one instance; two data folders are two instances of the host.
8
+ */
9
+ interface InstanceKey {
10
+ /** The host as `ph run` addresses it: its name, behind its package when an
11
+ * installed package supplies it (`@acme/tools/studio`). */
12
+ host: string;
13
+ /** The folder that holds the instance's `.ph` tree: PH_USER_DATA_DIR when
14
+ * set (a desktop shell's per-user folder), else the project folder. */
15
+ dataDir: string;
16
+ /** Both in one string, equal for equal keys. */
17
+ id: string;
18
+ }
19
+ /** The data folder of a project: where its `.ph` tree is. */
20
+ declare function instanceDataDir(projectDir?: string, env?: Env$1): string;
21
+ /** The key of `host` (a record key, see `runRecordKey`) in a project. */
22
+ declare function instanceKey(host: string, projectDir?: string, env?: Env$1): InstanceKey;
23
+ /** The `.ph` tree of a data folder. */
24
+ declare function instancePhDir(key: Pick<InstanceKey, "dataDir">): string;
25
+ /** Where the run records of a data folder are: the one place they are kept. */
26
+ declare function instanceRunDir(key: Pick<InstanceKey, "dataDir">): string;
27
+ /** Where a Cli keeps the state of its services: under the data folder, so
28
+ * two project folders never see each other's. */
29
+ declare function instanceServicesDir(key: Pick<InstanceKey, "dataDir">, cliName: string): string;
30
+ //#endregion
31
+ //#region src/instance.d.ts
32
+ /**
33
+ * The one instance rule: an instance is a host plus a data folder
34
+ * ({@link instanceKey}), its run record is the file that key names, and a
35
+ * start on a key that runs returns the running instance. This module reads
36
+ * the records only: it starts nothing and loads no runner.
37
+ */
38
+ type Env = Readonly<Record<string, string | undefined>>;
39
+ /** One drive a running switchboard serves. */
40
+ interface InstanceDrive {
41
+ id: string;
42
+ url: string;
43
+ }
44
+ /** A live instance, as its run record describes it. */
45
+ interface RunningInstance {
46
+ key: InstanceKey;
47
+ record: RunRecord;
48
+ /** The file the record is in. */
49
+ recordPath: string;
50
+ pid: number;
51
+ /** The channel its process answers commands on, when it has one. */
52
+ control?: ControlRecord;
53
+ /** The protocol of the channel its record names. Set without `control`:
54
+ * the instance speaks another protocol than this process. */
55
+ controlProtocol?: number;
56
+ /** The origin of its switchboard: the instance's own outputs for a
57
+ * switchboard host, a member's for a compound. */
58
+ switchboardUrl?: string;
59
+ /** The drives of that switchboard, by declared slug. */
60
+ drives: Record<string, InstanceDrive>;
61
+ /** Every URL it published: `origin` and `endpoints.<name>` of its outputs,
62
+ * keyed `<member>.<name>` for a compound's members. */
63
+ endpoints: Record<string, string>;
64
+ /** The ports it bound, by member (by host name for a single host). */
65
+ ports: Record<string, number>;
66
+ }
67
+ /** What a record says of a live instance. */
68
+ declare function instanceOfRecord(projectDir: string, record: RunRecord, env?: Env): RunningInstance;
69
+ interface FindInstanceOptions {
70
+ /** The host, or hosts in order of preference, as record keys. Without it:
71
+ * the project's live compound, else its first live host. */
72
+ host?: string | readonly string[];
73
+ /** Where PH_USER_DATA_DIR is read from (default: this process). */
74
+ env?: Env;
75
+ /** The project's name (default: its package.json `name`). */
76
+ projectName?: string;
77
+ }
78
+ /** The live instance of one key; undefined when none runs. A record another
79
+ * project left on this data folder (a foreign one) is not this project's. */
80
+ declare function runningInstance(projectDir: string, host: string, options?: Omit<FindInstanceOptions, "host">): RunningInstance | undefined;
81
+ /** Every live instance on the project's data folder. */
82
+ declare function listRunningInstances(projectDir: string, options?: Omit<FindInstanceOptions, "host">): RunningInstance[];
83
+ /**
84
+ * The running instance that belongs to a project folder and its data folder:
85
+ * its record, its control channel and its switchboard. Undefined when none
86
+ * runs.
87
+ */
88
+ declare function findRunningInstance(projectDir?: string, options?: FindInstanceOptions): RunningInstance | undefined;
89
+ /** What a second start on a running key prints: the instance, and how to
90
+ * stop it. */
91
+ declare function describeInstance(instance: RunningInstance): string;
92
+ /** What a start returns instead of a new instance when its key runs. */
93
+ interface AlreadyRunning {
94
+ running: RunningInstance;
95
+ }
96
+ declare function isAlreadyRunning(value: unknown): value is AlreadyRunning;
97
+ /** When an instance that ended on its own is started again. */
98
+ interface RestartPolicy {
99
+ enabled?: boolean;
100
+ /** Restarts in a row before it is left failed. */
101
+ maxRetries: number;
102
+ /** Ms between its end and the restart. */
103
+ delay: number;
104
+ }
105
+ type RestartDecision = {
106
+ action: "restart";
107
+ attempt: number;
108
+ delayMs: number;
109
+ } |
110
+ /** Restarts were tried `maxRetries` times. */
111
+ {
112
+ action: "give-up";
113
+ attempts: number;
114
+ } |
115
+ /** No policy, a supervisor that is stopping, or an instance that never got
116
+ * ready: it is not restarted. */
117
+ {
118
+ action: "none";
119
+ };
120
+ /**
121
+ * The restart rule of the host layer: an instance that was ready and ended
122
+ * on its own restarts after `delay`, at most `maxRetries` times in a row (a
123
+ * ready start resets the count). Never while its supervisor stops.
124
+ */
125
+ declare function restartDecision(policy: RestartPolicy | undefined, state: {
126
+ /** Restarts already made since it last got ready. */
127
+ attempt: number;
128
+ /** It was ready when it ended. */
129
+ wasReady: boolean;
130
+ /** The supervisor is stopping. */
131
+ closing?: boolean;
132
+ }): RestartDecision;
133
+ /** Where the restart policy of a supervised instance stands. */
134
+ interface RestartState {
135
+ /** Restarts in a row before it is left failed. */
136
+ maxRetries: number;
137
+ /** Ms between its end and the restart. */
138
+ delay: number;
139
+ /** Restarts made since it last got ready. */
140
+ attempt: number;
141
+ /** How it last ended on its own. */
142
+ lastExit?: {
143
+ code: number | null;
144
+ signal: string | null;
145
+ at: string;
146
+ };
147
+ /** When the restart it waits for is made. */
148
+ nextAt?: string;
149
+ /** Why it was left ended. */
150
+ failed?: string;
151
+ }
152
+ /**
153
+ * What a supervisor knows of an instance beyond its status, one line each,
154
+ * in the words every listing uses: the version that runs it, where its
155
+ * restart policy stands, and what cannot be done with it.
156
+ */
157
+ declare function supervisedFactLines(facts: {
158
+ runnerVersion?: string;
159
+ restart?: RestartState;
160
+ missing?: readonly string[];
161
+ }): string[];
162
+ //#endregion
163
+ export { instanceDataDir as _, RestartPolicy as a, instanceRunDir as b, describeInstance as c, isAlreadyRunning as d, listRunningInstances as f, InstanceKey as g, supervisedFactLines as h, RestartDecision as i, findRunningInstance as l, runningInstance as m, FindInstanceOptions as n, RestartState as o, restartDecision as p, InstanceDrive as r, RunningInstance as s, AlreadyRunning as t, instanceOfRecord as u, instanceKey as v, instanceServicesDir as x, instancePhDir as y };
164
+ export {};
165
+ //# sourceMappingURL=instance-C6uugZ32.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"instance-C6uugZ32.d.mts","names":[],"sources":["../src/instance-key.ts","../src/instance.ts"],"mappings":";;KAEK,QAAM,SAAS;;;;;;UAOH;;;EAGf;;;EAGA;;EAEA;;;iBAIc,gBACd,qBACA,MAAK;;iBAMS,YACd,cACA,qBACA,MAAK,QACJ;;iBAQa,cAAc,KAAK,KAAK;;iBAKxB,eAAe,KAAK,KAAK;;;iBAMzB,oBACd,KAAK,KAAK,yBACV;;;;;;;;;KCvBG,MAAM,SAAS;;UAGH;EACf;EACA;;;UAIe;EACf,KAAK;EACL,QAAQ;;EAER;EACA;;EAEA,UAAU;;;EAGV;;;EAGA;;EAEA,QAAQ,eAAe;;;EAGvB,WAAW;;EAEX,OAAO;;;iBAqCO,iBACd,oBACA,QAAQ,WACR,MAAK,MACJ;UA6Cc;;;EAGf;;EAEA,MAAM;;EAEN;;;;iBAKc,gBACd,oBACA,cACA,UAAS,KAAK,+BACb;;iBAca,qBACd,oBACA,UAAS,KAAK,+BACb;;;;;;iBAaa,oBACd,qBACA,UAAS,sBACR;;;iBAea,iBAAiB,UAAU;;UAiB1B;EACf,SAAS;;iBAGK,iBAAiB,iBAAiB,SAAS;;UAU1C;EACf;;EAEA;;EAEA;;KAGU;EACN;EAAmB;EAAiB;;;;EAEpC;EAAmB;;;;;EAGnB;;;;;;;iBAOU,gBACd,QAAQ,2BACR;;EAEE;;EAEA;;EAEA;IAED;;UAcc;;EAEf;;EAEA;;EAEA;;EAEA;IAAa;IAAqB;IAAuB;;;EAEzD;;EAEA;;;;;;;iBAYc,oBAAoB;EAClC;EACA,UAAU;EACV"}
@@ -0,0 +1,3 @@
1
+ import { _ as instanceDataDir, a as RestartPolicy, b as instanceRunDir, c as describeInstance, d as isAlreadyRunning, f as listRunningInstances, g as InstanceKey, h as supervisedFactLines, i as RestartDecision, l as findRunningInstance, m as runningInstance, n as FindInstanceOptions, o as RestartState, p as restartDecision, r as InstanceDrive, s as RunningInstance, t as AlreadyRunning, u as instanceOfRecord, v as instanceKey, x as instanceServicesDir, y as instancePhDir } from "./instance-C6uugZ32.mjs";
2
+ export { AlreadyRunning, FindInstanceOptions, InstanceDrive, type InstanceKey, RestartDecision, RestartPolicy, RestartState, RunningInstance, describeInstance, findRunningInstance, instanceDataDir, instanceKey, instanceOfRecord, instancePhDir, instanceRunDir, instanceServicesDir, isAlreadyRunning, listRunningInstances, restartDecision, runningInstance, supervisedFactLines };
3
+ export {};
@@ -0,0 +1,145 @@
1
+ import { S as instanceServicesDir, b as instancePhDir, c as recordKeyOf, i as probeRun, o as readProjectName, r as listRunRecords, u as runRecordPath, v as instanceDataDir, x as instanceRunDir, y as instanceKey } from "./run-record-C6oTZF_C.mjs";
2
+ import { controlProtocolOf, controlRecordOf } from "./control-channel.mjs";
3
+ //#region src/instance.ts
4
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
5
+ function portOf(url) {
6
+ if (typeof url !== "string") return void 0;
7
+ try {
8
+ const parsed = new URL(url);
9
+ if (parsed.port) return Number(parsed.port);
10
+ if (parsed.protocol === "https:") return 443;
11
+ if (parsed.protocol === "http:") return 80;
12
+ } catch {}
13
+ }
14
+ function drivesOf(outputs) {
15
+ const drives = {};
16
+ if (!isRecord(outputs.drives)) return drives;
17
+ for (const [slug, drive] of Object.entries(outputs.drives)) if (isRecord(drive) && typeof drive.id === "string" && typeof drive.url === "string") drives[slug] = {
18
+ id: drive.id,
19
+ url: drive.url
20
+ };
21
+ return drives;
22
+ }
23
+ /** What a record says of a live instance. */
24
+ function instanceOfRecord(projectDir, record, env = process.env) {
25
+ const host = recordKeyOf(record);
26
+ const instance = {
27
+ key: instanceKey(host, projectDir, env),
28
+ record,
29
+ recordPath: runRecordPath(projectDir, host, env),
30
+ pid: record.pid,
31
+ drives: {},
32
+ endpoints: {},
33
+ ports: {}
34
+ };
35
+ const control = controlRecordOf(record);
36
+ if (control) instance.control = control;
37
+ const controlProtocol = controlProtocolOf(record);
38
+ if (controlProtocol !== void 0) instance.controlProtocol = controlProtocol;
39
+ const read = (name, outputs, prefix) => {
40
+ if (!isRecord(outputs)) return;
41
+ const origin = typeof outputs.origin === "string" ? outputs.origin : void 0;
42
+ if (origin !== void 0) instance.endpoints[`${prefix}origin`] = origin;
43
+ const port = portOf(origin);
44
+ if (port !== void 0) instance.ports[name] = port;
45
+ if (isRecord(outputs.endpoints)) {
46
+ for (const [key, url] of Object.entries(outputs.endpoints)) if (typeof url === "string") instance.endpoints[`${prefix}${key}`] = url;
47
+ }
48
+ if (instance.switchboardUrl === void 0 && origin !== void 0 && isRecord(outputs.drives)) {
49
+ instance.switchboardUrl = origin;
50
+ instance.drives = drivesOf(outputs);
51
+ }
52
+ };
53
+ read(record.host, record.outputs, "");
54
+ for (const [name, member] of Object.entries(record.members ?? {})) read(name, member.outputs, `${name}.`);
55
+ return instance;
56
+ }
57
+ /** The live instance of one key; undefined when none runs. A record another
58
+ * project left on this data folder (a foreign one) is not this project's. */
59
+ function runningInstance(projectDir, host, options = {}) {
60
+ const env = options.env ?? process.env;
61
+ const probe = probeRun(projectDir, host, options.projectName ?? readProjectName(projectDir), env);
62
+ return probe.status === "live" ? instanceOfRecord(projectDir, probe.record, env) : void 0;
63
+ }
64
+ /** Every live instance on the project's data folder. */
65
+ function listRunningInstances(projectDir, options = {}) {
66
+ const env = options.env ?? process.env;
67
+ return listRunRecords(projectDir, env).flatMap((record) => {
68
+ const instance = runningInstance(projectDir, recordKeyOf(record), options);
69
+ return instance ? [instance] : [];
70
+ });
71
+ }
72
+ /**
73
+ * The running instance that belongs to a project folder and its data folder:
74
+ * its record, its control channel and its switchboard. Undefined when none
75
+ * runs.
76
+ */
77
+ function findRunningInstance(projectDir = process.cwd(), options = {}) {
78
+ const { host, ...rest } = options;
79
+ if (host !== void 0) {
80
+ for (const key of typeof host === "string" ? [host] : host) {
81
+ const instance = runningInstance(projectDir, key, rest);
82
+ if (instance) return instance;
83
+ }
84
+ return;
85
+ }
86
+ const live = listRunningInstances(projectDir, rest);
87
+ return live.find((i) => i.record.kind === "compound") ?? live.at(0);
88
+ }
89
+ /** What a second start on a running key prints: the instance, and how to
90
+ * stop it. */
91
+ function describeInstance(instance) {
92
+ const { key, record } = instance;
93
+ const lines = [`${key.host} is already running for this project (pid ${record.pid}, started ${record.startedAt}).`, ` data folder: ${key.dataDir}`];
94
+ for (const [name, url] of Object.entries(instance.endpoints)) lines.push(` ${name}: ${url}`);
95
+ lines.push(` record: ${instance.recordPath}`);
96
+ lines.push(`Nothing was started. Stop it with \`ph run ${key.host} --stop\`.`);
97
+ return lines.join("\n");
98
+ }
99
+ function isAlreadyRunning(value) {
100
+ return isRecord(value) && isRecord(value.running) && isRecord(value.running.key) && isRecord(value.running.record);
101
+ }
102
+ /**
103
+ * The restart rule of the host layer: an instance that was ready and ended
104
+ * on its own restarts after `delay`, at most `maxRetries` times in a row (a
105
+ * ready start resets the count). Never while its supervisor stops.
106
+ */
107
+ function restartDecision(policy, state) {
108
+ if (!policy?.enabled) return { action: "none" };
109
+ if (state.attempt >= policy.maxRetries) return {
110
+ action: "give-up",
111
+ attempts: state.attempt
112
+ };
113
+ if (state.closing || !state.wasReady) return { action: "none" };
114
+ return {
115
+ action: "restart",
116
+ attempt: state.attempt + 1,
117
+ delayMs: policy.delay
118
+ };
119
+ }
120
+ function exitWords(exit) {
121
+ return exit.signal !== null ? `signal ${exit.signal}` : `code ${exit.code}`;
122
+ }
123
+ /**
124
+ * What a supervisor knows of an instance beyond its status, one line each,
125
+ * in the words every listing uses: the version that runs it, where its
126
+ * restart policy stands, and what cannot be done with it.
127
+ */
128
+ function supervisedFactLines(facts) {
129
+ const lines = [];
130
+ if (facts.runnerVersion !== void 0) lines.push(`runner version: ${facts.runnerVersion}`);
131
+ const { restart } = facts;
132
+ if (restart) {
133
+ const parts = [`restarted by the supervisor: up to ${restart.maxRetries} time(s) in a row, ${restart.delay} ms apart`, `attempt ${restart.attempt} of ${restart.maxRetries}`];
134
+ if (restart.lastExit) parts.push(`last ended with ${exitWords(restart.lastExit)} at ${restart.lastExit.at}`);
135
+ if (restart.nextAt !== void 0) parts.push(`next start at ${restart.nextAt}`);
136
+ lines.push(parts.join("; "));
137
+ if (restart.failed !== void 0) lines.push(`failed: ${restart.failed}`);
138
+ }
139
+ for (const line of facts.missing ?? []) lines.push(`- ${line}`);
140
+ return lines;
141
+ }
142
+ //#endregion
143
+ export { describeInstance, findRunningInstance, instanceDataDir, instanceKey, instanceOfRecord, instancePhDir, instanceRunDir, instanceServicesDir, isAlreadyRunning, listRunningInstances, restartDecision, runningInstance, supervisedFactLines };
144
+
145
+ //# sourceMappingURL=instance.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"instance.mjs","names":[],"sources":["../src/instance.ts"],"sourcesContent":["import {\n controlProtocolOf,\n controlRecordOf,\n type ControlRecord,\n} from \"./control-channel.js\";\nimport { instanceKey, type InstanceKey } from \"./instance-key.js\";\nimport {\n listRunRecords,\n probeRun,\n readProjectName,\n recordKeyOf,\n runRecordPath,\n} from \"./run-record.js\";\nimport type { RunRecord } from \"./run-record-schema.js\";\n\nexport {\n instanceDataDir,\n instanceKey,\n instancePhDir,\n instanceRunDir,\n instanceServicesDir,\n type InstanceKey,\n} from \"./instance-key.js\";\n\n/**\n * The one instance rule: an instance is a host plus a data folder\n * ({@link instanceKey}), its run record is the file that key names, and a\n * start on a key that runs returns the running instance. This module reads\n * the records only: it starts nothing and loads no runner.\n */\n\ntype Env = Readonly<Record<string, string | undefined>>;\n\n/** One drive a running switchboard serves. */\nexport interface InstanceDrive {\n id: string;\n url: string;\n}\n\n/** A live instance, as its run record describes it. */\nexport interface RunningInstance {\n key: InstanceKey;\n record: RunRecord;\n /** The file the record is in. */\n recordPath: string;\n pid: number;\n /** The channel its process answers commands on, when it has one. */\n control?: ControlRecord;\n /** The protocol of the channel its record names. Set without `control`:\n * the instance speaks another protocol than this process. */\n controlProtocol?: number;\n /** The origin of its switchboard: the instance's own outputs for a\n * switchboard host, a member's for a compound. */\n switchboardUrl?: string;\n /** The drives of that switchboard, by declared slug. */\n drives: Record<string, InstanceDrive>;\n /** Every URL it published: `origin` and `endpoints.<name>` of its outputs,\n * keyed `<member>.<name>` for a compound's members. */\n endpoints: Record<string, string>;\n /** The ports it bound, by member (by host name for a single host). */\n ports: Record<string, number>;\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nfunction portOf(url: unknown): number | undefined {\n if (typeof url !== \"string\") return undefined;\n try {\n const parsed = new URL(url);\n if (parsed.port) return Number(parsed.port);\n if (parsed.protocol === \"https:\") return 443;\n if (parsed.protocol === \"http:\") return 80;\n } catch {\n // not a URL\n }\n return undefined;\n}\n\nfunction drivesOf(\n outputs: Record<string, unknown>,\n): Record<string, InstanceDrive> {\n const drives: Record<string, InstanceDrive> = {};\n if (!isRecord(outputs.drives)) return drives;\n for (const [slug, drive] of Object.entries(outputs.drives)) {\n if (\n isRecord(drive) &&\n typeof drive.id === \"string\" &&\n typeof drive.url === \"string\"\n ) {\n drives[slug] = { id: drive.id, url: drive.url };\n }\n }\n return drives;\n}\n\n/** What a record says of a live instance. */\nexport function instanceOfRecord(\n projectDir: string,\n record: RunRecord,\n env: Env = process.env,\n): RunningInstance {\n const host = recordKeyOf(record);\n const instance: RunningInstance = {\n key: instanceKey(host, projectDir, env),\n record,\n recordPath: runRecordPath(projectDir, host, env),\n pid: record.pid,\n drives: {},\n endpoints: {},\n ports: {},\n };\n const control = controlRecordOf(record);\n if (control) instance.control = control;\n const controlProtocol = controlProtocolOf(record);\n if (controlProtocol !== undefined) instance.controlProtocol = controlProtocol;\n const read = (name: string, outputs: unknown, prefix: string) => {\n if (!isRecord(outputs)) return;\n const origin =\n typeof outputs.origin === \"string\" ? outputs.origin : undefined;\n if (origin !== undefined) instance.endpoints[`${prefix}origin`] = origin;\n const port = portOf(origin);\n if (port !== undefined) instance.ports[name] = port;\n if (isRecord(outputs.endpoints)) {\n for (const [key, url] of Object.entries(outputs.endpoints)) {\n if (typeof url === \"string\")\n instance.endpoints[`${prefix}${key}`] = url;\n }\n }\n // A switchboard is the output that serves drives.\n if (\n instance.switchboardUrl === undefined &&\n origin !== undefined &&\n isRecord(outputs.drives)\n ) {\n instance.switchboardUrl = origin;\n instance.drives = drivesOf(outputs);\n }\n };\n read(record.host, record.outputs, \"\");\n for (const [name, member] of Object.entries(record.members ?? {})) {\n read(name, member.outputs, `${name}.`);\n }\n return instance;\n}\n\nexport interface FindInstanceOptions {\n /** The host, or hosts in order of preference, as record keys. Without it:\n * the project's live compound, else its first live host. */\n host?: string | readonly string[];\n /** Where PH_USER_DATA_DIR is read from (default: this process). */\n env?: Env;\n /** The project's name (default: its package.json `name`). */\n projectName?: string;\n}\n\n/** The live instance of one key; undefined when none runs. A record another\n * project left on this data folder (a foreign one) is not this project's. */\nexport function runningInstance(\n projectDir: string,\n host: string,\n options: Omit<FindInstanceOptions, \"host\"> = {},\n): RunningInstance | undefined {\n const env = options.env ?? process.env;\n const probe = probeRun(\n projectDir,\n host,\n options.projectName ?? readProjectName(projectDir),\n env,\n );\n return probe.status === \"live\"\n ? instanceOfRecord(projectDir, probe.record, env)\n : undefined;\n}\n\n/** Every live instance on the project's data folder. */\nexport function listRunningInstances(\n projectDir: string,\n options: Omit<FindInstanceOptions, \"host\"> = {},\n): RunningInstance[] {\n const env = options.env ?? process.env;\n return listRunRecords(projectDir, env).flatMap((record) => {\n const instance = runningInstance(projectDir, recordKeyOf(record), options);\n return instance ? [instance] : [];\n });\n}\n\n/**\n * The running instance that belongs to a project folder and its data folder:\n * its record, its control channel and its switchboard. Undefined when none\n * runs.\n */\nexport function findRunningInstance(\n projectDir: string = process.cwd(),\n options: FindInstanceOptions = {},\n): RunningInstance | undefined {\n const { host, ...rest } = options;\n if (host !== undefined) {\n for (const key of typeof host === \"string\" ? [host] : host) {\n const instance = runningInstance(projectDir, key, rest);\n if (instance) return instance;\n }\n return undefined;\n }\n const live = listRunningInstances(projectDir, rest);\n return live.find((i) => i.record.kind === \"compound\") ?? live.at(0);\n}\n\n/** What a second start on a running key prints: the instance, and how to\n * stop it. */\nexport function describeInstance(instance: RunningInstance): string {\n const { key, record } = instance;\n const lines = [\n `${key.host} is already running for this project (pid ${record.pid}, started ${record.startedAt}).`,\n ` data folder: ${key.dataDir}`,\n ];\n for (const [name, url] of Object.entries(instance.endpoints)) {\n lines.push(` ${name}: ${url}`);\n }\n lines.push(` record: ${instance.recordPath}`);\n lines.push(\n `Nothing was started. Stop it with \\`ph run ${key.host} --stop\\`.`,\n );\n return lines.join(\"\\n\");\n}\n\n/** What a start returns instead of a new instance when its key runs. */\nexport interface AlreadyRunning {\n running: RunningInstance;\n}\n\nexport function isAlreadyRunning(value: unknown): value is AlreadyRunning {\n return (\n isRecord(value) &&\n isRecord(value.running) &&\n isRecord(value.running.key) &&\n isRecord(value.running.record)\n );\n}\n\n/** When an instance that ended on its own is started again. */\nexport interface RestartPolicy {\n enabled?: boolean;\n /** Restarts in a row before it is left failed. */\n maxRetries: number;\n /** Ms between its end and the restart. */\n delay: number;\n}\n\nexport type RestartDecision =\n | { action: \"restart\"; attempt: number; delayMs: number }\n /** Restarts were tried `maxRetries` times. */\n | { action: \"give-up\"; attempts: number }\n /** No policy, a supervisor that is stopping, or an instance that never got\n * ready: it is not restarted. */\n | { action: \"none\" };\n\n/**\n * The restart rule of the host layer: an instance that was ready and ended\n * on its own restarts after `delay`, at most `maxRetries` times in a row (a\n * ready start resets the count). Never while its supervisor stops.\n */\nexport function restartDecision(\n policy: RestartPolicy | undefined,\n state: {\n /** Restarts already made since it last got ready. */\n attempt: number;\n /** It was ready when it ended. */\n wasReady: boolean;\n /** The supervisor is stopping. */\n closing?: boolean;\n },\n): RestartDecision {\n if (!policy?.enabled) return { action: \"none\" };\n if (state.attempt >= policy.maxRetries) {\n return { action: \"give-up\", attempts: state.attempt };\n }\n if (state.closing || !state.wasReady) return { action: \"none\" };\n return {\n action: \"restart\",\n attempt: state.attempt + 1,\n delayMs: policy.delay,\n };\n}\n\n/** Where the restart policy of a supervised instance stands. */\nexport interface RestartState {\n /** Restarts in a row before it is left failed. */\n maxRetries: number;\n /** Ms between its end and the restart. */\n delay: number;\n /** Restarts made since it last got ready. */\n attempt: number;\n /** How it last ended on its own. */\n lastExit?: { code: number | null; signal: string | null; at: string };\n /** When the restart it waits for is made. */\n nextAt?: string;\n /** Why it was left ended. */\n failed?: string;\n}\n\nfunction exitWords(exit: NonNullable<RestartState[\"lastExit\"]>): string {\n return exit.signal !== null ? `signal ${exit.signal}` : `code ${exit.code}`;\n}\n\n/**\n * What a supervisor knows of an instance beyond its status, one line each,\n * in the words every listing uses: the version that runs it, where its\n * restart policy stands, and what cannot be done with it.\n */\nexport function supervisedFactLines(facts: {\n runnerVersion?: string;\n restart?: RestartState;\n missing?: readonly string[];\n}): string[] {\n const lines: string[] = [];\n if (facts.runnerVersion !== undefined) {\n lines.push(`runner version: ${facts.runnerVersion}`);\n }\n const { restart } = facts;\n if (restart) {\n const parts = [\n `restarted by the supervisor: up to ${restart.maxRetries} time(s) in a row, ${restart.delay} ms apart`,\n `attempt ${restart.attempt} of ${restart.maxRetries}`,\n ];\n if (restart.lastExit) {\n parts.push(\n `last ended with ${exitWords(restart.lastExit)} at ${restart.lastExit.at}`,\n );\n }\n if (restart.nextAt !== undefined) {\n parts.push(`next start at ${restart.nextAt}`);\n }\n lines.push(parts.join(\"; \"));\n if (restart.failed !== undefined) lines.push(`failed: ${restart.failed}`);\n }\n for (const line of facts.missing ?? []) lines.push(`- ${line}`);\n return lines;\n}\n"],"mappings":";;;AA+DA,MAAM,YAAY,UAChB,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAErE,SAAS,OAAO,KAAkC;CAChD,IAAI,OAAO,QAAQ,UAAU,OAAO,KAAA;CACpC,IAAI;EACF,MAAM,SAAS,IAAI,IAAI,GAAG;EAC1B,IAAI,OAAO,MAAM,OAAO,OAAO,OAAO,IAAI;EAC1C,IAAI,OAAO,aAAa,UAAU,OAAO;EACzC,IAAI,OAAO,aAAa,SAAS,OAAO;CAC1C,QAAQ,CAER;AAEF;AAEA,SAAS,SACP,SAC+B;CAC/B,MAAM,SAAwC,CAAC;CAC/C,IAAI,CAAC,SAAS,QAAQ,MAAM,GAAG,OAAO;CACtC,KAAK,MAAM,CAAC,MAAM,UAAU,OAAO,QAAQ,QAAQ,MAAM,GACvD,IACE,SAAS,KAAK,KACd,OAAO,MAAM,OAAO,YACpB,OAAO,MAAM,QAAQ,UAErB,OAAO,QAAQ;EAAE,IAAI,MAAM;EAAI,KAAK,MAAM;CAAI;CAGlD,OAAO;AACT;;AAGA,SAAgB,iBACd,YACA,QACA,MAAW,QAAQ,KACF;CACjB,MAAM,OAAO,YAAY,MAAM;CAC/B,MAAM,WAA4B;EAChC,KAAK,YAAY,MAAM,YAAY,GAAG;EACtC;EACA,YAAY,cAAc,Y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wBA,SAAgB,gBACd,QACA,OAQiB;CACjB,IAAI,CAAC,QAAQ,SAAS,OAAO,EAAE,QAAQ,OAAO;CAC9C,IAAI,MAAM,WAAW,OAAO,YAC1B,OAAO;EAAE,QAAQ;EAAW,UAAU,MAAM;CAAQ;CAEtD,IAAI,MAAM,WAAW,CAAC,MAAM,UAAU,OAAO,EAAE,QAAQ,OAAO;CAC9D,OAAO;EACL,QAAQ;EACR,SAAS,MAAM,UAAU;EACzB,SAAS,OAAO;CAClB;AACF;AAkBA,SAAS,UAAU,MAAqD;CACtE,OAAO,KAAK,WAAW,OAAO,UAAU,KAAK,WAAW,QAAQ,KAAK;AACvE;;;;;;AAOA,SAAgB,oBAAoB,OAIvB;CACX,MAAM,QAAkB,CAAC;CACzB,IAAI,MAAM,kBAAkB,KAAA,GAC1B,MAAM,KAAK,mBAAmB,MAAM,eAAe;CAErD,MAAM,EAAE,YAAY;CACpB,IAAI,SAAS;EACX,MAAM,QAAQ,CACZ,sCAAsC,QAAQ,WAAW,qBAAqB,QAAQ,MAAM,YAC5F,WAAW,QAAQ,QAAQ,MAAM,QAAQ,YAC3C;EACA,IAAI,QAAQ,UACV,MAAM,KACJ,mBAAmB,UAAU,QAAQ,QAAQ,EAAE,MAAM,QAAQ,SAAS,IACxE;EAEF,IAAI,QAAQ,WAAW,KAAA,GACrB,MAAM,KAAK,iBAAiB,QAAQ,QAAQ;EAE9C,MAAM,KAAK,MAAM,KAAK,IAAI,CAAC;EAC3B,IAAI,QAAQ,WAAW,KAAA,GAAW,MAAM,KAAK,WAAW,QAAQ,QAAQ;CAC1E;CACA,KAAK,MAAM,QAAQ,MAAM,WAAW,CAAC,GAAG,MAAM,KAAK,KAAK,MAAM;CAC9D,OAAO;AACT"}
@@ -1,4 +1,6 @@
1
1
  //#region src/kill-tree.d.ts
2
+ /** POSIX: `pid` and all its descendants. */
3
+ export declare function treePids(pid: number): number[];
2
4
  /** Kill a supervised child's whole tree. `signal` only applies on POSIX;
3
5
  * Windows tree-kill is always forceful (there are no signals to deliver).
4
6
  * Never throws: a process already gone is skipped. */
@@ -1 +1 @@
1
- {"version":3,"file":"kill-tree.d.mts","names":[],"sources":["../src/kill-tree.ts"],"mappings":";;;;wBA+DgB,SACd,aACA,SAAQ,OAAO"}
1
+ {"version":3,"file":"kill-tree.d.mts","names":[],"sources":["../src/kill-tree.ts"],"mappings":";;wBAiDgB,SAAS;;;;wBAcT,SACd,aACA,SAAQ,OAAO"}
@@ -68,6 +68,6 @@ function killTree(pid, signal = "SIGTERM") {
68
68
  } catch {}
69
69
  }
70
70
  //#endregion
71
- export { killTree };
71
+ export { killTree, treePids };
72
72
 
73
73
  //# sourceMappingURL=kill-tree.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"kill-tree.mjs","names":[],"sources":["../src/kill-tree.ts"],"sourcesContent":["import { spawnSync } from \"node:child_process\";\nimport fs from \"node:fs\";\n\n/**\n * Kills a child's whole process tree. Attached children share their\n * parent's group on POSIX, so there is no group of their own to signal: the\n * process table is walked instead. On Windows it is `taskkill /T /F`.\n * (Moved from clint's process-platform.ts, which re-exports it.)\n */\n\nconst isWindows = process.platform === \"win32\";\n\n/** POSIX: child pids by parent pid, from /proc on Linux, else `ps`. */\nfunction childrenByParent(): Map<number, number[]> {\n const children = new Map<number, number[]>();\n const add = (pid: number, ppid: number) => {\n if (!Number.isInteger(pid) || !Number.isInteger(ppid)) return;\n const list = children.get(ppid);\n if (list) list.push(pid);\n else children.set(ppid, [pid]);\n };\n if (process.platform === \"linux\") {\n let entries: string[] = [];\n try {\n entries = fs.readdirSync(\"/proc\").filter((e) => /^\\d+$/.test(e));\n } catch {\n // no /proc: fall through to ps\n }\n for (const entry of entries) {\n try {\n // \"pid (comm) state ppid ...\": comm may hold spaces and parentheses.\n const stat = fs.readFileSync(`/proc/${entry}/stat`, \"utf8\");\n const fields = stat.slice(stat.lastIndexOf(\")\") + 2).split(\" \");\n add(Number(entry), Number(fields[1]));\n } catch {\n // exited meanwhile\n }\n }\n if (entries.length > 0) return children;\n }\n const ps = spawnSync(\"ps\", [\"-A\", \"-o\", \"pid=,ppid=\"], { encoding: \"utf8\" });\n for (const line of (ps.stdout ?? \"\").split(\"\\n\")) {\n const [pid, ppid] = line.trim().split(/\\s+/).map(Number);\n if (pid !== undefined && ppid !== undefined) add(pid, ppid);\n }\n return children;\n}\n\n/** POSIX: `pid` and all its descendants. */\nfunction treePids(pid: number): number[] {\n const children = childrenByParent();\n const tree = [pid];\n for (let i = 0; i < tree.length; i++) {\n for (const child of children.get(tree[i]!) ?? []) {\n if (!tree.includes(child)) tree.push(child);\n }\n }\n return tree;\n}\n\n/** Kill a supervised child's whole tree. `signal` only applies on POSIX;\n * Windows tree-kill is always forceful (there are no signals to deliver).\n * Never throws: a process already gone is skipped. */\nexport function killTree(\n pid: number,\n signal: NodeJS.Signals = \"SIGTERM\",\n): void {\n if (isWindows) {\n spawnSync(\"taskkill\", [\"/PID\", String(pid), \"/T\", \"/F\"], {\n stdio: \"ignore\",\n windowsHide: true,\n });\n return;\n }\n for (const target of treePids(pid)) {\n try {\n process.kill(target, signal);\n } catch {\n // already gone\n }\n }\n}\n"],"mappings":";;;;;;;;;AAUA,MAAM,YAAY,QAAQ,aAAa;;AAGvC,SAAS,mBAA0C;CACjD,MAAM,2BAAW,IAAI,IAAsB;CAC3C,MAAM,OAAO,KAAa,SAAiB;EACzC,IAAI,CAAC,OAAO,UAAU,GAAG,KAAK,CAAC,OAAO,UAAU,IAAI,GAAG;EACvD,MAAM,OAAO,SAAS,IAAI,IAAI;EAC9B,IAAI,MAAM,KAAK,KAAK,GAAG;OAClB,SAAS,IAAI,MAAM,CAAC,GAAG,CAAC;CAC/B;CACA,IAAI,QAAQ,aAAa,SAAS;EAChC,IAAI,UAAoB,CAAC;EACzB,IAAI;GACF,UAAU,GAAG,YAAY,OAAO,CAAC,CAAC,QAAQ,MAAM,QAAQ,KAAK,CAAC,CAAC;EACjE,QAAQ,CAER;EACA,KAAK,MAAM,SAAS,SA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\";\nimport fs from \"node:fs\";\n\n/**\n * Kills a child's whole process tree. Attached children share their\n * parent's group on POSIX, so there is no group of their own to signal: the\n * process table is walked instead. On Windows it is `taskkill /T /F`.\n * (Moved from clint's process-platform.ts, which re-exports it.)\n */\n\nconst isWindows = process.platform === \"win32\";\n\n/** POSIX: child pids by parent pid, from /proc on Linux, else `ps`. */\nfunction childrenByParent(): Map<number, number[]> {\n const children = new Map<number, number[]>();\n const add = (pid: number, ppid: number) => {\n if (!Number.isInteger(pid) || !Number.isInteger(ppid)) return;\n const list = children.get(ppid);\n if (list) list.push(pid);\n else children.set(ppid, [pid]);\n };\n if (process.platform === \"linux\") {\n let entries: string[] = [];\n try {\n entries = fs.readdirSync(\"/proc\").filter((e) => /^\\d+$/.test(e));\n } catch {\n // no /proc: fall through to ps\n }\n for (const entry of entries) {\n try {\n // \"pid (comm) state ppid ...\": comm may hold spaces and parentheses.\n const stat = fs.readFileSync(`/proc/${entry}/stat`, \"utf8\");\n const fields = stat.slice(stat.lastIndexOf(\")\") + 2).split(\" \");\n add(Number(entry), Number(fields[1]));\n } catch {\n // exited meanwhile\n }\n }\n if (entries.length > 0) return children;\n }\n const ps = spawnSync(\"ps\", [\"-A\", \"-o\", \"pid=,ppid=\"], { encoding: \"utf8\" });\n for (const line of (ps.stdout ?? \"\").split(\"\\n\")) {\n const [pid, ppid] = line.trim().split(/\\s+/).map(Number);\n if (pid !== undefined && ppid !== undefined) add(pid, ppid);\n }\n return children;\n}\n\n/** POSIX: `pid` and all its descendants. */\nexport function treePids(pid: number): number[] {\n const children = childrenByParent();\n const tree = [pid];\n for (let i = 0; i < tree.length; i++) {\n for (const child of children.get(tree[i]!) ?? []) {\n if (!tree.includes(child)) tree.push(child);\n }\n }\n return tree;\n}\n\n/** Kill a supervised child's whole tree. `signal` only applies on POSIX;\n * Windows tree-kill is always forceful (there are no signals to deliver).\n * Never throws: a process already gone is skipped. */\nexport function killTree(\n pid: number,\n signal: NodeJS.Signals = \"SIGTERM\",\n): void {\n if (isWindows) {\n spawnSync(\"taskkill\", [\"/PID\", String(pid), \"/T\", \"/F\"], {\n stdio: \"ignore\",\n windowsHide: true,\n });\n return;\n }\n for (const target of treePids(pid)) {\n try {\n process.kill(target, signal);\n } catch {\n // already gone\n }\n }\n}\n"],"mappings":";;;;;;;;;AAUA,MAAM,YAAY,QAAQ,aAAa;;AAGvC,SAAS,mBAA0C;CACjD,MAAM,2BAAW,IAAI,IAAsB;CAC3C,MAAM,OAAO,KAAa,SAAiB;EACzC,IAAI,CAAC,OAAO,UAAU,GAAG,KAAK,CAAC,OAAO,UAAU,IAAI,GAAG;EACvD,MAAM,OAAO,SAAS,IAAI,IAAI;EAC9B,IAAI,MAAM,KAAK,KAAK,GAAG;OAClB,SAAS,IAAI,MAAM,CAAC,GAAG,CAAC;CAC/B;CACA,IAAI,QAAQ,aAAa,SAAS;EAChC,IAAI,UAAoB,CAAC;EACzB,IAAI;GACF,UAAU,GAAG,YAAY,OAAO,CAAC,CAAC,QAAQ,MAAM,QAAQ,KAAK,CAAC,CAAC;EACjE,QAAQ,CAER;EACA,KAAK,MAAM,SAAS,SAClB,IAAI;GAEF,MAAM,OAAO,GAAG,aAAa,SAAS,MAAM,QAAQ,MAAM;GAC1D,MAAM,SAAS,KAAK,MAAM,KAAK,YAAY,GAAG,IAAI,CAAC,CAAC,CAAC,MAAM,GAAG;GAC9D,IAAI,OAAO,KAAK,GAAG,OAAO,OAAO,EAAE,CAAC;EACtC,QAAQ,CAER;EAEF,IAAI,QAAQ,SAAS,GAAG,OAAO;CACjC;CACA,MAAM,KAAK,UAAU,MAAM;EAAC;EAAM;EAAM;CAAY,GAAG,EAAE,UAAU,OAAO,CAAC;CAC3E,KAAK,MAAM,SAAS,GAAG,UAAU,GAAA,CAAI,MAAM,IAAI,GAAG;EAChD,MAAM,CAAC,KAAK,QAAQ,KAAK,KAAK,CAAC,CAAC,MAAM,KAAK,CAAC,CAAC,IAAI,MAAM;EACvD,IAAI,QAAQ,KAAA,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