posipaki 0.40.0 → 0.42.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/remote/gateway-cli.js +11 -2
- package/dist/remote/gateway-cli.js.map +1 -1
- package/dist/remote/index.d.ts +22 -41
- package/dist/remote/index.d.ts.map +1 -1
- package/dist/remote/index.js +24 -55
- package/dist/remote/index.js.map +1 -1
- package/dist/remote/node.d.ts +137 -3
- package/dist/remote/node.d.ts.map +1 -1
- package/dist/remote/node.js +379 -31
- package/dist/remote/node.js.map +1 -1
- package/dist/{version-D4C9wBG0.js → version-DnLiQ9Q-.js} +2 -2
- package/dist/{version-D4C9wBG0.js.map → version-DnLiQ9Q-.js.map} +1 -1
- package/dist/websocket-BYNYSi7b.d.ts +226 -0
- package/dist/websocket-BYNYSi7b.d.ts.map +1 -0
- package/dist/{json1-B-oUZzI_.js → websocket-DttBoCRL.js} +369 -47
- package/dist/websocket-DttBoCRL.js.map +1 -0
- package/package.json +1 -1
- package/dist/client-PWS8gJ0-.d.ts +0 -70
- package/dist/client-PWS8gJ0-.d.ts.map +0 -1
- package/dist/json1-B-oUZzI_.js.map +0 -1
package/dist/index.d.ts
CHANGED
|
@@ -20,7 +20,7 @@ declare function defineActor<Args, InternalState, InMsg extends Message, OutMsg
|
|
|
20
20
|
//#endregion
|
|
21
21
|
//#region src/version.d.ts
|
|
22
22
|
/** posipaki's release version. Must equal package.json's `version`. */
|
|
23
|
-
declare const LIB_VERSION = "0.
|
|
23
|
+
declare const LIB_VERSION = "0.42.0";
|
|
24
24
|
//#endregion
|
|
25
25
|
export { type ActorConfig, type ActorContext, type ActorDecorated, type ActorDefinition, type ActorPlugin, type ActorReflection, type AnyProcess, AsyncProcess, type AsyncProcessFn, type ExitMessage, type HandlerFn, type HandlerOptions, type HookResult, LIB_VERSION, type Message, type MethodOptions, type PluginTransform, Process, type ProcessCtx, type ProcessFn, type SenderInfo, type SenderOrigin, type SpawnedFrom, type StopMessage, type WithSender, type WithoutSender, asyncify, callHook, chainHook, defineActor, defineMessages, mergeConfigs, propagateError, runDispatch, runDispatchAsync, spawn, spawnAsync, stopPropagation };
|
|
26
26
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.js
CHANGED
|
@@ -2,7 +2,7 @@ import { i as runDispatch } from "./util-Brtfgv68.js";
|
|
|
2
2
|
import { a as spawnAsync, i as runDispatchAsync, o as asyncify, t as AsyncProcess } from "./process.async-C_-NpMFX.js";
|
|
3
3
|
import { n as chainHook, o as propagateError, r as mergeConfigs, s as stopPropagation, t as callHook } from "./hooks-CgXhmY4r.js";
|
|
4
4
|
import { n as defineMessages, t as defineActor } from "./define-actor-D7c9vn6S.js";
|
|
5
|
-
import { t as LIB_VERSION } from "./version-
|
|
5
|
+
import { t as LIB_VERSION } from "./version-DnLiQ9Q-.js";
|
|
6
6
|
//#region src/process.ts
|
|
7
7
|
/** @deprecated Use {@link spawnAsync} instead. */
|
|
8
8
|
function spawn(fn, pname, tp) {
|
|
@@ -4,9 +4,15 @@ import { tmpdir } from "node:os";
|
|
|
4
4
|
import { basename, join } from "node:path";
|
|
5
5
|
import { promisify } from "node:util";
|
|
6
6
|
import * as readline from "node:readline";
|
|
7
|
+
//#region src/remote/channel.ts
|
|
8
|
+
const ERROR_KEY = "$error";
|
|
9
|
+
/** The frame that says the wire is over: the reason, and the connection ends with it. */
|
|
10
|
+
function errorFrame$1(reason) {
|
|
11
|
+
return { [ERROR_KEY]: reason };
|
|
12
|
+
}
|
|
13
|
+
//#endregion
|
|
7
14
|
//#region src/remote/stdio.ts
|
|
8
15
|
const OUTPUT_KEY = "$fd";
|
|
9
|
-
const ERROR_KEY = "$error";
|
|
10
16
|
/** Raised when the wire itself fails: no frame, the wrong protocol, a peer that went away. */
|
|
11
17
|
var StdioWireError = class extends Error {
|
|
12
18
|
constructor(message) {
|
|
@@ -20,8 +26,11 @@ function outputFrame(fd, data) {
|
|
|
20
26
|
data
|
|
21
27
|
});
|
|
22
28
|
}
|
|
29
|
+
/** An `$error` frame as a line. The word and its shape are the shared vocabulary's
|
|
30
|
+
* (channel.ts) — one word for a wire that cannot be spoken over, whether the failure was at
|
|
31
|
+
* the start of a session or in the middle of one; what this file owns is its line form. */
|
|
23
32
|
function errorFrame(reason) {
|
|
24
|
-
return JSON.stringify(
|
|
33
|
+
return JSON.stringify(errorFrame$1(reason));
|
|
25
34
|
}
|
|
26
35
|
/** Is this write error just a peer that already left? */
|
|
27
36
|
function peerGone(code) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"gateway-cli.js","names":["errorText","Lines"],"sources":["../../src/remote/stdio.ts","../../src/remote/transports/fifo.ts","../../src/remote/gateway.ts","../../src/remote/gateway-cli.ts"],"sourcesContent":["// ── stdio wire ─────────────────────────────────────────────────────────────\n//\n// A newline-delimited JSON channel over a pair of streams: the one wire every\n// way into a foreign execution context can carry. Two callers rely on it, and\n// they are two halves of the same thing:\n//\n// * the client of a spawn we make ourselves, on fds handed to the child (see\n// `fdStreams`) — private fds, so the child's own stdout stays free;\n// * a first-stage command on its own stdin/stdout, over ssh, under `sudo`, in\n// a container — where stdio is the only channel there is.\n//\n// Frames are one JSON object per line. Whatever the far end prints is carried\n// as an *output frame* (`$fd`), so it can never be mistaken for a frame of the\n// protocol itself; a failed start is carried as an `$error` frame.\n//\n// Why the client filters output frames before handing the transport to the\n// seam: `json1Channel` decodes every line it sees, and the first frame of a\n// session is the peer's `$proto`. Stripping output frames in the transport\n// keeps the protocol view clean without the seam knowing anything about them.\n\nimport { createReadStream, createWriteStream } from \"node:fs\";\nimport * as readline from \"node:readline\";\nimport type { Readable, Writable } from \"node:stream\";\nimport { isProto, type Channel, type StringTransport } from \"./channel.js\";\nimport { VERSION, json1Channel } from \"./protocols/json1.js\";\n\n/** The stream pair a line transport talks over. */\nexport interface LineStreams {\n read: Readable;\n write: Writable;\n}\n\n/** A stream of the far end's process: its stdout or its stderr. */\nexport type OutputFd = 1 | 2;\n\n/** Where the far end's own output goes. */\nexport type OutputSink = (fd: OutputFd, data: string) => void;\n\n/** How long to wait for the far end's first protocol frame. */\nexport const HANDSHAKE_TIMEOUT_MS = 15_000;\n\nconst OUTPUT_KEY = \"$fd\";\n\nconst ERROR_KEY = \"$error\";\n\n/** Raised when the wire itself fails: no frame, the wrong protocol, a peer that went away. */\nexport class StdioWireError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"StdioWireError\";\n }\n}\n\n// ── output frames ──────────────────────────────────────────────────────────\n\n/** One frame of the far end's own output. */\nexport interface OutputFrame {\n fd: OutputFd;\n data: string;\n}\n\nexport function outputFrame(fd: OutputFd, data: string): string {\n return JSON.stringify({ [OUTPUT_KEY]: fd, data });\n}\n\n/** The output frame a line carries, or null when it carries something else. */\nexport function parseOutputFrame(line: string): OutputFrame | null {\n // Cheap reject first: almost every line of a session is protocol traffic.\n if (!line.startsWith('{\"$fd\"')) return null;\n let parsed: unknown;\n try {\n parsed = JSON.parse(line);\n } catch {\n return null;\n }\n if (typeof parsed !== \"object\" || parsed === null) return null;\n const frame = parsed as Record<string, unknown>;\n const fd = frame[OUTPUT_KEY];\n const data = frame.data;\n if (fd !== 1 && fd !== 2) return null;\n return { fd, data: typeof data === \"string\" ? data : JSON.stringify(data) };\n}\n\nexport function errorFrame(reason: string): string {\n return JSON.stringify({ [ERROR_KEY]: reason });\n}\n\n/** The reason an `$error` frame carries, or null when it is not one. */\nexport function errorReason(frame: Record<string, unknown>): string | null {\n const reason = frame[ERROR_KEY];\n return typeof reason === \"string\" ? reason : null;\n}\n\n// ── transports ─────────────────────────────────────────────────────────────\n\n/** Is this write error just a peer that already left? */\nfunction peerGone(code: unknown): boolean {\n return (\n code === \"EPIPE\" ||\n code === \"ERR_STREAM_DESTROYED\" ||\n code === \"ERR_STREAM_WRITE_AFTER_END\" ||\n code === \"ERR_STREAM_ALREADY_FINISHED\"\n );\n}\n\nfunction errorText(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\n/**\n * A `StringTransport` over a read/write stream pair, one JSON frame per line.\n *\n * `close()` is idempotent and never throws: teardown races are normal here —\n * the peer exits, the read side ends, and a write arrives a moment later.\n */\nexport class LineTransport implements StringTransport {\n private readonly streams: LineStreams;\n private pvtOnMessage: ((line: string) => void) | null = null;\n private pvtOnClose: (() => void) | null = null;\n private pvtClosed = false;\n private pvtClosing: Promise<void> | null = null;\n\n constructor(streams: LineStreams) {\n this.streams = streams;\n const lines = readline.createInterface({ input: streams.read });\n lines.on(\"line\", (line) => {\n if (this.pvtOnMessage && !this.pvtClosed) this.pvtOnMessage(line);\n });\n lines.on(\"close\", () => {\n this.pvtOnClose?.();\n void this.close();\n });\n // A stream error is a peer that went away, not a reason to take the process\n // down with an unhandled 'error' event.\n streams.read.on(\"error\", () => {\n void this.close();\n });\n streams.write.on(\"error\", () => {\n void this.close();\n });\n }\n\n get closed(): boolean {\n return this.pvtClosed;\n }\n\n get hasHandler(): boolean {\n return this.pvtOnMessage !== null;\n }\n\n onMessage(handler: (line: string) => void): void {\n if (this.pvtClosed) throw new StdioWireError(\"stdio transport: closed\");\n if (this.pvtOnMessage !== null) {\n throw new StdioWireError(\"stdio transport: handler already set — call removeHandler()\");\n }\n this.pvtOnMessage = handler;\n }\n\n removeHandler(): ((line: string) => void) | null {\n const previous = this.pvtOnMessage;\n this.pvtOnMessage = null;\n return previous;\n }\n\n onClose(handler: () => void): void {\n this.pvtOnClose = handler;\n }\n\n send(frame: string): Promise<void> {\n if (this.pvtClosed) {\n return Promise.resolve();\n }\n const line = frame.endsWith(\"\\n\") ? frame : `${frame}\\n`;\n return new Promise<void>((resolve, reject) => {\n try {\n this.streams.write.write(line, (err?: Error | null) => {\n if (!err) return resolve();\n const code = (err as { code?: unknown }).code;\n // A peer that has hung up cannot be told anything; the write that\n // races its exit is not an error in this transport.\n if (peerGone(code)) {\n return resolve();\n }\n reject(new StdioWireError(`stdio transport: ${err.message}`));\n });\n } catch (err) {\n reject(new StdioWireError(`stdio transport: ${errorText(err)}`));\n }\n });\n }\n\n async close(): Promise<void> {\n this.pvtClosing ??= this.pvtClose();\n await this.pvtClosing;\n }\n\n private async pvtClose(): Promise<void> {\n await Promise.resolve();\n\n this.pvtClosed = true;\n // Best effort: a half-open stream (the peer is already gone) must not turn\n // teardown into an exception.\n try {\n this.streams.read.destroy?.();\n } catch {\n /* already gone */\n }\n try {\n if (!this.streams.write.writableEnded) this.streams.write.end();\n } catch {\n /* already gone */\n }\n }\n}\n\n/** Streams over two fds of *our own* process — the child side of an fd wire. */\nexport function fdStreams(readFd: number, writeFd: number): LineStreams {\n const read = createReadStream(\"\", { fd: readFd, encoding: \"utf-8\", autoClose: false });\n const write = createWriteStream(\"\", { fd: writeFd, encoding: \"utf-8\", autoClose: false });\n return { read, write };\n}\n\n/**\n * A transport that lifts output frames out of the stream: everything else is\n * passed through untouched, so the protocol sees frames and only frames.\n */\nexport class OutputFilter implements StringTransport {\n private readonly inner: StringTransport;\n private readonly sink: OutputSink;\n\n constructor(inner: StringTransport, sink: OutputSink) {\n this.inner = inner;\n this.sink = sink;\n }\n\n send(frame: string): void | Promise<void> {\n return this.inner.send(frame);\n }\n\n onMessage(handler: (frame: string) => void): void {\n this.inner.onMessage((line) => {\n const output = parseOutputFrame(line);\n if (output) this.sink(output.fd, output.data);\n else handler(line);\n });\n }\n\n removeHandler(): void {\n this.inner.removeHandler();\n }\n\n onClose(handler: () => void): void {\n this.inner.onClose(handler);\n }\n\n close(): Promise<void> {\n return this.inner.close();\n }\n}\n\n// ── sinks ──────────────────────────────────────────────────────────────────\n\n/** Write the far end's output to our stderr, tagged with its name. */\nexport function stderrSink(name = \"\"): OutputSink {\n const tag = name ? `[${name}] ` : \"\";\n return (fd, data) => {\n const lead = fd === 1 ? tag : `${tag}err: `;\n for (const line of data.split(\"\\n\")) {\n if (line.length > 0) process.stderr.write(`${lead}${line}\\n`);\n }\n };\n}\n\n// ── handshakes ─────────────────────────────────────────────────────────────\n\n/** The next frame that arrives, or a timeout. */\nasync function nextFrame(channel: Channel, timeoutMs: number): Promise<Record<string, unknown>> {\n return await new Promise((resolve, reject) => {\n const timer = setTimeout(\n () => reject(new StdioWireError(`no protocol frame within ${timeoutMs}ms`)),\n timeoutMs,\n );\n timer.unref?.();\n channel.onMessage((frame) => {\n clearTimeout(timer);\n resolve(frame);\n });\n });\n}\n\nexport interface ClientChannelOptions {\n /** Where the far end's own output goes. Defaults to our stderr. */\n onOutput?: OutputSink;\n /** How long to wait for the peer's protocol frame. Defaults to {@link HANDSHAKE_TIMEOUT_MS}. */\n timeoutMs?: number;\n}\n\n/**\n * The client end of the wire: hand the streams to the seam (minus output\n * frames) and wait for the peer's `$proto`. A first stage reports a failed\n * start as an `$error` frame instead.\n */\nexport async function clientChannel(\n streams: LineStreams,\n opts: ClientChannelOptions = {},\n): Promise<Channel> {\n const transport = new LineTransport(streams);\n const channel = json1Channel(new OutputFilter(transport, opts.onOutput ?? stderrSink()));\n const frame = await nextFrame(channel, opts.timeoutMs ?? HANDSHAKE_TIMEOUT_MS);\n channel.removeHandler();\n\n const reason = errorReason(frame);\n if (reason) throw new StdioWireError(reason);\n if (!isProto(frame)) {\n throw new StdioWireError(`unexpected first frame: ${JSON.stringify(frame).slice(0, 120)}`);\n }\n if (frame.$proto !== VERSION) {\n throw new StdioWireError(`unsupported protocol ${String(frame.$proto)}, expected ${VERSION}`);\n }\n return channel;\n}\n\n/** The server end of the wire — a payload speaking stdio itself. */\nexport async function serverChannel(streams: LineStreams): Promise<Channel> {\n const channel = json1Channel(new LineTransport(streams));\n await channel.send({ $proto: VERSION });\n return channel;\n}\n","// ── FIFO transport ─────────────────────────────────────────────────────────\n//\n// Newline-delimited UTF-8 over named fifos. Strict handler lifecycle:\n// onMessage() throws if a handler is already set; call removeHandler() first.\n\nimport { open, type FileHandle } from \"node:fs/promises\";\nimport type { ReadStream, WriteStream } from \"node:fs\";\nimport * as readline from \"node:readline\";\nimport type { StringTransport } from \"../channel.js\";\n\nexport class FifoUtf8NlineTransport implements StringTransport {\n private readFd: FileHandle | null;\n private writeFd: FileHandle | null;\n private rl: readline.Interface | null;\n private rs: ReadStream | null;\n private ws: WriteStream | null;\n private pvtOnMessage: ((line: string) => void) | null = null;\n private pvtOnClose: (() => void) | null = null;\n private closed = false;\n private closingPromise: Promise<void> | null = null;\n private pvtError: Error | null = null;\n\n private constructor(opts: { readFd?: FileHandle; writeFd?: FileHandle }) {\n this.readFd = opts.readFd ?? null;\n this.writeFd = opts.writeFd ?? null;\n\n if (this.readFd) {\n this.rs = this.readFd.createReadStream({ encoding: \"utf-8\" });\n this.rl = readline.createInterface({ input: this.rs });\n\n this.rl.on(\"line\", (line) => {\n if (this.pvtOnMessage && !this.closed) this.pvtOnMessage(line);\n });\n\n this.rl.on(\"close\", () => {\n this.pvtOnClose?.();\n this.close();\n });\n\n this.rs.on(\"error\", (err: Error) => {\n this.pvtError = err;\n this.close();\n });\n } else {\n this.rs = null;\n this.rl = null;\n }\n\n if (this.writeFd) {\n this.ws = this.writeFd.createWriteStream({ encoding: \"utf-8\" });\n this.ws.on(\"error\", (err: Error) => {\n this.pvtError = err;\n this.close();\n });\n } else {\n this.ws = null;\n }\n }\n\n // ── factories ──────────────────────────────────────────────────────────\n\n static openReaderFd(readFd: FileHandle): FifoUtf8NlineTransport {\n return new FifoUtf8NlineTransport({ readFd });\n }\n\n static openWriterFd(writeFd: FileHandle): FifoUtf8NlineTransport {\n return new FifoUtf8NlineTransport({ writeFd });\n }\n\n static fromFds(readFd: FileHandle, writeFd: FileHandle): FifoUtf8NlineTransport {\n return new FifoUtf8NlineTransport({ readFd, writeFd });\n }\n\n // ── bidirectional connection ───────────────────────────────────────────\n\n /**\n * Start opening a bidirectional connection. Opens readPath for reading\n * in the background, returns a promise. The caller should do whatever\n * setup is needed to unblock the read (e.g. spawn a process that opens\n * readPath for writing), then await the returned transport.\n *\n * The transport itself is built only once both directions are open. A read\n * stream created while no writer exists on its fifo is handed an immediate\n * end-of-stream by some runtimes (bun), which closes a channel that has not\n * carried a byte yet — so the writes side is opened before the reader exists.\n */\n static beginConnect(\n readPath: string,\n writePath: string,\n ): { transport: Promise<FifoUtf8NlineTransport> } {\n const readFdPromise = open(readPath, \"r\");\n\n const transport = readFdPromise.then(async (readFd) => {\n const writeFd = await open(writePath, \"w\");\n return FifoUtf8NlineTransport.fromFds(readFd, writeFd);\n });\n\n return { transport };\n }\n\n /**\n * Open a bidirectional connection. Opens writePath for writing first\n * (unblocking the peer's read), starts reading readPath in the\n * background, then awaits both.\n *\n * Use this when you are the side that responds to the peer's beginConnect\n * (i.e. you don't need to interleave any setup between the read and write\n * opens). Built like `beginConnect`: the transport exists only after both\n * directions do.\n */\n static async connect(readPath: string, writePath: string): Promise<FifoUtf8NlineTransport> {\n const readFdPromise = open(readPath, \"r\");\n const writeFd = await open(writePath, \"w\");\n const readFd = await readFdPromise;\n return FifoUtf8NlineTransport.fromFds(readFd, writeFd);\n }\n\n // ── public API ─────────────────────────────────────────────────────────\n\n get canSend(): boolean {\n return this.writeFd !== null && !this.closed;\n }\n\n onMessage(handler: (line: string) => void): void {\n if (this.closed) throw new Error(\"FifoUtf8NlineTransport: closed\");\n if (this.readFd === null) throw new Error(\"FifoUtf8NlineTransport: not a reader\");\n if (this.pvtOnMessage !== null) {\n throw new Error(\"FifoUtf8NlineTransport: handler already set — call removeHandler() first\");\n }\n this.pvtOnMessage = handler;\n }\n\n removeHandler(): ((line: string) => void) | null {\n const prev = this.pvtOnMessage;\n this.pvtOnMessage = null;\n return prev;\n }\n\n onClose(handler: () => void): void {\n this.pvtOnClose = handler;\n }\n\n get hasHandler(): boolean {\n return this.pvtOnMessage !== null;\n }\n\n get lastError(): Error | null {\n return this.pvtError;\n }\n\n async send(line: string): Promise<void> {\n if (this.closed) throw new Error(\"FifoUtf8NlineTransport: closed\");\n if (this.writeFd === null) throw new Error(\"FifoUtf8NlineTransport: not a writer\");\n if (!line.endsWith(\"\\n\")) line += \"\\n\";\n await this.ws?.write(line);\n }\n\n async close(): Promise<void> {\n this.closingPromise = this.closingPromise || this.pvtClose();\n await this.closingPromise;\n this.closed = true;\n }\n\n private async pvtClose(): Promise<void> {\n // tranfser control back to caller\n // so they can capture the promise reference\n // and prevent reentry\n await Promise.resolve();\n\n if (this.rl) {\n this.rl.close();\n this.rl = null;\n }\n if (this.rs) {\n this.rs.destroy();\n this.rs = null;\n }\n if (this.ws) {\n await new Promise<void>((resolve) => {\n try {\n this.ws?.end(\"\", resolve);\n } catch {\n resolve();\n }\n });\n this.ws = null;\n }\n\n if (this.readFd) {\n try {\n await this.readFd.close();\n } catch {}\n this.readFd = null;\n }\n if (this.writeFd) {\n try {\n await this.writeFd.close();\n } catch {}\n this.writeFd = null;\n }\n }\n}\n","// ── Gateway ────────────────────────────────────────────────────────────────\n//\n// The first-stage command. Run this *inside* a foreign environment — directly,\n// under `sudo`, over ssh, in a container — and it:\n//\n// 1. creates the channel to the payload (fifo paths it makes itself, in a\n// private temp dir, so they belong to the uid that will open them),\n// 2. starts the payload — the first argument, required — hands it everything else it was\n// given (the host version among it) and relays frames between stdin/stdout,\n// 3. carries whatever the payload prints to the client as output frames\n// (`$fd`), so the payload's own stdout can never be mistaken for protocol.\n//\n// Why a gateway at all: a fifo path created on the client side is useless when the\n// payload runs as another uid (it cannot open it) or on another host (the path is\n// not there). stdio is the one channel every way into an environment gives us, so\n// the wire is stdio and the fifo stays inside the environment.\n//\n// The gateway reads nothing out of what it carries and owns no flag: the payload's path and\n// every argument after it go through verbatim, in order. The payload is the one who refuses a\n// host version it is not, and a relay that judged would be a second place for that decision.\n//\n// Directories and processes are cleaned up on every exit path, which is also why\n// the client never sees a transport being closed twice.\n//\n// It imports nothing but node builtins and this package, so the payload behind it\n// can be anything the runtime there can start.\n\nimport { execFile, spawn } from \"node:child_process\";\nimport type { ChildProcess } from \"node:child_process\";\nimport { mkdtemp, rm } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { basename, join } from \"node:path\";\nimport { promisify } from \"node:util\";\nimport { errorFrame, outputFrame } from \"./stdio.js\";\nimport type { LineTransport, OutputFd } from \"./stdio.js\";\nimport { LineTransport as Lines } from \"./stdio.js\";\nimport { FifoUtf8NlineTransport } from \"./transports/fifo.js\";\n\nconst run = promisify(execFile);\n\n/** Exit code for \"this environment could not be set up\". */\nexport const GATEWAY_FAILED = 1;\n\nexport interface GatewayBoot {\n /**\n * The program to start for the payload: the first word of the command the client composed —\n * a runtime, or a program that runs itself. Required, and first, and the gateway has no\n * opinion of its own about which it is.\n */\n worker: string;\n /**\n * Everything after the payload, carried to it **as is** and in order: the consumer's own\n * arguments, and posipaki's own facts among them (the host version travels this way). The\n * gateway reads nothing by name and owns no flag, so nothing of the caller's is interpreted,\n * eaten, re-ordered or re-spelled — and the next fact added to that line needs no new\n * vocabulary here.\n */\n passthrough: string[];\n}\n\nfunction errorText(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\n/**\n * A label for the gateway's own temp directory: the program this environment was made for.\n * It is the gateway's business alone — the payload is not told which label it is.\n */\nfunction label(worker: string): string {\n const name = basename(worker).replace(/[^A-Za-z0-9.+@_-]/g, \"-\").slice(0, 60);\n return name === \"\" ? \"payload\" : name;\n}\n\n/**\n * The argv that boots this gateway — built by the client, read by\n * {@link gatewayBoot}, so the two halves cannot drift apart.\n *\n * The payload comes first and its arguments after it, so a positional argument of the\n * payload's own can never be mistaken for the payload.\n */\nexport function gatewayArgs(boot: GatewayBoot): string[] {\n return [boot.worker, ...boot.passthrough];\n}\n\n/** The boot a gateway was started with, or the reason it cannot start. */\nexport function gatewayBoot(argv: string[]): GatewayBoot {\n const [worker, ...passthrough] = argv;\n if (worker === undefined || worker.startsWith(\"--\")) {\n throw new Error(\"no <payload>: the gateway relays to a payload, named as its first argument\");\n }\n return { passthrough, worker };\n}\n\n/**\n * End a start that failed. The reason has already gone out on the wire, and\n * returning is not enough: the `open()` on a fifo no payload will ever write sits\n * in the threadpool forever, so the loop never drains and the gateway would linger\n * with a dead payload on its books.\n */\nfunction abandon(): never {\n process.exit(GATEWAY_FAILED);\n}\n\n/** Carry a failed start to the client, then let the caller exit non-zero. */\nasync function fail(wire: LineTransport, reason: string): Promise<void> {\n process.stderr.write(`gateway: ${reason}\\n`);\n try {\n await wire.send(errorFrame(reason));\n } catch {\n /* the client is gone too — the exit code still says what happened */\n }\n}\n\n/** Copy everything the payload prints onto the wire as output frames. */\nfunction forwardOutput(stream: NodeJS.ReadableStream, wire: LineTransport, fd: OutputFd): void {\n stream.setEncoding(\"utf-8\");\n stream.on(\"data\", (chunk: string) => {\n void wire.send(outputFrame(fd, chunk)).catch(() => {\n /* the client hung up: the payload's exit is what matters now */\n });\n });\n}\n\n/**\n * Serve one environment over stdin/stdout. Returns the exit code; the caller\n * turns it into `process.exitCode`.\n */\nexport async function runGateway(argv: string[] = process.argv.slice(2)): Promise<number> {\n const wire = new Lines({ read: process.stdin, write: process.stdout });\n\n let booted: GatewayBoot;\n try {\n booted = gatewayBoot(argv);\n } catch (err) {\n // Nothing has been started yet, so there is nothing to tear down — but the\n // client still deserves the reason rather than a channel that closes on it,\n // and the loop can outlive us: an open stdin nobody will close keeps the\n // process alive, so this is an exit, not a return.\n await fail(wire, errorText(err));\n abandon();\n }\n const { passthrough, worker } = booted;\n\n const dir = await mkdtemp(join(tmpdir(), `posipaki-${label(worker)}-`));\n const fifoIn = join(dir, \"in\"); // the payload writes, we read\n const fifoOut = join(dir, \"out\"); // we write, the payload reads\n\n let child: ChildProcess | null = null;\n let fifo: FifoUtf8NlineTransport | null = null;\n\n /**\n * Everything this gateway owns, undone. All of it is idempotent, because the\n * exit path and the signal path can both arrive.\n */\n const teardown = async (): Promise<void> => {\n child?.kill();\n await fifo?.close().catch(() => {});\n await rm(dir, { recursive: true, force: true }).catch(() => {});\n };\n\n /**\n * A client that gives up stops us with a signal, and a gateway that died on the\n * spot would leave its payload behind in the environment — a process holding a\n * fifo nobody will ever write, which is a leak the environment cannot clean up\n * for us. So the signals do what the exit path does.\n */\n const onTerminate = () => {\n void teardown()\n .catch(() => {})\n .then(() => process.exit(GATEWAY_FAILED));\n };\n for (const signal of [\"SIGTERM\", \"SIGINT\", \"SIGHUP\"] as const) process.on(signal, onTerminate);\n\n try {\n await run(\"mkfifo\", [\"-m\", \"600\", fifoIn, fifoOut]);\n } catch (err) {\n await fail(wire, `cannot create the environment's fifos: ${errorText(err)}`);\n await teardown();\n abandon();\n }\n\n // Open the read side in the background, then start the payload that unblocks\n // it — the order the fifo handshake requires.\n const connection = FifoUtf8NlineTransport.beginConnect(fifoIn, fifoOut);\n const workerArgs = [worker, ...passthrough, `--fifo-in=${fifoIn}`, `--fifo-out=${fifoOut}`];\n // Whatever the client said starts the payload, run as it said: a runtime with a script of\n // ours, or a program of the caller's own. The gateway does not know which it is, and does\n // not choose a runtime on the far end's behalf.\n const workerProc = spawn(workerArgs[0]!, workerArgs.slice(1), {\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n });\n child = workerProc;\n forwardOutput(workerProc.stdout, wire, 1);\n forwardOutput(workerProc.stderr, wire, 2);\n\n const exited = new Promise<number>((settle) => {\n // A payload killed by a signal (the client hung up, and we killed it) has no\n // code — for us that is a clean end, not a failure.\n workerProc.once(\"exit\", (code) => settle(code ?? 0));\n });\n\n try {\n fifo = await Promise.race([\n connection.transport,\n exited.then((code) => {\n throw new Error(`the payload exited with code ${code} before it opened its channel`);\n }),\n ]);\n } catch (err) {\n await fail(wire, errorText(err));\n await teardown();\n abandon();\n }\n\n // Relay: the protocol is the client's and the payload's business, not ours.\n const relay = fifo;\n relay.onMessage((line) => {\n void wire.send(line).catch(() => {\n /* client gone */\n });\n });\n wire.onMessage((line) => {\n void relay.send(line).catch(() => {\n /* the payload is gone; its exit path cleans up */\n });\n });\n wire.onClose(() => {\n child?.kill();\n });\n\n const code = await exited;\n await teardown();\n await wire.close();\n return code;\n}\n","// ── The gateway, as a program ──────────────────────────────────────────────\n//\n// A gateway is something a client runs: the first-stage command that makes a fifo\n// inside a foreign environment and relays frames between its own stdin/stdout and\n// the payload. That is this file's whole job — it always serves, and it exits with\n// the code the run ended in.\n//\n// Serving lives in ./gateway.js and starts nothing by itself. A file cannot decide\n// \"am I the program?\" from where it is: a consumer that bundles the node surface\n// into its own program carries this code along, and there the bundle *is* the\n// program — a payload would find a gateway booting on its wire. So the decision is\n// in the layout instead: importing a module never starts anything, and running this\n// one always does.\n//\n// The client names it either way: `posipaki/remote/gateway-cli.js` is a published\n// specifier, so `import.meta.resolve` answers with the built file, and a consumer\n// with a program of its own stages that instead. Nothing here works out its own\n// location — a path derived from `import.meta.url` is a guess about a layout the\n// bundler owns, and the guess is wrong the moment the module moves into a chunk.\n\nimport { GATEWAY_FAILED, runGateway } from \"./gateway.js\";\n\nvoid (async () => {\n try {\n process.exitCode = await runGateway();\n } catch (err) {\n process.stderr.write(`gateway: ${err instanceof Error ? err.message : String(err)}\\n`);\n process.exitCode = GATEWAY_FAILED;\n }\n})();\n"],"mappings":";;;;;;;AAyCA,MAAM,aAAa;AAEnB,MAAM,YAAY;;AAGlB,IAAa,iBAAb,cAAoC,MAAM;CACxC,YAAY,SAAiB;EAC3B,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF;AAUA,SAAgB,YAAY,IAAc,MAAsB;CAC9D,OAAO,KAAK,UAAU;GAAG,aAAa;EAAI;CAAK,CAAC;AAClD;AAoBA,SAAgB,WAAW,QAAwB;CACjD,OAAO,KAAK,UAAU,GAAG,YAAY,OAAO,CAAC;AAC/C;;AAWA,SAAS,SAAS,MAAwB;CACxC,OACE,SAAS,WACT,SAAS,0BACT,SAAS,gCACT,SAAS;AAEb;AAEA,SAASA,YAAU,KAAsB;CACvC,OAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AACxD;;;;;;;AAQA,IAAa,gBAAb,MAAsD;CAOpD,YAAY,SAAsB;EALsB,KAAA,eAAA;EACd,KAAA,aAAA;EACtB,KAAA,YAAA;EACuB,KAAA,aAAA;EAGzC,K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SAAS;CACf,MAAM,KAAK,MAAM;CACjB,OAAO;AACT;;;CCpNM,YAAY;CAChB,IAAI;EACF,QAAQ,WAAW,MAAM,WAAW;CACtC,SAAS,KAAK;EACZ,QAAQ,OAAO,MAAM,YAAY,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,EAAE,GAAG;EACrF,QAAQ,WAAA;CACV;AACF,EAAA,CAAG"}
|
|
1
|
+
{"version":3,"file":"gateway-cli.js","names":["errorFrame","wireErrorFrame","errorText","Lines"],"sources":["../../src/remote/channel.ts","../../src/remote/stdio.ts","../../src/remote/transports/fifo.ts","../../src/remote/gateway.ts","../../src/remote/gateway-cli.ts"],"sourcesContent":["// ── Frame channel ──────────────────────────────────────────────────────────\n//\n// The seam's shared vocabulary. A StringTransport moves encoded frames\n// (strings); a Channel moves decoded frame objects. The frame guards narrow a\n// decoded frame to one of the `$`-key shapes. server.ts / client.ts speak only\n// in Channels and these guards — they never see a specific protocol or\n// transport.\n\nimport type { Message } from \"../types.js\";\nimport {\n decodeProcessRefs,\n encodeProcessRefs,\n type ProcessTable,\n type RefResolver,\n} from \"./process-ref.js\";\n\nexport interface StringTransport {\n send(frame: string): void | Promise<void>;\n onMessage(handler: (frame: string) => void): void;\n removeHandler(): void;\n /** Fires when the peer disconnects (transport closes from the other side). */\n onClose(handler: () => void): void;\n close(): Promise<void>;\n}\n\nexport interface Channel {\n send(frame: Record<string, unknown>): void | Promise<void>;\n onMessage(handler: (frame: Record<string, unknown>) => void): void;\n removeHandler(): void;\n /** Fires when the peer disconnects (transport closes from the other side). */\n onClose(handler: () => void): void;\n close(): Promise<void>;\n}\n\n// ── the address on a frame ─────────────────────────────────────────────────\n//\n// A frame that is about a process carries that process's id as `to`, at the top level\n// of the frame rather than inside its body: the frame is the envelope, and the address\n// says who it is for whatever kind it turns out to be. Every frame that is about a\n// process names it, the root of the connection included, since both ends number their\n// own root and neither has to be guessed at.\n\n/** The id a frame addresses, or null when it names no process. */\nexport function frameTo(frame: Record<string, unknown>): number | null {\n const to = frame.to;\n return typeof to === \"number\" ? to : null;\n}\n\n/**\n * A frame on its way out: every process in it becomes the reference this\n * connection uses for that process, and the process the frame addresses is\n * written down as `to`.\n */\nexport function encodeFrame(\n frame: Record<string, unknown>,\n table: ProcessTable,\n to: number,\n): Record<string, unknown> {\n const encoded = encodeProcessRefs(frame, table) as Record<string, unknown>;\n return { ...encoded, to };\n}\n\n/**\n * A frame just read: every reference in it becomes a handle on that process — or\n * the handle this side already made for it, since the same process handed over\n * twice is one process.\n */\nexport function decodeFrame(\n frame: Record<string, unknown>,\n resolve: RefResolver,\n): Record<string, unknown> {\n return decodeProcessRefs(frame, resolve) as Record<string, unknown>;\n}\n\n// ── frame guards ──────────────────────────────────────────────────────────\n\nexport function isProto(msg: Record<string, unknown>): msg is { $proto: string } {\n return \"$proto\" in msg;\n}\nexport function isInit(msg: Record<string, unknown>): msg is { $init: Record<string, unknown> } {\n return \"$init\" in msg;\n}\nexport function isState(msg: Record<string, unknown>): msg is { $state: Record<string, unknown> } {\n return \"$state\" in msg;\n}\nexport function isMsg(\n msg: Record<string, unknown>,\n): msg is { $msg: { fromName: string; body: Message } } {\n return \"$msg\" in msg;\n}\nexport function isExit(\n msg: Record<string, unknown>,\n): msg is { $exit: { code: number; state: unknown } } {\n return \"$exit\" in msg;\n}\n\n// ── a wire that could not be read ─────────────────────────────────────────\n//\n// Two frames are about the wire itself and not about a process: what a codec could\n// not read, and what a side says when the wire is over. Neither is addressed to\n// anything, and both are decided before a frame is looked up as news or as an ask —\n// a frame about the wire is about the ground the other frames stand on.\n//\n// {\"$bad\": {\"reason\": \"…\", \"raw\": \"…\"}} this side could not read that frame\n// {\"$error\": \"…\"} the wire cannot be spoken over, and why\n//\n// They are frames rather than raised errors on purpose. A frame is read inside the\n// transport's own callback — a socket's `message` event, a stream's line reader —\n// where a throw belongs to nobody: it arrives at the host as an uncaught exception,\n// and one unreadable frame from one peer takes the process down, every other\n// connection in it included. An unreadable frame is the connection's business, not\n// the process's, so it is carried as a frame the connection can answer: `$bad` is how\n// a reader says it inward, and `$error` is how a side says it outward before ending\n// that connection.\n//\n// `$error` is not a refused call — a call that is refused says so about itself, in\n// `$r.result.<name>` (see below). This one is about the wire the calls travel on.\n\nconst BAD_KEY = \"$bad\";\n\n/** How much of an unreadable line is carried: enough to see what it was, never enough to be it.\n * A line that failed to parse is the one line nobody vouched for, so quoting it whole would move\n * whatever it holds — a credential in a paste accident is how that happens — into every log,\n * transcript and context window that later reads the frame. Why, how long, and a short head of\n * it. (`reason` carries a little of the line on its own: a JSON parser says where it gave up and\n * quotes what it was looking at. That is the parser's business, not a promise this file makes.) */\nexport const BAD_PREFIX_LIMIT = 32;\n\nexport function isBad(msg: Record<string, unknown>): msg is { $bad: { reason: string } } {\n return BAD_KEY in msg;\n}\n\n/** The frame that says a frame could not be read: why, how long it was, and the head of it. */\nexport function badFrame(reason: string, raw: string): Record<string, unknown> {\n const prefix = raw.length > BAD_PREFIX_LIMIT ? `${raw.slice(0, BAD_PREFIX_LIMIT)}…` : raw;\n return { [BAD_KEY]: { reason, length: raw.length, prefix } };\n}\n\n/** Why a frame could not be read, or null when it is not a frame that says so. */\nexport function badReason(msg: Record<string, unknown>): string | null {\n const body = msg[BAD_KEY];\n if (typeof body !== \"object\" || body === null) return null;\n const reason = (body as { reason?: unknown }).reason;\n return typeof reason === \"string\" ? reason : null;\n}\n\nconst ERROR_KEY = \"$error\";\n\nexport function isError(msg: Record<string, unknown>): msg is { $error: string } {\n return ERROR_KEY in msg;\n}\n\n/** The frame that says the wire is over: the reason, and the connection ends with it. */\nexport function errorFrame(reason: string): Record<string, unknown> {\n return { [ERROR_KEY]: reason };\n}\n\n/** The reason a wire error carries, or null when it is not one. */\nexport function errorReason(msg: Record<string, unknown>): string | null {\n const reason = msg[ERROR_KEY];\n return typeof reason === \"string\" ? reason : null;\n}\n\n// ── what is said about a crossed process ────────────────────────────────────\n//\n// A process that crossed can be asked for less than everything, or for nothing at\n// all: what crosses about it is three categories, and only the ones asked for are\n// sent. Silence is the empty list, so a handle that asks for nothing hears\n// nothing — not its state, not its messages, and not that it is gone.\n//\n// {\"$tune\": {\"streams\": [\"state\"]}, \"to\": 3} this much about it, and no more\n\nexport type StreamKind = \"message\" | \"state\" | \"exit\";\n\n/** The three, in the one order they are ever named in — the order a tune frame\n * carries them in, so two ways of asking for the same thing look the same. */\nexport const STREAM_KINDS: StreamKind[] = [\"message\", \"state\", \"exit\"];\n\nexport function isStreamKind(value: unknown): value is StreamKind {\n return typeof value === \"string\" && (STREAM_KINDS as string[]).includes(value);\n}\n\n// ── control frames ─────────────────────────────────────────────────────────\n//\n// What the holder of a handle can ask of a process on the far side, beside\n// sending it a message. Each is a frame of its own rather than a message, so\n// nothing an actor reads is ever a control signal by accident:\n//\n// {\"$stop\": {}, \"to\": 3} stop it; it ends, and its `$exit` crosses back\n// {\"$pause\": {}, \"to\": 3} stop feeding it messages\n// {\"$resume\": {}, \"to\": 3} feed it again\n// {\"$release\": {}, \"to\": 3} let it go: forget this id, and stop telling me\n// about the process behind it\n// {\"$tune\": {\"streams\": [...]}, \"to\": 3}\n// say this much about it and no more: a subset of\n// message, state and exit, or the empty list for\n// silence\n//\n// They address the process they are about, so they are answered by whoever holds\n// that process — the side that can act on it. Stopping the *root* of a connection\n// is not one of these: that stays the STOP message it always was, since the root\n// is not a handle but the process this side is talking through.\n\nexport function isStop(msg: Record<string, unknown>): msg is { $stop: Record<string, unknown> } {\n return \"$stop\" in msg;\n}\nexport function isPause(msg: Record<string, unknown>): msg is { $pause: Record<string, unknown> } {\n return \"$pause\" in msg;\n}\nexport function isResume(msg: Record<string, unknown>): msg is { $resume: Record<string, unknown> } {\n return \"$resume\" in msg;\n}\nexport function isRelease(msg: Record<string, unknown>): msg is { $release: Record<string, unknown> } {\n return \"$release\" in msg;\n}\n\nexport function isTune(msg: Record<string, unknown>): msg is { $tune: Record<string, unknown> } {\n return \"$tune\" in msg;\n}\n\n/**\n * The categories a tune frame asks for, in the order they are named in — or null\n * when the frame says something this vocabulary has no word for, which is a frame\n * to ignore rather than to guess at.\n */\nexport function tuneFrame(frame: { $tune: unknown }): StreamKind[] | null {\n const body = frame.$tune;\n if (typeof body !== \"object\" || body === null) return null;\n const streams = (body as { streams?: unknown }).streams;\n if (!Array.isArray(streams)) return null;\n if (!streams.every(isStreamKind)) return null;\n return STREAM_KINDS.filter((kind) => (streams as StreamKind[]).includes(kind));\n}\n\n// ── reflection frames ──────────────────────────────────────────────────────\n//\n// A reflection call crosses the seam as one frame and its answer as another, and\n// both go both ways: whoever holds a process is the one that answers for it.\n//\n// {\"$r.methods\": [\"inspect.getTree\", …]} what a process can answer, once, when\n// it crosses (and, for the root, once\n// when the connection opens)\n// {\"$r.call.<name>\": {seq, args}} asking, addressed to the process\n// {\"$r.result.<name>\": {seq, value}} answered\n// {\"$r.result.<name>\": {seq, error}} refused\n//\n// The method name is in the frame key, so a frame says what it is without a\n// table, and `seq` — one connection's, never reused — tells two calls to the\n// same method apart while both are in flight. An answer is about the call and not\n// about a process, so it carries no address: it names the seq it settles.\n\nexport const REFLECT_METHODS = \"$r.methods\";\nexport const REFLECT_CALL = \"$r.call.\";\nexport const REFLECT_RESULT = \"$r.result.\";\n\nexport interface ReflectionCall {\n name: string;\n seq: number;\n args: unknown[];\n}\n\nexport interface ReflectionResult {\n name: string;\n seq: number;\n value?: unknown;\n error?: string;\n}\n\nexport function isReflectionMethods(\n msg: Record<string, unknown>,\n): msg is { \"$r.methods\": string[] } {\n const names = msg[REFLECT_METHODS];\n return Array.isArray(names) && names.every((name) => typeof name === \"string\");\n}\n\nfunction reflectionBody(\n frame: Record<string, unknown>,\n prefix: string,\n): { name: string; body: Record<string, unknown> } | null {\n for (const key of Object.keys(frame)) {\n if (!key.startsWith(prefix) || key.length === prefix.length) continue;\n const body = frame[key];\n if (typeof body !== \"object\" || body === null) return null;\n return { name: key.slice(prefix.length), body: body as Record<string, unknown> };\n }\n return null;\n}\n\n/** A call frame, or null — a malformed one is not worth an answer. */\nexport function asReflectionCall(frame: Record<string, unknown>): ReflectionCall | null {\n const parsed = reflectionBody(frame, REFLECT_CALL);\n if (!parsed || typeof parsed.body.seq !== \"number\") return null;\n const args = parsed.body.args;\n return {\n name: parsed.name,\n seq: parsed.body.seq,\n args: Array.isArray(args) ? args : [],\n };\n}\n\n/** An answer frame, or null. `error` present means the call was refused. */\nexport function asReflectionResult(frame: Record<string, unknown>): ReflectionResult | null {\n const parsed = reflectionBody(frame, REFLECT_RESULT);\n if (!parsed || typeof parsed.body.seq !== \"number\") return null;\n const { seq, value, error } = parsed.body;\n return typeof error === \"string\"\n ? { name: parsed.name, seq, error }\n : { name: parsed.name, seq, value };\n}\n\n/**\n * Why a value cannot cross a frame, or null when it can. Only JSON data\n * crosses: a function, a symbol or a bigint cannot be written down at all, and\n * a value with a cycle or a bigint inside it makes the encoder throw. What\n * JSON itself would quietly drop — a function stored inside an object — is the\n * caller's business, not something to invent a policy for here.\n */\nexport function jsonProblem(value: unknown): string | null {\n const kind = typeof value;\n if (kind === \"function\" || kind === \"symbol\" || kind === \"bigint\") return `a ${kind}`;\n if (kind !== \"object\" || value === null) return null;\n try {\n JSON.stringify(value);\n } catch (err) {\n return err instanceof Error ? err.message : String(err);\n }\n return null;\n}\n","// ── stdio wire ─────────────────────────────────────────────────────────────\n//\n// A newline-delimited JSON channel over a pair of streams: the one wire every\n// way into a foreign execution context can carry. Two callers rely on it, and\n// they are two halves of the same thing:\n//\n// * the client of a spawn we make ourselves, on fds handed to the child (see\n// `fdStreams`) — private fds, so the child's own stdout stays free;\n// * a first-stage command on its own stdin/stdout, over ssh, under `sudo`, in\n// a container — where stdio is the only channel there is.\n//\n// Frames are one JSON object per line. Whatever the far end prints is carried\n// as an *output frame* (`$fd`), so it can never be mistaken for a frame of the\n// protocol itself; a failed start is carried as an `$error` frame.\n//\n// Why the client filters output frames before handing the transport to the\n// seam: `json1Channel` decodes every line it sees, and the first frame of a\n// session is the peer's `$proto`. Stripping output frames in the transport\n// keeps the protocol view clean without the seam knowing anything about them.\n\nimport { createReadStream, createWriteStream } from \"node:fs\";\nimport * as readline from \"node:readline\";\nimport type { Readable, Writable } from \"node:stream\";\nimport {\n errorFrame as wireErrorFrame,\n errorReason as wireErrorReason,\n isProto,\n type Channel,\n type StringTransport,\n} from \"./channel.js\";\nimport { VERSION, json1Channel } from \"./protocols/json1.js\";\n\n/** The stream pair a line transport talks over. */\nexport interface LineStreams {\n read: Readable;\n write: Writable;\n}\n\n/** A stream of the far end's process: its stdout or its stderr. */\nexport type OutputFd = 1 | 2;\n\n/** Where the far end's own output goes. */\nexport type OutputSink = (fd: OutputFd, data: string) => void;\n\n/** How long to wait for the far end's first protocol frame. */\nexport const HANDSHAKE_TIMEOUT_MS = 15_000;\n\nconst OUTPUT_KEY = \"$fd\";\n\n/** Raised when the wire itself fails: no frame, the wrong protocol, a peer that went away. */\nexport class StdioWireError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"StdioWireError\";\n }\n}\n\n// ── output frames ──────────────────────────────────────────────────────────\n\n/** One frame of the far end's own output. */\nexport interface OutputFrame {\n fd: OutputFd;\n data: string;\n}\n\nexport function outputFrame(fd: OutputFd, data: string): string {\n return JSON.stringify({ [OUTPUT_KEY]: fd, data });\n}\n\n/** The output frame a line carries, or null when it carries something else. */\nexport function parseOutputFrame(line: string): OutputFrame | null {\n // Cheap reject first: almost every line of a session is protocol traffic.\n if (!line.startsWith('{\"$fd\"')) return null;\n let parsed: unknown;\n try {\n parsed = JSON.parse(line);\n } catch {\n return null;\n }\n if (typeof parsed !== \"object\" || parsed === null) return null;\n const frame = parsed as Record<string, unknown>;\n const fd = frame[OUTPUT_KEY];\n const data = frame.data;\n if (fd !== 1 && fd !== 2) return null;\n return { fd, data: typeof data === \"string\" ? data : JSON.stringify(data) };\n}\n\n/** An `$error` frame as a line. The word and its shape are the shared vocabulary's\n * (channel.ts) — one word for a wire that cannot be spoken over, whether the failure was at\n * the start of a session or in the middle of one; what this file owns is its line form. */\nexport function errorFrame(reason: string): string {\n return JSON.stringify(wireErrorFrame(reason));\n}\n\n/** The reason an `$error` frame carries, or null when it is not one. */\nexport function errorReason(frame: Record<string, unknown>): string | null {\n return wireErrorReason(frame);\n}\n\n// ── transports ─────────────────────────────────────────────────────────────\n\n/** Is this write error just a peer that already left? */\nfunction peerGone(code: unknown): boolean {\n return (\n code === \"EPIPE\" ||\n code === \"ERR_STREAM_DESTROYED\" ||\n code === \"ERR_STREAM_WRITE_AFTER_END\" ||\n code === \"ERR_STREAM_ALREADY_FINISHED\"\n );\n}\n\nfunction errorText(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\n/**\n * A `StringTransport` over a read/write stream pair, one JSON frame per line.\n *\n * `close()` is idempotent and never throws: teardown races are normal here —\n * the peer exits, the read side ends, and a write arrives a moment later.\n */\nexport class LineTransport implements StringTransport {\n private readonly streams: LineStreams;\n private pvtOnMessage: ((line: string) => void) | null = null;\n private pvtOnClose: (() => void) | null = null;\n private pvtClosed = false;\n private pvtClosing: Promise<void> | null = null;\n\n constructor(streams: LineStreams) {\n this.streams = streams;\n const lines = readline.createInterface({ input: streams.read });\n lines.on(\"line\", (line) => {\n if (this.pvtOnMessage && !this.pvtClosed) this.pvtOnMessage(line);\n });\n lines.on(\"close\", () => {\n this.pvtOnClose?.();\n void this.close();\n });\n // A stream error is a peer that went away, not a reason to take the process\n // down with an unhandled 'error' event.\n streams.read.on(\"error\", () => {\n void this.close();\n });\n streams.write.on(\"error\", () => {\n void this.close();\n });\n }\n\n get closed(): boolean {\n return this.pvtClosed;\n }\n\n get hasHandler(): boolean {\n return this.pvtOnMessage !== null;\n }\n\n onMessage(handler: (line: string) => void): void {\n if (this.pvtClosed) throw new StdioWireError(\"stdio transport: closed\");\n if (this.pvtOnMessage !== null) {\n throw new StdioWireError(\"stdio transport: handler already set — call removeHandler()\");\n }\n this.pvtOnMessage = handler;\n }\n\n removeHandler(): ((line: string) => void) | null {\n const previous = this.pvtOnMessage;\n this.pvtOnMessage = null;\n return previous;\n }\n\n onClose(handler: () => void): void {\n this.pvtOnClose = handler;\n }\n\n send(frame: string): Promise<void> {\n if (this.pvtClosed) {\n return Promise.resolve();\n }\n const line = frame.endsWith(\"\\n\") ? frame : `${frame}\\n`;\n return new Promise<void>((resolve, reject) => {\n try {\n this.streams.write.write(line, (err?: Error | null) => {\n if (!err) return resolve();\n const code = (err as { code?: unknown }).code;\n // A peer that has hung up cannot be told anything; the write that\n // races its exit is not an error in this transport.\n if (peerGone(code)) {\n return resolve();\n }\n reject(new StdioWireError(`stdio transport: ${err.message}`));\n });\n } catch (err) {\n reject(new StdioWireError(`stdio transport: ${errorText(err)}`));\n }\n });\n }\n\n async close(): Promise<void> {\n this.pvtClosing ??= this.pvtClose();\n await this.pvtClosing;\n }\n\n private async pvtClose(): Promise<void> {\n await Promise.resolve();\n\n this.pvtClosed = true;\n // Best effort: a half-open stream (the peer is already gone) must not turn\n // teardown into an exception.\n try {\n this.streams.read.destroy?.();\n } catch {\n /* already gone */\n }\n try {\n if (!this.streams.write.writableEnded) this.streams.write.end();\n } catch {\n /* already gone */\n }\n }\n}\n\n/** Streams over two fds of *our own* process — the child side of an fd wire. */\nexport function fdStreams(readFd: number, writeFd: number): LineStreams {\n const read = createReadStream(\"\", { fd: readFd, encoding: \"utf-8\", autoClose: false });\n const write = createWriteStream(\"\", { fd: writeFd, encoding: \"utf-8\", autoClose: false });\n return { read, write };\n}\n\n/**\n * A transport that lifts output frames out of the stream: everything else is\n * passed through untouched, so the protocol sees frames and only frames.\n */\nexport class OutputFilter implements StringTransport {\n private readonly inner: StringTransport;\n private readonly sink: OutputSink;\n\n constructor(inner: StringTransport, sink: OutputSink) {\n this.inner = inner;\n this.sink = sink;\n }\n\n send(frame: string): void | Promise<void> {\n return this.inner.send(frame);\n }\n\n onMessage(handler: (frame: string) => void): void {\n this.inner.onMessage((line) => {\n const output = parseOutputFrame(line);\n if (output) this.sink(output.fd, output.data);\n else handler(line);\n });\n }\n\n removeHandler(): void {\n this.inner.removeHandler();\n }\n\n onClose(handler: () => void): void {\n this.inner.onClose(handler);\n }\n\n close(): Promise<void> {\n return this.inner.close();\n }\n}\n\n// ── sinks ──────────────────────────────────────────────────────────────────\n\n/** Write the far end's output to our stderr, tagged with its name. */\nexport function stderrSink(name = \"\"): OutputSink {\n const tag = name ? `[${name}] ` : \"\";\n return (fd, data) => {\n const lead = fd === 1 ? tag : `${tag}err: `;\n for (const line of data.split(\"\\n\")) {\n if (line.length > 0) process.stderr.write(`${lead}${line}\\n`);\n }\n };\n}\n\n// ── handshakes ─────────────────────────────────────────────────────────────\n\n/** The next frame that arrives, or a timeout. */\nasync function nextFrame(channel: Channel, timeoutMs: number): Promise<Record<string, unknown>> {\n return await new Promise((resolve, reject) => {\n const timer = setTimeout(\n () => reject(new StdioWireError(`no protocol frame within ${timeoutMs}ms`)),\n timeoutMs,\n );\n timer.unref?.();\n channel.onMessage((frame) => {\n clearTimeout(timer);\n resolve(frame);\n });\n });\n}\n\nexport interface ClientChannelOptions {\n /** Where the far end's own output goes. Defaults to our stderr. */\n onOutput?: OutputSink;\n /** How long to wait for the peer's protocol frame. Defaults to {@link HANDSHAKE_TIMEOUT_MS}. */\n timeoutMs?: number;\n}\n\n/**\n * The client end of the wire: hand the streams to the seam (minus output\n * frames) and wait for the peer's `$proto`. A first stage reports a failed\n * start as an `$error` frame instead.\n */\nexport async function clientChannel(\n streams: LineStreams,\n opts: ClientChannelOptions = {},\n): Promise<Channel> {\n const transport = new LineTransport(streams);\n const channel = json1Channel(new OutputFilter(transport, opts.onOutput ?? stderrSink()));\n const frame = await nextFrame(channel, opts.timeoutMs ?? HANDSHAKE_TIMEOUT_MS);\n channel.removeHandler();\n\n const reason = errorReason(frame);\n if (reason) throw new StdioWireError(reason);\n if (!isProto(frame)) {\n throw new StdioWireError(`unexpected first frame: ${JSON.stringify(frame).slice(0, 120)}`);\n }\n if (frame.$proto !== VERSION) {\n throw new StdioWireError(`unsupported protocol ${String(frame.$proto)}, expected ${VERSION}`);\n }\n return channel;\n}\n\n/** The server end of the wire — a payload speaking stdio itself. */\nexport async function serverChannel(streams: LineStreams): Promise<Channel> {\n const channel = json1Channel(new LineTransport(streams));\n await channel.send({ $proto: VERSION });\n return channel;\n}\n","// ── FIFO transport ─────────────────────────────────────────────────────────\n//\n// Newline-delimited UTF-8 over named fifos. Strict handler lifecycle:\n// onMessage() throws if a handler is already set; call removeHandler() first.\n\nimport { open, type FileHandle } from \"node:fs/promises\";\nimport type { ReadStream, WriteStream } from \"node:fs\";\nimport * as readline from \"node:readline\";\nimport type { StringTransport } from \"../channel.js\";\n\nexport class FifoUtf8NlineTransport implements StringTransport {\n private readFd: FileHandle | null;\n private writeFd: FileHandle | null;\n private rl: readline.Interface | null;\n private rs: ReadStream | null;\n private ws: WriteStream | null;\n private pvtOnMessage: ((line: string) => void) | null = null;\n private pvtOnClose: (() => void) | null = null;\n private closed = false;\n private closingPromise: Promise<void> | null = null;\n private pvtError: Error | null = null;\n\n private constructor(opts: { readFd?: FileHandle; writeFd?: FileHandle }) {\n this.readFd = opts.readFd ?? null;\n this.writeFd = opts.writeFd ?? null;\n\n if (this.readFd) {\n this.rs = this.readFd.createReadStream({ encoding: \"utf-8\" });\n this.rl = readline.createInterface({ input: this.rs });\n\n this.rl.on(\"line\", (line) => {\n if (this.pvtOnMessage && !this.closed) this.pvtOnMessage(line);\n });\n\n this.rl.on(\"close\", () => {\n this.pvtOnClose?.();\n this.close();\n });\n\n this.rs.on(\"error\", (err: Error) => {\n this.pvtError = err;\n this.close();\n });\n } else {\n this.rs = null;\n this.rl = null;\n }\n\n if (this.writeFd) {\n this.ws = this.writeFd.createWriteStream({ encoding: \"utf-8\" });\n this.ws.on(\"error\", (err: Error) => {\n this.pvtError = err;\n this.close();\n });\n } else {\n this.ws = null;\n }\n }\n\n // ── factories ──────────────────────────────────────────────────────────\n\n static openReaderFd(readFd: FileHandle): FifoUtf8NlineTransport {\n return new FifoUtf8NlineTransport({ readFd });\n }\n\n static openWriterFd(writeFd: FileHandle): FifoUtf8NlineTransport {\n return new FifoUtf8NlineTransport({ writeFd });\n }\n\n static fromFds(readFd: FileHandle, writeFd: FileHandle): FifoUtf8NlineTransport {\n return new FifoUtf8NlineTransport({ readFd, writeFd });\n }\n\n // ── bidirectional connection ───────────────────────────────────────────\n\n /**\n * Start opening a bidirectional connection. Opens readPath for reading\n * in the background, returns a promise. The caller should do whatever\n * setup is needed to unblock the read (e.g. spawn a process that opens\n * readPath for writing), then await the returned transport.\n *\n * The transport itself is built only once both directions are open. A read\n * stream created while no writer exists on its fifo is handed an immediate\n * end-of-stream by some runtimes (bun), which closes a channel that has not\n * carried a byte yet — so the writes side is opened before the reader exists.\n */\n static beginConnect(\n readPath: string,\n writePath: string,\n ): { transport: Promise<FifoUtf8NlineTransport> } {\n const readFdPromise = open(readPath, \"r\");\n\n const transport = readFdPromise.then(async (readFd) => {\n const writeFd = await open(writePath, \"w\");\n return FifoUtf8NlineTransport.fromFds(readFd, writeFd);\n });\n\n return { transport };\n }\n\n /**\n * Open a bidirectional connection. Opens writePath for writing first\n * (unblocking the peer's read), starts reading readPath in the\n * background, then awaits both.\n *\n * Use this when you are the side that responds to the peer's beginConnect\n * (i.e. you don't need to interleave any setup between the read and write\n * opens). Built like `beginConnect`: the transport exists only after both\n * directions do.\n */\n static async connect(readPath: string, writePath: string): Promise<FifoUtf8NlineTransport> {\n const readFdPromise = open(readPath, \"r\");\n const writeFd = await open(writePath, \"w\");\n const readFd = await readFdPromise;\n return FifoUtf8NlineTransport.fromFds(readFd, writeFd);\n }\n\n // ── public API ─────────────────────────────────────────────────────────\n\n get canSend(): boolean {\n return this.writeFd !== null && !this.closed;\n }\n\n onMessage(handler: (line: string) => void): void {\n if (this.closed) throw new Error(\"FifoUtf8NlineTransport: closed\");\n if (this.readFd === null) throw new Error(\"FifoUtf8NlineTransport: not a reader\");\n if (this.pvtOnMessage !== null) {\n throw new Error(\"FifoUtf8NlineTransport: handler already set — call removeHandler() first\");\n }\n this.pvtOnMessage = handler;\n }\n\n removeHandler(): ((line: string) => void) | null {\n const prev = this.pvtOnMessage;\n this.pvtOnMessage = null;\n return prev;\n }\n\n onClose(handler: () => void): void {\n this.pvtOnClose = handler;\n }\n\n get hasHandler(): boolean {\n return this.pvtOnMessage !== null;\n }\n\n get lastError(): Error | null {\n return this.pvtError;\n }\n\n async send(line: string): Promise<void> {\n if (this.closed) throw new Error(\"FifoUtf8NlineTransport: closed\");\n if (this.writeFd === null) throw new Error(\"FifoUtf8NlineTransport: not a writer\");\n if (!line.endsWith(\"\\n\")) line += \"\\n\";\n await this.ws?.write(line);\n }\n\n async close(): Promise<void> {\n this.closingPromise = this.closingPromise || this.pvtClose();\n await this.closingPromise;\n this.closed = true;\n }\n\n private async pvtClose(): Promise<void> {\n // tranfser control back to caller\n // so they can capture the promise reference\n // and prevent reentry\n await Promise.resolve();\n\n if (this.rl) {\n this.rl.close();\n this.rl = null;\n }\n if (this.rs) {\n this.rs.destroy();\n this.rs = null;\n }\n if (this.ws) {\n await new Promise<void>((resolve) => {\n try {\n this.ws?.end(\"\", resolve);\n } catch {\n resolve();\n }\n });\n this.ws = null;\n }\n\n if (this.readFd) {\n try {\n await this.readFd.close();\n } catch {}\n this.readFd = null;\n }\n if (this.writeFd) {\n try {\n await this.writeFd.close();\n } catch {}\n this.writeFd = null;\n }\n }\n}\n","// ── Gateway ────────────────────────────────────────────────────────────────\n//\n// The first-stage command. Run this *inside* a foreign environment — directly,\n// under `sudo`, over ssh, in a container — and it:\n//\n// 1. creates the channel to the payload (fifo paths it makes itself, in a\n// private temp dir, so they belong to the uid that will open them),\n// 2. starts the payload — the first argument, required — hands it everything else it was\n// given (the host version among it) and relays frames between stdin/stdout,\n// 3. carries whatever the payload prints to the client as output frames\n// (`$fd`), so the payload's own stdout can never be mistaken for protocol.\n//\n// Why a gateway at all: a fifo path created on the client side is useless when the\n// payload runs as another uid (it cannot open it) or on another host (the path is\n// not there). stdio is the one channel every way into an environment gives us, so\n// the wire is stdio and the fifo stays inside the environment.\n//\n// The gateway reads nothing out of what it carries and owns no flag: the payload's path and\n// every argument after it go through verbatim, in order. The payload is the one who refuses a\n// host version it is not, and a relay that judged would be a second place for that decision.\n//\n// Directories and processes are cleaned up on every exit path, which is also why\n// the client never sees a transport being closed twice.\n//\n// It imports nothing but node builtins and this package, so the payload behind it\n// can be anything the runtime there can start.\n\nimport { execFile, spawn } from \"node:child_process\";\nimport type { ChildProcess } from \"node:child_process\";\nimport { mkdtemp, rm } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { basename, join } from \"node:path\";\nimport { promisify } from \"node:util\";\nimport { errorFrame, outputFrame } from \"./stdio.js\";\nimport type { LineTransport, OutputFd } from \"./stdio.js\";\nimport { LineTransport as Lines } from \"./stdio.js\";\nimport { FifoUtf8NlineTransport } from \"./transports/fifo.js\";\n\nconst run = promisify(execFile);\n\n/** Exit code for \"this environment could not be set up\". */\nexport const GATEWAY_FAILED = 1;\n\nexport interface GatewayBoot {\n /**\n * The program to start for the payload: the first word of the command the client composed —\n * a runtime, or a program that runs itself. Required, and first, and the gateway has no\n * opinion of its own about which it is.\n */\n worker: string;\n /**\n * Everything after the payload, carried to it **as is** and in order: the consumer's own\n * arguments, and posipaki's own facts among them (the host version travels this way). The\n * gateway reads nothing by name and owns no flag, so nothing of the caller's is interpreted,\n * eaten, re-ordered or re-spelled — and the next fact added to that line needs no new\n * vocabulary here.\n */\n passthrough: string[];\n}\n\nfunction errorText(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\n/**\n * A label for the gateway's own temp directory: the program this environment was made for.\n * It is the gateway's business alone — the payload is not told which label it is.\n */\nfunction label(worker: string): string {\n const name = basename(worker).replace(/[^A-Za-z0-9.+@_-]/g, \"-\").slice(0, 60);\n return name === \"\" ? \"payload\" : name;\n}\n\n/**\n * The argv that boots this gateway — built by the client, read by\n * {@link gatewayBoot}, so the two halves cannot drift apart.\n *\n * The payload comes first and its arguments after it, so a positional argument of the\n * payload's own can never be mistaken for the payload.\n */\nexport function gatewayArgs(boot: GatewayBoot): string[] {\n return [boot.worker, ...boot.passthrough];\n}\n\n/** The boot a gateway was started with, or the reason it cannot start. */\nexport function gatewayBoot(argv: string[]): GatewayBoot {\n const [worker, ...passthrough] = argv;\n if (worker === undefined || worker.startsWith(\"--\")) {\n throw new Error(\"no <payload>: the gateway relays to a payload, named as its first argument\");\n }\n return { passthrough, worker };\n}\n\n/**\n * End a start that failed. The reason has already gone out on the wire, and\n * returning is not enough: the `open()` on a fifo no payload will ever write sits\n * in the threadpool forever, so the loop never drains and the gateway would linger\n * with a dead payload on its books.\n */\nfunction abandon(): never {\n process.exit(GATEWAY_FAILED);\n}\n\n/** Carry a failed start to the client, then let the caller exit non-zero. */\nasync function fail(wire: LineTransport, reason: string): Promise<void> {\n process.stderr.write(`gateway: ${reason}\\n`);\n try {\n await wire.send(errorFrame(reason));\n } catch {\n /* the client is gone too — the exit code still says what happened */\n }\n}\n\n/** Copy everything the payload prints onto the wire as output frames. */\nfunction forwardOutput(stream: NodeJS.ReadableStream, wire: LineTransport, fd: OutputFd): void {\n stream.setEncoding(\"utf-8\");\n stream.on(\"data\", (chunk: string) => {\n void wire.send(outputFrame(fd, chunk)).catch(() => {\n /* the client hung up: the payload's exit is what matters now */\n });\n });\n}\n\n/**\n * Serve one environment over stdin/stdout. Returns the exit code; the caller\n * turns it into `process.exitCode`.\n */\nexport async function runGateway(argv: string[] = process.argv.slice(2)): Promise<number> {\n const wire = new Lines({ read: process.stdin, write: process.stdout });\n\n let booted: GatewayBoot;\n try {\n booted = gatewayBoot(argv);\n } catch (err) {\n // Nothing has been started yet, so there is nothing to tear down — but the\n // client still deserves the reason rather than a channel that closes on it,\n // and the loop can outlive us: an open stdin nobody will close keeps the\n // process alive, so this is an exit, not a return.\n await fail(wire, errorText(err));\n abandon();\n }\n const { passthrough, worker } = booted;\n\n const dir = await mkdtemp(join(tmpdir(), `posipaki-${label(worker)}-`));\n const fifoIn = join(dir, \"in\"); // the payload writes, we read\n const fifoOut = join(dir, \"out\"); // we write, the payload reads\n\n let child: ChildProcess | null = null;\n let fifo: FifoUtf8NlineTransport | null = null;\n\n /**\n * Everything this gateway owns, undone. All of it is idempotent, because the\n * exit path and the signal path can both arrive.\n */\n const teardown = async (): Promise<void> => {\n child?.kill();\n await fifo?.close().catch(() => {});\n await rm(dir, { recursive: true, force: true }).catch(() => {});\n };\n\n /**\n * A client that gives up stops us with a signal, and a gateway that died on the\n * spot would leave its payload behind in the environment — a process holding a\n * fifo nobody will ever write, which is a leak the environment cannot clean up\n * for us. So the signals do what the exit path does.\n */\n const onTerminate = () => {\n void teardown()\n .catch(() => {})\n .then(() => process.exit(GATEWAY_FAILED));\n };\n for (const signal of [\"SIGTERM\", \"SIGINT\", \"SIGHUP\"] as const) process.on(signal, onTerminate);\n\n try {\n await run(\"mkfifo\", [\"-m\", \"600\", fifoIn, fifoOut]);\n } catch (err) {\n await fail(wire, `cannot create the environment's fifos: ${errorText(err)}`);\n await teardown();\n abandon();\n }\n\n // Open the read side in the background, then start the payload that unblocks\n // it — the order the fifo handshake requires.\n const connection = FifoUtf8NlineTransport.beginConnect(fifoIn, fifoOut);\n const workerArgs = [worker, ...passthrough, `--fifo-in=${fifoIn}`, `--fifo-out=${fifoOut}`];\n // Whatever the client said starts the payload, run as it said: a runtime with a script of\n // ours, or a program of the caller's own. The gateway does not know which it is, and does\n // not choose a runtime on the far end's behalf.\n const workerProc = spawn(workerArgs[0]!, workerArgs.slice(1), {\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n });\n child = workerProc;\n forwardOutput(workerProc.stdout, wire, 1);\n forwardOutput(workerProc.stderr, wire, 2);\n\n const exited = new Promise<number>((settle) => {\n // A payload killed by a signal (the client hung up, and we killed it) has no\n // code — for us that is a clean end, not a failure.\n workerProc.once(\"exit\", (code) => settle(code ?? 0));\n });\n\n try {\n fifo = await Promise.race([\n connection.transport,\n exited.then((code) => {\n throw new Error(`the payload exited with code ${code} before it opened its channel`);\n }),\n ]);\n } catch (err) {\n await fail(wire, errorText(err));\n await teardown();\n abandon();\n }\n\n // Relay: the protocol is the client's and the payload's business, not ours.\n const relay = fifo;\n relay.onMessage((line) => {\n void wire.send(line).catch(() => {\n /* client gone */\n });\n });\n wire.onMessage((line) => {\n void relay.send(line).catch(() => {\n /* the payload is gone; its exit path cleans up */\n });\n });\n wire.onClose(() => {\n child?.kill();\n });\n\n const code = await exited;\n await teardown();\n await wire.close();\n return code;\n}\n","// ── The gateway, as a program ──────────────────────────────────────────────\n//\n// A gateway is something a client runs: the first-stage command that makes a fifo\n// inside a foreign environment and relays frames between its own stdin/stdout and\n// the payload. That is this file's whole job — it always serves, and it exits with\n// the code the run ended in.\n//\n// Serving lives in ./gateway.js and starts nothing by itself. A file cannot decide\n// \"am I the program?\" from where it is: a consumer that bundles the node surface\n// into its own program carries this code along, and there the bundle *is* the\n// program — a payload would find a gateway booting on its wire. So the decision is\n// in the layout instead: importing a module never starts anything, and running this\n// one always does.\n//\n// The client names it either way: `posipaki/remote/gateway-cli.js` is a published\n// specifier, so `import.meta.resolve` answers with the built file, and a consumer\n// with a program of its own stages that instead. Nothing here works out its own\n// location — a path derived from `import.meta.url` is a guess about a layout the\n// bundler owns, and the guess is wrong the moment the module moves into a chunk.\n\nimport { GATEWAY_FAILED, runGateway } from \"./gateway.js\";\n\nvoid (async () => {\n try {\n process.exitCode = await runGateway();\n } catch (err) {\n process.stderr.write(`gateway: ${err instanceof Error ? err.message : String(err)}\\n`);\n process.exitCode = GATEWAY_FAILED;\n }\n})();\n"],"mappings":";;;;;;;AAkJA,MAAM,YAAY;;AAOlB,SAAgBA,aAAW,QAAyC;CAClE,OAAO,GAAG,YAAY,OAAO;AAC/B;;;AC5GA,MAAM,aAAa;;AAGnB,IAAa,iBAAb,cAAoC,MAAM;CACxC,YAAY,SAAiB;EAC3B,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF;AAUA,SAAgB,YAAY,IAAc,MAAsB;CA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pB,MAAM,IAAI,MAAM,gCAAgC,KAAK,8BAA8B;EACrF,CAAC,CACH,CAAC;CACH,SAAS,KAAK;EACZ,MAAM,KAAK,MAAM,UAAU,GAAG,CAAC;EAC/B,MAAM,SAAS;EACf,QAAQ;CACV;CAGA,MAAM,QAAQ;CACd,MAAM,WAAW,SAAS;EACxB,KAAU,KAAK,IAAI,CAAC,CAAC,YAAY,CAEjC,CAAC;CACH,CAAC;CACD,KAAK,WAAW,SAAS;EACvB,MAAW,KAAK,IAAI,CAAC,CAAC,YAAY,CAElC,CAAC;CACH,CAAC;CACD,KAAK,cAAc;EACjB,OAAO,KAAK;CACd,CAAC;CAED,MAAM,OAAO,MAAM;CACnB,MAAM,SAAS;CACf,MAAM,KAAK,MAAM;CACjB,OAAO;AACT;;;CCpNM,YAAY;CAChB,IAAI;EACF,QAAQ,WAAW,MAAM,WAAW;CACtC,SAAS,KAAK;EACZ,QAAQ,OAAO,MAAM,YAAY,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,EAAE,GAAG;EACrF,QAAQ,WAAA;CACV;AACF,EAAA,CAAG"}
|
package/dist/remote/index.d.ts
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { i as Message, s as SenderInfo } from "../types-DYd-DDFB.js";
|
|
2
|
-
import { l as
|
|
3
|
-
import { a as StreamKind, c as isInit, d as isProto, f as isRelease, h as isStop, i as Channel, l as isMsg, m as isState, n as ClientSpawner, o as StringTransport, p as isResume, r as remoteClient, s as isExit, t as CHANNEL_LOST, u as isPause } from "../client-PWS8gJ0-.js";
|
|
2
|
+
import { A as isError, C as StreamKind, D as errorFrame, E as badReason, F as isProto, I as isRelease, L as isResume, M as isInit, N as isMsg, O as errorReason, P as isPause, R as isState, S as Channel, T as badFrame, _ as Init, a as ClientSpawner, b as Spawner, c as Connection, d as ReactorOptions, f as Session, g as serveRemoteActor, h as reactor, i as CHANNEL_LOST, j as isExit, k as isBad, l as Listener, m as oneConnection, n as WebSocketLike, o as remoteClient, p as SessionFactory, r as WebSocketTransport, s as AnyActorDefinition, t as WS_OPEN, u as Reactor, v as Served, w as StringTransport, x as BAD_PREFIX_LIMIT, y as ServedProcess, z as isStop } from "../websocket-BYNYSi7b.js";
|
|
4
3
|
//#region src/remote/remote-process.d.ts
|
|
5
4
|
interface RemoteExit {
|
|
6
5
|
code: number;
|
|
@@ -229,51 +228,20 @@ type IdParity = "odd" | "even";
|
|
|
229
228
|
* build can hold two copies of the class. */
|
|
230
229
|
declare function isRemoteProcess(value: unknown): value is RemoteProcess;
|
|
231
230
|
//#endregion
|
|
232
|
-
//#region src/remote/server.d.ts
|
|
233
|
-
type Spawner = () => Promise<Channel>;
|
|
234
|
-
declare function serveRemoteActor<Args, State, InMsg extends Message, OutMsg extends Message, R extends ReflectionOptions>(actor: ActorDefinition<Args, State, InMsg, OutMsg, R>, spawner: Spawner): Promise<void>;
|
|
235
|
-
//#endregion
|
|
236
231
|
//#region src/remote/sender.d.ts
|
|
237
232
|
declare function makeSender(fromName: string, parentName: string | null, parentId: symbol | null): SenderInfo;
|
|
238
233
|
//#endregion
|
|
239
234
|
//#region src/remote/protocols/json1.d.ts
|
|
240
235
|
declare const VERSION = "json.v1";
|
|
241
236
|
declare function encode(frame: Record<string, unknown>): string;
|
|
237
|
+
/** The frame a line carries, throwing on a line that is not JSON. `readFrame` is how the
|
|
238
|
+
* seam reads a line; this is the primitive underneath it. */
|
|
242
239
|
declare function decode(str: string): Record<string, unknown>;
|
|
240
|
+
/** A line read as a frame: the frame itself, or the frame that says this one could not be
|
|
241
|
+
* read. Never throws — see the note at the top of this file. */
|
|
242
|
+
declare function readFrame(str: string): Record<string, unknown>;
|
|
243
243
|
declare function json1Channel(transport: StringTransport): Channel;
|
|
244
244
|
//#endregion
|
|
245
|
-
//#region src/remote/transports/websocket.d.ts
|
|
246
|
-
/**
|
|
247
|
-
* The subset of a WebSocket the transport needs. The WHATWG client WebSocket
|
|
248
|
-
* (Node, Bun, browsers) satisfies this directly; a Bun server socket is adapted
|
|
249
|
-
* by the consumer (see spawners/ws-server.ts).
|
|
250
|
-
*/
|
|
251
|
-
interface WebSocketLike {
|
|
252
|
-
send(data: string): void;
|
|
253
|
-
close(code?: number, reason?: string): void;
|
|
254
|
-
readonly readyState: number;
|
|
255
|
-
onmessage: ((event: {
|
|
256
|
-
data: unknown;
|
|
257
|
-
}) => void) | null;
|
|
258
|
-
onclose: (() => void) | null;
|
|
259
|
-
}
|
|
260
|
-
/** WHATWG WebSocket readyState: OPEN. */
|
|
261
|
-
declare const WS_OPEN = 1;
|
|
262
|
-
declare class WebSocketTransport implements StringTransport {
|
|
263
|
-
private ws;
|
|
264
|
-
private pvtOnMessage;
|
|
265
|
-
private pvtOnClose;
|
|
266
|
-
private closed;
|
|
267
|
-
constructor(ws: WebSocketLike);
|
|
268
|
-
get canSend(): boolean;
|
|
269
|
-
onMessage(handler: (frame: string) => void): void;
|
|
270
|
-
removeHandler(): ((frame: string) => void) | null;
|
|
271
|
-
onClose(handler: () => void): void;
|
|
272
|
-
get hasHandler(): boolean;
|
|
273
|
-
send(frame: string): Promise<void>;
|
|
274
|
-
close(): Promise<void>;
|
|
275
|
-
}
|
|
276
|
-
//#endregion
|
|
277
245
|
//#region src/remote/transports/worker.d.ts
|
|
278
246
|
/** The worker encoding: native structured clone (no JSON). */
|
|
279
247
|
declare const WORKER_VERSION = "clone.v1";
|
|
@@ -306,7 +274,8 @@ declare class WorkerTransport implements Channel {
|
|
|
306
274
|
}
|
|
307
275
|
//#endregion
|
|
308
276
|
//#region src/remote/spawners/ws-client.d.ts
|
|
309
|
-
|
|
277
|
+
/** The socket the spawner needs: what the transport reads and writes, and the open/error slots. */
|
|
278
|
+
type OpenedWebSocket = {
|
|
310
279
|
readonly readyState: number;
|
|
311
280
|
send(data: string): void;
|
|
312
281
|
close(code?: number, reason?: string): void;
|
|
@@ -317,7 +286,19 @@ type WebSocketCtor = new (url: string) => {
|
|
|
317
286
|
}) => void) | null;
|
|
318
287
|
onclose: (() => void) | null;
|
|
319
288
|
};
|
|
320
|
-
|
|
289
|
+
type WebSocketCtor = new (url: string) => OpenedWebSocket;
|
|
290
|
+
/**
|
|
291
|
+
* How a socket is opened when a constructor is not enough: the URL to open, and the arguments this
|
|
292
|
+
* spawn was called with. A per-tenant header, a bearer token, an authority the machine does not
|
|
293
|
+
* already know — each of them is a fact about the connection, and each of them is the caller's to
|
|
294
|
+
* express in its own runtime's shape rather than in one posipaki was taught.
|
|
295
|
+
*/
|
|
296
|
+
type WebSocketOpener<Args = unknown> = (url: string, args: Args) => OpenedWebSocket;
|
|
297
|
+
interface WebSocketClientOptions<Args = unknown> {
|
|
298
|
+
/** Opens the socket. Given, it replaces the constructor. */
|
|
299
|
+
open?: WebSocketOpener<Args>;
|
|
300
|
+
}
|
|
301
|
+
declare function wsClientSpawner<Args = unknown>(url: string | ((args: Args) => string), WebSocketImpl?: WebSocketCtor, opts?: WebSocketClientOptions<Args>): ClientSpawner<Args>;
|
|
321
302
|
//#endregion
|
|
322
303
|
//#region src/remote/spawners/ws-server.d.ts
|
|
323
304
|
declare function wsServerSpawner(ws: WebSocketLike): Spawner;
|
|
@@ -361,5 +342,5 @@ declare function workerClientSpawner<Args = unknown>(url: string | ((args: Args)
|
|
|
361
342
|
//#region src/remote/spawners/worker-self.d.ts
|
|
362
343
|
declare function workerSelfSpawner(selfScope?: WorkerLike): Spawner;
|
|
363
344
|
//#endregion
|
|
364
|
-
export { type BunServerWebSocketLike, CHANNEL_LOST, type Channel, type ClientSpawner, type FrameSink, PROCESS_REF, type ProcessRef, type RemoteMessage, RemoteProcess, type Spawner, type StringTransport, VERSION, WORKER_VERSION, WS_OPEN, type WebSocketCtor, type WebSocketLike, WebSocketTransport, type WorkerCtor, type WorkerLike, WorkerTransport, bunServerWebSocket, decode, encode, isExit, isInit, isMsg, isPause, isProto, isRelease, isRemoteProcess, isResume, isState, isStop, json1Channel, makeSender, remoteClient, rootIdFor, serveRemoteActor, workerClientSpawner, workerSelfSpawner, wsClientSpawner, wsServerSpawner };
|
|
345
|
+
export { type AnyActorDefinition, BAD_PREFIX_LIMIT, type BunServerWebSocketLike, CHANNEL_LOST, type Channel, type ClientSpawner, type Connection, type FrameSink, type Init, type Listener, type OpenedWebSocket, PROCESS_REF, type ProcessRef, type Reactor, type ReactorOptions, type RemoteMessage, RemoteProcess, type Served, type ServedProcess, type Session, type SessionFactory, type Spawner, type StringTransport, VERSION, WORKER_VERSION, WS_OPEN, type WebSocketClientOptions, type WebSocketCtor, type WebSocketLike, type WebSocketOpener, WebSocketTransport, type WorkerCtor, type WorkerLike, WorkerTransport, badFrame, badReason, bunServerWebSocket, decode, encode, errorFrame, errorReason, isBad, isError, isExit, isInit, isMsg, isPause, isProto, isRelease, isRemoteProcess, isResume, isState, isStop, json1Channel, makeSender, oneConnection, reactor, readFrame, remoteClient, rootIdFor, serveRemoteActor, workerClientSpawner, workerSelfSpawner, wsClientSpawner, wsServerSpawner };
|
|
365
346
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/remote/remote-process.ts","../../src/remote/process-ref.ts","../../src/remote/
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/remote/remote-process.ts","../../src/remote/process-ref.ts","../../src/remote/sender.ts","../../src/remote/protocols/json1.ts","../../src/remote/transports/worker.ts","../../src/remote/spawners/ws-client.ts","../../src/remote/spawners/ws-server.ts","../../src/remote/spawners/worker-client.ts","../../src/remote/spawners/worker-self.ts"],"mappings":";;;UAyDiB;EACf;EACA;;;;;KAMU,aAAa,OAAO,yBAAyB,sBAAsB;;;KAInE,eAAe;;KAGf,cAAc,eAAe,UAAU,YAAY,KAAK,QAAQ;cAE/D,cAAc,cAAc,UAAU,SAAS,eAAe,UAAU;;WAE1E;;;WAGA,KAAK;;;WAGL;;EAET,OAAO;;WAEE,aAAa,mBAAmB,oBAAoB;UAErD;UACA;UACA;;;;UAIA;UACA;;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;;;;KAQrC,gBAAgB,mBAAmB,aAAa,MAAM,SAAS;UAE1D,uBAAuB;;EAEtC,OAAO,gBAAgB;;iBA6BT,gBAAgB,gBAC9B,gBAAgB,MAAM,kBACtB,gBAAe,eACf,OAAM,uBAAuB,QAC5B,cAAc;;;iBC/DD,gBAAgB,IAAI,gBAAgB;;;;;;;UAcnC;EACf,KAAK;EACL,MAAM,eAAe;WACZ;EACT;;;;;;;;;;;;;;;;;;;;;iBAsBc,mBAAmB,IAAI,yBAAyB;;;KCxCpD,kBAAkB,gBAAgB;iBAI9B,oBAAoB,gBAClC,gBAAgB,MAAM,kBACtB,aAAY,aACX,cAAc;;;iBCRD,kBAAkB,YAAW,aAAmD"}
|
package/dist/remote/index.js
CHANGED
|
@@ -1,54 +1,4 @@
|
|
|
1
|
-
import { _ as
|
|
2
|
-
//#region src/remote/transports/websocket.ts
|
|
3
|
-
/** WHATWG WebSocket readyState: OPEN. */
|
|
4
|
-
const WS_OPEN = 1;
|
|
5
|
-
var WebSocketTransport = class {
|
|
6
|
-
constructor(ws) {
|
|
7
|
-
this.pvtOnMessage = null;
|
|
8
|
-
this.pvtOnClose = null;
|
|
9
|
-
this.closed = false;
|
|
10
|
-
this.ws = ws;
|
|
11
|
-
ws.onmessage = (event) => {
|
|
12
|
-
if (this.pvtOnMessage && !this.closed) this.pvtOnMessage(String(event.data));
|
|
13
|
-
};
|
|
14
|
-
ws.onclose = () => {
|
|
15
|
-
this.closed = true;
|
|
16
|
-
this.pvtOnClose?.();
|
|
17
|
-
};
|
|
18
|
-
}
|
|
19
|
-
get canSend() {
|
|
20
|
-
return !this.closed && this.ws.readyState === 1;
|
|
21
|
-
}
|
|
22
|
-
onMessage(handler) {
|
|
23
|
-
if (this.closed) throw new Error("WebSocketTransport: closed");
|
|
24
|
-
if (this.pvtOnMessage !== null) throw new Error("WebSocketTransport: handler already set — call removeHandler() first");
|
|
25
|
-
this.pvtOnMessage = handler;
|
|
26
|
-
}
|
|
27
|
-
removeHandler() {
|
|
28
|
-
const prev = this.pvtOnMessage;
|
|
29
|
-
this.pvtOnMessage = null;
|
|
30
|
-
return prev;
|
|
31
|
-
}
|
|
32
|
-
onClose(handler) {
|
|
33
|
-
this.pvtOnClose = handler;
|
|
34
|
-
}
|
|
35
|
-
get hasHandler() {
|
|
36
|
-
return this.pvtOnMessage !== null;
|
|
37
|
-
}
|
|
38
|
-
async send(frame) {
|
|
39
|
-
if (this.closed) throw new Error("WebSocketTransport: closed");
|
|
40
|
-
if (this.ws.readyState !== 1) throw new Error("WebSocketTransport: not open");
|
|
41
|
-
this.ws.send(frame);
|
|
42
|
-
}
|
|
43
|
-
async close() {
|
|
44
|
-
if (this.closed) return;
|
|
45
|
-
this.closed = true;
|
|
46
|
-
try {
|
|
47
|
-
this.ws.close();
|
|
48
|
-
} catch {}
|
|
49
|
-
}
|
|
50
|
-
};
|
|
51
|
-
//#endregion
|
|
1
|
+
import { A as isStop, C as isInit, D as isRelease, E as isProto, M as isRemoteProcess, N as rootIdFor, O as isResume, S as isExit, T as isPause, _ as badReason, a as oneConnection, b as isBad, c as makeSender, d as decode, f as encode, g as badFrame, h as BAD_PREFIX_LIMIT, i as remoteClient, j as PROCESS_REF, k as isState, l as RemoteProcess, m as readFrame, n as WebSocketTransport, o as reactor, p as json1Channel, r as CHANNEL_LOST, s as serveRemoteActor, t as WS_OPEN, u as VERSION, v as errorFrame, w as isMsg, x as isError, y as errorReason } from "../websocket-DttBoCRL.js";
|
|
52
2
|
//#region src/remote/transports/worker.ts
|
|
53
3
|
/** The worker encoding: native structured clone (no JSON). */
|
|
54
4
|
const WORKER_VERSION = "clone.v1";
|
|
@@ -98,16 +48,35 @@ var WorkerTransport = class {
|
|
|
98
48
|
//#endregion
|
|
99
49
|
//#region src/remote/spawners/ws-client.ts
|
|
100
50
|
const defaultWebSocket = globalThis.WebSocket;
|
|
51
|
+
/** What a socket failure says about itself.
|
|
52
|
+
*
|
|
53
|
+
* A WHATWG WebSocket reports an open failure as an ErrorEvent, and `String(event)` is
|
|
54
|
+
* `[object ErrorEvent]`: its type, its message and the underlying error are all in its
|
|
55
|
+
* own fields, so read those rather than stringify the event that carries them.
|
|
56
|
+
*/
|
|
57
|
+
function describeSocketError(err) {
|
|
58
|
+
if (typeof err !== "object" || err === null) return String(err);
|
|
59
|
+
const event = err;
|
|
60
|
+
const cause = event.error instanceof Error ? event.error.message : event.error;
|
|
61
|
+
const parts = [
|
|
62
|
+
event.type,
|
|
63
|
+
event.message,
|
|
64
|
+
cause
|
|
65
|
+
].filter((part) => typeof part === "string" && part.length > 0);
|
|
66
|
+
return parts.length > 0 ? parts.join(": ") : String(err);
|
|
67
|
+
}
|
|
101
68
|
function openWebSocket(ws) {
|
|
102
69
|
return new Promise((resolve, reject) => {
|
|
103
70
|
if (ws.readyState === 1) return resolve();
|
|
104
71
|
ws.onopen = () => resolve();
|
|
105
|
-
ws.onerror = (err) => reject(/* @__PURE__ */ new Error(`websocket failed to open: ${
|
|
72
|
+
ws.onerror = (err) => reject(/* @__PURE__ */ new Error(`websocket failed to open: ${describeSocketError(err)}`));
|
|
106
73
|
});
|
|
107
74
|
}
|
|
108
|
-
function wsClientSpawner(url, WebSocketImpl = defaultWebSocket) {
|
|
75
|
+
function wsClientSpawner(url, WebSocketImpl = defaultWebSocket, opts = {}) {
|
|
76
|
+
const open = opts.open ?? ((target) => new WebSocketImpl(target));
|
|
109
77
|
return async (args) => {
|
|
110
|
-
const
|
|
78
|
+
const target = typeof url === "function" ? url(args) : url;
|
|
79
|
+
const ws = open(target, args);
|
|
111
80
|
const transport = new WebSocketTransport(ws);
|
|
112
81
|
const channel = json1Channel(transport);
|
|
113
82
|
const protoPromise = new Promise((resolve) => {
|
|
@@ -181,6 +150,6 @@ function workerSelfSpawner(selfScope = globalThis) {
|
|
|
181
150
|
};
|
|
182
151
|
}
|
|
183
152
|
//#endregion
|
|
184
|
-
export { CHANNEL_LOST, PROCESS_REF, RemoteProcess, VERSION, WORKER_VERSION, WS_OPEN, WebSocketTransport, WorkerTransport, bunServerWebSocket, decode, encode, isExit, isInit, isMsg, isPause, isProto, isRelease, isRemoteProcess, isResume, isState, isStop, json1Channel, makeSender, remoteClient, rootIdFor, serveRemoteActor, workerClientSpawner, workerSelfSpawner, wsClientSpawner, wsServerSpawner };
|
|
153
|
+
export { BAD_PREFIX_LIMIT, CHANNEL_LOST, PROCESS_REF, RemoteProcess, VERSION, WORKER_VERSION, WS_OPEN, WebSocketTransport, WorkerTransport, badFrame, badReason, bunServerWebSocket, decode, encode, errorFrame, errorReason, isBad, isError, isExit, isInit, isMsg, isPause, isProto, isRelease, isRemoteProcess, isResume, isState, isStop, json1Channel, makeSender, oneConnection, reactor, readFrame, remoteClient, rootIdFor, serveRemoteActor, workerClientSpawner, workerSelfSpawner, wsClientSpawner, wsServerSpawner };
|
|
185
154
|
|
|
186
155
|
//# sourceMappingURL=index.js.map
|
package/dist/remote/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../src/remote/transports/websocket.ts","../../src/remote/transports/worker.ts","../../src/remote/spawners/ws-client.ts","../../src/remote/spawners/ws-server.ts","../../src/remote/spawners/worker-client.ts","../../src/remote/spawners/worker-self.ts"],"sourcesContent":["/* eslint-disable unicorn/prefer-add-event-listener */\n// ── WebSocket transport ─────────────────────────────────────────────────────────\n//\n// Message-boundary transport over a WebSocket. The socket's native framing means\n// one `send` is one frame — there is no delimiter to add or strip. It moves\n// encoded frames (strings); json1Channel sits above it and handles JSON.\n\nimport type { StringTransport } from \"../channel.js\";\n\n/**\n * The subset of a WebSocket the transport needs. The WHATWG client WebSocket\n * (Node, Bun, browsers) satisfies this directly; a Bun server socket is adapted\n * by the consumer (see spawners/ws-server.ts).\n */\nexport interface WebSocketLike {\n send(data: string): void;\n close(code?: number, reason?: string): void;\n readonly readyState: number;\n onmessage: ((event: { data: unknown }) => void) | null;\n onclose: (() => void) | null;\n}\n\n/** WHATWG WebSocket readyState: OPEN. */\nexport const WS_OPEN = 1;\n\nexport class WebSocketTransport implements StringTransport {\n private ws: WebSocketLike;\n private pvtOnMessage: ((frame: string) => void) | null = null;\n private pvtOnClose: (() => void) | null = null;\n private closed = false;\n\n constructor(ws: WebSocketLike) {\n this.ws = ws;\n ws.onmessage = (event) => {\n if (this.pvtOnMessage && !this.closed) this.pvtOnMessage(String(event.data));\n };\n ws.onclose = () => {\n this.closed = true;\n this.pvtOnClose?.();\n };\n }\n\n get canSend(): boolean {\n return !this.closed && this.ws.readyState === WS_OPEN;\n }\n\n onMessage(handler: (frame: string) => void): void {\n if (this.closed) throw new Error(\"WebSocketTransport: closed\");\n if (this.pvtOnMessage !== null) {\n throw new Error(\"WebSocketTransport: handler already set — call removeHandler() first\");\n }\n this.pvtOnMessage = handler;\n }\n\n removeHandler(): ((frame: string) => void) | null {\n const prev = this.pvtOnMessage;\n this.pvtOnMessage = null;\n return prev;\n }\n\n onClose(handler: () => void): void {\n this.pvtOnClose = handler;\n }\n\n get hasHandler(): boolean {\n return this.pvtOnMessage !== null;\n }\n\n async send(frame: string): Promise<void> {\n if (this.closed) throw new Error(\"WebSocketTransport: closed\");\n if (this.ws.readyState !== WS_OPEN) throw new Error(\"WebSocketTransport: not open\");\n this.ws.send(frame);\n }\n\n async close(): Promise<void> {\n if (this.closed) return;\n this.closed = true;\n try {\n this.ws.close();\n } catch {\n // already closing / closed — ignore\n }\n }\n}\n","/* eslint-disable unicorn/prefer-add-event-listener, unicorn/require-post-message-target-origin */\n// ── Worker transport ────────────────────────────────────────────────────────────\n//\n// Moves frame objects directly over postMessage. postMessage structured-clones\n// the frame object, so there is no JSON encode/decode — this transport implements\n// Channel directly (not StringTransport). Structured clone is the worker's\n// native encoding, named by WORKER_VERSION.\n\nimport type { Channel } from \"../channel.js\";\n\n/** The worker encoding: native structured clone (no JSON). */\nexport const WORKER_VERSION = \"clone.v1\";\n\n/**\n * The subset of a worker the transport needs. The main-thread `Worker` and the\n * worker-global `self` both satisfy it; `terminate` is present only on the\n * main-thread side.\n */\nexport interface WorkerLike {\n postMessage(data: unknown): void;\n onmessage: ((event: { data: unknown }) => void) | null;\n onerror?: ((event: unknown) => void) | null;\n terminate?(): void;\n}\n\nexport class WorkerTransport implements Channel {\n private worker: WorkerLike;\n private pvtOnMessage: ((frame: Record<string, unknown>) => void) | null = null;\n private pvtOnClose: (() => void) | null = null;\n private closed = false;\n\n constructor(worker: WorkerLike) {\n this.worker = worker;\n worker.onmessage = (event) => {\n if (this.pvtOnMessage && !this.closed) {\n this.pvtOnMessage(event.data as Record<string, unknown>);\n }\n };\n // An uncaught error in the worker is the closest thing to an abrupt drop.\n if (\"onerror\" in worker) {\n worker.onerror = () => {\n this.closed = true;\n this.pvtOnClose?.();\n };\n }\n }\n\n get canSend(): boolean {\n return !this.closed;\n }\n\n onMessage(handler: (frame: Record<string, unknown>) => void): void {\n if (this.closed) throw new Error(\"WorkerTransport: closed\");\n if (this.pvtOnMessage !== null) {\n throw new Error(\"WorkerTransport: handler already set — call removeHandler() first\");\n }\n this.pvtOnMessage = handler;\n }\n\n removeHandler(): ((frame: Record<string, unknown>) => void) | null {\n const prev = this.pvtOnMessage;\n this.pvtOnMessage = null;\n return prev;\n }\n\n onClose(handler: () => void): void {\n this.pvtOnClose = handler;\n }\n\n get hasHandler(): boolean {\n return this.pvtOnMessage !== null;\n }\n\n async send(frame: Record<string, unknown>): Promise<void> {\n if (this.closed) throw new Error(\"WorkerTransport: closed\");\n this.worker.postMessage(frame);\n }\n\n async close(): Promise<void> {\n if (this.closed) return;\n this.closed = true;\n this.worker.terminate?.();\n }\n}\n","/* eslint-disable unicorn/prefer-add-event-listener */\n// ── WebSocket client spawner ────────────────────────────────────────────────────\n//\n// Environment-specific: connects to a `ws://` URL with the WHATWG WebSocket,\n// wraps it in a WebSocketTransport, and returns a frame Channel with the $proto\n// handshake already validated.\n\nimport { WebSocketTransport } from \"../transports/websocket.js\";\nimport { json1Channel, VERSION } from \"../protocols/json1.js\";\nimport { isProto } from \"../channel.js\";\nimport type { ClientSpawner } from \"../client.js\";\n\nexport type WebSocketCtor = new (url: string) => {\n readonly readyState: number;\n send(data: string): void;\n close(code?: number, reason?: string): void;\n onopen: (() => void) | null;\n onerror: ((err: unknown) => void) | null;\n onmessage: ((event: { data: unknown }) => void) | null;\n onclose: (() => void) | null;\n};\n\nconst defaultWebSocket = (globalThis as { WebSocket?: WebSocketCtor }).WebSocket;\n\nfunction openWebSocket(ws: { readonly readyState: number; onopen: (() => void) | null; onerror: ((err: unknown) => void) | null }): Promise<void> {\n return new Promise((resolve, reject) => {\n if (ws.readyState === 1 /* OPEN */) return resolve();\n ws.onopen = () => resolve();\n ws.onerror = (err) => reject(new Error(`websocket failed to open: ${String(err)}`));\n });\n}\n\nexport function wsClientSpawner<Args = unknown>(\n url: string | ((args: Args) => string),\n WebSocketImpl: WebSocketCtor = defaultWebSocket as WebSocketCtor,\n): ClientSpawner<Args> {\n return async (args) => {\n const target = typeof url === \"function\" ? url(args) : url;\n const ws = new WebSocketImpl(target);\n const transport = new WebSocketTransport(ws);\n const channel = json1Channel(transport);\n\n // Set the $proto waiter before awaiting open so a fast server's handshake\n // frame is not dropped.\n const protoPromise = new Promise<Record<string, unknown>>((resolve) => {\n channel.onMessage((frame) => resolve(frame));\n });\n await openWebSocket(ws);\n const protoFrame = await protoPromise;\n channel.removeHandler();\n\n if (!isProto(protoFrame) || protoFrame.$proto !== VERSION) {\n throw new Error(`unsupported protocol: ${JSON.stringify(protoFrame).slice(0, 50)}`);\n }\n return channel;\n };\n}\n","// ── WebSocket server spawner ────────────────────────────────────────────────────\n//\n// Environment-specific: serves an already-upgraded WebSocket connection. The\n// consumer's HTTP server does the upgrade and hands us the socket; we wrap it in\n// a WebSocketTransport, send $proto, and return the frame Channel.\n\nimport { WebSocketTransport, type WebSocketLike } from \"../transports/websocket.js\";\nimport { json1Channel, VERSION } from \"../protocols/json1.js\";\nimport type { Spawner } from \"../server.js\";\n\nexport function wsServerSpawner(ws: WebSocketLike): Spawner {\n return async () => {\n const channel = json1Channel(new WebSocketTransport(ws));\n await channel.send({ $proto: VERSION });\n return channel;\n };\n}\n\n/**\n * A minimal Bun `ServerWebSocket` — `send`/`close`/`readyState` plus the data\n * slot the server uses to stash per-connection state. Bun delivers message and\n * close events through the `Bun.serve` websocket config callbacks, not through\n * properties on the socket, so the consumer routes them onto the adapter.\n */\nexport interface BunServerWebSocketLike {\n send(data: string): void;\n close(code?: number, reason?: string): void;\n readonly readyState: number;\n data?: unknown;\n}\n\n/**\n * Adapt a Bun server socket to the `WebSocketLike` the transport consumes. The\n * returned adapter owns settable `onmessage`/`onclose` slots; the consumer\n * routes Bun's `message`/`close` config callbacks into them, e.g.:\n *\n * ```ts\n * Bun.serve({\n * websocket: {\n * open(ws) {\n * const adapter = bunServerWebSocket(ws);\n * ws.data = adapter;\n * serveRemoteActor(actor, wsServerSpawner(adapter));\n * },\n * message(ws, msg) { (ws.data as WebSocketLike).onmessage?.({ data: msg }); },\n * close(ws) { (ws.data as WebSocketLike).onclose?.(); },\n * },\n * });\n * ```\n */\nexport function bunServerWebSocket(ws: BunServerWebSocketLike): WebSocketLike {\n return {\n send: (data) => ws.send(data),\n close: (code, reason) => ws.close(code, reason),\n readyState: ws.readyState,\n onmessage: null,\n onclose: null,\n };\n}\n","// ── Worker client spawner (command) ─────────────────────────────────────────────\n//\n// Environment-specific: spawns a Worker with the WHATWG `new Worker(url)` API,\n// wraps it in a WorkerTransport, and returns a frame Channel with the $proto\n// handshake already validated.\n\nimport { WorkerTransport, WORKER_VERSION, type WorkerLike } from \"../transports/worker.js\";\nimport { isProto } from \"../channel.js\";\nimport type { ClientSpawner } from \"../client.js\";\n\nexport type WorkerCtor = new (url: string) => WorkerLike;\n\nconst defaultWorker = (globalThis as { Worker?: WorkerCtor }).Worker;\n\nexport function workerClientSpawner<Args = unknown>(\n url: string | ((args: Args) => string),\n WorkerImpl: WorkerCtor = defaultWorker as WorkerCtor,\n): ClientSpawner<Args> {\n return async (args) => {\n const target = typeof url === \"function\" ? url(args) : url;\n const channel = new WorkerTransport(new WorkerImpl(target));\n\n const protoFrame = await new Promise<Record<string, unknown>>((resolve) => {\n channel.onMessage((frame) => resolve(frame));\n });\n channel.removeHandler();\n\n if (!isProto(protoFrame) || protoFrame.$proto !== WORKER_VERSION) {\n throw new Error(`unsupported protocol: ${JSON.stringify(protoFrame).slice(0, 50)}`);\n }\n return channel;\n };\n}\n","// ── Worker server spawner (self) ────────────────────────────────────────────────\n//\n// Environment-specific: serves the worker-global scope (`self`) as a frame\n// Channel with the $proto handshake already sent. The worker entry script calls\n// `serveRemoteActor(actor, workerSelfSpawner())`.\n\nimport { WorkerTransport, WORKER_VERSION, type WorkerLike } from \"../transports/worker.js\";\nimport type { Spawner } from \"../server.js\";\n\nexport function workerSelfSpawner(selfScope: WorkerLike = globalThis as unknown as WorkerLike): Spawner {\n return async () => {\n const channel = new WorkerTransport(selfScope);\n await channel.send({ $proto: WORKER_VERSION });\n return channel;\n };\n}\n"],"mappings":";;;AAuBA,MAAa,UAAU;AAEvB,IAAa,qBAAb,MAA2D;CAMzD,YAAY,IAAmB;EAJ0B,KAAA,eAAA;EACf,KAAA,aAAA;EACzB,KAAA,SAAA;EAGf,KAAK,KAAK;EACV,GAAG,aAAa,UAAU;GACxB,IAAI,KAAK,gBAAgB,CAAC,KAAK,QAAQ,KAAK,aAAa,OAAO,MAAM,IAAI,CAAC;EAC7E;EACA,GAAG,gBAAgB;GACjB,KAAK,SAAS;GACd,KAAK,aAAa;EACpB;CACF;CAEA,IAAI,UAAmB;EACrB,OAAO,CAAC,KAAK,UAAU,KAAK,GAAG,eAAA;CACjC;CAEA,UAAU,SAAwC;EAChD,IAAI,KAAK,QAAQ,MAAM,IAAI,MAAM,4BAA4B;EAC7D,IAAI,KAAK,iBAAiB,MACxB,MAAM,IAAI,MAAM,sEAAsE;EAExF,KAAK,eAAe;CACtB;CAEA,gBAAkD;EAChD,MAAM,OAAO,KAAK;EAClB,KAAK,eAAe;EACpB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AG;EACf,WAAW;EACX,SAAS;CACX;AACF;;;AC9CA,MAAM,gBAAiB,WAAuC;AAE9D,SAAgB,oBACd,KACA,aAAyB,eACJ;CACrB,OAAO,OAAO,SAAS;EAErB,MAAM,UAAU,IAAI,gBAAgB,IAAI,WADzB,OAAO,QAAQ,aAAa,IAAI,IAAI,IAAI,GACE,CAAC;EAE1D,MAAM,aAAa,MAAM,IAAI,SAAkC,YAAY;GACzE,QAAQ,WAAW,UAAU,QAAQ,KAAK,CAAC;EAC7C,CAAC;EACD,QAAQ,cAAc;EAEtB,IAAI,CAAC,QAAQ,UAAU,KAAK,WAAW,WAAA,YACrC,MAAM,IAAI,MAAM,yBAAyB,KAAK,UAAU,UAAU,CAAC,CAAC,MAAM,GAAG,EAAE,GAAG;EAEpF,OAAO;CACT;AACF;;;ACvBA,SAAgB,kBAAkB,YAAwB,YAA8C;CACtG,OAAO,YAAY;EACjB,MAAM,UAAU,IAAI,gBAAgB,SAAS;EAC7C,MAAM,QAAQ,KAAK,EAAE,QAAQ,eAAe,CAAC;EAC7C,OAAO;CACT;AACF"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../src/remote/transports/worker.ts","../../src/remote/spawners/ws-client.ts","../../src/remote/spawners/ws-server.ts","../../src/remote/spawners/worker-client.ts","../../src/remote/spawners/worker-self.ts"],"sourcesContent":["/* eslint-disable unicorn/prefer-add-event-listener, unicorn/require-post-message-target-origin */\n// ── Worker transport ────────────────────────────────────────────────────────────\n//\n// Moves frame objects directly over postMessage. postMessage structured-clones\n// the frame object, so there is no JSON encode/decode — this transport implements\n// Channel directly (not StringTransport). Structured clone is the worker's\n// native encoding, named by WORKER_VERSION.\n\nimport type { Channel } from \"../channel.js\";\n\n/** The worker encoding: native structured clone (no JSON). */\nexport const WORKER_VERSION = \"clone.v1\";\n\n/**\n * The subset of a worker the transport needs. The main-thread `Worker` and the\n * worker-global `self` both satisfy it; `terminate` is present only on the\n * main-thread side.\n */\nexport interface WorkerLike {\n postMessage(data: unknown): void;\n onmessage: ((event: { data: unknown }) => void) | null;\n onerror?: ((event: unknown) => void) | null;\n terminate?(): void;\n}\n\nexport class WorkerTransport implements Channel {\n private worker: WorkerLike;\n private pvtOnMessage: ((frame: Record<string, unknown>) => void) | null = null;\n private pvtOnClose: (() => void) | null = null;\n private closed = false;\n\n constructor(worker: WorkerLike) {\n this.worker = worker;\n worker.onmessage = (event) => {\n if (this.pvtOnMessage && !this.closed) {\n this.pvtOnMessage(event.data as Record<string, unknown>);\n }\n };\n // An uncaught error in the worker is the closest thing to an abrupt drop.\n if (\"onerror\" in worker) {\n worker.onerror = () => {\n this.closed = true;\n this.pvtOnClose?.();\n };\n }\n }\n\n get canSend(): boolean {\n return !this.closed;\n }\n\n onMessage(handler: (frame: Record<string, unknown>) => void): void {\n if (this.closed) throw new Error(\"WorkerTransport: closed\");\n if (this.pvtOnMessage !== null) {\n throw new Error(\"WorkerTransport: handler already set — call removeHandler() first\");\n }\n this.pvtOnMessage = handler;\n }\n\n removeHandler(): ((frame: Record<string, unknown>) => void) | null {\n const prev = this.pvtOnMessage;\n this.pvtOnMessage = null;\n return prev;\n }\n\n onClose(handler: () => void): void {\n this.pvtOnClose = handler;\n }\n\n get hasHandler(): boolean {\n return this.pvtOnMessage !== null;\n }\n\n async send(frame: Record<string, unknown>): Promise<void> {\n if (this.closed) throw new Error(\"WorkerTransport: closed\");\n this.worker.postMessage(frame);\n }\n\n async close(): Promise<void> {\n if (this.closed) return;\n this.closed = true;\n this.worker.terminate?.();\n }\n}\n","/* eslint-disable unicorn/prefer-add-event-listener */\n// ── WebSocket client spawner ────────────────────────────────────────────────────\n//\n// Environment-specific: connects to a `ws://` URL with the WHATWG WebSocket,\n// wraps it in a WebSocketTransport, and returns a frame Channel with the $proto\n// handshake already validated.\n//\n// How the socket is opened is the caller's. The second parameter constructs one from a URL, which is\n// what a runtime's own client takes; an opener replaces it with a function of the connection, which is\n// where a header belongs — a token in a URL is a token in every log the URL passes through — and the\n// only place a value that varies per spawn can be attached at all.\n\nimport { WebSocketTransport } from \"../transports/websocket.js\";\nimport { json1Channel, VERSION } from \"../protocols/json1.js\";\nimport { isProto } from \"../channel.js\";\nimport type { ClientSpawner } from \"../client.js\";\n\n/** The socket the spawner needs: what the transport reads and writes, and the open/error slots. */\nexport type OpenedWebSocket = {\n readonly readyState: number;\n send(data: string): void;\n close(code?: number, reason?: string): void;\n onopen: (() => void) | null;\n onerror: ((err: unknown) => void) | null;\n onmessage: ((event: { data: unknown }) => void) | null;\n onclose: (() => void) | null;\n};\n\nexport type WebSocketCtor = new (url: string) => OpenedWebSocket;\n\n/**\n * How a socket is opened when a constructor is not enough: the URL to open, and the arguments this\n * spawn was called with. A per-tenant header, a bearer token, an authority the machine does not\n * already know — each of them is a fact about the connection, and each of them is the caller's to\n * express in its own runtime's shape rather than in one posipaki was taught.\n */\nexport type WebSocketOpener<Args = unknown> = (url: string, args: Args) => OpenedWebSocket;\n\nexport interface WebSocketClientOptions<Args = unknown> {\n /** Opens the socket. Given, it replaces the constructor. */\n open?: WebSocketOpener<Args>;\n}\n\nconst defaultWebSocket = (globalThis as { WebSocket?: WebSocketCtor }).WebSocket;\n\n/** What a socket failure says about itself.\n *\n * A WHATWG WebSocket reports an open failure as an ErrorEvent, and `String(event)` is\n * `[object ErrorEvent]`: its type, its message and the underlying error are all in its\n * own fields, so read those rather than stringify the event that carries them.\n */\nfunction describeSocketError(err: unknown): string {\n if (typeof err !== \"object\" || err === null) return String(err);\n const event = err as { type?: unknown; message?: unknown; error?: unknown };\n const cause = event.error instanceof Error ? event.error.message : event.error;\n const parts = [event.type, event.message, cause].filter(\n (part): part is string => typeof part === \"string\" && part.length > 0,\n );\n return parts.length > 0 ? parts.join(\": \") : String(err);\n}\n\nfunction openWebSocket(ws: { readonly readyState: number; onopen: (() => void) | null; onerror: ((err: unknown) => void) | null }): Promise<void> {\n return new Promise((resolve, reject) => {\n if (ws.readyState === 1 /* OPEN */) return resolve();\n ws.onopen = () => resolve();\n ws.onerror = (err) => reject(new Error(`websocket failed to open: ${describeSocketError(err)}`));\n });\n}\n\nexport function wsClientSpawner<Args = unknown>(\n url: string | ((args: Args) => string),\n WebSocketImpl: WebSocketCtor = defaultWebSocket as WebSocketCtor,\n opts: WebSocketClientOptions<Args> = {},\n): ClientSpawner<Args> {\n // The constructor is the default opener, so the socket is opened one way either way.\n const open: WebSocketOpener<Args> = opts.open ?? ((target) => new WebSocketImpl(target));\n return async (args) => {\n const target = typeof url === \"function\" ? url(args) : url;\n const ws = open(target, args);\n const transport = new WebSocketTransport(ws);\n const channel = json1Channel(transport);\n\n // Set the $proto waiter before awaiting open so a fast server's handshake\n // frame is not dropped.\n const protoPromise = new Promise<Record<string, unknown>>((resolve) => {\n channel.onMessage((frame) => resolve(frame));\n });\n await openWebSocket(ws);\n const protoFrame = await protoPromise;\n channel.removeHandler();\n\n if (!isProto(protoFrame) || protoFrame.$proto !== VERSION) {\n throw new Error(`unsupported protocol: ${JSON.stringify(protoFrame).slice(0, 50)}`);\n }\n return channel;\n };\n}\n","// ── WebSocket server spawner ────────────────────────────────────────────────────\n//\n// Environment-specific: serves an already-upgraded WebSocket connection. The\n// consumer's HTTP server does the upgrade and hands us the socket; we wrap it in\n// a WebSocketTransport, send $proto, and return the frame Channel.\n\nimport { WebSocketTransport, type WebSocketLike } from \"../transports/websocket.js\";\nimport { json1Channel, VERSION } from \"../protocols/json1.js\";\nimport type { Spawner } from \"../server.js\";\n\nexport function wsServerSpawner(ws: WebSocketLike): Spawner {\n return async () => {\n const channel = json1Channel(new WebSocketTransport(ws));\n await channel.send({ $proto: VERSION });\n return channel;\n };\n}\n\n/**\n * A minimal Bun `ServerWebSocket` — `send`/`close`/`readyState` plus the data\n * slot the server uses to stash per-connection state. Bun delivers message and\n * close events through the `Bun.serve` websocket config callbacks, not through\n * properties on the socket, so the consumer routes them onto the adapter.\n */\nexport interface BunServerWebSocketLike {\n send(data: string): void;\n close(code?: number, reason?: string): void;\n readonly readyState: number;\n data?: unknown;\n}\n\n/**\n * Adapt a Bun server socket to the `WebSocketLike` the transport consumes. The\n * returned adapter owns settable `onmessage`/`onclose` slots; the consumer\n * routes Bun's `message`/`close` config callbacks into them, e.g.:\n *\n * ```ts\n * Bun.serve({\n * websocket: {\n * open(ws) {\n * const adapter = bunServerWebSocket(ws);\n * ws.data = adapter;\n * serveRemoteActor(actor, wsServerSpawner(adapter));\n * },\n * message(ws, msg) { (ws.data as WebSocketLike).onmessage?.({ data: msg }); },\n * close(ws) { (ws.data as WebSocketLike).onclose?.(); },\n * },\n * });\n * ```\n */\nexport function bunServerWebSocket(ws: BunServerWebSocketLike): WebSocketLike {\n return {\n send: (data) => ws.send(data),\n close: (code, reason) => ws.close(code, reason),\n readyState: ws.readyState,\n onmessage: null,\n onclose: null,\n };\n}\n","// ── Worker client spawner (command) ─────────────────────────────────────────────\n//\n// Environment-specific: spawns a Worker with the WHATWG `new Worker(url)` API,\n// wraps it in a WorkerTransport, and returns a frame Channel with the $proto\n// handshake already validated.\n\nimport { WorkerTransport, WORKER_VERSION, type WorkerLike } from \"../transports/worker.js\";\nimport { isProto } from \"../channel.js\";\nimport type { ClientSpawner } from \"../client.js\";\n\nexport type WorkerCtor = new (url: string) => WorkerLike;\n\nconst defaultWorker = (globalThis as { Worker?: WorkerCtor }).Worker;\n\nexport function workerClientSpawner<Args = unknown>(\n url: string | ((args: Args) => string),\n WorkerImpl: WorkerCtor = defaultWorker as WorkerCtor,\n): ClientSpawner<Args> {\n return async (args) => {\n const target = typeof url === \"function\" ? url(args) : url;\n const channel = new WorkerTransport(new WorkerImpl(target));\n\n const protoFrame = await new Promise<Record<string, unknown>>((resolve) => {\n channel.onMessage((frame) => resolve(frame));\n });\n channel.removeHandler();\n\n if (!isProto(protoFrame) || protoFrame.$proto !== WORKER_VERSION) {\n throw new Error(`unsupported protocol: ${JSON.stringify(protoFrame).slice(0, 50)}`);\n }\n return channel;\n };\n}\n","// ── Worker server spawner (self) ────────────────────────────────────────────────\n//\n// Environment-specific: serves the worker-global scope (`self`) as a frame\n// Channel with the $proto handshake already sent. The worker entry script calls\n// `serveRemoteActor(actor, workerSelfSpawner())`.\n\nimport { WorkerTransport, WORKER_VERSION, type WorkerLike } from \"../transports/worker.js\";\nimport type { Spawner } from \"../server.js\";\n\nexport function workerSelfSpawner(selfScope: WorkerLike = globalThis as unknown as WorkerLike): Spawner {\n return async () => {\n const channel = new WorkerTransport(selfScope);\n await channel.send({ $proto: WORKER_VERSION });\n return channel;\n };\n}\n"],"mappings":";;;AAWA,MAAa,iBAAiB;AAc9B,IAAa,kBAAb,MAAgD;CAM9C,YAAY,QAAoB;EAJ0C,KAAA,eAAA;EAChC,KAAA,aAAA;EACzB,KAAA,SAAA;EAGf,KAAK,SAAS;EACd,OAAO,aAAa,UAAU;GAC5B,IAAI,KAAK,gBAAgB,CAAC,KAAK,QAC7B,KAAK,aAAa,MAAM,IAA+B;EAE3D;EAEA,IAAI,aAAa,QACf,OAAO,gBAAgB;GACrB,KAAK,SAAS;GACd,KAAK,aAAa;EACpB;CAEJ;CAEA,IAAI,UAAmB;EACrB,OAAO,CAAC,KAAK;CACf;CAEA,UAAU,SAAyD;EACjE,IAAI,KAAK,QAAQ,MAAM,IAAI,MAAM,yBAAyB;EAC1D,IAAI,KAAK,iBAAiB,MACxB,MAAM,IAAI,MAAM,mEAAmE;EAErF,KAAK,eAAe;CACtB;CAEA,gBAAmE;EACjE,MAAM,OAAO,KAAK;EAClB,KAAK,eAAe;EACpB,OAAO;CACT;CAEA,QAAQ,SAA2B;EACjC,KAAK,aAAa;CACpB;CAEA,IAAI,aAAsB;EACxB,OAAO,KAAK,iBAAiB;CAC/B;CAEA,MAAM,KAAK,OAA+C;EACxD,IAAI,KAAK,QAAQ,MAAM,IAAI,MAAM,yBAAyB;EAC1D,KAAK,OAAO,YAAY,KAAK;CAC/B;CAEA,MAAM,QAAuB;EAC3B,IAAI,KAAK,QAAQ;EACjB,KAAK,SAAS;EACd,KAAK,OAAO,YAAY;C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