@zhin.js/isolate 1.0.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 凉菜
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,102 @@
1
+ # @zhin.js/isolate
2
+
3
+ 下一代 Zhin Runtime 的可选 Node 隔离适配器。它为每个 `runtime: isolated` Plugin generation 创建独立 Worker 或 child process,并只通过 structured-clone RPC 与 Host 通信。
4
+
5
+ > 当前包属于 `feature/next` 绿地实现,版本仍为 `0.0.0` 且未作为稳定 API 发布。
6
+
7
+ ## 为什么独立成包
8
+
9
+ `@zhin.js/runtime` 只定义 `IsolatedPluginRuntimePort`,不强制默认 IM 安装携带隔离实现。需要故障或并发隔离的 Root 显式安装本包;trusted Plugin 的启动路径和生产闭包不变。
10
+
11
+ 本包没有第三方运行时依赖,只使用 Node 的 `worker_threads`、`child_process` 和 IPC。它不依赖 Vite、编译器、CSS 工具或 native/wasm 模块。
12
+
13
+ ## 使用
14
+
15
+ ```ts
16
+ import { NodeIsolatedPluginRuntime } from '@zhin.js/isolate';
17
+ import { RootRuntime } from '@zhin.js/runtime';
18
+
19
+ const runtime = new RootRuntime({
20
+ projectRoot: process.cwd(),
21
+ modules,
22
+ environment,
23
+ isolation: new NodeIsolatedPluginRuntime({
24
+ mode: 'worker',
25
+ hostMethods: {
26
+ audit(input, { owner }) {
27
+ return auditLog.write({ owner, input });
28
+ },
29
+ },
30
+ }),
31
+ });
32
+ ```
33
+
34
+ child Plugin manifest 显式选择隔离:
35
+
36
+ ```json
37
+ {
38
+ "name": "@acme/reports",
39
+ "zhin": {
40
+ "protocol": 1,
41
+ "type": "plugin",
42
+ "runtime": "isolated",
43
+ "entry": "./plugin.js"
44
+ }
45
+ }
46
+ ```
47
+
48
+ Root Plugin 负责整个进程生命周期,因此不能使用 `runtime: isolated`。
49
+
50
+ ## Plugin 通道
51
+
52
+ 隔离 Plugin 只能要求 `isolatedChannelToken` 和 `runtimeEnvironmentToken`。Host Scope、数据库、EnvStore 与自定义 Token 不会隐式复制到隔离侧;需要的数据应进入 owner config,操作应成为显式 allowlist RPC。
53
+
54
+ ```ts
55
+ import { definePlugin } from '@zhin.js/plugin-runtime';
56
+ import { isolatedChannelToken } from '@zhin.js/isolate';
57
+
58
+ export default definePlugin({
59
+ name: 'reports',
60
+ requires: [isolatedChannelToken],
61
+ setup({ resources, config }) {
62
+ const channel = resources.use(isolatedChannelToken);
63
+ return channel.expose('render', async (input) => ({
64
+ report: await render(input, config.get()),
65
+ }));
66
+ },
67
+ });
68
+ ```
69
+
70
+ Host 从对应 owner 的 Resource snapshot 取得 `isolatedPluginToken`,再调用 `handle.call()`。输入、输出、事件与 config 都必须可 structured clone;函数、socket、数据库连接等对象会在发送前被拒绝。
71
+
72
+ ## 代际切换
73
+
74
+ 适配器参与 Runtime generation handoff:
75
+
76
+ 1. `prepare` 创建候选 isolate、import entry 并校验 definition,但不执行 setup。
77
+ 2. `quiescePrevious` 停止旧 handle 接收新调用,并等待所有已接收 RPC 完成。
78
+ 3. `activateNext` 在候选 isolate 内执行 setup;失败会清理候选并恢复旧 handle。
79
+ 4. Runtime 原子提交 snapshot 后,`openNext` 才开放新 handle。
80
+ 5. 旧 generation 的最后一个 lease 释放后,Scope disposer 终止旧 isolate。
81
+
82
+ RPC 超时会把整个实例标记为 failed 并终止 transport,因为远端工作可能仍在运行,不能把超时伪装成安全 drain。Worker/进程意外退出会拒绝全部 pending RPC,并通过 `onCrash` 上报;当前 generation 内不静默重启。
83
+
84
+ ## 隔离边界
85
+
86
+ 这是故障和并发隔离,不是安全沙箱。Worker 与 child process 仍拥有启动用户授予 Node 进程的文件、网络和系统权限。运行不可信代码需要在 Host 外再叠加容器、OS account、permission model 或其他真正的 sandbox。
87
+
88
+ 普通 Feature definition 含函数、Endpoint 和闭包,不能安全 structured clone。因此 isolated Plugin 当前不能 mount Host Feature provider。未来跨边界 Feature 必须提供显式 codec/代理契约,不能序列化任意函数来绕过边界。
89
+
90
+ ## 开发验证
91
+
92
+ ```bash
93
+ pnpm --filter @zhin.js/isolate test
94
+ pnpm --filter @zhin.js/isolate build
95
+ pnpm --filter @zhin.js/isolate check:size
96
+ ```
97
+
98
+ ## 相关文档
99
+
100
+ - [隔离 Plugin Runtime ADR](../../../docs/adr/0049-isolated-plugin-runtime.md)
101
+ - [Plugin Runtime](../runtime/README.md)
102
+ - [Greenfield Bootstrap 状态](../../../docs/architecture/target-implementation/greenfield-bootstrap.md)
@@ -0,0 +1,5 @@
1
+ /**
2
+ * This function is serialized into Worker and child-process entry scripts.
3
+ * It must remain self-contained: every dependency belongs inside the function.
4
+ */
5
+ export declare function isolateBootstrap(): void;
@@ -0,0 +1,188 @@
1
+ /* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-require-imports --
2
+ * The serialized bootstrap cannot retain imported runtime values or external types. */
3
+ /**
4
+ * This function is serialized into Worker and child-process entry scripts.
5
+ * It must remain self-contained: every dependency belongs inside the function.
6
+ */
7
+ export function isolateBootstrap() {
8
+ const processSend = process.send?.bind(process);
9
+ const workerThreads = processSend ? undefined : require('node:worker_threads');
10
+ const endpoint = processSend
11
+ ? {
12
+ send: (message) => processSend(message),
13
+ receive: (listener) => process.on('message', listener),
14
+ }
15
+ : {
16
+ send: (message) => workerThreads.parentPort.postMessage(message),
17
+ receive: (listener) => workerThreads.parentPort.on('message', listener),
18
+ };
19
+ let definition;
20
+ let preparePayload;
21
+ let state = 'empty';
22
+ const disposers = [];
23
+ const handlers = new Map();
24
+ const hostCalls = new Map();
25
+ let nextHostCall = 1;
26
+ const errorValue = (error) => {
27
+ const value = error instanceof Error ? error : new Error(String(error));
28
+ return { name: value.name, message: value.message, stack: value.stack };
29
+ };
30
+ const fromErrorValue = (error) => {
31
+ const value = new Error(error?.message ?? 'Unknown Host RPC error');
32
+ value.name = error?.name ?? 'Error';
33
+ if (error?.stack)
34
+ value.stack = error.stack;
35
+ return value;
36
+ };
37
+ const clone = (value) => structuredClone(value);
38
+ // Construct native import inside the isolate so test runners and future
39
+ // Host compilers cannot rewrite it to a Host-only helper.
40
+ const importModule = new Function('specifier', 'return import(specifier)');
41
+ const channel = {
42
+ expose(method, handler) {
43
+ if (!method || handlers.has(method))
44
+ throw new Error(`Duplicate isolated method: ${method}`);
45
+ handlers.set(method, handler);
46
+ return () => handlers.delete(method);
47
+ },
48
+ call(method, input) {
49
+ const id = nextHostCall++;
50
+ endpoint.send({ type: 'host-call', id, method, input: clone(input) });
51
+ return new Promise((resolve, reject) => hostCalls.set(id, { resolve, reject }));
52
+ },
53
+ emit(name, payload) {
54
+ endpoint.send({ type: 'event', name, payload: clone(payload) });
55
+ },
56
+ };
57
+ const disposeSetup = async () => {
58
+ const errors = [];
59
+ for (const dispose of disposers.splice(0).reverse()) {
60
+ try {
61
+ await dispose();
62
+ }
63
+ catch (error) {
64
+ errors.push(error);
65
+ }
66
+ }
67
+ handlers.clear();
68
+ if (errors.length > 0)
69
+ throw new AggregateError(errors, 'Isolated Plugin disposal failed');
70
+ };
71
+ const methods = {
72
+ async prepare(payload) {
73
+ if (state !== 'empty')
74
+ throw new Error('Isolated Plugin has already been prepared');
75
+ preparePayload = payload;
76
+ const namespace = await importModule(payload.entry);
77
+ definition = namespace.default;
78
+ if (!definition || typeof definition.name !== 'string') {
79
+ throw new TypeError(`${payload.packageName} does not default-export a Plugin definition`);
80
+ }
81
+ const allowed = new Set(['zhin.isolate.channel', 'zhin.runtime-environment']);
82
+ for (const token of definition.requires ?? []) {
83
+ if (!allowed.has(token.id))
84
+ throw new Error(`Host resource cannot cross isolation boundary: ${token.id}`);
85
+ }
86
+ const descriptor = { name: definition.name, metadata: definition.metadata };
87
+ clone(descriptor);
88
+ state = 'prepared';
89
+ return descriptor;
90
+ },
91
+ async activate() {
92
+ if (state !== 'prepared')
93
+ throw new Error(`Cannot activate isolated Plugin from ${state}`);
94
+ const local = new Map([
95
+ ['zhin.isolate.channel', channel],
96
+ ['zhin.runtime-environment', Object.freeze(preparePayload.environment)],
97
+ ]);
98
+ const lifecycle = {
99
+ add(dispose) { disposers.push(dispose); return dispose; },
100
+ seal() { },
101
+ dispose: disposeSetup,
102
+ };
103
+ const resources = {
104
+ use(token) {
105
+ if (!local.has(token.id))
106
+ throw new Error(`Missing isolated resource ${token.id}`);
107
+ return local.get(token.id);
108
+ },
109
+ has(token) { return local.has(token.id); },
110
+ provide(token, value, dispose) {
111
+ if (local.has(token.id))
112
+ throw new Error(`Duplicate isolated resource ${token.id}`);
113
+ local.set(token.id, value);
114
+ if (dispose)
115
+ disposers.push(dispose);
116
+ },
117
+ };
118
+ const plugin = Object.freeze({
119
+ id: preparePayload.owner,
120
+ instanceKey: preparePayload.owner.split('/').at(-1),
121
+ parent: preparePayload.parent,
122
+ root: 'root',
123
+ role: 'child',
124
+ });
125
+ try {
126
+ const returned = await definition.setup?.({
127
+ plugin,
128
+ config: { get: () => Object.freeze(preparePayload.config) },
129
+ resources,
130
+ lifecycle,
131
+ handoff: { add() { throw new Error('Nested generation handoff is unavailable in isolation'); } },
132
+ });
133
+ if (returned)
134
+ disposers.push(returned);
135
+ state = 'active';
136
+ }
137
+ catch (error) {
138
+ await disposeSetup();
139
+ state = 'prepared';
140
+ throw error;
141
+ }
142
+ },
143
+ async deactivate() {
144
+ if (state === 'active')
145
+ await disposeSetup();
146
+ if (state !== 'closed')
147
+ state = 'prepared';
148
+ },
149
+ async call(payload) {
150
+ if (state !== 'active')
151
+ throw new Error(`Isolated Plugin is not active: ${state}`);
152
+ const handler = handlers.get(payload.method);
153
+ if (!handler)
154
+ throw new Error(`Unknown isolated method: ${payload.method}`);
155
+ return clone(await handler(payload.input));
156
+ },
157
+ async dispose() {
158
+ if (state === 'active')
159
+ await disposeSetup();
160
+ state = 'closed';
161
+ for (const pending of hostCalls.values())
162
+ pending.reject(new Error('Isolated Plugin closed'));
163
+ hostCalls.clear();
164
+ },
165
+ };
166
+ endpoint.receive(async (message) => {
167
+ if (message?.type === 'host-result') {
168
+ const pending = hostCalls.get(message.id);
169
+ if (!pending)
170
+ return;
171
+ hostCalls.delete(message.id);
172
+ if (message.ok)
173
+ pending.resolve(message.value);
174
+ else
175
+ pending.reject(fromErrorValue(message.error));
176
+ return;
177
+ }
178
+ if (message?.type !== 'request')
179
+ return;
180
+ try {
181
+ const value = await methods[message.method](message.payload);
182
+ endpoint.send({ type: 'response', id: message.id, ok: true, value: clone(value) });
183
+ }
184
+ catch (error) {
185
+ endpoint.send({ type: 'response', id: message.id, ok: false, error: errorValue(error) });
186
+ }
187
+ });
188
+ }
@@ -0,0 +1,21 @@
1
+ import { type Dispose, type PluginId } from '@zhin.js/plugin-runtime';
2
+ export type IsolatedPluginStatus = 'prepared' | 'active' | 'quiesced' | 'failed' | 'closed';
3
+ export interface IsolatedPluginEvent {
4
+ readonly name: string;
5
+ readonly payload: unknown;
6
+ }
7
+ /** Host-side capability for an isolated Plugin instance. */
8
+ export interface IsolatedPluginHandle {
9
+ readonly owner: PluginId;
10
+ readonly status: IsolatedPluginStatus;
11
+ call<TResult = unknown>(method: string, input?: unknown): Promise<TResult>;
12
+ onEvent(listener: (event: IsolatedPluginEvent) => void): Dispose;
13
+ }
14
+ /** Plugin-side boundary. Imported by isolated Plugin entry modules. */
15
+ export interface IsolatedChannel {
16
+ expose(method: string, handler: (input: unknown) => unknown | Promise<unknown>): Dispose;
17
+ call<TResult = unknown>(method: string, input?: unknown): Promise<TResult>;
18
+ emit(name: string, payload?: unknown): void;
19
+ }
20
+ export declare const isolatedPluginToken: import("@zhin.js/plugin-runtime").Token<IsolatedPluginHandle>;
21
+ export declare const isolatedChannelToken: import("@zhin.js/plugin-runtime").Token<IsolatedChannel>;
@@ -0,0 +1,3 @@
1
+ import { createToken } from '@zhin.js/plugin-runtime';
2
+ export const isolatedPluginToken = createToken('zhin.isolated-plugin', 'Owner-scoped handle for an isolated Plugin instance');
3
+ export const isolatedChannelToken = createToken('zhin.isolate.channel', 'Structured-clone RPC boundary available inside an isolated Plugin');
package/lib/index.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ export * from './contracts.js';
2
+ export * from './runtime.js';
3
+ export type { IsolateMode } from './transport.js';
package/lib/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export * from './contracts.js';
2
+ export * from './runtime.js';
@@ -0,0 +1,40 @@
1
+ export interface RequestMessage {
2
+ readonly type: 'request';
3
+ readonly id: number;
4
+ readonly method: 'prepare' | 'activate' | 'deactivate' | 'call' | 'dispose';
5
+ readonly payload?: unknown;
6
+ }
7
+ export interface ResponseMessage {
8
+ readonly type: 'response';
9
+ readonly id: number;
10
+ readonly ok: boolean;
11
+ readonly value?: unknown;
12
+ readonly error?: SerializedError;
13
+ }
14
+ export interface HostCallMessage {
15
+ readonly type: 'host-call';
16
+ readonly id: number;
17
+ readonly method: string;
18
+ readonly input?: unknown;
19
+ }
20
+ export interface HostResultMessage {
21
+ readonly type: 'host-result';
22
+ readonly id: number;
23
+ readonly ok: boolean;
24
+ readonly value?: unknown;
25
+ readonly error?: SerializedError;
26
+ }
27
+ export interface EventMessage {
28
+ readonly type: 'event';
29
+ readonly name: string;
30
+ readonly payload?: unknown;
31
+ }
32
+ export interface SerializedError {
33
+ readonly name: string;
34
+ readonly message: string;
35
+ readonly stack?: string;
36
+ }
37
+ export type HostMessage = ResponseMessage | HostCallMessage | EventMessage;
38
+ export type IsolateMessage = RequestMessage | HostResultMessage;
39
+ export declare function serializeError(error: unknown): SerializedError;
40
+ export declare function deserializeError(error?: SerializedError): Error;
@@ -0,0 +1,13 @@
1
+ export function serializeError(error) {
2
+ if (error instanceof Error) {
3
+ return { name: error.name, message: error.message, stack: error.stack };
4
+ }
5
+ return { name: 'Error', message: String(error) };
6
+ }
7
+ export function deserializeError(error) {
8
+ const result = new Error(error?.message ?? 'Unknown isolated runtime error');
9
+ result.name = error?.name ?? 'Error';
10
+ if (error?.stack)
11
+ result.stack = error.stack;
12
+ return result;
13
+ }
@@ -0,0 +1,19 @@
1
+ import type { PluginId } from '@zhin.js/plugin-runtime';
2
+ import type { IsolatedPluginPrepareRequest, IsolatedPluginRuntimePort, PreparedIsolatedPlugin } from '@zhin.js/runtime';
3
+ import { type IsolateMode } from './transport.js';
4
+ export interface IsolatedHostCallContext {
5
+ readonly owner: PluginId;
6
+ }
7
+ export type IsolatedHostMethod = (input: unknown, context: IsolatedHostCallContext) => unknown | Promise<unknown>;
8
+ export interface NodeIsolatedPluginRuntimeOptions {
9
+ readonly mode?: IsolateMode;
10
+ readonly requestTimeoutMs?: number;
11
+ readonly hostMethods?: Readonly<Record<string, IsolatedHostMethod>>;
12
+ readonly onCrash?: (owner: PluginId, error: Error) => void;
13
+ }
14
+ /** Node isolation adapter with one Worker/process per Plugin generation. */
15
+ export declare class NodeIsolatedPluginRuntime implements IsolatedPluginRuntimePort {
16
+ #private;
17
+ constructor(options?: NodeIsolatedPluginRuntimeOptions);
18
+ prepare(request: IsolatedPluginPrepareRequest): Promise<PreparedIsolatedPlugin>;
19
+ }
package/lib/runtime.js ADDED
@@ -0,0 +1,233 @@
1
+ import { pathToFileURL } from 'node:url';
2
+ import { isolatedPluginToken, } from './contracts.js';
3
+ import { deserializeError, serializeError, } from './protocol.js';
4
+ import { createTransport } from './transport.js';
5
+ /** Node isolation adapter with one Worker/process per Plugin generation. */
6
+ export class NodeIsolatedPluginRuntime {
7
+ #mode;
8
+ #requestTimeoutMs;
9
+ #hostMethods;
10
+ #onCrash;
11
+ #quiescedPrevious = new Map();
12
+ constructor(options = {}) {
13
+ this.#mode = options.mode ?? 'worker';
14
+ this.#requestTimeoutMs = options.requestTimeoutMs ?? 10_000;
15
+ this.#hostMethods = Object.freeze({ ...options.hostMethods });
16
+ this.#onCrash = options.onCrash;
17
+ }
18
+ async prepare(request) {
19
+ assertCloneable(request.config, `Config for ${request.owner}`);
20
+ const instance = new IsolatedInstance(request.owner, createTransport(this.#mode), this.#requestTimeoutMs, this.#hostMethods, this.#onCrash);
21
+ try {
22
+ const descriptor = await instance.request('prepare', {
23
+ ...request,
24
+ entry: pathToFileURL(request.entry).href,
25
+ });
26
+ return {
27
+ descriptor,
28
+ resources: [{ token: isolatedPluginToken, value: instance }],
29
+ handoff: {
30
+ quiescePrevious: async (previous) => {
31
+ const handle = previous.resources.get(request.owner)?.get(isolatedPluginToken.id);
32
+ if (!(handle instanceof IsolatedInstance))
33
+ return;
34
+ await handle.quiesce();
35
+ this.#quiescedPrevious.set(request.owner, handle);
36
+ },
37
+ activateNext: () => instance.activate(),
38
+ deactivateNext: () => instance.deactivate(),
39
+ resumePrevious: () => {
40
+ const previous = this.#quiescedPrevious.get(request.owner);
41
+ this.#quiescedPrevious.delete(request.owner);
42
+ previous?.resume();
43
+ },
44
+ openNext: () => {
45
+ instance.open();
46
+ this.#quiescedPrevious.delete(request.owner);
47
+ },
48
+ },
49
+ dispose: () => instance.close(),
50
+ };
51
+ }
52
+ catch (error) {
53
+ await instance.close();
54
+ throw error;
55
+ }
56
+ }
57
+ }
58
+ class IsolatedInstance {
59
+ owner;
60
+ transport;
61
+ timeoutMs;
62
+ hostMethods;
63
+ onCrash;
64
+ #status = 'prepared';
65
+ #nextRequest = 1;
66
+ #inFlight = 0;
67
+ #drainWaiters = [];
68
+ #closed = false;
69
+ #pending = new Map();
70
+ #listeners = new Set();
71
+ constructor(owner, transport, timeoutMs, hostMethods, onCrash) {
72
+ this.owner = owner;
73
+ this.transport = transport;
74
+ this.timeoutMs = timeoutMs;
75
+ this.hostMethods = hostMethods;
76
+ this.onCrash = onCrash;
77
+ transport.onMessage((message) => this.#onMessage(message));
78
+ transport.onExit((error) => this.#fail(error));
79
+ }
80
+ get status() { return this.#status; }
81
+ async activate() {
82
+ await this.request('activate');
83
+ }
84
+ async deactivate() {
85
+ if (this.#closed || this.#status === 'failed')
86
+ return;
87
+ await this.request('deactivate');
88
+ this.#status = 'prepared';
89
+ }
90
+ open() {
91
+ if (this.#closed || this.#status === 'failed')
92
+ throw new Error(`Cannot open ${this.owner}`);
93
+ this.#status = 'active';
94
+ }
95
+ async quiesce() {
96
+ if (this.#status !== 'active')
97
+ return;
98
+ this.#status = 'quiesced';
99
+ if (this.#inFlight === 0)
100
+ return;
101
+ await new Promise((resolve) => this.#drainWaiters.push(resolve));
102
+ }
103
+ resume() {
104
+ if (this.#status === 'quiesced')
105
+ this.#status = 'active';
106
+ }
107
+ async call(method, input) {
108
+ if (this.#status !== 'active') {
109
+ throw new Error(`Isolated Plugin ${this.owner} is not accepting calls: ${this.#status}`);
110
+ }
111
+ assertMethod(method);
112
+ assertCloneable(input, `Input for ${method}`);
113
+ this.#inFlight += 1;
114
+ try {
115
+ return await this.request('call', { method, input });
116
+ }
117
+ finally {
118
+ this.#inFlight -= 1;
119
+ if (this.#inFlight === 0) {
120
+ for (const resolve of this.#drainWaiters.splice(0))
121
+ resolve();
122
+ }
123
+ }
124
+ }
125
+ onEvent(listener) {
126
+ this.#listeners.add(listener);
127
+ return () => { this.#listeners.delete(listener); };
128
+ }
129
+ request(method, payload) {
130
+ if (this.#closed)
131
+ return Promise.reject(new Error(`Isolated Plugin ${this.owner} is closed`));
132
+ const id = this.#nextRequest++;
133
+ return new Promise((resolve, reject) => {
134
+ const timer = setTimeout(() => {
135
+ this.#pending.delete(id);
136
+ const error = new Error(`Isolated request timed out after ${this.timeoutMs}ms: ${method}`);
137
+ reject(error);
138
+ // A timed-out remote call may still mutate state. Retiring the whole
139
+ // instance preserves the generation boundary instead of faking drain.
140
+ this.#fail(error);
141
+ void this.transport.close();
142
+ }, this.timeoutMs);
143
+ this.#pending.set(id, {
144
+ resolve: (value) => resolve(value),
145
+ reject,
146
+ timer,
147
+ });
148
+ this.transport.send({ type: 'request', id, method, payload });
149
+ });
150
+ }
151
+ async close() {
152
+ if (this.#closed)
153
+ return;
154
+ try {
155
+ if (this.#status !== 'failed')
156
+ await this.request('dispose');
157
+ }
158
+ finally {
159
+ this.#closed = true;
160
+ this.#status = 'closed';
161
+ this.#rejectPending(new Error(`Isolated Plugin ${this.owner} closed`));
162
+ await this.transport.close();
163
+ }
164
+ }
165
+ #onMessage(message) {
166
+ if (message.type === 'response') {
167
+ const pending = this.#pending.get(message.id);
168
+ if (!pending)
169
+ return;
170
+ this.#pending.delete(message.id);
171
+ clearTimeout(pending.timer);
172
+ if (message.ok)
173
+ pending.resolve(message.value);
174
+ else
175
+ pending.reject(deserializeError(message.error));
176
+ return;
177
+ }
178
+ if (message.type === 'event') {
179
+ const event = Object.freeze({ name: message.name, payload: message.payload });
180
+ for (const listener of this.#listeners)
181
+ listener(event);
182
+ return;
183
+ }
184
+ void this.#handleHostCall(message);
185
+ }
186
+ async #handleHostCall(message) {
187
+ const method = this.hostMethods[message.method];
188
+ try {
189
+ if (!method)
190
+ throw new Error(`Host RPC method is not allowed: ${message.method}`);
191
+ const value = await method(message.input, { owner: this.owner });
192
+ assertCloneable(value, `Host RPC result for ${message.method}`);
193
+ this.transport.send({ type: 'host-result', id: message.id, ok: true, value });
194
+ }
195
+ catch (error) {
196
+ this.transport.send({
197
+ type: 'host-result',
198
+ id: message.id,
199
+ ok: false,
200
+ error: serializeError(error),
201
+ });
202
+ }
203
+ }
204
+ #fail(error) {
205
+ if (this.#closed || this.#status === 'closed' || this.#status === 'failed')
206
+ return;
207
+ this.#status = 'failed';
208
+ this.#rejectPending(error);
209
+ for (const resolve of this.#drainWaiters.splice(0))
210
+ resolve();
211
+ this.onCrash?.(this.owner, error);
212
+ }
213
+ #rejectPending(error) {
214
+ for (const pending of this.#pending.values()) {
215
+ clearTimeout(pending.timer);
216
+ pending.reject(error);
217
+ }
218
+ this.#pending.clear();
219
+ }
220
+ }
221
+ function assertCloneable(value, label) {
222
+ try {
223
+ structuredClone(value);
224
+ }
225
+ catch (error) {
226
+ throw new TypeError(`${label} is not structured-cloneable`, { cause: error });
227
+ }
228
+ }
229
+ function assertMethod(method) {
230
+ if (!method || method === '__proto__' || method === 'constructor' || method === 'prototype') {
231
+ throw new TypeError(`Invalid isolated RPC method: ${method}`);
232
+ }
233
+ }
@@ -0,0 +1,9 @@
1
+ import type { HostMessage, IsolateMessage } from './protocol.js';
2
+ export type IsolateMode = 'worker' | 'process';
3
+ export interface MessageTransport {
4
+ send(message: IsolateMessage): void;
5
+ onMessage(listener: (message: HostMessage) => void): void;
6
+ onExit(listener: (error: Error) => void): void;
7
+ close(): Promise<void>;
8
+ }
9
+ export declare function createTransport(mode: IsolateMode): MessageTransport;
@@ -0,0 +1,53 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { Worker } from 'node:worker_threads';
3
+ import { isolateBootstrap } from './bootstrap.js';
4
+ export function createTransport(mode) {
5
+ const source = `(${isolateBootstrap.toString()})()`;
6
+ return mode === 'worker'
7
+ ? new WorkerTransport(new Worker(source, { eval: true }))
8
+ : new ProcessTransport(spawn(process.execPath, ['-e', source], {
9
+ stdio: ['ignore', 'inherit', 'inherit', 'ipc'],
10
+ serialization: 'advanced',
11
+ }));
12
+ }
13
+ class WorkerTransport {
14
+ worker;
15
+ constructor(worker) {
16
+ this.worker = worker;
17
+ }
18
+ send(message) { this.worker.postMessage(message); }
19
+ onMessage(listener) { this.worker.on('message', listener); }
20
+ onExit(listener) {
21
+ this.worker.once('error', listener);
22
+ this.worker.once('exit', (code) => {
23
+ if (code !== 0)
24
+ listener(new Error(`Isolated Worker exited with code ${code}`));
25
+ });
26
+ }
27
+ async close() { await this.worker.terminate(); }
28
+ }
29
+ class ProcessTransport {
30
+ child;
31
+ constructor(child) {
32
+ this.child = child;
33
+ }
34
+ send(message) {
35
+ if (!this.child.send)
36
+ throw new Error('Isolated process IPC is unavailable');
37
+ this.child.send(message);
38
+ }
39
+ onMessage(listener) { this.child.on('message', listener); }
40
+ onExit(listener) {
41
+ this.child.once('error', listener);
42
+ this.child.once('exit', (code, signal) => {
43
+ if (code !== 0)
44
+ listener(new Error(`Isolated process exited (${code ?? signal})`));
45
+ });
46
+ }
47
+ async close() {
48
+ if (this.child.exitCode !== null || this.child.signalCode !== null)
49
+ return;
50
+ this.child.kill();
51
+ await new Promise((resolve) => this.child.once('exit', () => resolve()));
52
+ }
53
+ }
package/package.json ADDED
@@ -0,0 +1,45 @@
1
+ {
2
+ "name": "@zhin.js/isolate",
3
+ "version": "1.0.0",
4
+ "description": "Worker and child-process isolation adapter for the Zhin Plugin Runtime",
5
+ "type": "module",
6
+ "main": "./lib/index.js",
7
+ "types": "./lib/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./lib/index.d.ts",
11
+ "development": "./src/index.ts",
12
+ "import": "./lib/index.js"
13
+ }
14
+ },
15
+ "files": [
16
+ "lib"
17
+ ],
18
+ "dependencies": {
19
+ "@zhin.js/plugin-runtime": "1.0.0",
20
+ "@zhin.js/runtime": "1.0.0"
21
+ },
22
+ "devDependencies": {
23
+ "@types/node": "^26.1.0",
24
+ "typescript": "^6.0.3"
25
+ },
26
+ "engines": {
27
+ "node": "^20.19.0 || >=22.12.0"
28
+ },
29
+ "license": "MIT",
30
+ "repository": {
31
+ "type": "git",
32
+ "url": "git+https://github.com/zhinjs/zhin.git",
33
+ "directory": "packages/im/isolate"
34
+ },
35
+ "publishConfig": {
36
+ "access": "public",
37
+ "registry": "https://registry.npmjs.org"
38
+ },
39
+ "scripts": {
40
+ "build": "tsc",
41
+ "clean": "rimraf lib",
42
+ "test": "vitest run --root ../../.. packages/im/isolate/tests",
43
+ "check:size": "node ../../../scripts/check-plugin-runtime-install-size.mjs @zhin.js/isolate"
44
+ }
45
+ }