@powerhousedao/host-core 6.4.0-next.2 → 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.
- package/dist/{compound-L62ALvYc.d.mts → compound-BLhEewO6.d.mts} +8 -2
- package/dist/compound-BLhEewO6.d.mts.map +1 -0
- package/dist/{compound-Q9sZSEZF.mjs → compound-g6x_KkWp.mjs} +133 -1208
- package/dist/compound-g6x_KkWp.mjs.map +1 -0
- package/dist/control-channel-DVn4dvfQ.d.mts +206 -0
- package/dist/control-channel-DVn4dvfQ.d.mts.map +1 -0
- package/dist/control-channel.d.mts +2 -2
- package/dist/control-channel.mjs +358 -47
- package/dist/control-channel.mjs.map +1 -1
- package/dist/host-entry-B8n_590_.mjs +188 -0
- package/dist/host-entry-B8n_590_.mjs.map +1 -0
- package/dist/index.d.mts +68 -102
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +6 -3
- package/dist/index.mjs.map +1 -1
- package/dist/instance-C6uugZ32.d.mts +165 -0
- package/dist/instance-C6uugZ32.d.mts.map +1 -0
- package/dist/instance.d.mts +3 -0
- package/dist/instance.mjs +145 -0
- package/dist/instance.mjs.map +1 -0
- package/dist/kill-tree.d.mts +2 -0
- package/dist/kill-tree.d.mts.map +1 -1
- package/dist/kill-tree.mjs +1 -1
- package/dist/kill-tree.mjs.map +1 -1
- package/dist/run-record-C6oTZF_C.mjs +1077 -0
- package/dist/run-record-C6oTZF_C.mjs.map +1 -0
- package/dist/runners/compound.d.mts +1 -1
- package/dist/runners/compound.mjs +2 -1
- package/dist/runners/compound.mjs.map +1 -1
- package/dist/spawn-host-DWroRe1S.d.mts +107 -0
- package/dist/spawn-host-DWroRe1S.d.mts.map +1 -0
- package/dist/supervisor-record.d.mts +88 -0
- package/dist/supervisor-record.d.mts.map +1 -0
- package/dist/supervisor-record.mjs +127 -0
- package/dist/supervisor-record.mjs.map +1 -0
- package/dist/supervisor.d.mts +205 -0
- package/dist/supervisor.d.mts.map +1 -0
- package/dist/supervisor.mjs +905 -0
- package/dist/supervisor.mjs.map +1 -0
- package/package.json +21 -3
- package/dist/compound-L62ALvYc.d.mts.map +0 -1
- package/dist/compound-Q9sZSEZF.mjs.map +0 -1
- package/dist/control-channel-eqvyUF03.d.mts +0 -123
- package/dist/control-channel-eqvyUF03.d.mts.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"control-channel.mjs","names":[],"sources":["../src/control-channel.ts"],"sourcesContent":["import crypto from \"node:crypto\";\nimport fs from \"node:fs\";\nimport net from \"node:net\";\nimport os from \"node:os\";\nimport path from \"node:path\";\nimport { z } from \"zod\";\nimport type { RunRecord } from \"./run-record-schema.js\";\n\n/**\n * The control channel of a process that keeps running (a serving Cli, a\n * compound with one): a local stream other processes of the same OS user\n * send requests to, so a command typed in a second terminal acts on what\n * runs in the first. A named pipe on Windows, a socket file elsewhere. Its\n * address and token are in the process's run record (`extra.control`).\n *\n * Same user only. Elsewhere the socket is mode 0600 in a 0700 folder of the\n * user. On Windows the pipe's default access lets only its creator,\n * administrators and the system write to it; everyone may open it to read,\n * so the server sends nothing before a request that carries the token.\n *\n * One request and one answer per line, as JSON:\n * `{ protocol, id, token, method, params }` and\n * `{ id, ok: true, result }` or `{ id, ok: false, error: { code, message } }`.\n */\n\nexport const CONTROL_PROTOCOL = 1;\n\n/** A run record's `extra.control`. */\nexport const controlRecordSchema = z.object({\n protocol: z.number().int(),\n address: z.string().min(1),\n token: z.string().min(1),\n});\nexport type ControlRecord = z.infer<typeof controlRecordSchema>;\n\nexport type ControlErrorCode =\n | \"unauthorized\"\n | \"protocol\"\n | \"bad-request\"\n | \"unknown-method\"\n | \"failed\"\n | \"unreachable\";\n\nexport class ControlError extends Error {\n constructor(\n readonly code: ControlErrorCode,\n message: string,\n ) {\n super(message);\n this.name = \"ControlError\";\n }\n}\n\nexport type ControlHandler = (params: unknown) => unknown;\n\nexport interface ControlChannel {\n /** What the run record holds. */\n readonly record: ControlRecord;\n /** Answers `method` from now on (replacing an earlier handler). */\n handle(method: string, handler: ControlHandler): void;\n /** Added to the answer to `hello`. */\n describe(info: Record<string, unknown>): void;\n close(): Promise<void>;\n}\n\nexport interface OpenControlChannelOptions {\n /** The folder of the socket file (not on Windows). Default: a folder of\n * the user under the system's temporary folder. */\n socketDir?: string;\n}\n\nconst MAX_LINE_BYTES = 1024 * 1024;\n\n/** The control channel a live run of this record answers on, when it has\n * one of a protocol this version speaks. */\nexport function controlRecordOf(\n record: Pick<RunRecord, \"extra\"> | undefined,\n): ControlRecord | undefined {\n const parsed = controlRecordSchema.safeParse(record?.extra?.control);\n if (!parsed.success || parsed.data.protocol !== CONTROL_PROTOCOL) {\n return undefined;\n }\n return parsed.data;\n}\n\nfunction sameToken(given: unknown, token: string): boolean {\n if (typeof given !== \"string\") return false;\n const a = Buffer.from(given);\n const b = Buffer.from(token);\n return a.length === b.length && crypto.timingSafeEqual(a, b);\n}\n\n/** The user's folder for socket files: theirs alone, or none. */\nfunction userSocketDir(given?: string): string {\n const uid = process.getuid?.() ?? 0;\n const dir = given ?? path.join(os.tmpdir(), `ph-control-${uid}`);\n fs.mkdirSync(dir, { recursive: true, mode: 0o700 });\n const stat = fs.lstatSync(dir);\n if (!stat.isDirectory() || stat.uid !== uid) {\n throw new Error(`${dir} is not a folder of this user.`);\n }\n if ((stat.mode & 0o077) !== 0) fs.chmodSync(dir, 0o700);\n return dir;\n}\n\n/** Socket files whose process is gone (it was killed). */\nfunction sweepSockets(dir: string): void {\n for (const name of fs.readdirSync(dir)) {\n const pid = Number(/^(\\d+)-[\\da-f]+\\.sock$/.exec(name)?.[1]);\n if (!Number.isInteger(pid) || pid === process.pid) continue;\n try {\n process.kill(pid, 0);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ESRCH\") continue;\n fs.rmSync(path.join(dir, name), { force: true });\n }\n }\n}\n\nfunction listen(server: net.Server, address: string): Promise<void> {\n return new Promise((resolve, reject) => {\n server.once(\"error\", reject);\n server.listen(address, () => {\n server.off(\"error\", reject);\n resolve();\n });\n });\n}\n\n/**\n * Opens a control channel for this process and resolves once it listens.\n * The server holds no process open. `hello` is answered by the channel\n * itself: `{ protocol, pid, mode: \"ad hoc\", methods }` and what `describe`\n * added.\n */\nexport async function openControlChannel(\n options: OpenControlChannelOptions = {},\n): Promise<ControlChannel> {\n const token = crypto.randomBytes(32).toString(\"base64url\");\n const name = `${process.pid}-${crypto.randomBytes(8).toString(\"hex\")}`;\n const handlers = new Map<string, ControlHandler>();\n let description: Record<string, unknown> = {};\n handlers.set(\"hello\", () => ({\n ...description,\n protocol: CONTROL_PROTOCOL,\n pid: process.pid,\n mode: \"ad hoc\",\n methods: [...handlers.keys()],\n }));\n\n const answer = async (line: string): Promise<Record<string, unknown>> => {\n let request: Record<string, unknown>;\n try {\n const parsed: unknown = JSON.parse(line);\n if (typeof parsed !== \"object\" || parsed === null) throw new Error();\n request = parsed as Record<string, unknown>;\n } catch {\n return refusal(undefined, \"bad-request\", \"The request is not JSON.\");\n }\n const { id } = request;\n // Before anything else: nothing is said to a caller without the token.\n if (!sameToken(request.token, token)) {\n return refusal(id, \"unauthorized\", \"The token is missing or wrong.\");\n }\n if (request.protocol !== CONTROL_PROTOCOL) {\n return refusal(\n id,\n \"protocol\",\n `This process speaks control protocol ${CONTROL_PROTOCOL}, not ${JSON.stringify(request.protocol)}.`,\n );\n }\n const handler =\n typeof request.method === \"string\"\n ? handlers.get(request.method)\n : undefined;\n if (!handler) {\n return refusal(\n id,\n \"unknown-method\",\n `Nothing here answers \"${String(request.method)}\".`,\n );\n }\n try {\n return { id, ok: true, result: (await handler(request.params)) ?? null };\n } catch (error) {\n return refusal(\n id,\n \"failed\",\n error instanceof Error ? error.message : String(error),\n );\n }\n };\n\n const sockets = new Set<net.Socket>();\n const server = net.createServer((socket) => {\n sockets.add(socket);\n socket.once(\"close\", () => sockets.delete(socket));\n socket.on(\"error\", () => undefined);\n socket.setEncoding(\"utf8\");\n let pending = \"\";\n let queue = Promise.resolve();\n socket.on(\"data\", (chunk: string) => {\n pending += chunk;\n if (pending.length > MAX_LINE_BYTES) {\n socket.destroy();\n return;\n }\n for (;;) {\n const end = pending.indexOf(\"\\n\");\n if (end === -1) break;\n const line = pending.slice(0, end);\n pending = pending.slice(end + 1);\n if (line.trim() === \"\") continue;\n queue = queue.then(async () => {\n const response = await answer(line);\n if (socket.destroyed) return;\n const refused =\n response.ok === false &&\n (response.error as { code: string }).code === \"unauthorized\";\n const text = `${JSON.stringify(response)}\\n`;\n if (refused) socket.end(text);\n else socket.write(text);\n });\n }\n });\n });\n server.on(\"error\", () => undefined);\n\n let address: string;\n let socketFile: string | undefined;\n if (process.platform === \"win32\") {\n address = `\\\\\\\\.\\\\pipe\\\\ph-control-${name}`;\n await listen(server, address);\n } else {\n const dir = userSocketDir(options.socketDir);\n sweepSockets(dir);\n address = socketFile = path.join(dir, `${name}.sock`);\n // The file is the user's from the moment it exists.\n let umask: number | undefined;\n try {\n umask = process.umask(0o177);\n } catch {\n // a worker thread has no umask of its own; the folder is the user's\n }\n try {\n await listen(server, address);\n } finally {\n if (umask !== undefined) process.umask(umask);\n }\n fs.chmodSync(address, 0o600);\n }\n server.unref();\n\n const removeSocket = () => {\n if (socketFile) fs.rmSync(socketFile, { force: true });\n };\n process.once(\"exit\", removeSocket);\n\n let closing: Promise<void> | undefined;\n return {\n record: { protocol: CONTROL_PROTOCOL, address, token },\n handle(method, handler) {\n handlers.set(method, handler);\n },\n describe(info) {\n description = { ...description, ...info };\n },\n close: () =>\n (closing ??= new Promise<void>((resolve) => {\n process.off(\"exit\", removeSocket);\n for (const socket of sockets) socket.destroy();\n server.close(() => {\n removeSocket();\n resolve();\n });\n })),\n };\n}\n\nfunction refusal(\n id: unknown,\n code: ControlErrorCode,\n message: string,\n): Record<string, unknown> {\n return { id, ok: false, error: { code, message } };\n}\n\n// One channel per process, whichever copy of this module asks: a compound\n// and the Cli in front of it may each have loaded their own.\nconst SLOT = Symbol.for(\"@powerhousedao/host-core/control-channel\");\ntype Slot = { channel?: ControlChannel; opening?: Promise<ControlChannel> };\nconst slot = () =>\n ((globalThis as { [SLOT]?: Slot })[SLOT] ??= {}) satisfies Slot;\n\n/**\n * This process's control channel, opened on the first call. Undefined when\n * it cannot be opened: the process then runs without one, as before.\n */\nexport async function ensureProcessControlChannel(\n options: OpenControlChannelOptions = {},\n): Promise<ControlChannel | undefined> {\n const held = slot();\n if (held.channel) return held.channel;\n held.opening ??= openControlChannel(options);\n try {\n held.channel = await held.opening;\n return held.channel;\n } catch {\n return undefined;\n } finally {\n held.opening = undefined;\n }\n}\n\n/** This process's control channel, when it has opened one. */\nexport function processControlChannel(): ControlChannel | undefined {\n return slot().channel;\n}\n\n/** Closes this process's control channel, if it has one. */\nexport async function closeProcessControlChannel(): Promise<void> {\n const held = slot();\n const channel = held.channel;\n held.channel = undefined;\n await channel?.close();\n}\n\nexport interface CallControlOptions {\n /** How long the answer may take (default: no limit; the request ends when\n * the other process does). */\n timeoutMs?: number;\n /** How long connecting may take (default 2 s). */\n connectTimeoutMs?: number;\n /** Do not hold this process open for the answer. */\n unref?: boolean;\n}\n\nconst CONNECT_TIMEOUT_MS = 2_000;\n\n/**\n * One request to the control channel a run record names. Resolves with the\n * result; rejects with a {@link ControlError}: `unreachable` when nothing\n * answers there, else the code the other process refused with.\n */\nexport function callControl(\n control: ControlRecord,\n method: string,\n params?: unknown,\n options: CallControlOptions = {},\n): Promise<unknown> {\n return new Promise((resolve, reject) => {\n const socket = net.connect(control.address);\n if (options.unref) socket.unref();\n let settled = false;\n let pending = \"\";\n const timers: NodeJS.Timeout[] = [];\n const settle = (finish: () => void) => {\n if (settled) return;\n settled = true;\n for (const timer of timers) clearTimeout(timer);\n socket.destroy();\n finish();\n };\n const unreachable = (why: string) =>\n settle(() => reject(new ControlError(\"unreachable\", why)));\n const limit = (ms: number, why: string) => {\n const timer = setTimeout(() => unreachable(why), ms);\n if (options.unref) timer.unref();\n timers.push(timer);\n return timer;\n };\n const connecting = limit(\n options.connectTimeoutMs ?? CONNECT_TIMEOUT_MS,\n `No answer at the control channel ${control.address}.`,\n );\n socket.setEncoding(\"utf8\");\n socket.once(\"connect\", () => {\n clearTimeout(connecting);\n if (options.timeoutMs !== undefined) {\n limit(\n options.timeoutMs,\n `\"${method}\" was not answered within ${options.timeoutMs} ms.`,\n );\n }\n socket.write(\n `${JSON.stringify({\n protocol: CONTROL_PROTOCOL,\n id: 1,\n token: control.token,\n method,\n ...(params === undefined ? {} : { params }),\n })}\\n`,\n );\n });\n socket.on(\"data\", (chunk: string) => {\n pending += chunk;\n const end = pending.indexOf(\"\\n\");\n if (end === -1) return;\n let response: {\n ok?: unknown;\n result?: unknown;\n error?: { code?: ControlErrorCode; message?: string };\n };\n try {\n response = JSON.parse(pending.slice(0, end)) as typeof response;\n } catch {\n unreachable(`The control channel ${control.address} answered no JSON.`);\n return;\n }\n if (response.ok === true) {\n settle(() => resolve(response.result));\n return;\n }\n settle(() =>\n reject(\n new ControlError(\n response.error?.code ?? \"failed\",\n response.error?.message ?? `\"${method}\" failed.`,\n ),\n ),\n );\n });\n socket.once(\"error\", (error) =>\n unreachable(\n `Cannot reach the control channel ${control.address}: ${error.message}`,\n ),\n );\n socket.once(\"close\", () =>\n unreachable(\n `The process behind the control channel ${control.address} went away before it answered \"${method}\".`,\n ),\n );\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAyBA,MAAa,mBAAmB;;AAGhC,MAAa,sBAAsB,EAAE,OAAO;CAC1C,UAAU,EAAE,OAAO,CAAC,CAAC,IAAI;CACzB,SAAS,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC;CACzB,OAAO,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC;AACzB,CAAC;AAWD,IAAa,eAAb,cAAkC,MAAM;CAE3B;CADX,YACE,MACA,SACA;EACA,MAAM,OAAO;EAHJ,KAAA,OAAA;EAIT,KAAK,OAAO;CACd;AACF;AAoBA,MAAM,iBAAi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AI;IACF,WAAW,KAAK,MAAM,QAAQ,MAAM,GAAG,GAAG,CAAC;GAC7C,QAAQ;IACN,YAAY,uBAAuB,QAAQ,QAAQ,mBAAmB;IACtE;GACF;GACA,IAAI,SAAS,OAAO,MAAM;IACxB,aAAa,QAAQ,SAAS,MAAM,CAAC;IACrC;GACF;GACA,aACE,OACE,IAAI,aACF,SAAS,OAAO,QAAQ,UACxB,SAAS,OAAO,WAAW,IAAI,OAAO,UACxC,CACF,CACF;EACF,CAAC;EACD,OAAO,KAAK,UAAU,UACpB,YACE,oCAAoC,QAAQ,QAAQ,IAAI,MAAM,SAChE,CACF;EACA,OAAO,KAAK,eACV,YACE,0CAA0C,QAAQ,QAAQ,iCAAiC,OAAO,GACpG,CACF;CACF,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"control-channel.mjs","names":[],"sources":["../src/control-channel.ts"],"sourcesContent":["import { execFile } from \"node:child_process\";\nimport crypto from \"node:crypto\";\nimport fs from \"node:fs\";\nimport net from \"node:net\";\nimport os from \"node:os\";\nimport path from \"node:path\";\nimport { z } from \"zod\";\nimport type { RunRecord } from \"./run-record-schema.js\";\n\n/**\n * The control channel of a process that keeps running (a serving Cli, a\n * compound with one): a local stream other processes of the same OS user\n * send requests to, so a command typed in a second terminal acts on what\n * runs in the first. A named pipe on Windows, a socket file elsewhere. Its\n * address and token are in the process's run record (`extra.control`).\n *\n * Same user only. Elsewhere the socket is mode 0600 in a 0700 folder of the\n * user. On Windows the pipe's access list is replaced once it listens: the\n * user alone, and no caller from the network ({@link ControlChannel.ownerOnly}\n * says whether that took). Until then, and when it did not take, the pipe has\n * the system's default list: only its creator, administrators and the system\n * write to it, everyone may open it to read. So the server sends nothing\n * before a request that carries the token, and drops a caller that sends\n * none in time.\n *\n * One JSON value per line. A request is\n * `{ protocol, id, token, method, params }`. Its answer ends with\n * `{ id, ok: true, result }` or `{ id, ok: false, error: { code, message } }`;\n * before that a handler may send output as it is produced:\n * `{ id, stream: \"stdout\" | \"stderr\", data }`, in the order it was written.\n * `{ protocol, id, token, cancel: true }` cancels the request `id` of the\n * same connection, and so does the end of the connection.\n *\n * A caller that can answer questions while its request runs lists their\n * kinds in the request, `asks: [kind, ...]`. The handler may then ask one:\n * `{ id, ask: { seq, kind, payload } }`, and the caller answers on the same\n * connection with `{ protocol, id, token, answer: { seq, ok: true, result } }`\n * or `{ ..., answer: { seq, ok: false, error: { code, message } } }`. An\n * answer is taken at once, not behind the request it answers.\n */\n\n/** 2: output frames, `cancel`, and asks for the kinds a request lists. A\n * caller and a process of different protocols refuse each other, each naming\n * both. */\nexport const CONTROL_PROTOCOL = 2;\n\n/** How long an ask waits for its answer unless told otherwise. */\nexport const ASK_TIMEOUT_MS = 10 * 60_000;\n\n/** A run record's `extra.control`. */\nexport const controlRecordSchema = z.object({\n protocol: z.number().int(),\n address: z.string().min(1),\n token: z.string().min(1),\n});\nexport type ControlRecord = z.infer<typeof controlRecordSchema>;\n\nexport type ControlErrorCode =\n | \"unauthorized\"\n | \"protocol\"\n | \"bad-request\"\n | \"unknown-method\"\n | \"failed\"\n | \"cancelled\"\n | \"unreachable\"\n /** The caller does not answer asks of this kind. */\n | \"unsupported\"\n /** The caller would not answer: what it said is the message. */\n | \"refused\"\n /** The caller did not answer in time. */\n | \"timeout\";\n\nconst ERROR_CODES: ReadonlySet<string> = new Set<ControlErrorCode>([\n \"unauthorized\",\n \"protocol\",\n \"bad-request\",\n \"unknown-method\",\n \"failed\",\n \"cancelled\",\n \"unreachable\",\n \"unsupported\",\n \"refused\",\n \"timeout\",\n]);\n\n/** `code` when it is one of ours, else `failed`. */\nfunction errorCodeOf(code: unknown): ControlErrorCode {\n return typeof code === \"string\" && ERROR_CODES.has(code)\n ? (code as ControlErrorCode)\n : \"failed\";\n}\n\nexport class ControlError extends Error {\n constructor(\n readonly code: ControlErrorCode,\n message: string,\n ) {\n super(message);\n this.name = \"ControlError\";\n }\n}\n\nexport type ControlStream = \"stdout\" | \"stderr\";\n\n/** One request, as its handler sees it. */\nexport interface ControlCall {\n /** Aborted when the caller cancels, or goes away. */\n readonly signal: AbortSignal;\n /** Sends output to the caller now. Nothing is sent once the request is\n * cancelled. */\n write(stream: ControlStream, data: string): void;\n /** The kinds of ask the caller answers (its request's `asks`). */\n readonly asks: ReadonlySet<string>;\n /**\n * Asks the caller and resolves with its answer. Rejects with a\n * {@link ControlError}: `unsupported` for a kind the caller did not list,\n * the code the caller refused with, `cancelled` when the request ends\n * first, `timeout` after `timeoutMs` (default {@link ASK_TIMEOUT_MS}).\n */\n ask(\n kind: string,\n payload?: unknown,\n options?: { timeoutMs?: number },\n ): Promise<unknown>;\n}\n\n/** A question a handler asked and the caller has not answered yet. */\ninterface PendingAsk {\n resolve(result: unknown): void;\n reject(error: ControlError): void;\n}\n\n/** A request of a connection that has not ended. */\ninterface RunningRequest {\n controller: AbortController;\n asks: Map<number, PendingAsk>;\n}\n\nexport type ControlHandler = (params: unknown, call: ControlCall) => unknown;\n\nexport interface ControlChannel {\n /** What the run record holds. */\n readonly record: ControlRecord;\n /** Whether the system lets this user alone open the channel: the socket\n * file's mode, or on Windows the pipe's access list once it was replaced.\n * False: the token is what keeps other users out. */\n readonly ownerOnly: boolean;\n /** Answers `method` from now on (replacing an earlier handler). */\n handle(method: string, handler: ControlHandler): void;\n /** Added to the answer to `hello`. */\n describe(info: Record<string, unknown>): void;\n close(): Promise<void>;\n}\n\nexport interface OpenControlChannelOptions {\n /** The folder of the socket file (not on Windows). Default: a folder of\n * the user under the system's temporary folder. */\n socketDir?: string;\n /** How long a caller may take to send its first request (default 5 s). */\n handshakeTimeoutMs?: number;\n /** What `hello` answers as `mode` (default \"ad hoc\": the process\n * supervises what it started itself). A supervisor names its own. */\n mode?: string;\n}\n\n/** The longest request line, and the longest line of output. */\nexport const MAX_LINE_BYTES = 1024 * 1024;\nconst MAX_FRAME_CHARS = 64 * 1024;\nconst HANDSHAKE_TIMEOUT_MS = 5_000;\nconst MAX_CONNECTIONS = 64;\n\n/** The control channel a live run of this record answers on, when it has\n * one of a protocol this version speaks. */\nexport function controlRecordOf(\n record: Pick<RunRecord, \"extra\"> | undefined,\n): ControlRecord | undefined {\n const parsed = controlRecordSchema.safeParse(record?.extra?.control);\n if (!parsed.success || parsed.data.protocol !== CONTROL_PROTOCOL) {\n return undefined;\n }\n return parsed.data;\n}\n\n/** The protocol of the control channel a record names, whichever it is. */\nexport function controlProtocolOf(\n record: Pick<RunRecord, \"extra\"> | undefined,\n): number | undefined {\n const parsed = controlRecordSchema.safeParse(record?.extra?.control);\n return parsed.success ? parsed.data.protocol : undefined;\n}\n\n/** What a caller of one protocol is told about a process of another. */\nexport function protocolMismatch(theirs: unknown): string {\n return `It speaks control protocol ${JSON.stringify(theirs)}, this process speaks ${CONTROL_PROTOCOL}: both must run the same version.`;\n}\n\nfunction sameToken(given: unknown, token: string): boolean {\n if (typeof given !== \"string\") return false;\n const a = Buffer.from(given);\n const b = Buffer.from(token);\n return a.length === b.length && crypto.timingSafeEqual(a, b);\n}\n\n/** The user's folder for socket files: theirs alone, or none. */\nfunction userSocketDir(given?: string): string {\n const uid = process.getuid?.() ?? 0;\n const dir = given ?? path.join(os.tmpdir(), `ph-control-${uid}`);\n fs.mkdirSync(dir, { recursive: true, mode: 0o700 });\n const stat = fs.lstatSync(dir);\n if (!stat.isDirectory() || stat.uid !== uid) {\n throw new Error(`${dir} is not a folder of this user.`);\n }\n if ((stat.mode & 0o077) !== 0) fs.chmodSync(dir, 0o700);\n return dir;\n}\n\n/** Socket files whose process is gone (it was killed). */\nfunction sweepSockets(dir: string): void {\n for (const name of fs.readdirSync(dir)) {\n const pid = Number(/^(\\d+)-[\\da-f]+\\.sock$/.exec(name)?.[1]);\n if (!Number.isInteger(pid) || pid === process.pid) continue;\n try {\n process.kill(pid, 0);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ESRCH\") continue;\n fs.rmSync(path.join(dir, name), { force: true });\n }\n }\n}\n\nfunction listen(server: net.Server, address: string): Promise<void> {\n return new Promise((resolve, reject) => {\n server.once(\"error\", reject);\n server.listen(address, () => {\n server.off(\"error\", reject);\n resolve();\n });\n });\n}\n\n/** Windows PowerShell, by its own path: never one found through PATH. */\nfunction windowsPowerShell(): string {\n return path.join(\n process.env.SystemRoot ?? \"C:\\\\Windows\",\n \"System32\",\n \"WindowsPowerShell\",\n \"v1.0\",\n \"powershell.exe\",\n );\n}\n\n/** `$pipe`: the pipe `name`, opened with `rights`. */\nconst openPipe = (name: string, rights: string) =>\n `$pipe = New-Object System.IO.Pipes.NamedPipeClientStream('.', '${name}', ` +\n `[System.IO.Pipes.PipeAccessRights]'${rights}', [System.IO.Pipes.PipeOptions]::None, ` +\n \"[System.Security.Principal.TokenImpersonationLevel]::None, [System.IO.HandleInheritability]::None); \" +\n \"$pipe.Connect(2000); \";\n\nfunction powerShell(script: string): Promise<string | undefined> {\n return new Promise((resolve) => {\n execFile(\n windowsPowerShell(),\n [\"-NoProfile\", \"-NonInteractive\", \"-Command\", script],\n { windowsHide: true, timeout: 15_000, encoding: \"utf8\" },\n (error, stdout) => resolve(error ? undefined : stdout.trim()),\n );\n });\n}\n\n/**\n * The access list (SDDL) of the pipe `name` (as in `\\\\.\\pipe\\<name>`);\n * undefined when it cannot be read. Windows only.\n */\nexport function pipeAccessList(name: string): Promise<string | undefined> {\n return powerShell(\n \"$ErrorActionPreference = 'Stop'; \" +\n openPipe(name, \"ReadData, ReadPermissions\") +\n \"try { $pipe.GetAccessControl().GetSecurityDescriptorSddlForm('Access') } finally { $pipe.Dispose() }\",\n );\n}\n\n/** The access list a control pipe gets: no caller from the network, and the\n * user `sid` alone. */\nexport const ownerOnlyPipeAccess = (sid: string) =>\n `D:P(D;;FA;;;NU)(A;;FA;;;${sid})`;\n\n/**\n * Replaces the access list of this process's pipe `name` with\n * {@link ownerOnlyPipeAccess}. Node creates a pipe with the system's default\n * list and has no call to set another, so a helper process of the same user\n * does it (.NET's PipeSecurity through Windows PowerShell). Resolves false\n * when that failed: the pipe keeps the default list.\n */\nasync function restrictPipe(name: string): Promise<boolean> {\n const done = await powerShell(\n \"$ErrorActionPreference = 'Stop'; \" +\n \"$sid = [System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value; \" +\n openPipe(name, \"ReadData, ReadPermissions, ChangePermissions\") +\n \"try { $security = New-Object System.IO.Pipes.PipeSecurity; \" +\n `$security.SetSecurityDescriptorSddlForm('${ownerOnlyPipeAccess(\"' + $sid + '\")}', 'Access'); ` +\n \"$pipe.SetAccessControl($security); 'restricted' } finally { $pipe.Dispose() }\",\n );\n return done === \"restricted\";\n}\n\n/**\n * Opens a control channel for this process and resolves once it listens.\n * The server holds no process open. `hello` is answered by the channel\n * itself: `{ protocol, pid, mode, methods }` and what `describe` added.\n */\nexport async function openControlChannel(\n options: OpenControlChannelOptions = {},\n): Promise<ControlChannel> {\n const token = crypto.randomBytes(32).toString(\"base64url\");\n const name = `${process.pid}-${crypto.randomBytes(8).toString(\"hex\")}`;\n const handlers = new Map<string, ControlHandler>();\n let description: Record<string, unknown> = {};\n handlers.set(\"hello\", () => ({\n ...description,\n protocol: CONTROL_PROTOCOL,\n pid: process.pid,\n mode: options.mode ?? \"ad hoc\",\n methods: [...handlers.keys()],\n }));\n\n /** The request a line holds, or the refusal it gets. */\n const read = (\n line: string,\n ):\n | { request: Record<string, unknown> }\n | { refused: Record<string, unknown> } => {\n let request: Record<string, unknown>;\n try {\n const parsed: unknown = JSON.parse(line);\n if (typeof parsed !== \"object\" || parsed === null) throw new Error();\n request = parsed as Record<string, unknown>;\n } catch {\n return {\n refused: refusal(undefined, \"bad-request\", \"The request is not JSON.\"),\n };\n }\n const { id } = request;\n // Before anything else: nothing is said to a caller without the token.\n if (!sameToken(request.token, token)) {\n return {\n refused: refusal(id, \"unauthorized\", \"The token is missing or wrong.\"),\n };\n }\n if (request.protocol !== CONTROL_PROTOCOL) {\n return {\n refused: refusal(\n id,\n \"protocol\",\n `This process speaks control protocol ${CONTROL_PROTOCOL}, the request is of protocol ${JSON.stringify(request.protocol)}: both must run the same version.`,\n ),\n };\n }\n return { request };\n };\n\n const answer = async (\n request: Record<string, unknown>,\n call: ControlCall,\n ): Promise<Record<string, unknown>> => {\n const { id } = request;\n const handler =\n typeof request.method === \"string\"\n ? handlers.get(request.method)\n : undefined;\n if (!handler) {\n return refusal(\n id,\n \"unknown-method\",\n `Nothing here answers \"${String(request.method)}\".`,\n );\n }\n try {\n return {\n id,\n ok: true,\n result: (await handler(request.params, call)) ?? null,\n };\n } catch (error) {\n return refusal(\n id,\n call.signal.aborted ? \"cancelled\" : \"failed\",\n error instanceof Error ? error.message : String(error),\n );\n }\n };\n\n const sockets = new Set<net.Socket>();\n const server = net.createServer((socket) => {\n sockets.add(socket);\n // The requests of this connection that have not ended, by id.\n const running = new Map<unknown, RunningRequest>();\n // A caller that sends nothing holds a connection for this long.\n let handshake: NodeJS.Timeout | undefined = setTimeout(\n () => socket.destroy(),\n options.handshakeTimeoutMs ?? HANDSHAKE_TIMEOUT_MS,\n );\n handshake.unref();\n socket.once(\"close\", () => {\n sockets.delete(socket);\n clearTimeout(handshake);\n for (const { controller } of running.values()) controller.abort();\n });\n socket.on(\"error\", () => undefined);\n socket.setEncoding(\"utf8\");\n let pending = \"\";\n let dropped = false;\n let queue = Promise.resolve();\n const send = (value: Record<string, unknown>, end = false) => {\n if (socket.destroyed) return;\n const text = `${JSON.stringify(value)}\\n`;\n if (end) socket.end(text);\n else socket.write(text);\n };\n const take = (line: string) => {\n if (dropped) return;\n const parsed = read(line);\n if (\"refused\" in parsed) {\n // A caller without the token is answered once, and not heard again.\n const { error } = parsed.refused as { error: { code: string } };\n dropped = error.code !== \"protocol\";\n queue = queue.then(() => send(parsed.refused, dropped));\n return;\n }\n clearTimeout(handshake);\n handshake = undefined;\n const { request } = parsed;\n const { id } = request;\n // Not behind the request it cancels.\n if (request.cancel === true) {\n running.get(id)?.controller.abort();\n return;\n }\n // Nor behind the request it answers: that one waits for it.\n if (\"answer\" in request) {\n settleAsk(running.get(id), request.answer);\n return;\n }\n const controller = new AbortController();\n const asks = new Map<number, PendingAsk>();\n running.set(id, { controller, asks });\n let seq = 0;\n const call: ControlCall = {\n signal: controller.signal,\n write: (stream, data) => {\n if (controller.signal.aborted) return;\n for (let at = 0; at < data.length; at += MAX_FRAME_CHARS) {\n send({ id, stream, data: data.slice(at, at + MAX_FRAME_CHARS) });\n }\n },\n asks: asksOf(request),\n ask: (kind, payload, askOptions = {}) =>\n askCaller(\n { id, kind, payload, seq: ++seq, asks, call, send },\n askOptions.timeoutMs ?? ASK_TIMEOUT_MS,\n ),\n };\n queue = queue.then(async () => {\n const response = controller.signal.aborted\n ? refusal(id, \"cancelled\", \"The request was cancelled.\")\n : await answer(request, call);\n running.delete(id);\n for (const pending of asks.values()) {\n pending.reject(\n new ControlError(\"cancelled\", \"The request ended first.\"),\n );\n }\n asks.clear();\n send(response);\n });\n };\n socket.on(\"data\", (chunk: string) => {\n pending += chunk;\n for (;;) {\n const end = pending.indexOf(\"\\n\");\n if (end === -1) break;\n const line = pending.slice(0, end);\n pending = pending.slice(end + 1);\n if (line.trim() === \"\") continue;\n if (Buffer.byteLength(line) > MAX_LINE_BYTES) {\n socket.destroy();\n return;\n }\n take(line);\n }\n if (Buffer.byteLength(pending) > MAX_LINE_BYTES) socket.destroy();\n });\n });\n server.maxConnections = MAX_CONNECTIONS;\n server.on(\"error\", () => undefined);\n\n let address: string;\n let socketFile: string | undefined;\n let ownerOnly: boolean;\n if (process.platform === \"win32\") {\n address = `\\\\\\\\.\\\\pipe\\\\ph-control-${name}`;\n await listen(server, address);\n ownerOnly = await restrictPipe(`ph-control-${name}`);\n } else {\n const dir = userSocketDir(options.socketDir);\n sweepSockets(dir);\n address = socketFile = path.join(dir, `${name}.sock`);\n // The file is the user's from the moment it exists.\n let umask: number | undefined;\n try {\n umask = process.umask(0o177);\n } catch {\n // a worker thread has no umask of its own; the folder is the user's\n }\n try {\n await listen(server, address);\n } finally {\n if (umask !== undefined) process.umask(umask);\n }\n fs.chmodSync(address, 0o600);\n ownerOnly = true;\n }\n server.unref();\n\n const removeSocket = () => {\n if (socketFile) fs.rmSync(socketFile, { force: true });\n };\n process.once(\"exit\", removeSocket);\n\n let closing: Promise<void> | undefined;\n return {\n record: { protocol: CONTROL_PROTOCOL, address, token },\n ownerOnly,\n handle(method, handler) {\n handlers.set(method, handler);\n },\n describe(info) {\n description = { ...description, ...info };\n },\n close: () =>\n (closing ??= new Promise<void>((resolve) => {\n process.off(\"exit\", removeSocket);\n for (const socket of sockets) socket.destroy();\n server.close(() => {\n removeSocket();\n resolve();\n });\n })),\n };\n}\n\nfunction refusal(\n id: unknown,\n code: ControlErrorCode,\n message: string,\n): Record<string, unknown> {\n return { id, ok: false, error: { code, message } };\n}\n\n/** The kinds of ask a request says its caller answers. */\nfunction asksOf(request: Record<string, unknown>): ReadonlySet<string> {\n const { asks } = request;\n return new Set(\n Array.isArray(asks)\n ? asks.filter((kind): kind is string => typeof kind === \"string\")\n : [],\n );\n}\n\n/** Settles the ask an answer line names; one that names none is dropped. */\nfunction settleAsk(request: RunningRequest | undefined, answer: unknown): void {\n if (!request || typeof answer !== \"object\" || answer === null) return;\n const { seq, ok, result, error } = answer as {\n seq?: unknown;\n ok?: unknown;\n result?: unknown;\n error?: { code?: unknown; message?: unknown };\n };\n if (typeof seq !== \"number\") return;\n const pending = request.asks.get(seq);\n if (!pending) return;\n request.asks.delete(seq);\n if (ok === true) {\n pending.resolve(result);\n return;\n }\n pending.reject(\n new ControlError(\n errorCodeOf(error?.code),\n typeof error?.message === \"string\"\n ? error.message\n : \"The caller did not answer.\",\n ),\n );\n}\n\n/** Sends one ask to the caller and waits for its answer. */\nfunction askCaller(\n o: {\n id: unknown;\n kind: string;\n payload: unknown;\n seq: number;\n asks: Map<number, PendingAsk>;\n call: ControlCall;\n send: (value: Record<string, unknown>) => void;\n },\n timeoutMs: number,\n): Promise<unknown> {\n const { id, kind, seq, asks, call } = o;\n if (!call.asks.has(kind)) {\n return Promise.reject(\n new ControlError(\n \"unsupported\",\n `The caller does not answer \"${kind}\": it runs another version.`,\n ),\n );\n }\n if (call.signal.aborted) {\n return Promise.reject(\n new ControlError(\"cancelled\", \"The request was cancelled.\"),\n );\n }\n const frame = { id, ask: { seq, kind, payload: o.payload ?? null } };\n if (Buffer.byteLength(JSON.stringify(frame)) > MAX_LINE_BYTES - 1024) {\n return Promise.reject(\n new ControlError(\n \"bad-request\",\n `\"${kind}\" is too large to ask the caller (${Math.floor(MAX_LINE_BYTES / 1024)} KiB at most).`,\n ),\n );\n }\n return new Promise((resolve, reject) => {\n const done = () => {\n clearTimeout(timer);\n call.signal.removeEventListener(\"abort\", cancelled);\n asks.delete(seq);\n };\n const cancelled = () => {\n done();\n reject(new ControlError(\"cancelled\", \"The request was cancelled.\"));\n };\n const timer = setTimeout(() => {\n done();\n reject(\n new ControlError(\n \"timeout\",\n `The caller did not answer \"${kind}\" within ${Math.round(timeoutMs / 1000)} s.`,\n ),\n );\n }, timeoutMs);\n timer.unref();\n call.signal.addEventListener(\"abort\", cancelled, { once: true });\n asks.set(seq, {\n resolve: (result) => {\n done();\n resolve(result);\n },\n reject: (error) => {\n done();\n reject(error);\n },\n });\n o.send(frame);\n });\n}\n\n// One channel per process, whichever copy of this module asks: a compound\n// and the Cli in front of it may each have loaded their own.\nconst SLOT = Symbol.for(\"@powerhousedao/host-core/control-channel\");\ntype Slot = { channel?: ControlChannel; opening?: Promise<ControlChannel> };\nconst slot = () =>\n ((globalThis as { [SLOT]?: Slot })[SLOT] ??= {}) satisfies Slot;\n\n/**\n * This process's control channel, opened on the first call. Undefined when\n * it cannot be opened: the process then runs without one, as before.\n */\nexport async function ensureProcessControlChannel(\n options: OpenControlChannelOptions = {},\n): Promise<ControlChannel | undefined> {\n const held = slot();\n if (held.channel) return held.channel;\n held.opening ??= openControlChannel(options);\n try {\n held.channel = await held.opening;\n return held.channel;\n } catch {\n return undefined;\n } finally {\n held.opening = undefined;\n }\n}\n\n/** This process's control channel, when it has opened one. */\nexport function processControlChannel(): ControlChannel | undefined {\n return slot().channel;\n}\n\n/** Closes this process's control channel, if it has one. */\nexport async function closeProcessControlChannel(): Promise<void> {\n const held = slot();\n const channel = held.channel;\n held.channel = undefined;\n await channel?.close();\n}\n\nexport interface CallControlOptions {\n /** How long the answer may take (default: no limit; the request ends when\n * the other process does). */\n timeoutMs?: number;\n /** How long connecting may take (default 2 s). */\n connectTimeoutMs?: number;\n /** Do not hold this process open for the answer. */\n unref?: boolean;\n /** Output the other process sends while it works on the request. */\n onOutput?: (stream: ControlStream, data: string) => void;\n /** Cancels the request there; the call then rejects with `cancelled`. */\n signal?: AbortSignal;\n /**\n * Answers what the other process asks while it works on the request, for\n * the kinds in `asks`. Its result is the answer; what it throws is a\n * refusal, with the error's `code` when that is a {@link ControlErrorCode}.\n * `signal` aborts when the request ends.\n */\n onAsk?: (kind: string, payload: unknown, signal: AbortSignal) => unknown;\n /** The kinds `onAsk` answers; sent with the request. */\n asks?: readonly string[];\n}\n\nconst CONNECT_TIMEOUT_MS = 2_000;\n\n/**\n * One request to the control channel a run record names. Resolves with the\n * result; rejects with a {@link ControlError}: `unreachable` when nothing\n * answers there, `protocol` when it speaks another protocol, else the code\n * the other process refused with. A request that is cancelled, or whose\n * caller ends, is cancelled in the other process.\n */\nexport function callControl(\n control: ControlRecord,\n method: string,\n params?: unknown,\n options: CallControlOptions = {},\n): Promise<unknown> {\n if (control.protocol !== CONTROL_PROTOCOL) {\n return Promise.reject(\n new ControlError(\n \"protocol\",\n `Cannot ask the process at ${control.address} for \"${method}\". ${protocolMismatch(control.protocol)}`,\n ),\n );\n }\n const { signal } = options;\n if (signal?.aborted) {\n return Promise.reject(\n new ControlError(\"cancelled\", `\"${method}\" was cancelled.`),\n );\n }\n return new Promise((resolve, reject) => {\n const socket = net.connect(control.address);\n if (options.unref) socket.unref();\n let settled = false;\n let connected = false;\n let pending = \"\";\n const timers: NodeJS.Timeout[] = [];\n const request = { protocol: CONTROL_PROTOCOL, id: 1, token: control.token };\n const cancel = () => {\n const stop = () =>\n reject(new ControlError(\"cancelled\", `\"${method}\" was cancelled.`));\n if (settled) return;\n if (!connected) {\n settle(stop);\n return;\n }\n settled = true;\n for (const timer of timers) clearTimeout(timer);\n // The end of the connection cancels as well; the line says so first.\n socket.end(`${JSON.stringify({ ...request, cancel: true })}\\n`);\n setTimeout(() => socket.destroy(), 500).unref();\n stop();\n };\n const settle = (finish: () => void) => {\n if (settled) return;\n settled = true;\n for (const timer of timers) clearTimeout(timer);\n signal?.removeEventListener(\"abort\", cancel);\n asking.abort();\n socket.destroy();\n finish();\n };\n // What answers the other process's asks stops when the request ends.\n const asking = new AbortController();\n signal?.addEventListener(\"abort\", () => asking.abort(), { once: true });\n const answerAsk = async (ask: {\n seq?: unknown;\n kind?: unknown;\n payload?: unknown;\n }) => {\n const reply = (answer: Record<string, unknown>) => {\n if (settled || socket.destroyed) return;\n socket.write(\n `${JSON.stringify({ ...request, answer: { seq: ask.seq, ...answer } })}\\n`,\n );\n };\n const kind = typeof ask.kind === \"string\" ? ask.kind : \"\";\n if (!options.onAsk || !options.asks?.includes(kind)) {\n reply({\n ok: false,\n error: {\n code: \"unsupported\",\n message: `This process does not answer \"${kind}\".`,\n },\n });\n return;\n }\n try {\n const result = await options.onAsk(kind, ask.payload, asking.signal);\n reply({ ok: true, result: result ?? null });\n } catch (error) {\n reply({\n ok: false,\n error: {\n code: errorCodeOf((error as { code?: unknown } | null)?.code),\n message: error instanceof Error ? error.message : String(error),\n },\n });\n }\n };\n signal?.addEventListener(\"abort\", cancel, { once: true });\n const unreachable = (why: string) =>\n settle(() => reject(new ControlError(\"unreachable\", why)));\n const limit = (ms: number, why: string) => {\n const timer = setTimeout(() => unreachable(why), ms);\n if (options.unref) timer.unref();\n timers.push(timer);\n return timer;\n };\n const connecting = limit(\n options.connectTimeoutMs ?? CONNECT_TIMEOUT_MS,\n `No answer at the control channel ${control.address}.`,\n );\n socket.setEncoding(\"utf8\");\n socket.once(\"connect\", () => {\n connected = true;\n clearTimeout(connecting);\n if (options.timeoutMs !== undefined) {\n limit(\n options.timeoutMs,\n `\"${method}\" was not answered within ${options.timeoutMs} ms.`,\n );\n }\n socket.write(\n `${JSON.stringify({\n ...request,\n method,\n ...(params === undefined ? {} : { params }),\n ...(options.onAsk && options.asks?.length\n ? { asks: options.asks }\n : {}),\n })}\\n`,\n );\n });\n const take = (line: string) => {\n let frame: {\n ok?: unknown;\n result?: unknown;\n stream?: unknown;\n data?: unknown;\n ask?: { seq?: unknown; kind?: unknown; payload?: unknown };\n error?: { code?: ControlErrorCode; message?: string };\n };\n try {\n frame = JSON.parse(line) as typeof frame;\n } catch {\n unreachable(`The control channel ${control.address} answered no JSON.`);\n return;\n }\n if (frame.stream === \"stdout\" || frame.stream === \"stderr\") {\n if (typeof frame.data === \"string\") {\n options.onOutput?.(frame.stream, frame.data);\n }\n return;\n }\n if (typeof frame.ask === \"object\" && frame.ask !== null) {\n void answerAsk(frame.ask);\n return;\n }\n if (frame.ok === true) {\n settle(() => resolve(frame.result));\n return;\n }\n settle(() =>\n reject(\n new ControlError(\n frame.error?.code ?? \"failed\",\n frame.error?.message ?? `\"${method}\" failed.`,\n ),\n ),\n );\n };\n socket.on(\"data\", (chunk: string) => {\n pending += chunk;\n for (;;) {\n if (settled) return;\n const end = pending.indexOf(\"\\n\");\n if (end === -1) break;\n const line = pending.slice(0, end);\n pending = pending.slice(end + 1);\n if (line.trim() !== \"\") take(line);\n }\n });\n socket.once(\"error\", (error) =>\n unreachable(\n `Cannot reach the control channel ${control.address}: ${error.message}`,\n ),\n );\n socket.once(\"close\", () =>\n unreachable(\n `The process behind the control channel ${control.address} went away before it answered \"${method}\".`,\n ),\n );\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4CA,MAAa,mBAAmB;;AAGhC,MAAa,iBAAiB;;AAG9B,MAAa,sBAAsB,EAAE,OAAO;CAC1C,UAAU,EAAE,OAAO,CAAC,CAAC,I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ACF;EACA,OAAO,KAAK,eACV,YACE,0CAA0C,QAAQ,QAAQ,iCAAiC,OAAO,GACpG,CACF;CACF,CAAC;AACH"}
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
import { i as probeRun, n as isPidAlive, o as readProjectName, s as readRunRecord, t as clearRunRecord } from "./run-record-C6oTZF_C.mjs";
|
|
2
|
+
import { createRequire } from "node:module";
|
|
3
|
+
import fs from "node:fs";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { pathToFileURL } from "node:url";
|
|
6
|
+
import net from "node:net";
|
|
7
|
+
//#region src/stop-channel.ts
|
|
8
|
+
/** Set by a supervisor that holds this process's stdin. */
|
|
9
|
+
const STOP_ON_STDIN_ENV = "PH_STOP_ON_STDIN";
|
|
10
|
+
/**
|
|
11
|
+
* Windows has no SIGTERM: `process.kill(pid, "SIGTERM")` ends the process at
|
|
12
|
+
* once, so no handler runs and a stack's stores are left as a crash leaves
|
|
13
|
+
* them. A started host therefore listens on a pipe named after its pid, and
|
|
14
|
+
* a connection to it is delivered as the SIGTERM it stands for. Elsewhere
|
|
15
|
+
* the signal itself does this, and there is no channel.
|
|
16
|
+
*/
|
|
17
|
+
function stopChannelPath(pid, platform = process.platform) {
|
|
18
|
+
return platform === "win32" ? `\\\\.\\pipe\\ph-stop-${pid}` : void 0;
|
|
19
|
+
}
|
|
20
|
+
/** Calls `onStop` for each connection to `channel`. The server holds no
|
|
21
|
+
* process open, and one that cannot listen leaves the host running without
|
|
22
|
+
* a channel rather than not running. */
|
|
23
|
+
function listenForStop(channel, onStop) {
|
|
24
|
+
const server = net.createServer((socket) => {
|
|
25
|
+
socket.on("error", () => void 0);
|
|
26
|
+
socket.end();
|
|
27
|
+
onStop();
|
|
28
|
+
});
|
|
29
|
+
server.on("error", () => void 0);
|
|
30
|
+
server.listen(channel);
|
|
31
|
+
server.unref();
|
|
32
|
+
return server;
|
|
33
|
+
}
|
|
34
|
+
let installed = false;
|
|
35
|
+
/** What a host's process calls once before it starts anything: from then on
|
|
36
|
+
* {@link requestStop} reaches its SIGTERM handlers on every platform. */
|
|
37
|
+
function installStopChannel() {
|
|
38
|
+
const channel = stopChannelPath(process.pid);
|
|
39
|
+
if (!channel || installed) return;
|
|
40
|
+
installed = true;
|
|
41
|
+
listenForStop(channel, () => {
|
|
42
|
+
if (!process.emit("SIGTERM", "SIGTERM")) process.exit(143);
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
const ASK_TIMEOUT_MS = 2e3;
|
|
46
|
+
/** Connects to a stop channel; true once the listener took the request. */
|
|
47
|
+
function askToStop(channel, timeoutMs = ASK_TIMEOUT_MS) {
|
|
48
|
+
return new Promise((resolve) => {
|
|
49
|
+
let connected = false;
|
|
50
|
+
const socket = net.connect(channel);
|
|
51
|
+
socket.setTimeout(timeoutMs, () => socket.destroy());
|
|
52
|
+
socket.once("connect", () => connected = true);
|
|
53
|
+
socket.on("error", () => void 0);
|
|
54
|
+
socket.once("close", () => resolve(connected));
|
|
55
|
+
socket.resume();
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Asks the process to stop as SIGTERM would. False when it could not be
|
|
60
|
+
* asked: on Windows a process without a stop channel (started by an older
|
|
61
|
+
* version, or not a host), which only a kill ends.
|
|
62
|
+
*/
|
|
63
|
+
async function requestStop(pid, platform = process.platform) {
|
|
64
|
+
const channel = stopChannelPath(pid, platform);
|
|
65
|
+
if (channel) return askToStop(channel);
|
|
66
|
+
try {
|
|
67
|
+
process.kill(pid, "SIGTERM");
|
|
68
|
+
} catch {}
|
|
69
|
+
return true;
|
|
70
|
+
}
|
|
71
|
+
const STOP_RUN_TIMEOUT_MS = 6e4;
|
|
72
|
+
/** Asks the project's running `hostName` to stop and waits until its process
|
|
73
|
+
* is gone. It never kills: a host that does not answer keeps running. */
|
|
74
|
+
async function stopRun(projectDir, hostName, options = {}) {
|
|
75
|
+
const env = options.env ?? process.env;
|
|
76
|
+
const projectName = readProjectName(projectDir);
|
|
77
|
+
const probe = probeRun(projectDir, hostName, projectName, env);
|
|
78
|
+
if (probe.status === "none" || probe.status === "stale") return { status: "none" };
|
|
79
|
+
const { pid } = probe.record;
|
|
80
|
+
if (probe.status === "foreign") return {
|
|
81
|
+
status: "foreign",
|
|
82
|
+
pid,
|
|
83
|
+
projectName: probe.record.projectName
|
|
84
|
+
};
|
|
85
|
+
if (!await requestStop(pid)) return {
|
|
86
|
+
status: "unreachable",
|
|
87
|
+
pid
|
|
88
|
+
};
|
|
89
|
+
const deadline = Date.now() + (options.timeoutMs ?? 6e4);
|
|
90
|
+
while (isPidAlive(pid)) {
|
|
91
|
+
if (Date.now() >= deadline) return {
|
|
92
|
+
status: "timeout",
|
|
93
|
+
pid
|
|
94
|
+
};
|
|
95
|
+
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
96
|
+
}
|
|
97
|
+
if (readRunRecord(projectDir, hostName, env)?.pid === pid) clearRunRecord(projectDir, hostName, env);
|
|
98
|
+
return {
|
|
99
|
+
status: "stopped",
|
|
100
|
+
pid
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
//#endregion
|
|
104
|
+
//#region src/host-entry.ts
|
|
105
|
+
/**
|
|
106
|
+
* How a host is started as a child of the process that supervises it: the
|
|
107
|
+
* project's own `ph run`, in an environment of its own. Read by `spawnHost`
|
|
108
|
+
* and by the supervisor, which loads nothing of the project.
|
|
109
|
+
*/
|
|
110
|
+
const BASE_ENV_KEYS = [
|
|
111
|
+
"PATH",
|
|
112
|
+
"HOME",
|
|
113
|
+
"TMPDIR"
|
|
114
|
+
];
|
|
115
|
+
const WIN32_ENV_KEYS = [
|
|
116
|
+
"SystemRoot",
|
|
117
|
+
"USERPROFILE",
|
|
118
|
+
"APPDATA",
|
|
119
|
+
"LOCALAPPDATA",
|
|
120
|
+
"TEMP",
|
|
121
|
+
"TMP",
|
|
122
|
+
"ComSpec",
|
|
123
|
+
"PATHEXT"
|
|
124
|
+
];
|
|
125
|
+
/** The child's whole env: without a `baseEnv`, no other `process.env` key
|
|
126
|
+
* reaches it. */
|
|
127
|
+
function childEnv(dataDir, env = {}, baseEnv) {
|
|
128
|
+
if ("PH_USER_DATA_DIR" in env) throw new Error("spawnHost: set the data dir with `dataDir`, not env.PH_USER_DATA_DIR.");
|
|
129
|
+
if (baseEnv) {
|
|
130
|
+
const base = {};
|
|
131
|
+
for (const [key, value] of Object.entries(baseEnv)) if (value !== void 0) base[key] = value;
|
|
132
|
+
return {
|
|
133
|
+
...base,
|
|
134
|
+
PH_USER_DATA_DIR: dataDir,
|
|
135
|
+
...env
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
const keys = process.platform === "win32" ? [...BASE_ENV_KEYS, ...WIN32_ENV_KEYS] : BASE_ENV_KEYS;
|
|
139
|
+
const base = {};
|
|
140
|
+
for (const key of keys) {
|
|
141
|
+
const value = process.env[key];
|
|
142
|
+
if (value !== void 0) base[key] = value;
|
|
143
|
+
}
|
|
144
|
+
return {
|
|
145
|
+
...base,
|
|
146
|
+
PH_USER_DATA_DIR: dataDir,
|
|
147
|
+
PH_NO_TELEMETRY: "1",
|
|
148
|
+
PH_NO_DOTENV: "1",
|
|
149
|
+
...env
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
/** The version of the package an entry of {@link resolvePhCliEntry} is in. */
|
|
153
|
+
function phCliEntryVersion(entry) {
|
|
154
|
+
try {
|
|
155
|
+
const pkg = JSON.parse(fs.readFileSync(path.join(path.dirname(path.dirname(entry)), "package.json"), "utf8"));
|
|
156
|
+
return typeof pkg.version === "string" ? pkg.version : void 0;
|
|
157
|
+
} catch {
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
/** Whether a standalone host of that release stops when its stdin ends
|
|
162
|
+
* (6.4 on); an earlier one is asked over its stop channel. An unknown
|
|
163
|
+
* version counts as this one. */
|
|
164
|
+
function stopsOnStdin(version) {
|
|
165
|
+
const match = /^(\d+)\.(\d+)\./.exec(version ?? "");
|
|
166
|
+
if (!match) return true;
|
|
167
|
+
const major = Number(match[1]);
|
|
168
|
+
return major > 6 || major === 6 && Number(match[2]) >= 4;
|
|
169
|
+
}
|
|
170
|
+
/** The project's ph-cli, else its ph-run (a packaged app has only that). */
|
|
171
|
+
function resolvePhCliEntry(projectRoot) {
|
|
172
|
+
const require_ = createRequire(pathToFileURL(path.join(projectRoot, "package.json")).href);
|
|
173
|
+
let pkgPath;
|
|
174
|
+
try {
|
|
175
|
+
pkgPath = require_.resolve("@powerhousedao/ph-cli/package.json");
|
|
176
|
+
} catch (error) {
|
|
177
|
+
try {
|
|
178
|
+
pkgPath = require_.resolve("@powerhousedao/ph-run/package.json");
|
|
179
|
+
} catch {
|
|
180
|
+
throw error;
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
return path.join(path.dirname(pkgPath), "dist", "cli.mjs");
|
|
184
|
+
}
|
|
185
|
+
//#endregion
|
|
186
|
+
export { STOP_ON_STDIN_ENV as a, installStopChannel as c, stopChannelPath as d, stopRun as f, stopsOnStdin as i, listenForStop as l, phCliEntryVersion as n, STOP_RUN_TIMEOUT_MS as o, resolvePhCliEntry as r, askToStop as s, childEnv as t, requestStop as u };
|
|
187
|
+
|
|
188
|
+
//# sourceMappingURL=host-entry-B8n_590_.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"host-entry-B8n_590_.mjs","names":[],"sources":["../src/stop-channel.ts","../src/host-entry.ts"],"sourcesContent":["import net from \"node:net\";\nimport {\n clearRunRecord,\n isPidAlive,\n probeRun,\n readProjectName,\n readRunRecord,\n} from \"./run-record.js\";\n\n/** Set by a supervisor that holds this process's stdin. */\nexport const STOP_ON_STDIN_ENV = \"PH_STOP_ON_STDIN\";\n\n/**\n * Windows has no SIGTERM: `process.kill(pid, \"SIGTERM\")` ends the process at\n * once, so no handler runs and a stack's stores are left as a crash leaves\n * them. A started host therefore listens on a pipe named after its pid, and\n * a connection to it is delivered as the SIGTERM it stands for. Elsewhere\n * the signal itself does this, and there is no channel.\n */\nexport function stopChannelPath(\n pid: number,\n platform: NodeJS.Platform = process.platform,\n): string | undefined {\n return platform === \"win32\" ? `\\\\\\\\.\\\\pipe\\\\ph-stop-${pid}` : undefined;\n}\n\n/** Calls `onStop` for each connection to `channel`. The server holds no\n * process open, and one that cannot listen leaves the host running without\n * a channel rather than not running. */\nexport function listenForStop(channel: string, onStop: () => void): net.Server {\n const server = net.createServer((socket) => {\n socket.on(\"error\", () => undefined);\n // The asker waits for this end: the request arrived.\n socket.end();\n onStop();\n });\n server.on(\"error\", () => undefined);\n server.listen(channel);\n server.unref();\n return server;\n}\n\nlet installed = false;\n\n/** What a host's process calls once before it starts anything: from then on\n * {@link requestStop} reaches its SIGTERM handlers on every platform. */\nexport function installStopChannel(): void {\n const channel = stopChannelPath(process.pid);\n if (!channel || installed) return;\n installed = true;\n listenForStop(channel, () => {\n // As the signal: the handlers when there are any, the exit when not.\n if (!process.emit(\"SIGTERM\", \"SIGTERM\")) process.exit(143);\n });\n}\n\nconst ASK_TIMEOUT_MS = 2_000;\n\n/** Connects to a stop channel; true once the listener took the request. */\nexport function askToStop(\n channel: string,\n timeoutMs: number = ASK_TIMEOUT_MS,\n): Promise<boolean> {\n return new Promise((resolve) => {\n let connected = false;\n const socket = net.connect(channel);\n socket.setTimeout(timeoutMs, () => socket.destroy());\n socket.once(\"connect\", () => (connected = true));\n socket.on(\"error\", () => undefined);\n socket.once(\"close\", () => resolve(connected));\n socket.resume();\n });\n}\n\n/**\n * Asks the process to stop as SIGTERM would. False when it could not be\n * asked: on Windows a process without a stop channel (started by an older\n * version, or not a host), which only a kill ends.\n */\nexport async function requestStop(\n pid: number,\n platform: NodeJS.Platform = process.platform,\n): Promise<boolean> {\n const channel = stopChannelPath(pid, platform);\n if (channel) return askToStop(channel);\n try {\n process.kill(pid, \"SIGTERM\");\n } catch {\n // Already gone.\n }\n return true;\n}\n\nexport type StopRunResult =\n /** No live instance of this host for this project. */\n | { status: \"none\" }\n | { status: \"foreign\"; pid: number; projectName: string }\n | { status: \"stopped\"; pid: number }\n /** It runs, and has no stop channel. */\n | { status: \"unreachable\"; pid: number }\n /** Asked, and still running after `timeoutMs`. */\n | { status: \"timeout\"; pid: number };\n\nexport interface StopRunOptions {\n /** How long the host may take to stop (default {@link STOP_RUN_TIMEOUT_MS}). */\n timeoutMs?: number;\n env?: Readonly<Record<string, string | undefined>>;\n}\n\nexport const STOP_RUN_TIMEOUT_MS = 60_000;\n\n/** Asks the project's running `hostName` to stop and waits until its process\n * is gone. It never kills: a host that does not answer keeps running. */\nexport async function stopRun(\n projectDir: string,\n hostName: string,\n options: StopRunOptions = {},\n): Promise<StopRunResult> {\n const env = options.env ?? process.env;\n const projectName = readProjectName(projectDir);\n const probe = probeRun(projectDir, hostName, projectName, env);\n if (probe.status === \"none\" || probe.status === \"stale\") {\n return { status: \"none\" };\n }\n const { pid } = probe.record;\n if (probe.status === \"foreign\") {\n return { status: \"foreign\", pid, projectName: probe.record.projectName };\n }\n if (!(await requestStop(pid))) return { status: \"unreachable\", pid };\n const deadline = Date.now() + (options.timeoutMs ?? STOP_RUN_TIMEOUT_MS);\n while (isPidAlive(pid)) {\n if (Date.now() >= deadline) return { status: \"timeout\", pid };\n await new Promise((resolve) => setTimeout(resolve, 100));\n }\n // A host clears its own record as it exits; one that was killed did not.\n if (readRunRecord(projectDir, hostName, env)?.pid === pid) {\n clearRunRecord(projectDir, hostName, env);\n }\n return { status: \"stopped\", pid };\n}\n","import fs from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\n\n/**\n * How a host is started as a child of the process that supervises it: the\n * project's own `ph run`, in an environment of its own. Read by `spawnHost`\n * and by the supervisor, which loads nothing of the project.\n */\n\nconst BASE_ENV_KEYS = [\"PATH\", \"HOME\", \"TMPDIR\"];\nconst WIN32_ENV_KEYS = [\n \"SystemRoot\",\n \"USERPROFILE\",\n \"APPDATA\",\n \"LOCALAPPDATA\",\n \"TEMP\",\n \"TMP\",\n \"ComSpec\",\n \"PATHEXT\",\n];\n\n/** The child's whole env: without a `baseEnv`, no other `process.env` key\n * reaches it. */\nexport function childEnv(\n dataDir: string,\n env: Record<string, string> = {},\n baseEnv?: Readonly<Record<string, string | undefined>>,\n): Record<string, string> {\n if (\"PH_USER_DATA_DIR\" in env) {\n throw new Error(\n \"spawnHost: set the data dir with `dataDir`, not env.PH_USER_DATA_DIR.\",\n );\n }\n if (baseEnv) {\n const base: Record<string, string> = {};\n for (const [key, value] of Object.entries(baseEnv)) {\n if (value !== undefined) base[key] = value;\n }\n return { ...base, PH_USER_DATA_DIR: dataDir, ...env };\n }\n const keys =\n process.platform === \"win32\"\n ? [...BASE_ENV_KEYS, ...WIN32_ENV_KEYS]\n : BASE_ENV_KEYS;\n const base: Record<string, string> = {};\n for (const key of keys) {\n const value = process.env[key];\n if (value !== undefined) base[key] = value;\n }\n return {\n ...base,\n PH_USER_DATA_DIR: dataDir,\n PH_NO_TELEMETRY: \"1\",\n PH_NO_DOTENV: \"1\",\n ...env,\n };\n}\n\n/** The version of the package an entry of {@link resolvePhCliEntry} is in. */\nexport function phCliEntryVersion(entry: string): string | undefined {\n try {\n const pkg = JSON.parse(\n fs.readFileSync(\n path.join(path.dirname(path.dirname(entry)), \"package.json\"),\n \"utf8\",\n ),\n ) as { version?: unknown };\n return typeof pkg.version === \"string\" ? pkg.version : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** Whether a standalone host of that release stops when its stdin ends\n * (6.4 on); an earlier one is asked over its stop channel. An unknown\n * version counts as this one. */\nexport function stopsOnStdin(version: string | undefined): boolean {\n const match = /^(\\d+)\\.(\\d+)\\./.exec(version ?? \"\");\n if (!match) return true;\n const major = Number(match[1]);\n return major > 6 || (major === 6 && Number(match[2]) >= 4);\n}\n\n/** The project's ph-cli, else its ph-run (a packaged app has only that). */\nexport function resolvePhCliEntry(projectRoot: string): string {\n const require_ = createRequire(\n pathToFileURL(path.join(projectRoot, \"package.json\")).href,\n );\n let pkgPath: string;\n try {\n pkgPath = require_.resolve(\"@powerhousedao/ph-cli/package.json\");\n } catch (error) {\n try {\n pkgPath = require_.resolve(\"@powerhousedao/ph-run/package.json\");\n } catch {\n throw error;\n }\n }\n return path.join(path.dirname(pkgPath), \"dist\", \"cli.mjs\");\n}\n"],"mappings":";;;;;;;;AAUA,MAAa,oBAAoB;;;;;;;;AASjC,SAAgB,gBACd,KACA,WAA4B,QAAQ,UAChB;CACpB,OAAO,aAAa,UAAU,wBAAwB,QAAQ,KAAA;AAChE;;;;AAKA,SAAgB,cAAc,SAAiB,QAAgC;CAC7E,MAAM,SAAS,IAAI,cAAc,WAAW;EAC1C,OAAO,GAAG,eAAe,KAAA,CAAS;EAElC,OAAO,IAAI;EACX,OAAO;CACT,CAAC;CACD,OAAO,GAAG,eAAe,KAAA,CAAS;CAClC,OAAO,OAAO,OAAO;CACrB,OAAO,MAAM;CACb,OAAO;AACT;AAEA,IAAI,YAAY;;;AAIhB,SAAgB,qBAA2B;CACzC,MAAM,UAAU,gBAAgB,QAAQ,GAAG;CAC3C,IAAI,CAAC,WAAW,WAAW;CAC3B,YAAY;CACZ,cAAc,eAAe;EAE3B,IAAI,CAAC,QAAQ,KAAK,WAAW,SAAS,GAAG,QAAQ,KAAK,GAAG;CAC3D,CAAC;AACH;AAEA,MAAM,iBAAiB;;AAGvB,SAAgB,UACd,SACA,YAAoB,gBACF;CAClB,OAAO,IAAI,SAAS,YAAY;EAC9B,IAAI,YAAY;EAChB,MAAM,SAAS,IAAI,QAAQ,OAAO;EAClC,OAAO,WAAW,iBAAiB,OAAO,QAAQ,CAAC;EACnD,OAAO,KAAK,iBAAkB,YAAY,IAAK;EAC/C,OAAO,GAAG,eAAe,KAAA,CAAS;EAClC,OAAO,KAAK,eAAe,QAAQ,SAAS,CAAC;EAC7C,OAAO,OAAO;CAChB,CAAC;AACH;;;;;;AAOA,eAAsB,YACpB,KACA,WAA4B,QAAQ,UAClB;CAClB,MAAM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GED
|
@@ -1,9 +1,12 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { $ as validateHost, $t as profileSchema, A as ForegroundContext, An as findToken, At as ReactorHostInput, B as RunnerVerb, Bn as tokenable, Bt as compoundWiringSchema, C as planCompound, Cn as TokenFor, Ct as PACKAGE_NAME_PATTERN, D as BootIssue, Dn as concatTokenSchema, Dt as ReactorBackendKind, E as BootCheckContext, En as TokenableSchema, Et as ReactorBackend, F as ONE_SHOT_VERBS, Fn as mapTokenSchema, Ft as RunnerBase, G as hostSchemaIssues, Gn as findHostPackage, Gt as emitHostJsonSchema, H as SchemaIssue, Hn as HostLocation, Ht as declaredGenericCompoundHostSchema, I as RunnerContext, In as outputTokenSchema, It as RunnerKind, J as knownVerbIssues, Jn as locateHost, Jt as hostNameSchema, K as isSchemaLike, Kn as formatHostRef, Kt as emittedHostSchemas, L as RunnerError, Ln as ref, Lt as childWrapperSchema, M as HostSchemaIssues, Mn as isToken, Mt as ReactorProtocol, N as HostSchemaLike, Nn as itemTokenSchema, Nt as ReactorRemoteConfig, O as CONNECT_RUNNER, On as envTokenSchema, Ot as ReactorConfig, P as MemberStatus, Pn as keyTokenSchema, Pt as ReactorStorageConfig, Q as validateDeclaredHost, Qt as placementKeyIssues, R as RunnerIssue, Rn as tokenKeyOf, Rt as childrenSchema, S as memberForRef, Sn as Token, St as MemberProcess, T as applyChildWrapper, Tn as TokenMode, Tt as Profile, U as ValidateHostOptions, Un as HostPackage, Ut as declaredHostSchemas, V as STORE_VERBS, Vn as HostLoadError, Vt as connectReactorIssues, W as getVerb, Wn as HostRef, Wt as defineHostSchemas, X as packageBuildRefusal, Xn as resolvePackageRoot, Xt as memberProcessSchema, Y as listVerbs, Yn as parseHostRef, Yt as makeHostSchemas, Z as resolveRunnerModule, Zt as originOrUrlSchema, _ as toStartedHandle, _n as RecordMapToken, _t as HOST_NAME_PATTERN, a as RunCompoundResult, an as refineConnectReactor, at as envSitesOf, b as PlanError, bn as TOKEN_KEYS, bt as HostDefinition, c as memberCycle, cn as runnerKindSchema, ct as refKey, d as runCompound, dn as EnvToken, dt as ChildWrapper, en as reactorBackendKindSchema, et as DeclaredIssue, f as stopStreamOf, fn as ItemToken, ft as CompoundHost, g as runnerHandleSchema, gn as OutputToken, gt as HOST_NAME_MESSAGE, h as StartedHandle, hn as OutputPath, ht as HOST_NAME_MAX_LENGTH, i as RunCompoundOptions, in as reactorSchema, it as checkTokenSites, j as HostSchemaIssue, jn as forbidRef, jt as ReactorPackageConfig, k as DeclaredHostOptions, kn as envTokenable, kt as ReactorHost, l as memberProcessOf, ln as ArrayMapToken, lt as schemaAtPath, m as RunnerHandleData, mn as MapToken, mt as CompoundWiring, n as ForegroundPlan, nn as reactorHostSchema, nt as OutputsSchemaLookup, o as STOP_STREAM_LIMIT_MS, on as refineStartOrder, ot as outputRefsOf, p as RunnerHandle, pn as KeyToken, pt as CompoundHostInput, q as kindShapeIssues, qn as hostFileLabel, qt as genericCompoundHostSchema, r as HoldStopOptions, rn as reactorProtocolSchema, rt as checkOutputPaths, s as holdStopRequests, sn as runnerBaseSchema, st as outputSitesOf, t as ForegroundCandidate, tn as reactorBackendSchema, tt as OutputRef, u as planForeground, un as ConcatToken, ut as CONNECT_PRIMARY_MESSAGE, v as CompoundPlan, vn as RefFn, vt as HOST_REF_MESSAGE, w as MemberDraft, wn as TokenKey, wt as PlacementKeyIssue, x as PlanMember, xn as Template, xt as HostSchemas, y as PlanEdge, yn as TOKEN_ESCAPE_KEY, yt as HOST_REF_PATTERN, z as RunnerModule, zn as tokenSchema, zt as compoundHostSchema } from "./compound-
|
|
1
|
+
import { C as protocolMismatch, D as runRecordSchema, E as runRecordMemberSchema, S as processControlChannel, T as RunRecordMember, _ as controlRecordSchema, a as ControlChannel, b as ownerOnlyPipeAccess, c as ControlHandler, d as MAX_LINE_BYTES, f as OpenControlChannelOptions, g as controlRecordOf, h as controlProtocolOf, i as ControlCall, l as ControlRecord, m as closeProcessControlChannel, n as CONTROL_PROTOCOL, o as ControlError, p as callControl, r as CallControlOptions, s as ControlErrorCode, t as ASK_TIMEOUT_MS, u as ControlStream, v as ensureProcessControlChannel, w as RunRecord, x as pipeAccessList, y as openControlChannel } from "./control-channel-DVn4dvfQ.mjs";
|
|
2
|
+
import { $ as validateHost, $t as profileSchema, A as ForegroundContext, An as findToken, At as ReactorHostInput, B as RunnerVerb, Bn as tokenable, Bt as compoundWiringSchema, C as planCompound, Cn as TokenFor, Ct as PACKAGE_NAME_PATTERN, D as BootIssue, Dn as concatTokenSchema, Dt as ReactorBackendKind, E as BootCheckContext, En as TokenableSchema, Et as ReactorBackend, F as ONE_SHOT_VERBS, Fn as mapTokenSchema, Ft as RunnerBase, G as hostSchemaIssues, Gn as findHostPackage, Gt as emitHostJsonSchema, H as SchemaIssue, Hn as HostLocation, Ht as declaredGenericCompoundHostSchema, I as RunnerContext, In as outputTokenSchema, It as RunnerKind, J as knownVerbIssues, Jn as locateHost, Jt as hostNameSchema, K as isSchemaLike, Kn as formatHostRef, Kt as emittedHostSchemas, L as RunnerError, Ln as ref, Lt as childWrapperSchema, M as HostSchemaIssues, Mn as isToken, Mt as ReactorProtocol, N as HostSchemaLike, Nn as itemTokenSchema, Nt as ReactorRemoteConfig, O as CONNECT_RUNNER, On as envTokenSchema, Ot as ReactorConfig, P as MemberStatus, Pn as keyTokenSchema, Pt as ReactorStorageConfig, Q as validateDeclaredHost, Qt as placementKeyIssues, R as RunnerIssue, Rn as tokenKeyOf, Rt as childrenSchema, S as memberForRef, Sn as Token, St as MemberProcess, T as applyChildWrapper, Tn as TokenMode, Tt as Profile, U as ValidateHostOptions, Un as HostPackage, Ut as declaredHostSchemas, V as STORE_VERBS, Vn as HostLoadError, Vt as connectReactorIssues, W as getVerb, Wn as HostRef, Wt as defineHostSchemas, X as packageBuildRefusal, Xn as resolvePackageRoot, Xt as memberProcessSchema, Y as listVerbs, Yn as parseHostRef, Yt as makeHostSchemas, Z as resolveRunnerModule, Zt as originOrUrlSchema, _ as toStartedHandle, _n as RecordMapToken, _t as HOST_NAME_PATTERN, a as RunCompoundResult, an as refineConnectReactor, at as envSitesOf, b as PlanError, bn as TOKEN_KEYS, bt as HostDefinition, c as memberCycle, cn as runnerKindSchema, ct as refKey, d as runCompound, dn as EnvToken, dt as ChildWrapper, en as reactorBackendKindSchema, et as DeclaredIssue, f as stopStreamOf, fn as ItemToken, ft as CompoundHost, g as runnerHandleSchema, gn as OutputToken, gt as HOST_NAME_MESSAGE, h as StartedHandle, hn as OutputPath, ht as HOST_NAME_MAX_LENGTH, i as RunCompoundOptions, in as reactorSchema, it as checkTokenSites, j as HostSchemaIssue, jn as forbidRef, jt as ReactorPackageConfig, k as DeclaredHostOptions, kn as envTokenable, kt as ReactorHost, l as memberProcessOf, ln as ArrayMapToken, lt as schemaAtPath, m as RunnerHandleData, mn as MapToken, mt as CompoundWiring, n as ForegroundPlan, nn as reactorHostSchema, nt as OutputsSchemaLookup, o as STOP_STREAM_LIMIT_MS, on as refineStartOrder, ot as outputRefsOf, p as RunnerHandle, pn as KeyToken, pt as CompoundHostInput, q as kindShapeIssues, qn as hostFileLabel, qt as genericCompoundHostSchema, r as HoldStopOptions, rn as reactorProtocolSchema, rt as checkOutputPaths, s as holdStopRequests, sn as runnerBaseSchema, st as outputSitesOf, t as ForegroundCandidate, tn as reactorBackendSchema, tt as OutputRef, u as planForeground, un as ConcatToken, ut as CONNECT_PRIMARY_MESSAGE, v as CompoundPlan, vn as RefFn, vt as HOST_REF_MESSAGE, w as MemberDraft, wn as TokenKey, wt as PlacementKeyIssue, x as PlanMember, xn as Template, xt as HostSchemas, y as PlanEdge, yn as TOKEN_ESCAPE_KEY, yt as HOST_REF_PATTERN, z as RunnerModule, zn as tokenSchema, zt as compoundHostSchema } from "./compound-BLhEewO6.mjs";
|
|
3
|
+
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";
|
|
3
4
|
import { killTree } from "./kill-tree.mjs";
|
|
5
|
+
import { a as SpawnHostPhase, c as COMPOUND_MEMBER_ENV, i as SpawnHostOptions, l as CompoundMemberHost, n as SPAWN_STOPPING_NOTE, o as SpawnedHost, r as SpawnHostError, s as spawnHost, t as HostExit, u as takeCompoundMember } from "./spawn-host-DWroRe1S.mjs";
|
|
4
6
|
import { z } from "zod";
|
|
5
7
|
import { SwitchboardDrive, driveAddressMessage, switchboardOfDrive } from "@powerhousedao/shared/host-tokens";
|
|
6
8
|
import { ORIGIN_PLACEHOLDER, SWITCHBOARD_PROXY_PATHS, isHtmlNavigation, isOriginPlaceholderUrl, isSwitchboardProxyPath, resolveOriginPlaceholders, toOriginPlaceholder, withOriginPlaceholders } from "@powerhousedao/shared/connect/origin-placeholder";
|
|
9
|
+
import { createOwnerOnlyFile, fileAccessList, restrictFileToOwner, writeOwnerOnlyFile } from "@powerhousedao/shared/clis/owner-only";
|
|
7
10
|
import net from "node:net";
|
|
8
11
|
import { PHConnectCollection, PHConnectDefaultDrive, PHConnectRuntimeConfig, PHConnectRuntimeDefaultDrive } from "@powerhousedao/shared/clis";
|
|
9
12
|
//#region src/host-loader.d.ts
|
|
@@ -241,6 +244,8 @@ type Env$1 = Readonly<Record<string, string | undefined>>;
|
|
|
241
244
|
export declare function runRecordKey(name: string, hostPackage?: string): string;
|
|
242
245
|
/** The key of a record as read: where it is filed. */
|
|
243
246
|
export declare function recordKeyOf(record: Pick<RunRecord, "host" | "package">): string;
|
|
247
|
+
/** The file of an instance's record: `(host, data folder)` is its path. */
|
|
248
|
+
export declare function runRecordPath(projectDir: string, key: string, env?: Env$1): string;
|
|
244
249
|
export declare function readRunRecord(projectDir: string, hostName: string, env?: Env$1): RunRecord | undefined;
|
|
245
250
|
/** Every valid v2 record under `.ph/run/`, package hosts' included (invalid
|
|
246
251
|
* and v1 files skipped). */
|
|
@@ -263,6 +268,30 @@ export declare function isPidAlive(pid: number): boolean;
|
|
|
263
268
|
*/
|
|
264
269
|
export declare function probeRun(projectDir: string, hostName: string, projectName: string, env?: Env$1): RunProbe;
|
|
265
270
|
//#endregion
|
|
271
|
+
//#region src/local-sign-in.d.ts
|
|
272
|
+
/** The secret a stack's record keeps, if any. */
|
|
273
|
+
export declare function signInSecretOf(record: Pick<RunRecord, "extra"> | undefined): string | undefined;
|
|
274
|
+
/** A Connect member's sign-in link, with a code minted now. */
|
|
275
|
+
interface SignInLink {
|
|
276
|
+
member: string;
|
|
277
|
+
link: string;
|
|
278
|
+
/** As the member was asked (`--open`, `runner.openBrowser`). */
|
|
279
|
+
open?: boolean;
|
|
280
|
+
}
|
|
281
|
+
/** The members of a stack that sign pages in by link (their outputs say
|
|
282
|
+
* `localSignIn`), and their app URLs. */
|
|
283
|
+
export declare function signInMembersOf(members: Readonly<Record<string, {
|
|
284
|
+
outputs?: unknown;
|
|
285
|
+
}>>): {
|
|
286
|
+
member: string;
|
|
287
|
+
app: string;
|
|
288
|
+
open?: boolean;
|
|
289
|
+
}[];
|
|
290
|
+
/** A fresh link for each member of the stack that signs pages in by link. */
|
|
291
|
+
export declare function signInLinksOf(record: RunRecord): SignInLink[];
|
|
292
|
+
/** Prints each link, and opens it as asked, else on a terminal. */
|
|
293
|
+
export declare function announceSignInLinks(links: readonly SignInLink[], open?: (url: string) => void): void;
|
|
294
|
+
//#endregion
|
|
266
295
|
//#region src/stop-channel.d.ts
|
|
267
296
|
/** Set by a supervisor that holds this process's stdin. */
|
|
268
297
|
export declare const STOP_ON_STDIN_ENV = "PH_STOP_ON_STDIN";
|
|
@@ -321,105 +350,6 @@ export declare const STOP_RUN_TIMEOUT_MS = 60000;
|
|
|
321
350
|
* is gone. It never kills: a host that does not answer keeps running. */
|
|
322
351
|
export declare function stopRun(projectDir: string, hostName: string, options?: StopRunOptions): Promise<StopRunResult>;
|
|
323
352
|
//#endregion
|
|
324
|
-
//#region src/compound-member.d.ts
|
|
325
|
-
/**
|
|
326
|
-
* How a compound hands an own-process member its host. The member's
|
|
327
|
-
* `host.js` alone is not the member: the compound's wrapper (reactor, config
|
|
328
|
-
* and runner overrides) and its resolved tokens are. So the compound
|
|
329
|
-
* resolves the member as it would in its own process and the child's
|
|
330
|
-
* `ph run <folder>` runs that host instead of reading the file.
|
|
331
|
-
*/
|
|
332
|
-
/** Carries a {@link CompoundMemberHost} as JSON to the child's `ph run`. */
|
|
333
|
-
export declare const COMPOUND_MEMBER_ENV = "PH_COMPOUND_MEMBER";
|
|
334
|
-
interface CompoundMemberHost {
|
|
335
|
-
/** The compound host's name. */
|
|
336
|
-
compound: string;
|
|
337
|
-
/** The member's key in the compound's `children`. */
|
|
338
|
-
member: string;
|
|
339
|
-
/** The member's host folder: the child's `ph run <folder>`. */
|
|
340
|
-
folder: string;
|
|
341
|
-
/** The member's host, its wrapper applied and its tokens resolved. */
|
|
342
|
-
host: Record<string, unknown>;
|
|
343
|
-
}
|
|
344
|
-
/**
|
|
345
|
-
* The member host a compound handed this process for `folder`, taken out of
|
|
346
|
-
* `env` so nothing this process starts inherits it. Undefined when there is
|
|
347
|
-
* none; throws when it is malformed or names another folder.
|
|
348
|
-
*/
|
|
349
|
-
export declare function takeCompoundMember(env: Record<string, string | undefined>, folder: string): CompoundMemberHost | undefined;
|
|
350
|
-
//#endregion
|
|
351
|
-
//#region src/spawn-host.d.ts
|
|
352
|
-
interface SpawnHostOptions {
|
|
353
|
-
projectRoot: string;
|
|
354
|
-
/** Folder name under hosts/, or `<package>/<host>` for a host an
|
|
355
|
-
* installed package supplies: what the child's `ph run` takes. */
|
|
356
|
-
host: string;
|
|
357
|
-
/** The child's PH_USER_DATA_DIR (created if missing). */
|
|
358
|
-
dataDir: string;
|
|
359
|
-
verb?: string;
|
|
360
|
-
/** What follows `ph run <host> [verb]`: the runner's arguments. */
|
|
361
|
-
argv?: readonly string[];
|
|
362
|
-
/** Merged over the base env; may not set PH_USER_DATA_DIR. */
|
|
363
|
-
env?: Record<string, string>;
|
|
364
|
-
/** The env the child starts from instead of the clean one, as it is: a
|
|
365
|
-
* compound hands its members its own, so a member sees what it would in
|
|
366
|
-
* the compound's process. */
|
|
367
|
-
baseEnv?: Readonly<Record<string, string | undefined>>;
|
|
368
|
-
/** The host the child runs instead of reading `hosts/<host>/host.js`: a
|
|
369
|
-
* compound's member, its wrapper applied and its tokens resolved. */
|
|
370
|
-
definition?: Omit<CompoundMemberHost, "folder">;
|
|
371
|
-
/** Ask the child to stop through its stdin (it gets a pipe and
|
|
372
|
-
* PH_STOP_ON_STDIN=1): a request on every platform, which this process
|
|
373
|
-
* ending makes too; after stopTimeoutMs its whole process tree is killed.
|
|
374
|
-
* Without it a stop is SIGTERM, on Windows the kill itself, and SIGKILL of
|
|
375
|
-
* the child follows after stopTimeoutMs. */
|
|
376
|
-
stopOnStdin?: boolean;
|
|
377
|
-
/** ph-cli entry; default: the project's `@powerhousedao/ph-cli/dist/cli.mjs`. */
|
|
378
|
-
cli?: string;
|
|
379
|
-
readyTimeoutMs?: number;
|
|
380
|
-
stopTimeoutMs?: number;
|
|
381
|
-
/** Before ready: stop and reject. After: stop. */
|
|
382
|
-
signal?: AbortSignal;
|
|
383
|
-
onOutput?: (stream: "stdout" | "stderr", chunk: string) => void;
|
|
384
|
-
/** Appends both streams. */
|
|
385
|
-
logFile?: string;
|
|
386
|
-
}
|
|
387
|
-
interface HostExit {
|
|
388
|
-
code: number | null;
|
|
389
|
-
signal: NodeJS.Signals | null;
|
|
390
|
-
/** SIGKILL after stopTimeoutMs. */
|
|
391
|
-
forced: boolean;
|
|
392
|
-
}
|
|
393
|
-
interface SpawnedHost {
|
|
394
|
-
pid: number;
|
|
395
|
-
dataDir: string;
|
|
396
|
-
record: RunRecord;
|
|
397
|
-
outputs: Record<string, unknown> | undefined;
|
|
398
|
-
members: RunRecord["members"];
|
|
399
|
-
/** Resolves (never rejects) when the child exits. */
|
|
400
|
-
exited: Promise<HostExit>;
|
|
401
|
-
/** SIGTERM (or the end of its stdin), SIGKILL after stopTimeoutMs, clear
|
|
402
|
-
* a leftover record. */
|
|
403
|
-
stop(): Promise<HostExit>;
|
|
404
|
-
}
|
|
405
|
-
type SpawnHostPhase = "exited" | "timeout" | "aborted";
|
|
406
|
-
/** The tail line before which a timed-out or aborted run's output is its own. */
|
|
407
|
-
export declare const SPAWN_STOPPING_NOTE = "spawnHost: stopping it";
|
|
408
|
-
export declare class SpawnHostError extends Error {
|
|
409
|
-
readonly phase: SpawnHostPhase;
|
|
410
|
-
readonly outputTail: string;
|
|
411
|
-
readonly exit?: HostExit | undefined;
|
|
412
|
-
constructor(message: string, phase: SpawnHostPhase, outputTail: string, exit?: HostExit | undefined);
|
|
413
|
-
}
|
|
414
|
-
/**
|
|
415
|
-
* `ph run <host> [verb]` as a child; ready when its run record appears.
|
|
416
|
-
*
|
|
417
|
-
* The child shares this process's group, so a terminal Ctrl-C reaches both.
|
|
418
|
-
* It runs the project's own ph-cli (else its ph-run): one older than
|
|
419
|
-
* PH_NO_DOTENV reads the project's `.env` anyway.
|
|
420
|
-
*/
|
|
421
|
-
export declare function spawnHost(options: SpawnHostOptions): Promise<SpawnedHost>;
|
|
422
|
-
//#endregion
|
|
423
353
|
//#region src/host-issues.d.ts
|
|
424
354
|
/** Where in the `ph run` pipeline a host check found an issue. */
|
|
425
355
|
type CheckStage = "load" | "declared" | "resolve" | "resolved" | "boot";
|
|
@@ -1477,6 +1407,42 @@ interface MemberInput extends Omit<ExpectHostInput, "members" | "plan"> {
|
|
|
1477
1407
|
*/
|
|
1478
1408
|
export declare function expectHost(input: ExpectHostInput): HostExpectation;
|
|
1479
1409
|
//#endregion
|
|
1480
|
-
|
|
1410
|
+
//#region src/connect-dev.d.ts
|
|
1411
|
+
/** What the tool that started a dev server knows of the run. */
|
|
1412
|
+
interface ConnectDevRun {
|
|
1413
|
+
/** The tool that runs the dev server, for example the `ph` CLI. */
|
|
1414
|
+
tool: {
|
|
1415
|
+
name: string;
|
|
1416
|
+
version: string;
|
|
1417
|
+
};
|
|
1418
|
+
/** When the run came up, as an ISO timestamp. Null when the tool does not
|
|
1419
|
+
* know. */
|
|
1420
|
+
startedAt: string | null;
|
|
1421
|
+
/** Where the run's other services answer: a URL by service name, for
|
|
1422
|
+
* example `switchboard`. A service the run does not have is left out. */
|
|
1423
|
+
services: Readonly<Record<string, string>>;
|
|
1424
|
+
}
|
|
1425
|
+
/** What the dev server of a Connect host hands a plugin's `devServer` hook. */
|
|
1426
|
+
interface ConnectDevServerContext {
|
|
1427
|
+
/** The folder of the project the dev server runs. */
|
|
1428
|
+
projectRoot: string;
|
|
1429
|
+
/** Read at each call: the services of a run come up after its dev server. */
|
|
1430
|
+
run: () => ConnectDevRun;
|
|
1431
|
+
}
|
|
1432
|
+
/**
|
|
1433
|
+
* The hooks of a Connect dev-server plugin, which a host lists in
|
|
1434
|
+
* `runner.devPlugins`. Only a dev server loads these plugins, so nothing they
|
|
1435
|
+
* add reaches a build or a production server.
|
|
1436
|
+
*
|
|
1437
|
+
* `TVitePlugin` is Vite's `PluginOption`: host-core does not depend on Vite.
|
|
1438
|
+
*/
|
|
1439
|
+
interface ConnectDevHooks<TVitePlugin = unknown> {
|
|
1440
|
+
/** Vite plugins for the dev server: its middleware, the tags it puts in
|
|
1441
|
+
* the page and the modules it serves the page. */
|
|
1442
|
+
devServer: Provide<readonly TVitePlugin[], ConnectDevServerContext>;
|
|
1443
|
+
}
|
|
1444
|
+
type ConnectDevPlugin<TVitePlugin = unknown> = HostPlugin<ConnectDevHooks<TVitePlugin>>;
|
|
1445
|
+
//#endregion
|
|
1446
|
+
export { ASK_TIMEOUT_MS, type AlreadyRunning, type ArrayMapToken, type BootCheckContext, type BootIssue, type BuiltinEnv, COMPOUND_MEMBER_ENV, CONNECT_PRIMARY_MESSAGE, CONNECT_RUNNER, CONTROL_PROTOCOL, type CallControlOptions, type CheckDeferred, type CheckHostOptions, type CheckHostResult, type CheckStage, type ChildWrapper, type CompoundArgvMember, type CompoundHost, type CompoundHostInput, type CompoundMemberHost, type CompoundPlan, type CompoundWiring, type ConcatToken, type ConnectDevHooks, type ConnectDevPlugin, type ConnectDevRun, type ConnectDevServerContext, type ConnectPluginSlices, type ConnectReactorProjection, type ConnectRouterSettings, type ConnectStorageKind, type ConsumedOutput, type ContributedDrive, type ContributedDriveInput, type ContributionSource, type Contributions, type ControlCall, type ControlChannel, ControlError, type ControlErrorCode, type ControlHandler, type ControlRecord, type ControlStream, type DeadConfigWarning, type DeclaredHostOptions, type DeclaredIssue, type DeferredResolution, type DeferredToken, type DriveDeclaration, type DrivePlanEntry, type DriveProjectionInput, type DriveSeederClient, type EnvToken, type ExpectHostInput, type ExpectedBackend, type ExpectedDrive, type FindInstanceOptions, type ForegroundCandidate, type ForegroundContext, type ForegroundPlan, HOST_NAME_MAX_LENGTH, HOST_NAME_MESSAGE, HOST_NAME_PATTERN, HOST_REF_MESSAGE, HOST_REF_PATTERN, type HoldStopOptions, type HostDefinition, type HostExit, type HostExpectation, type HostExport, type HostImports, type HostIssue, HostLoadError, type HostLocation, type HostOutputsDescription, type HostPackage, type HostPlugin, type HostPluginModule, type HostRef, type HostSchemaIssue, type HostSchemaIssues, type HostSchemaLike, type HostSchemas, type HostsFolderStatus, type InstanceDrive, type InstanceKey, type ItemToken, type KeyToken, type LoadHostOptions, type LoadedHost, MAX_LINE_BYTES, type MapToken, type MemberDraft, type MemberExpectation, type MemberInput, type MemberProcess, type MemberStatus, type MergedContribution, type NormalizedPluginEntry, ONE_SHOT_VERBS, ORIGIN_PLACEHOLDER, type Observe, type OpenControlChannelOptions, type OutputLookup, type OutputPath, type OutputRef, type OutputSource, type OutputToken, type OutputsSchemaLookup, type OwnedConfigSlice, PACKAGE_NAME_PATTERN, type PHHost, type PHHostOutputs, type PlacedConnectDrives, type PlacementKeyIssue, type PlanEdge, PlanError, type PlanMember, type PluginContributionsPlan, type PluginEntry, type PluginEntryData, type ProducerInfo, type ProducerMap, type Profile, type ProjectedDescriptor, type ProjectedStorage, type Provide, type ReactorBackend, type ReactorBackendKind, type ReactorClientMode, type ReactorConfig, type ReactorHost, type ReactorHostInput, type ReactorPackageConfig, type ReactorProtocol, type ReactorRemoteConfig, type ReactorStorageConfig, type RecordMapToken, type RefFn, type RemovedForm, type ResolveOptions, type ResolveSources, type ResolvedDrive, type ResolvedPlugin, type RestartDecision, type RestartPolicy, type RestartState, type RunCompoundOptions, type RunCompoundResult, type RunProbe, type RunRecord, type RunRecordMember, type RunnerArgsSchema, type RunnerArgvTarget, type RunnerBase, type RunnerContext, RunnerError, type RunnerHandle, type RunnerHandleData, type RunnerIssue, type RunnerKind, type RunnerModule, type RunnerVerb, type RunningInstance, SPAWN_STOPPING_NOTE, STOP_STREAM_LIMIT_MS, STORE_VERBS, SWITCHBOARD_PROXY_PATHS, type SchemaIssue, type SeedResult, type SelfMembers, type ServedRemoteBackend, type SignInLink, SpawnHostError, type SpawnHostOptions, type SpawnHostPhase, type SpawnedHost, type SplitRunArgv, type StartedHandle, type StopRunOptions, type StopRunResult, type SwitchboardDrive, type SwitchboardReactorLayer, TOKEN_ESCAPE_KEY, TOKEN_KEYS, type Template, type Token, type TokenFor, type TokenKey, type TokenMode, type TokenPosition, type TokenSite, type TokenableSchema, type Transform, type ValidateHostOptions, applyChildWrapper, callControl, checkOutputPaths, checkTokenSites, childWrapperSchema, childrenSchema, closeProcessControlChannel, compoundHostSchema, compoundWiringSchema, concatTokenSchema, connectReactorIssues, controlProtocolOf, controlRecordOf, controlRecordSchema, createOwnerOnlyFile, declaredGenericCompoundHostSchema, declaredHostSchemas, defineHostSchemas, describeInstance, driveAddressMessage, emitHostJsonSchema, emittedHostSchemas, ensureProcessControlChannel, envSitesOf, envTokenSchema, envTokenable, fileAccessList, findHostPackage, findRunningInstance, findToken, forbidRef, formatHostRef, genericCompoundHostSchema, getVerb, holdStopRequests, hostFileLabel, hostNameSchema, hostSchemaIssues, instanceDataDir, instanceKey, instanceOfRecord, instancePhDir, instanceRunDir, instanceServicesDir, isAlreadyRunning, isHtmlNavigation, isOriginPlaceholderUrl, isSchemaLike, isSwitchboardProxyPath, isToken, itemTokenSchema, keyTokenSchema, killTree, kindShapeIssues, knownVerbIssues, listRunningInstances, listVerbs, locateHost, makeHostSchemas, mapTokenSchema, memberCycle, memberForRef, memberProcessOf, memberProcessSchema, openControlChannel, originOrUrlSchema, outputRefsOf, outputSitesOf, outputTokenSchema, ownerOnlyPipeAccess, packageBuildRefusal, parseHostRef, pipeAccessList, placementKeyIssues, planCompound, planForeground, processControlChannel, profileSchema, protocolMismatch, reactorBackendKindSchema, reactorBackendSchema, reactorHostSchema, reactorProtocolSchema, reactorSchema, ref, refKey, refineConnectReactor, refineStartOrder, resolveOriginPlaceholders, resolvePackageRoot, resolveRunnerModule, restartDecision, restrictFileToOwner, runCompound, runRecordMemberSchema, runRecordSchema, runnerBaseSchema, runnerHandleSchema, runnerKindSchema, runningInstance, schemaAtPath, spawnHost, stopStreamOf, supervisedFactLines, switchboardOfDrive, takeCompoundMember, toOriginPlaceholder, toStartedHandle, tokenKeyOf, tokenSchema, tokenable, validateDeclaredHost, validateHost, withOriginPlaceholders, writeOwnerOnlyFile };
|
|
1481
1447
|
export {};
|
|
1482
1448
|
//# sourceMappingURL=index.d.mts.map
|