@iso4/sandbox 0.0.0 → 0.0.1
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 +21 -0
- package/README.md +130 -0
- package/dist/index.d.mts +441 -0
- package/dist/index.mjs +1196 -0
- package/package.json +62 -5
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,1196 @@
|
|
|
1
|
+
import { access, unlink } from "node:fs/promises";
|
|
2
|
+
import { cpus, tmpdir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { randomUUID } from "node:crypto";
|
|
5
|
+
import process from "node:process";
|
|
6
|
+
import { spawn } from "node:child_process";
|
|
7
|
+
import { existsSync } from "node:fs";
|
|
8
|
+
import { fileURLToPath } from "node:url";
|
|
9
|
+
import { createConnection } from "node:net";
|
|
10
|
+
import { Buffer } from "node:buffer";
|
|
11
|
+
//#region src/binary.ts
|
|
12
|
+
function resolveRuntimeBinary(options = {}) {
|
|
13
|
+
if (options.binaryPath) return options.binaryPath;
|
|
14
|
+
const platformPackage = platformBinaryPackage();
|
|
15
|
+
let binaryPath;
|
|
16
|
+
try {
|
|
17
|
+
binaryPath = fileURLToPath(import.meta.resolve(platformPackage.binarySpecifier));
|
|
18
|
+
} catch {
|
|
19
|
+
throw new Error(`Missing iso4-v8 binary package for ${process.platform}/${process.arch}: ${platformPackage.packageName}. Install it with:\n\n npm install ${platformPackage.packageName}\n\nor pass SandboxOptions.binaryPath.`);
|
|
20
|
+
}
|
|
21
|
+
if (!existsSync(binaryPath)) throw new Error(`The iso4-v8 binary package ${platformPackage.packageName} is installed, but its binary was not found at ${binaryPath}.`);
|
|
22
|
+
return binaryPath;
|
|
23
|
+
}
|
|
24
|
+
function platformBinaryPackage() {
|
|
25
|
+
if (process.platform === "darwin" && process.arch === "arm64") return {
|
|
26
|
+
packageName: "@iso4/v8-darwin-arm64",
|
|
27
|
+
binarySpecifier: "@iso4/v8-darwin-arm64/bin/iso4-v8"
|
|
28
|
+
};
|
|
29
|
+
if (process.platform === "darwin" && process.arch === "x64") return {
|
|
30
|
+
packageName: "@iso4/v8-darwin-x64",
|
|
31
|
+
binarySpecifier: "@iso4/v8-darwin-x64/bin/iso4-v8"
|
|
32
|
+
};
|
|
33
|
+
if (process.platform === "linux" && process.arch === "arm64") return {
|
|
34
|
+
packageName: "@iso4/v8-linux-arm64-gnu",
|
|
35
|
+
binarySpecifier: "@iso4/v8-linux-arm64-gnu/bin/iso4-v8"
|
|
36
|
+
};
|
|
37
|
+
if (process.platform === "linux" && process.arch === "x64") return {
|
|
38
|
+
packageName: "@iso4/v8-linux-x64-gnu",
|
|
39
|
+
binarySpecifier: "@iso4/v8-linux-x64-gnu/bin/iso4-v8"
|
|
40
|
+
};
|
|
41
|
+
throw new Error(`Unsupported platform: ${process.platform}/${process.arch}. @iso4/sandbox supports darwin/arm64, darwin/x64, linux/arm64, and linux/x64.`);
|
|
42
|
+
}
|
|
43
|
+
//#endregion
|
|
44
|
+
//#region src/wire.ts
|
|
45
|
+
/**
|
|
46
|
+
* Binary wire codec - decoder for the iso4 Rust → TypeScript protocol.
|
|
47
|
+
*
|
|
48
|
+
* Implements `WireValue` decoding per `docs/protocol.md` §4 and
|
|
49
|
+
* `RunCompletionPayload` decoding per §5.6.
|
|
50
|
+
*
|
|
51
|
+
* This module is decode-only: encoding lives on the Rust side.
|
|
52
|
+
* `decodeWireValue` is exported for testing; normal callers use
|
|
53
|
+
* `decodeRunCompletionPayload` only.
|
|
54
|
+
*/
|
|
55
|
+
const TAG_UNDEFINED = 0;
|
|
56
|
+
const TAG_NULL = 1;
|
|
57
|
+
const TAG_FALSE = 2;
|
|
58
|
+
const TAG_TRUE = 3;
|
|
59
|
+
const TAG_NUMBER = 4;
|
|
60
|
+
const TAG_STRING = 5;
|
|
61
|
+
const TAG_BIGINT = 6;
|
|
62
|
+
const TAG_BYTES = 7;
|
|
63
|
+
const TAG_ARRAY = 8;
|
|
64
|
+
const TAG_OBJECT = 9;
|
|
65
|
+
var WireDecodeError = class extends Error {
|
|
66
|
+
name = "WireDecodeError";
|
|
67
|
+
constructor(message) {
|
|
68
|
+
super(message);
|
|
69
|
+
}
|
|
70
|
+
};
|
|
71
|
+
/**
|
|
72
|
+
* Stateful cursor over a byte buffer.
|
|
73
|
+
* Every read advances the internal offset; out-of-bounds reads throw
|
|
74
|
+
* `WireDecodeError` immediately so callers never see partial state.
|
|
75
|
+
*/
|
|
76
|
+
var WireReader = class {
|
|
77
|
+
view;
|
|
78
|
+
offset = 0;
|
|
79
|
+
constructor(buf) {
|
|
80
|
+
this.view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
|
|
81
|
+
}
|
|
82
|
+
get remaining() {
|
|
83
|
+
return this.view.byteLength - this.offset;
|
|
84
|
+
}
|
|
85
|
+
readU8() {
|
|
86
|
+
if (this.remaining < 1) throw new WireDecodeError("unexpected end of data reading u8");
|
|
87
|
+
return this.view.getUint8(this.offset++);
|
|
88
|
+
}
|
|
89
|
+
readU32() {
|
|
90
|
+
if (this.remaining < 4) throw new WireDecodeError("unexpected end of data reading u32");
|
|
91
|
+
const n = this.view.getUint32(this.offset, false);
|
|
92
|
+
this.offset += 4;
|
|
93
|
+
return n;
|
|
94
|
+
}
|
|
95
|
+
readF64() {
|
|
96
|
+
if (this.remaining < 8) throw new WireDecodeError("unexpected end of data reading f64");
|
|
97
|
+
const n = this.view.getFloat64(this.offset, false);
|
|
98
|
+
this.offset += 8;
|
|
99
|
+
return n;
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Read a big-endian u64 as a JS `bigint`. Uses two u32 reads to avoid
|
|
103
|
+
* floating-point precision loss from DataView.getBigUint64 on older runtimes
|
|
104
|
+
* (though Node 18+ supports it; this is belt-and-suspenders).
|
|
105
|
+
*/
|
|
106
|
+
readU64BE() {
|
|
107
|
+
if (this.remaining < 8) throw new WireDecodeError("unexpected end of data reading u64");
|
|
108
|
+
const hi = BigInt(this.view.getUint32(this.offset, false));
|
|
109
|
+
const lo = BigInt(this.view.getUint32(this.offset + 4, false));
|
|
110
|
+
this.offset += 8;
|
|
111
|
+
return hi << 32n | lo;
|
|
112
|
+
}
|
|
113
|
+
readRawBytes(len) {
|
|
114
|
+
if (this.remaining < len) throw new WireDecodeError(`unexpected end of data: need ${len} bytes, have ${this.remaining}`);
|
|
115
|
+
const slice = new Uint8Array(this.view.buffer, this.view.byteOffset + this.offset, len);
|
|
116
|
+
this.offset += len;
|
|
117
|
+
return slice;
|
|
118
|
+
}
|
|
119
|
+
readString() {
|
|
120
|
+
const len = this.readU32();
|
|
121
|
+
const bytes = this.readRawBytes(len);
|
|
122
|
+
return new TextDecoder().decode(bytes);
|
|
123
|
+
}
|
|
124
|
+
readBool() {
|
|
125
|
+
const b = this.readU8();
|
|
126
|
+
if (b !== 0 && b !== 1) throw new WireDecodeError(`invalid bool byte: 0x${b.toString(16).padStart(2, "0")}`);
|
|
127
|
+
return b === 1;
|
|
128
|
+
}
|
|
129
|
+
readStringList() {
|
|
130
|
+
const count = this.readU32();
|
|
131
|
+
const items = [];
|
|
132
|
+
for (let i = 0; i < count; i++) items.push(this.readString());
|
|
133
|
+
return items;
|
|
134
|
+
}
|
|
135
|
+
assertDone() {
|
|
136
|
+
if (this.remaining !== 0) throw new WireDecodeError(`${this.remaining} trailing bytes after expected end of payload`);
|
|
137
|
+
}
|
|
138
|
+
};
|
|
139
|
+
function decodeWireValueFromReader(reader) {
|
|
140
|
+
const tag = reader.readU8();
|
|
141
|
+
switch (tag) {
|
|
142
|
+
case TAG_UNDEFINED: return;
|
|
143
|
+
case TAG_NULL: return null;
|
|
144
|
+
case TAG_FALSE: return false;
|
|
145
|
+
case TAG_TRUE: return true;
|
|
146
|
+
case TAG_NUMBER: return reader.readF64();
|
|
147
|
+
case TAG_STRING: return reader.readString();
|
|
148
|
+
case TAG_BIGINT: {
|
|
149
|
+
const sign = reader.readU8();
|
|
150
|
+
const count = reader.readU32();
|
|
151
|
+
let magnitude = 0n;
|
|
152
|
+
for (let i = 0; i < count; i++) magnitude |= reader.readU64BE() << BigInt(i * 64);
|
|
153
|
+
return sign ? -magnitude : magnitude;
|
|
154
|
+
}
|
|
155
|
+
case TAG_BYTES: {
|
|
156
|
+
const len = reader.readU32();
|
|
157
|
+
return reader.readRawBytes(len).slice();
|
|
158
|
+
}
|
|
159
|
+
case TAG_ARRAY: {
|
|
160
|
+
const count = reader.readU32();
|
|
161
|
+
const items = [];
|
|
162
|
+
for (let i = 0; i < count; i++) items.push(decodeWireValueFromReader(reader));
|
|
163
|
+
return items;
|
|
164
|
+
}
|
|
165
|
+
case TAG_OBJECT: {
|
|
166
|
+
const count = reader.readU32();
|
|
167
|
+
const obj = Object.create(null);
|
|
168
|
+
for (let i = 0; i < count; i++) {
|
|
169
|
+
const key = reader.readString();
|
|
170
|
+
const val = decodeWireValueFromReader(reader);
|
|
171
|
+
if (key === "__proto__") continue;
|
|
172
|
+
obj[key] = val;
|
|
173
|
+
}
|
|
174
|
+
return obj;
|
|
175
|
+
}
|
|
176
|
+
default: throw new WireDecodeError(`unknown WireValue tag: 0x${tag.toString(16).padStart(2, "0")}`);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* Decode a single `WireValue` from the start of `buf`, returning both the
|
|
181
|
+
* decoded value and the number of bytes consumed.
|
|
182
|
+
*
|
|
183
|
+
* Used by `decodeBridgeCallPayload` in `ipc.ts` where multiple values are
|
|
184
|
+
* packed sequentially in a larger payload buffer.
|
|
185
|
+
* @param buf
|
|
186
|
+
*/
|
|
187
|
+
function decodeWireValueFromSlice(buf) {
|
|
188
|
+
const reader = new WireReader(buf);
|
|
189
|
+
return [decodeWireValueFromReader(reader), buf.byteLength - reader.remaining];
|
|
190
|
+
}
|
|
191
|
+
/**
|
|
192
|
+
* Decode a `RunCompletionPayload` from a `Result` frame payload.
|
|
193
|
+
*
|
|
194
|
+
* Wire layout per `docs/protocol.md` §5.6:
|
|
195
|
+
* ```
|
|
196
|
+
* u32 runId
|
|
197
|
+
* u8 ok
|
|
198
|
+
* u8 successPresent (1 when ok = 1)
|
|
199
|
+
* WireValue exports
|
|
200
|
+
* List<String> stdout
|
|
201
|
+
* List<String> stderr
|
|
202
|
+
* f64 durationMs
|
|
203
|
+
* u8 failurePresent (1 when ok = 0)
|
|
204
|
+
* String code
|
|
205
|
+
* String name
|
|
206
|
+
* String message
|
|
207
|
+
* Optional<String> stack
|
|
208
|
+
* List<String> stdout
|
|
209
|
+
* List<String> stderr
|
|
210
|
+
* f64 durationMs
|
|
211
|
+
* ```
|
|
212
|
+
* @param buf
|
|
213
|
+
*/
|
|
214
|
+
function decodeRunCompletionPayload(buf) {
|
|
215
|
+
const reader = new WireReader(buf);
|
|
216
|
+
const runId = reader.readU32();
|
|
217
|
+
if (reader.readBool()) {
|
|
218
|
+
if (reader.readU8() !== 1) throw new WireDecodeError("expected success present byte = 1 when ok = true");
|
|
219
|
+
const exportsRaw = decodeWireValueFromReader(reader);
|
|
220
|
+
const stdout = reader.readStringList();
|
|
221
|
+
const stderr = reader.readStringList();
|
|
222
|
+
const durationMs = reader.readF64();
|
|
223
|
+
reader.readU8();
|
|
224
|
+
reader.assertDone();
|
|
225
|
+
return {
|
|
226
|
+
runId,
|
|
227
|
+
result: {
|
|
228
|
+
ok: true,
|
|
229
|
+
exports: wireObjectToExports(exportsRaw),
|
|
230
|
+
stdout,
|
|
231
|
+
stderr,
|
|
232
|
+
durationMs
|
|
233
|
+
}
|
|
234
|
+
};
|
|
235
|
+
}
|
|
236
|
+
reader.readU8();
|
|
237
|
+
if (reader.readU8() !== 1) throw new WireDecodeError("expected failure present byte = 1 when ok = false");
|
|
238
|
+
const code = reader.readString();
|
|
239
|
+
const name = reader.readString();
|
|
240
|
+
const message = reader.readString();
|
|
241
|
+
const stack = reader.readU8() === 1 ? reader.readString() : void 0;
|
|
242
|
+
const stdout = reader.readStringList();
|
|
243
|
+
const stderr = reader.readStringList();
|
|
244
|
+
const durationMs = reader.readF64();
|
|
245
|
+
reader.assertDone();
|
|
246
|
+
return {
|
|
247
|
+
runId,
|
|
248
|
+
result: {
|
|
249
|
+
ok: false,
|
|
250
|
+
error: {
|
|
251
|
+
code,
|
|
252
|
+
name,
|
|
253
|
+
message,
|
|
254
|
+
stack
|
|
255
|
+
},
|
|
256
|
+
stdout,
|
|
257
|
+
stderr,
|
|
258
|
+
durationMs
|
|
259
|
+
}
|
|
260
|
+
};
|
|
261
|
+
}
|
|
262
|
+
/**
|
|
263
|
+
* Decode a `PrecompileResultPayload` from a `PrecompileResult` frame.
|
|
264
|
+
*
|
|
265
|
+
* Wire layout per `docs/protocol.md` §5.6:
|
|
266
|
+
* ```
|
|
267
|
+
* u8 ok
|
|
268
|
+
* u8 prefixIdPresent (1 when ok = true)
|
|
269
|
+
* String prefixId
|
|
270
|
+
* u8 errorPresent (1 when ok = false)
|
|
271
|
+
* RunErrorPayload error
|
|
272
|
+
* ```
|
|
273
|
+
* @param buf
|
|
274
|
+
*/
|
|
275
|
+
function decodePrecompileResultPayload(buf) {
|
|
276
|
+
const reader = new WireReader(buf);
|
|
277
|
+
if (reader.readBool()) {
|
|
278
|
+
if (reader.readU8() !== 1) throw new WireDecodeError("expected prefixId present byte = 1 when ok = true");
|
|
279
|
+
const prefixId = reader.readString();
|
|
280
|
+
reader.readU8();
|
|
281
|
+
reader.assertDone();
|
|
282
|
+
return {
|
|
283
|
+
ok: true,
|
|
284
|
+
prefixId
|
|
285
|
+
};
|
|
286
|
+
}
|
|
287
|
+
reader.readU8();
|
|
288
|
+
if (reader.readU8() !== 1) throw new WireDecodeError("expected error present byte = 1 when ok = false");
|
|
289
|
+
const code = reader.readString();
|
|
290
|
+
const name = reader.readString();
|
|
291
|
+
const message = reader.readString();
|
|
292
|
+
const stack = reader.readU8() === 1 ? reader.readString() : void 0;
|
|
293
|
+
reader.assertDone();
|
|
294
|
+
return {
|
|
295
|
+
ok: false,
|
|
296
|
+
error: {
|
|
297
|
+
code,
|
|
298
|
+
name,
|
|
299
|
+
message,
|
|
300
|
+
stack
|
|
301
|
+
}
|
|
302
|
+
};
|
|
303
|
+
}
|
|
304
|
+
const ENC_TAG_UNDEFINED = 0;
|
|
305
|
+
const ENC_TAG_NULL = 1;
|
|
306
|
+
const ENC_TAG_FALSE = 2;
|
|
307
|
+
const ENC_TAG_TRUE = 3;
|
|
308
|
+
const ENC_TAG_NUMBER = 4;
|
|
309
|
+
const ENC_TAG_STRING = 5;
|
|
310
|
+
const ENC_TAG_BIGINT = 6;
|
|
311
|
+
const ENC_TAG_BYTES = 7;
|
|
312
|
+
const ENC_TAG_ARRAY = 8;
|
|
313
|
+
const ENC_TAG_OBJECT = 9;
|
|
314
|
+
var WireWriter = class {
|
|
315
|
+
parts = [];
|
|
316
|
+
/**
|
|
317
|
+
* Objects currently on the recursion stack. Used for cycle detection.
|
|
318
|
+
* Mirrors the `visiting` Vec in Rust's `value_to_wire`.
|
|
319
|
+
*
|
|
320
|
+
* Path-based (add before recursing, delete after): allows diamond shapes
|
|
321
|
+
* (`{ a: x, b: x }` where x is the same object) but rejects true cycles.
|
|
322
|
+
*/
|
|
323
|
+
visiting = /* @__PURE__ */ new WeakSet();
|
|
324
|
+
writeU8(n) {
|
|
325
|
+
const b = Buffer.allocUnsafe(1);
|
|
326
|
+
b.writeUInt8(n, 0);
|
|
327
|
+
this.parts.push(b);
|
|
328
|
+
return this;
|
|
329
|
+
}
|
|
330
|
+
writeU32(n) {
|
|
331
|
+
const b = Buffer.allocUnsafe(4);
|
|
332
|
+
b.writeUInt32BE(n, 0);
|
|
333
|
+
this.parts.push(b);
|
|
334
|
+
return this;
|
|
335
|
+
}
|
|
336
|
+
writeF64(n) {
|
|
337
|
+
const b = Buffer.allocUnsafe(8);
|
|
338
|
+
b.writeDoubleBE(n, 0);
|
|
339
|
+
this.parts.push(b);
|
|
340
|
+
return this;
|
|
341
|
+
}
|
|
342
|
+
/**
|
|
343
|
+
* Write a JS `bigint` as a big-endian u64 (must fit in 64 bits).
|
|
344
|
+
* @param n
|
|
345
|
+
*/
|
|
346
|
+
writeU64BE(n) {
|
|
347
|
+
const b = Buffer.allocUnsafe(8);
|
|
348
|
+
b.writeUInt32BE(Number(n >> 32n & 4294967295n), 0);
|
|
349
|
+
b.writeUInt32BE(Number(n & 4294967295n), 4);
|
|
350
|
+
this.parts.push(b);
|
|
351
|
+
return this;
|
|
352
|
+
}
|
|
353
|
+
writeString(s) {
|
|
354
|
+
const encoded = Buffer.from(s, "utf8");
|
|
355
|
+
this.writeU32(encoded.byteLength);
|
|
356
|
+
this.parts.push(encoded);
|
|
357
|
+
return this;
|
|
358
|
+
}
|
|
359
|
+
writeValue(value) {
|
|
360
|
+
if (value === void 0) return this.writeU8(ENC_TAG_UNDEFINED);
|
|
361
|
+
if (value === null) return this.writeU8(ENC_TAG_NULL);
|
|
362
|
+
if (typeof value === "boolean") return this.writeU8(value ? ENC_TAG_TRUE : ENC_TAG_FALSE);
|
|
363
|
+
if (typeof value === "number") return this.writeU8(ENC_TAG_NUMBER).writeF64(value);
|
|
364
|
+
if (typeof value === "string") return this.writeU8(ENC_TAG_STRING).writeString(value);
|
|
365
|
+
if (typeof value === "bigint") {
|
|
366
|
+
const sign = value < 0n ? 1 : 0;
|
|
367
|
+
let magnitude = value < 0n ? -value : value;
|
|
368
|
+
const words = [];
|
|
369
|
+
while (magnitude > 0n) {
|
|
370
|
+
words.push(magnitude & 18446744073709551615n);
|
|
371
|
+
magnitude >>= 64n;
|
|
372
|
+
}
|
|
373
|
+
this.writeU8(ENC_TAG_BIGINT);
|
|
374
|
+
this.writeU8(sign);
|
|
375
|
+
this.writeU32(words.length);
|
|
376
|
+
for (const word of words) this.writeU64BE(word);
|
|
377
|
+
return this;
|
|
378
|
+
}
|
|
379
|
+
if (value instanceof Uint8Array) {
|
|
380
|
+
this.writeU8(ENC_TAG_BYTES);
|
|
381
|
+
this.writeU32(value.byteLength);
|
|
382
|
+
this.parts.push(Buffer.from(value.buffer, value.byteOffset, value.byteLength));
|
|
383
|
+
return this;
|
|
384
|
+
}
|
|
385
|
+
if (Array.isArray(value)) {
|
|
386
|
+
if (this.visiting.has(value)) throw new TypeError("[iso4] encodeWireValue: cyclic or self-referential structure");
|
|
387
|
+
this.visiting.add(value);
|
|
388
|
+
this.writeU8(ENC_TAG_ARRAY);
|
|
389
|
+
this.writeU32(value.length);
|
|
390
|
+
for (const item of value) this.writeValue(item);
|
|
391
|
+
this.visiting.delete(value);
|
|
392
|
+
return this;
|
|
393
|
+
}
|
|
394
|
+
if (typeof value === "object") {
|
|
395
|
+
if (this.visiting.has(value)) throw new TypeError("[iso4] encodeWireValue: cyclic or self-referential structure");
|
|
396
|
+
this.visiting.add(value);
|
|
397
|
+
const entries = Object.entries(value).filter(([k]) => k !== "__proto__");
|
|
398
|
+
this.writeU8(ENC_TAG_OBJECT);
|
|
399
|
+
this.writeU32(entries.length);
|
|
400
|
+
for (const [k, v] of entries) {
|
|
401
|
+
this.writeString(k);
|
|
402
|
+
this.writeValue(v);
|
|
403
|
+
}
|
|
404
|
+
this.visiting.delete(value);
|
|
405
|
+
return this;
|
|
406
|
+
}
|
|
407
|
+
throw new TypeError(`[iso4] encodeWireValue: cannot encode value of type "${typeof value}"`);
|
|
408
|
+
}
|
|
409
|
+
toBuffer() {
|
|
410
|
+
return Buffer.concat(this.parts);
|
|
411
|
+
}
|
|
412
|
+
};
|
|
413
|
+
/**
|
|
414
|
+
* Encode a single JavaScript value as a `WireValue` byte sequence.
|
|
415
|
+
* Used to encode host bridge response return values.
|
|
416
|
+
* @param value
|
|
417
|
+
*/
|
|
418
|
+
function encodeWireValue(value) {
|
|
419
|
+
return new WireWriter().writeValue(value).toBuffer();
|
|
420
|
+
}
|
|
421
|
+
function wireObjectToExports(raw) {
|
|
422
|
+
if (raw === null || typeof raw !== "object" || Array.isArray(raw)) throw new WireDecodeError(`exports must decode to a WireValue::Object, got: ${Array.isArray(raw) ? "array" : typeof raw}`);
|
|
423
|
+
return raw;
|
|
424
|
+
}
|
|
425
|
+
//#endregion
|
|
426
|
+
//#region src/ipc.ts
|
|
427
|
+
const DEFAULT_MAX_FRAME_LENGTH = 64 * 1024 * 1024;
|
|
428
|
+
const TsToRustMessageTypes = {
|
|
429
|
+
Authenticate: 1,
|
|
430
|
+
Run: 2,
|
|
431
|
+
Precompile: 3,
|
|
432
|
+
PrefixRun: 4,
|
|
433
|
+
DisposePrefix: 5,
|
|
434
|
+
BridgeResponse: 6,
|
|
435
|
+
Terminate: 7
|
|
436
|
+
};
|
|
437
|
+
const RustToTsMessageTypes = {
|
|
438
|
+
BridgeCall: 1,
|
|
439
|
+
Result: 2,
|
|
440
|
+
PrecompileResult: 3,
|
|
441
|
+
Log: 4
|
|
442
|
+
};
|
|
443
|
+
var FrameReader = class {
|
|
444
|
+
buffer = Buffer.alloc(0);
|
|
445
|
+
pendingReads = [];
|
|
446
|
+
closedError = null;
|
|
447
|
+
push(chunk) {
|
|
448
|
+
if (this.closedError !== null) return;
|
|
449
|
+
this.buffer = Buffer.concat([this.buffer, Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength)]);
|
|
450
|
+
this.flushPendingReads();
|
|
451
|
+
}
|
|
452
|
+
readFrame() {
|
|
453
|
+
const frame = this.tryReadFrame();
|
|
454
|
+
if (frame !== null) return Promise.resolve(frame);
|
|
455
|
+
if (this.closedError !== null) return Promise.reject(this.closedError);
|
|
456
|
+
return new Promise((resolve, reject) => {
|
|
457
|
+
this.pendingReads.push({
|
|
458
|
+
resolve,
|
|
459
|
+
reject
|
|
460
|
+
});
|
|
461
|
+
});
|
|
462
|
+
}
|
|
463
|
+
async readRustToTsFrame() {
|
|
464
|
+
const frame = await this.readFrame();
|
|
465
|
+
return {
|
|
466
|
+
messageType: parseRustToTsMessageType(frame.messageType),
|
|
467
|
+
payload: frame.payload
|
|
468
|
+
};
|
|
469
|
+
}
|
|
470
|
+
async *[Symbol.asyncIterator]() {
|
|
471
|
+
for (;;) yield await this.readRustToTsFrame();
|
|
472
|
+
}
|
|
473
|
+
close(error = /* @__PURE__ */ new Error("frame reader closed")) {
|
|
474
|
+
if (this.closedError !== null) return;
|
|
475
|
+
this.closedError = error;
|
|
476
|
+
this.flushPendingReads();
|
|
477
|
+
while (this.pendingReads.length > 0) this.pendingReads.shift()?.reject(error);
|
|
478
|
+
}
|
|
479
|
+
flushPendingReads() {
|
|
480
|
+
while (this.pendingReads.length > 0) {
|
|
481
|
+
const frame = this.tryReadFrame();
|
|
482
|
+
if (frame === null) break;
|
|
483
|
+
this.pendingReads.shift()?.resolve(frame);
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
tryReadFrame() {
|
|
487
|
+
if (this.buffer.byteLength < 4) return null;
|
|
488
|
+
const length = this.buffer.readUInt32BE(0);
|
|
489
|
+
if (length === 0) {
|
|
490
|
+
const error = /* @__PURE__ */ new Error("frame length cannot be zero");
|
|
491
|
+
this.close(error);
|
|
492
|
+
throw error;
|
|
493
|
+
}
|
|
494
|
+
if (length > 67108864) {
|
|
495
|
+
const error = /* @__PURE__ */ new Error(`frame length ${length} exceeds max frame length ${DEFAULT_MAX_FRAME_LENGTH}`);
|
|
496
|
+
this.close(error);
|
|
497
|
+
throw error;
|
|
498
|
+
}
|
|
499
|
+
if (this.buffer.byteLength < 4 + length) return null;
|
|
500
|
+
const frameBytes = this.buffer.subarray(0, 4 + length);
|
|
501
|
+
this.buffer = this.buffer.subarray(4 + length);
|
|
502
|
+
return decodeFrame(frameBytes);
|
|
503
|
+
}
|
|
504
|
+
};
|
|
505
|
+
function encodeFrame(messageType, payload, maxFrameLength = DEFAULT_MAX_FRAME_LENGTH) {
|
|
506
|
+
if (!Number.isInteger(messageType) || messageType < 0 || messageType > 255) throw new Error(`message type must fit in one byte: ${messageType}`);
|
|
507
|
+
const length = payload.byteLength + 1;
|
|
508
|
+
if (length > maxFrameLength) throw new Error(`frame length ${length} exceeds max frame length ${maxFrameLength}`);
|
|
509
|
+
const frame = Buffer.allocUnsafe(4 + length);
|
|
510
|
+
frame.writeUInt32BE(length, 0);
|
|
511
|
+
frame[4] = messageType;
|
|
512
|
+
Buffer.from(payload.buffer, payload.byteOffset, payload.byteLength).copy(frame, 5);
|
|
513
|
+
return frame;
|
|
514
|
+
}
|
|
515
|
+
function decodeFrame(bytes, maxFrameLength = DEFAULT_MAX_FRAME_LENGTH) {
|
|
516
|
+
if (bytes.byteLength < 4) throw new Error("frame is missing 4-byte length prefix");
|
|
517
|
+
const view = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
518
|
+
const length = view.readUInt32BE(0);
|
|
519
|
+
if (length === 0) throw new Error("frame length cannot be zero");
|
|
520
|
+
if (length > maxFrameLength) throw new Error(`frame length ${length} exceeds max frame length ${maxFrameLength}`);
|
|
521
|
+
if (view.byteLength < 4 + length) throw new Error("frame body is truncated");
|
|
522
|
+
if (view.byteLength > 4 + length) throw new Error("buffer contains trailing bytes after frame");
|
|
523
|
+
const messageType = view[4];
|
|
524
|
+
if (messageType === void 0) throw new Error("frame is missing message type");
|
|
525
|
+
return {
|
|
526
|
+
messageType,
|
|
527
|
+
payload: view.subarray(5)
|
|
528
|
+
};
|
|
529
|
+
}
|
|
530
|
+
function encodeTsToRustFrame(messageType, payload) {
|
|
531
|
+
return encodeFrame(messageType, payload);
|
|
532
|
+
}
|
|
533
|
+
function encodeAuthenticatePayload(auth) {
|
|
534
|
+
if (!Number.isInteger(auth.protocolVersion)) throw new Error("protocolVersion must be an integer");
|
|
535
|
+
if (auth.protocolVersion < 0 || auth.protocolVersion > 65535) throw new Error(`protocolVersion out of u16 range: ${auth.protocolVersion}`);
|
|
536
|
+
const token = Buffer.from(auth.token, "utf8");
|
|
537
|
+
const payload = Buffer.allocUnsafe(2 + token.byteLength);
|
|
538
|
+
payload.writeUInt16BE(auth.protocolVersion, 0);
|
|
539
|
+
token.copy(payload, 2);
|
|
540
|
+
return payload;
|
|
541
|
+
}
|
|
542
|
+
var PayloadWriter = class {
|
|
543
|
+
parts = [];
|
|
544
|
+
writeU8(n) {
|
|
545
|
+
const b = Buffer.allocUnsafe(1);
|
|
546
|
+
b.writeUInt8(n, 0);
|
|
547
|
+
this.parts.push(b);
|
|
548
|
+
return this;
|
|
549
|
+
}
|
|
550
|
+
writeU32(n) {
|
|
551
|
+
const b = Buffer.allocUnsafe(4);
|
|
552
|
+
b.writeUInt32BE(n, 0);
|
|
553
|
+
this.parts.push(b);
|
|
554
|
+
return this;
|
|
555
|
+
}
|
|
556
|
+
writeString(s) {
|
|
557
|
+
const encoded = Buffer.from(s, "utf8");
|
|
558
|
+
this.writeU32(encoded.byteLength);
|
|
559
|
+
this.parts.push(encoded);
|
|
560
|
+
return this;
|
|
561
|
+
}
|
|
562
|
+
writeBytes(bytes) {
|
|
563
|
+
this.parts.push(Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength));
|
|
564
|
+
return this;
|
|
565
|
+
}
|
|
566
|
+
writeOptionalString(s) {
|
|
567
|
+
if (s === void 0) this.writeU8(0);
|
|
568
|
+
else {
|
|
569
|
+
this.writeU8(1);
|
|
570
|
+
this.writeString(s);
|
|
571
|
+
}
|
|
572
|
+
return this;
|
|
573
|
+
}
|
|
574
|
+
writeResourceLimits(limits) {
|
|
575
|
+
this.writeU32(limits.memoryMb ?? 0);
|
|
576
|
+
this.writeU32(limits.cpuTimeMs ?? 0);
|
|
577
|
+
this.writeU32(limits.wallTimeMs ?? 0);
|
|
578
|
+
this.writeU32(limits.maxExportBytes ?? 0);
|
|
579
|
+
this.writeU32(limits.maxStdoutBytes ?? 0);
|
|
580
|
+
this.writeU32(limits.maxStderrBytes ?? 0);
|
|
581
|
+
this.writeU32(limits.maxBridgeCallBytes ?? 0);
|
|
582
|
+
this.writeU32(limits.maxBridgeCalls ?? 10);
|
|
583
|
+
return this;
|
|
584
|
+
}
|
|
585
|
+
toBuffer() {
|
|
586
|
+
return Buffer.concat(this.parts);
|
|
587
|
+
}
|
|
588
|
+
};
|
|
589
|
+
/**
|
|
590
|
+
* Encode a `RunPayload` per `docs/protocol.md` §5.2.
|
|
591
|
+
* @param options
|
|
592
|
+
*/
|
|
593
|
+
function encodeRunPayload(options) {
|
|
594
|
+
const w = new PayloadWriter().writeU32(options.runId).writeString(options.code).writeOptionalString(options.filename).writeResourceLimits(options.limits ?? {});
|
|
595
|
+
const globals = options.globals ?? [];
|
|
596
|
+
w.writeU32(globals.length);
|
|
597
|
+
for (const name of globals) w.writeString(name);
|
|
598
|
+
w.writeU32(0);
|
|
599
|
+
return w.toBuffer();
|
|
600
|
+
}
|
|
601
|
+
/**
|
|
602
|
+
* Encode a `PrecompilePayload` per `docs/protocol.md` §5.2.
|
|
603
|
+
* Same as `RunPayload` without `runId`.
|
|
604
|
+
* @param options
|
|
605
|
+
*/
|
|
606
|
+
function encodePrecompilePayload(options) {
|
|
607
|
+
const w = new PayloadWriter().writeString(options.code).writeOptionalString(options.filename).writeResourceLimits(options.limits ?? {});
|
|
608
|
+
const globals = options.globals ?? [];
|
|
609
|
+
w.writeU32(globals.length);
|
|
610
|
+
for (const name of globals) w.writeString(name);
|
|
611
|
+
w.writeU32(0);
|
|
612
|
+
return w.toBuffer();
|
|
613
|
+
}
|
|
614
|
+
/**
|
|
615
|
+
* Encode a `PrefixRunPayload` per `docs/protocol.md` §5.2.
|
|
616
|
+
* `runId` is managed by the client and injected at call time — not part of
|
|
617
|
+
* the public options interface.
|
|
618
|
+
* @param options
|
|
619
|
+
*/
|
|
620
|
+
function encodePrefixRunPayload(options) {
|
|
621
|
+
const w = new PayloadWriter().writeU32(options.runId).writeString(options.prefixId).writeString(options.code).writeOptionalString(options.filename).writeResourceLimits(options.limits ?? {});
|
|
622
|
+
const globals = options.globals ?? [];
|
|
623
|
+
w.writeU32(globals.length);
|
|
624
|
+
for (const name of globals) w.writeString(name);
|
|
625
|
+
w.writeU32(0);
|
|
626
|
+
return w.toBuffer();
|
|
627
|
+
}
|
|
628
|
+
/**
|
|
629
|
+
* Encode a `DisposePrefix` payload — just the PrefixId string.
|
|
630
|
+
* @param prefixId
|
|
631
|
+
*/
|
|
632
|
+
function encodeDisposePrefixPayload(prefixId) {
|
|
633
|
+
return new PayloadWriter().writeString(prefixId).toBuffer();
|
|
634
|
+
}
|
|
635
|
+
/**
|
|
636
|
+
* Decode a `BridgeCallPayload` from a `BridgeCall` frame sent by Rust.
|
|
637
|
+
* Per `docs/protocol.md` §5.4.
|
|
638
|
+
* @param buf
|
|
639
|
+
*/
|
|
640
|
+
function decodeBridgeCallPayload(buf) {
|
|
641
|
+
const view = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
|
|
642
|
+
let offset = 0;
|
|
643
|
+
const readU8 = () => {
|
|
644
|
+
if (offset >= view.byteLength) throw new Error("BridgeCall payload truncated (u8)");
|
|
645
|
+
return view.readUInt8(offset++);
|
|
646
|
+
};
|
|
647
|
+
const readU32 = () => {
|
|
648
|
+
if (offset + 4 > view.byteLength) throw new Error("BridgeCall payload truncated (u32)");
|
|
649
|
+
const n = view.readUInt32BE(offset);
|
|
650
|
+
offset += 4;
|
|
651
|
+
return n;
|
|
652
|
+
};
|
|
653
|
+
const readString = () => {
|
|
654
|
+
const len = readU32();
|
|
655
|
+
if (offset + len > view.byteLength) throw new Error("BridgeCall payload truncated (string)");
|
|
656
|
+
const s = view.subarray(offset, offset + len).toString("utf8");
|
|
657
|
+
offset += len;
|
|
658
|
+
return s;
|
|
659
|
+
};
|
|
660
|
+
const readWireValue = () => {
|
|
661
|
+
const [value, consumed] = decodeWireValueFromSlice(new Uint8Array(view.buffer, view.byteOffset + offset, view.byteLength - offset));
|
|
662
|
+
offset += consumed;
|
|
663
|
+
return [value, consumed];
|
|
664
|
+
};
|
|
665
|
+
const callId = readU32();
|
|
666
|
+
const targetKindRaw = readU8();
|
|
667
|
+
if (targetKindRaw !== 0 && targetKindRaw !== 1) throw new Error(`invalid bridge targetKind: ${targetKindRaw}`);
|
|
668
|
+
const targetKind = targetKindRaw;
|
|
669
|
+
const specifier = readU8() === 1 ? readString() : void 0;
|
|
670
|
+
const exportName = readString();
|
|
671
|
+
const argCount = readU32();
|
|
672
|
+
const args = [];
|
|
673
|
+
for (let i = 0; i < argCount; i++) {
|
|
674
|
+
const [value] = readWireValue();
|
|
675
|
+
args.push(value);
|
|
676
|
+
}
|
|
677
|
+
return {
|
|
678
|
+
callId,
|
|
679
|
+
targetKind,
|
|
680
|
+
specifier,
|
|
681
|
+
exportName,
|
|
682
|
+
args
|
|
683
|
+
};
|
|
684
|
+
}
|
|
685
|
+
/**
|
|
686
|
+
* Encode a `BridgeResponsePayload` per `docs/protocol.md` §5.4.
|
|
687
|
+
*
|
|
688
|
+
* When `ok = true`, `encodedValue` contains pre-encoded WireValue bytes.
|
|
689
|
+
* When `ok = false`, `errorMessage` is the handler rejection message.
|
|
690
|
+
* @param callId
|
|
691
|
+
* @param ok
|
|
692
|
+
* @param encodedValue
|
|
693
|
+
* @param errorMessage
|
|
694
|
+
*/
|
|
695
|
+
function encodeBridgeResponsePayload(callId, ok, encodedValue, errorMessage) {
|
|
696
|
+
const w = new PayloadWriter();
|
|
697
|
+
w.writeU32(callId);
|
|
698
|
+
if (ok) {
|
|
699
|
+
w.writeU8(1);
|
|
700
|
+
if (encodedValue !== void 0 && encodedValue.byteLength > 0) {
|
|
701
|
+
w.writeU8(1);
|
|
702
|
+
w.writeBytes(encodedValue);
|
|
703
|
+
} else w.writeU8(0);
|
|
704
|
+
} else {
|
|
705
|
+
w.writeU8(0);
|
|
706
|
+
w.writeString("ERR_HOST_BRIDGE");
|
|
707
|
+
w.writeString("Error");
|
|
708
|
+
w.writeString(errorMessage ?? "host handler failed");
|
|
709
|
+
w.writeU8(0);
|
|
710
|
+
}
|
|
711
|
+
return w.toBuffer();
|
|
712
|
+
}
|
|
713
|
+
function parseRustToTsMessageType(byte) {
|
|
714
|
+
switch (byte) {
|
|
715
|
+
case RustToTsMessageTypes.BridgeCall:
|
|
716
|
+
case RustToTsMessageTypes.Result:
|
|
717
|
+
case RustToTsMessageTypes.PrecompileResult:
|
|
718
|
+
case RustToTsMessageTypes.Log: return byte;
|
|
719
|
+
default: throw new Error(`unknown Rust->TS message type: ${formatByte(byte)}`);
|
|
720
|
+
}
|
|
721
|
+
}
|
|
722
|
+
function formatByte(byte) {
|
|
723
|
+
return `0x${byte.toString(16).padStart(2, "0")}`;
|
|
724
|
+
}
|
|
725
|
+
//#endregion
|
|
726
|
+
//#region src/client.ts
|
|
727
|
+
var RuntimeIpcClient = class RuntimeIpcClient {
|
|
728
|
+
socket;
|
|
729
|
+
reader;
|
|
730
|
+
disposed = false;
|
|
731
|
+
constructor(socket) {
|
|
732
|
+
this.socket = socket;
|
|
733
|
+
this.reader = new FrameReader();
|
|
734
|
+
socket.on("data", (chunk) => {
|
|
735
|
+
this.reader.push(chunk);
|
|
736
|
+
});
|
|
737
|
+
socket.once("error", (error) => {
|
|
738
|
+
this.reader.close(error);
|
|
739
|
+
});
|
|
740
|
+
socket.once("end", () => {
|
|
741
|
+
this.reader.close(/* @__PURE__ */ new Error("socket ended"));
|
|
742
|
+
});
|
|
743
|
+
socket.once("close", () => {
|
|
744
|
+
this.reader.close(/* @__PURE__ */ new Error("socket closed"));
|
|
745
|
+
});
|
|
746
|
+
}
|
|
747
|
+
static async connect(options) {
|
|
748
|
+
const client = new RuntimeIpcClient(await connectSocket(options.socketPath));
|
|
749
|
+
await client.write(encodeTsToRustFrame(TsToRustMessageTypes.Authenticate, encodeAuthenticatePayload({
|
|
750
|
+
protocolVersion: 1,
|
|
751
|
+
token: options.token
|
|
752
|
+
})));
|
|
753
|
+
return client;
|
|
754
|
+
}
|
|
755
|
+
nextRunId = 0;
|
|
756
|
+
nextRunIdValue() {
|
|
757
|
+
this.nextRunId = this.nextRunId + 1 & 4294967295;
|
|
758
|
+
return this.nextRunId;
|
|
759
|
+
}
|
|
760
|
+
async runRawCode(code, options) {
|
|
761
|
+
if (this.disposed) throw new Error("runtime IPC client is disposed");
|
|
762
|
+
const globals = options?.globals ?? {};
|
|
763
|
+
const globalNames = Object.keys(globals);
|
|
764
|
+
await this.write(encodeTsToRustFrame(TsToRustMessageTypes.Run, encodeRunPayload({
|
|
765
|
+
runId: this.nextRunIdValue(),
|
|
766
|
+
code,
|
|
767
|
+
filename: options?.filename,
|
|
768
|
+
limits: options?.limits,
|
|
769
|
+
globals: globalNames
|
|
770
|
+
})));
|
|
771
|
+
return this.drainUntilResult(makeDispatcher(globals));
|
|
772
|
+
}
|
|
773
|
+
async precompile(options) {
|
|
774
|
+
if (this.disposed) throw new Error("runtime IPC client is disposed");
|
|
775
|
+
await this.write(encodeTsToRustFrame(TsToRustMessageTypes.Precompile, encodePrecompilePayload({
|
|
776
|
+
code: options.code,
|
|
777
|
+
filename: options.filename,
|
|
778
|
+
limits: options.limits,
|
|
779
|
+
globals: Object.keys(options.globals ?? {})
|
|
780
|
+
})));
|
|
781
|
+
for await (const frame of this.reader) {
|
|
782
|
+
if (frame.messageType === RustToTsMessageTypes.PrecompileResult) return frame.payload;
|
|
783
|
+
if (frame.messageType === RustToTsMessageTypes.Log) continue;
|
|
784
|
+
}
|
|
785
|
+
throw new Error("connection closed before receiving a PrecompileResult frame");
|
|
786
|
+
}
|
|
787
|
+
async prefixRun(options) {
|
|
788
|
+
if (this.disposed) throw new Error("runtime IPC client is disposed");
|
|
789
|
+
const globals = options.globals ?? {};
|
|
790
|
+
const globalNames = Object.keys(globals);
|
|
791
|
+
await this.write(encodeTsToRustFrame(TsToRustMessageTypes.PrefixRun, encodePrefixRunPayload({
|
|
792
|
+
prefixId: options.prefixId,
|
|
793
|
+
code: options.code,
|
|
794
|
+
filename: options.filename,
|
|
795
|
+
limits: options.limits,
|
|
796
|
+
globals: globalNames,
|
|
797
|
+
runId: this.nextRunIdValue()
|
|
798
|
+
})));
|
|
799
|
+
return this.drainUntilResult(makeDispatcher(globals));
|
|
800
|
+
}
|
|
801
|
+
async disposePrefix(prefixId) {
|
|
802
|
+
if (this.disposed) return;
|
|
803
|
+
await this.write(encodeTsToRustFrame(TsToRustMessageTypes.DisposePrefix, encodeDisposePrefixPayload(prefixId)));
|
|
804
|
+
}
|
|
805
|
+
async dispose() {
|
|
806
|
+
if (this.disposed) return;
|
|
807
|
+
this.disposed = true;
|
|
808
|
+
this.socket.end();
|
|
809
|
+
await new Promise((resolve) => {
|
|
810
|
+
if (this.socket.destroyed) {
|
|
811
|
+
resolve();
|
|
812
|
+
return;
|
|
813
|
+
}
|
|
814
|
+
this.socket.once("close", () => resolve());
|
|
815
|
+
this.socket.destroy();
|
|
816
|
+
});
|
|
817
|
+
}
|
|
818
|
+
/**
|
|
819
|
+
* Read frames until the `Result` frame arrives, dispatching `BridgeCall`
|
|
820
|
+
* frames to the handler in the meantime.
|
|
821
|
+
*
|
|
822
|
+
* Dispatches are fire-and-forget — the loop does NOT await the handler.
|
|
823
|
+
* This means the loop continues reading frames immediately. When the Rust
|
|
824
|
+
* side fires a wall timeout it sends a `Result` frame; the loop reads it
|
|
825
|
+
* and returns without waiting for the handler.
|
|
826
|
+
*
|
|
827
|
+
* The handler promise is then **orphaned**: it has no listener and will be
|
|
828
|
+
* garbage-collected when it eventually settles. Any in-flight I/O or timers
|
|
829
|
+
* continue to completion. Rust silently ignores any late `BridgeResponse`
|
|
830
|
+
* that arrives after the run has completed (see session.rs).
|
|
831
|
+
* @param dispatcher
|
|
832
|
+
*/
|
|
833
|
+
async drainUntilResult(dispatcher) {
|
|
834
|
+
for await (const frame of this.reader) switch (frame.messageType) {
|
|
835
|
+
case RustToTsMessageTypes.Result: return { result: frame.payload };
|
|
836
|
+
case RustToTsMessageTypes.Log: break;
|
|
837
|
+
case RustToTsMessageTypes.BridgeCall: {
|
|
838
|
+
const call = decodeBridgeCallPayload(frame.payload);
|
|
839
|
+
if (dispatcher === void 0) await this.write(encodeTsToRustFrame(TsToRustMessageTypes.BridgeResponse, encodeBridgeResponsePayload(call.callId, false, void 0, "no bridge dispatcher configured")));
|
|
840
|
+
else {
|
|
841
|
+
const { callId } = call;
|
|
842
|
+
dispatcher(call.exportName, call.args).then((value) => {
|
|
843
|
+
let encoded;
|
|
844
|
+
try {
|
|
845
|
+
encoded = encodeWireValue(value);
|
|
846
|
+
} catch (e) {
|
|
847
|
+
return this.write(encodeTsToRustFrame(TsToRustMessageTypes.BridgeResponse, encodeBridgeResponsePayload(callId, false, void 0, e instanceof Error ? e.message : String(e))));
|
|
848
|
+
}
|
|
849
|
+
return this.write(encodeTsToRustFrame(TsToRustMessageTypes.BridgeResponse, encodeBridgeResponsePayload(callId, true, encoded)));
|
|
850
|
+
}, (err) => this.write(encodeTsToRustFrame(TsToRustMessageTypes.BridgeResponse, encodeBridgeResponsePayload(callId, false, void 0, err instanceof Error ? err.message : String(err))))).catch(() => {});
|
|
851
|
+
}
|
|
852
|
+
break;
|
|
853
|
+
}
|
|
854
|
+
}
|
|
855
|
+
throw new Error("connection closed before receiving a Result frame");
|
|
856
|
+
}
|
|
857
|
+
async write(frame) {
|
|
858
|
+
await new Promise((resolve, reject) => {
|
|
859
|
+
this.socket.write(frame, (error) => {
|
|
860
|
+
if (error) {
|
|
861
|
+
reject(error);
|
|
862
|
+
return;
|
|
863
|
+
}
|
|
864
|
+
resolve();
|
|
865
|
+
});
|
|
866
|
+
});
|
|
867
|
+
}
|
|
868
|
+
};
|
|
869
|
+
/**
|
|
870
|
+
* Build a dispatcher from a globals map; returns undefined when map is empty.
|
|
871
|
+
* @param globals
|
|
872
|
+
*/
|
|
873
|
+
function makeDispatcher(globals) {
|
|
874
|
+
if (Object.keys(globals).length === 0) return void 0;
|
|
875
|
+
return async (name, args) => {
|
|
876
|
+
const handler = globals[name];
|
|
877
|
+
if (handler === void 0) throw new Error(`no handler configured for global '${name}'`);
|
|
878
|
+
return handler(...args);
|
|
879
|
+
};
|
|
880
|
+
}
|
|
881
|
+
function connectSocket(socketPath) {
|
|
882
|
+
return new Promise((resolve, reject) => {
|
|
883
|
+
const socket = createConnection(socketPath);
|
|
884
|
+
socket.once("connect", () => {
|
|
885
|
+
socket.off("error", reject);
|
|
886
|
+
resolve(socket);
|
|
887
|
+
});
|
|
888
|
+
socket.once("error", reject);
|
|
889
|
+
});
|
|
890
|
+
}
|
|
891
|
+
//#endregion
|
|
892
|
+
//#region src/pool.ts
|
|
893
|
+
var ConnectionPool = class {
|
|
894
|
+
free;
|
|
895
|
+
waiters = [];
|
|
896
|
+
disposed = false;
|
|
897
|
+
constructor(clients) {
|
|
898
|
+
this.free = [...clients];
|
|
899
|
+
}
|
|
900
|
+
/**
|
|
901
|
+
* Borrow a client, run `fn`, then unconditionally return the client.
|
|
902
|
+
* If the pool is disposed while `fn` is running, the client is disposed
|
|
903
|
+
* on release rather than returned to the free list.
|
|
904
|
+
* @param fn
|
|
905
|
+
*/
|
|
906
|
+
async withClient(fn) {
|
|
907
|
+
const client = await this.acquire();
|
|
908
|
+
try {
|
|
909
|
+
return await fn(client);
|
|
910
|
+
} finally {
|
|
911
|
+
this.release(client);
|
|
912
|
+
}
|
|
913
|
+
}
|
|
914
|
+
async dispose() {
|
|
915
|
+
if (this.disposed) return;
|
|
916
|
+
this.disposed = true;
|
|
917
|
+
for (const { reject } of this.waiters.splice(0)) reject(/* @__PURE__ */ new Error("runtime disposed"));
|
|
918
|
+
await Promise.all(this.free.splice(0).map((c) => c.dispose()));
|
|
919
|
+
}
|
|
920
|
+
acquire() {
|
|
921
|
+
if (this.disposed) return Promise.reject(/* @__PURE__ */ new Error("runtime is disposed"));
|
|
922
|
+
const client = this.free.pop();
|
|
923
|
+
if (client !== void 0) return Promise.resolve(client);
|
|
924
|
+
return new Promise((resolve, reject) => {
|
|
925
|
+
this.waiters.push({
|
|
926
|
+
resolve,
|
|
927
|
+
reject
|
|
928
|
+
});
|
|
929
|
+
});
|
|
930
|
+
}
|
|
931
|
+
release(client) {
|
|
932
|
+
if (this.disposed) {
|
|
933
|
+
client.dispose();
|
|
934
|
+
return;
|
|
935
|
+
}
|
|
936
|
+
const next = this.waiters.shift();
|
|
937
|
+
if (next !== void 0) next.resolve(client);
|
|
938
|
+
else this.free.push(client);
|
|
939
|
+
}
|
|
940
|
+
};
|
|
941
|
+
//#endregion
|
|
942
|
+
//#region src/globals.ts
|
|
943
|
+
function isBridgeWithShim(v) {
|
|
944
|
+
return typeof v === "object" && v !== null && v.kind === "bridge-with-shim";
|
|
945
|
+
}
|
|
946
|
+
/**
|
|
947
|
+
* Split a `HostGlobals` map into:
|
|
948
|
+
* - `bridgeGlobals`: plain functions sent to Rust as bridge stubs.
|
|
949
|
+
* - `HostExportFunction` → registered under its own name.
|
|
950
|
+
* - `BridgeWithShim` handler → registered under `__iso4_<name>_h`.
|
|
951
|
+
* - `preamble`: JS source prepended to the user's code.
|
|
952
|
+
* - `string` → `globalThis["name"] = (<expr>)`
|
|
953
|
+
* - `BridgeWithShim` → wrapper that calls the private stub and passes the
|
|
954
|
+
* result through the shim: `async (...args) => await (shim)(await __iso4_<name>_h(...args))`
|
|
955
|
+
* @param globals
|
|
956
|
+
*/
|
|
957
|
+
function processGlobals(globals) {
|
|
958
|
+
const bridgeGlobals = {};
|
|
959
|
+
const parts = [];
|
|
960
|
+
for (const [name, value] of Object.entries(globals)) if (typeof value === "function") bridgeGlobals[name] = value;
|
|
961
|
+
else if (typeof value === "string") parts.push(`globalThis[${JSON.stringify(name)}] = (${value})`);
|
|
962
|
+
else if (isBridgeWithShim(value)) {
|
|
963
|
+
const privateKey = `__iso4_${name}_h`;
|
|
964
|
+
bridgeGlobals[privateKey] = value.handler;
|
|
965
|
+
parts.push(`globalThis[${JSON.stringify(name)}] = async (...args) => await (${value.shim})(await ${privateKey}(...args))`);
|
|
966
|
+
}
|
|
967
|
+
return {
|
|
968
|
+
bridgeGlobals,
|
|
969
|
+
preamble: parts.length > 0 ? parts.join("\n") : void 0
|
|
970
|
+
};
|
|
971
|
+
}
|
|
972
|
+
/**
|
|
973
|
+
* Resolve bridge globals for a `prefix.run()` call.
|
|
974
|
+
*
|
|
975
|
+
* The preamble is already compiled into the snapshot — only the bridge
|
|
976
|
+
* function pointers need resolving. Shimmed globals are routed to their
|
|
977
|
+
* private `__iso4_<name>_h` key so rebinding updates the handler the shim
|
|
978
|
+
* calls, without touching the shim itself.
|
|
979
|
+
* @param runGlobals
|
|
980
|
+
* @param precompileGlobals
|
|
981
|
+
*/
|
|
982
|
+
function extractBridgeGlobals(runGlobals, precompileGlobals) {
|
|
983
|
+
const out = {};
|
|
984
|
+
for (const [name, value] of Object.entries(precompileGlobals)) {
|
|
985
|
+
if (typeof value === "string") continue;
|
|
986
|
+
if (isBridgeWithShim(value)) {
|
|
987
|
+
const privateKey = `__iso4_${name}_h`;
|
|
988
|
+
const override = runGlobals[name];
|
|
989
|
+
out[privateKey] = typeof override === "function" ? override : value.handler;
|
|
990
|
+
} else if (typeof value === "function") {
|
|
991
|
+
const override = runGlobals[name];
|
|
992
|
+
out[name] = typeof override === "function" ? override : value;
|
|
993
|
+
}
|
|
994
|
+
}
|
|
995
|
+
for (const [name, override] of Object.entries(runGlobals)) {
|
|
996
|
+
if (name in precompileGlobals) continue;
|
|
997
|
+
if (typeof override === "function") out[name] = override;
|
|
998
|
+
}
|
|
999
|
+
return out;
|
|
1000
|
+
}
|
|
1001
|
+
//#endregion
|
|
1002
|
+
//#region src/index.ts
|
|
1003
|
+
/**
|
|
1004
|
+
* \@iso4/sandbox - public entry point.
|
|
1005
|
+
*
|
|
1006
|
+
* Spawns the Rust V8 subprocess, manages a pool of UDS connections (one per
|
|
1007
|
+
* isolate slot), and exposes the `Sandbox` + `Prefix` API.
|
|
1008
|
+
*/
|
|
1009
|
+
async function createSandbox(options) {
|
|
1010
|
+
const binaryPath = resolveRuntimeBinary(options);
|
|
1011
|
+
const maxIsolates = options?.maxIsolates ?? cpus().length;
|
|
1012
|
+
const socketPath = join(tmpdir(), `iso4-v8-${process.pid}-${randomUUID().slice(0, 8)}.sock`);
|
|
1013
|
+
const token = randomUUID();
|
|
1014
|
+
const proc = spawn(binaryPath, [
|
|
1015
|
+
"--socket",
|
|
1016
|
+
socketPath,
|
|
1017
|
+
"--token",
|
|
1018
|
+
token
|
|
1019
|
+
], { stdio: [
|
|
1020
|
+
"ignore",
|
|
1021
|
+
"ignore",
|
|
1022
|
+
"inherit"
|
|
1023
|
+
] });
|
|
1024
|
+
proc.once("error", (err) => {
|
|
1025
|
+
process.stderr.write(`[@iso4/sandbox] failed to start V8 process: ${err.message}\n`);
|
|
1026
|
+
});
|
|
1027
|
+
await waitForSocket(socketPath);
|
|
1028
|
+
return new SandboxImpl(proc, new ConnectionPool(await Promise.all(Array.from({ length: maxIsolates }, () => RuntimeIpcClient.connect({
|
|
1029
|
+
socketPath,
|
|
1030
|
+
token
|
|
1031
|
+
})))), socketPath);
|
|
1032
|
+
}
|
|
1033
|
+
async function waitForSocket(socketPath, timeoutMs = 5e3) {
|
|
1034
|
+
const deadline = Date.now() + timeoutMs;
|
|
1035
|
+
while (Date.now() < deadline) try {
|
|
1036
|
+
await access(socketPath);
|
|
1037
|
+
return;
|
|
1038
|
+
} catch {
|
|
1039
|
+
await new Promise((resolve) => {
|
|
1040
|
+
setTimeout(resolve, 50);
|
|
1041
|
+
});
|
|
1042
|
+
}
|
|
1043
|
+
throw new Error(`[@iso4/sandbox] V8 process socket not available after ${timeoutMs}ms: ${socketPath}`);
|
|
1044
|
+
}
|
|
1045
|
+
/**
|
|
1046
|
+
* Map user-facing ResourceLimits to the wire-level encoding fields.
|
|
1047
|
+
* @param limits
|
|
1048
|
+
*/
|
|
1049
|
+
function toWireLimits(limits) {
|
|
1050
|
+
return {
|
|
1051
|
+
memoryMb: limits?.memoryMb ?? 64,
|
|
1052
|
+
cpuTimeMs: limits?.cpuTimeMs ?? 5e3,
|
|
1053
|
+
wallTimeMs: limits?.wallTimeMs ?? 3e4,
|
|
1054
|
+
maxExportBytes: limits?.maxExportBytes ?? 16 * 1024 * 1024,
|
|
1055
|
+
maxStdoutBytes: limits?.maxStdoutBytes ?? 1 * 1024 * 1024,
|
|
1056
|
+
maxStderrBytes: limits?.maxStderrBytes ?? 1 * 1024 * 1024,
|
|
1057
|
+
maxBridgeCallBytes: limits?.maxBridgeCallBytes ?? 16 * 1024 * 1024,
|
|
1058
|
+
maxBridgeCalls: limits?.maxBridgeCalls ?? 10
|
|
1059
|
+
};
|
|
1060
|
+
}
|
|
1061
|
+
var SandboxImpl = class {
|
|
1062
|
+
proc;
|
|
1063
|
+
pool;
|
|
1064
|
+
socketPath;
|
|
1065
|
+
_alive = true;
|
|
1066
|
+
constructor(proc, pool, socketPath) {
|
|
1067
|
+
this.proc = proc;
|
|
1068
|
+
this.pool = pool;
|
|
1069
|
+
this.socketPath = socketPath;
|
|
1070
|
+
proc.once("exit", () => {
|
|
1071
|
+
this._alive = false;
|
|
1072
|
+
});
|
|
1073
|
+
}
|
|
1074
|
+
get alive() {
|
|
1075
|
+
return this._alive;
|
|
1076
|
+
}
|
|
1077
|
+
async run(options) {
|
|
1078
|
+
if (options.signal?.aborted) return {
|
|
1079
|
+
ok: false,
|
|
1080
|
+
error: {
|
|
1081
|
+
code: "ERR_ABORTED",
|
|
1082
|
+
name: "AbortError",
|
|
1083
|
+
message: "run was aborted"
|
|
1084
|
+
},
|
|
1085
|
+
stdout: [],
|
|
1086
|
+
stderr: [],
|
|
1087
|
+
durationMs: 0
|
|
1088
|
+
};
|
|
1089
|
+
const { bridgeGlobals, preamble } = processGlobals(options.globals ?? {});
|
|
1090
|
+
const code = preamble ? `${preamble}\n${options.code}` : options.code;
|
|
1091
|
+
return this.pool.withClient(async (client) => {
|
|
1092
|
+
return decodeRunCompletionPayload((await client.runRawCode(code, {
|
|
1093
|
+
filename: options.filename,
|
|
1094
|
+
limits: toWireLimits(options.limits),
|
|
1095
|
+
globals: bridgeGlobals
|
|
1096
|
+
})).result).result;
|
|
1097
|
+
});
|
|
1098
|
+
}
|
|
1099
|
+
async precompile(options) {
|
|
1100
|
+
return this.pool.withClient(async (client) => {
|
|
1101
|
+
const rawGlobals = options.globals ?? {};
|
|
1102
|
+
const { bridgeGlobals, preamble } = processGlobals(rawGlobals);
|
|
1103
|
+
const code = preamble ? `${preamble}\n${options.code}` : options.code;
|
|
1104
|
+
const result = decodePrecompileResultPayload(await client.precompile({
|
|
1105
|
+
code,
|
|
1106
|
+
filename: options.filename,
|
|
1107
|
+
limits: toWireLimits(options.limits),
|
|
1108
|
+
globals: bridgeGlobals
|
|
1109
|
+
}));
|
|
1110
|
+
if (!result.ok) {
|
|
1111
|
+
const err = new Error(result.error.message);
|
|
1112
|
+
err.name = result.error.name;
|
|
1113
|
+
err.code = result.error.code;
|
|
1114
|
+
if (result.error.stack) err.stack = result.error.stack;
|
|
1115
|
+
throw err;
|
|
1116
|
+
}
|
|
1117
|
+
return new PrefixImpl(result.prefixId, this.pool, rawGlobals);
|
|
1118
|
+
});
|
|
1119
|
+
}
|
|
1120
|
+
async dispose() {
|
|
1121
|
+
if (!this._alive) return;
|
|
1122
|
+
this._alive = false;
|
|
1123
|
+
await this.pool.dispose();
|
|
1124
|
+
this.proc.kill();
|
|
1125
|
+
try {
|
|
1126
|
+
await unlink(this.socketPath);
|
|
1127
|
+
} catch {}
|
|
1128
|
+
}
|
|
1129
|
+
async [Symbol.asyncDispose]() {
|
|
1130
|
+
await this.dispose();
|
|
1131
|
+
}
|
|
1132
|
+
};
|
|
1133
|
+
var PrefixImpl = class {
|
|
1134
|
+
id;
|
|
1135
|
+
pool;
|
|
1136
|
+
/**
|
|
1137
|
+
* Handlers declared at precompile time. Used as defaults for any run that
|
|
1138
|
+
* does not supply its own override, per DESIGN.md §11.4 "Rebinding rules":
|
|
1139
|
+
* "If the prefix declared a global the run doesn't supply, the
|
|
1140
|
+
* precompile-time implementation is reused."
|
|
1141
|
+
*/
|
|
1142
|
+
defaultGlobals;
|
|
1143
|
+
_alive = true;
|
|
1144
|
+
constructor(id, pool, defaultGlobals) {
|
|
1145
|
+
this.id = id;
|
|
1146
|
+
this.pool = pool;
|
|
1147
|
+
this.defaultGlobals = defaultGlobals;
|
|
1148
|
+
}
|
|
1149
|
+
get alive() {
|
|
1150
|
+
return this._alive;
|
|
1151
|
+
}
|
|
1152
|
+
async run(options) {
|
|
1153
|
+
if (!this._alive) return {
|
|
1154
|
+
ok: false,
|
|
1155
|
+
error: {
|
|
1156
|
+
code: "ERR_PREFIX_DISPOSED",
|
|
1157
|
+
name: "Error",
|
|
1158
|
+
message: `prefix '${this.id}' has been disposed`
|
|
1159
|
+
},
|
|
1160
|
+
stdout: [],
|
|
1161
|
+
stderr: [],
|
|
1162
|
+
durationMs: 0
|
|
1163
|
+
};
|
|
1164
|
+
if (options.signal?.aborted) return {
|
|
1165
|
+
ok: false,
|
|
1166
|
+
error: {
|
|
1167
|
+
code: "ERR_ABORTED",
|
|
1168
|
+
name: "AbortError",
|
|
1169
|
+
message: "run was aborted"
|
|
1170
|
+
},
|
|
1171
|
+
stdout: [],
|
|
1172
|
+
stderr: [],
|
|
1173
|
+
durationMs: 0
|
|
1174
|
+
};
|
|
1175
|
+
const bridgeGlobals = extractBridgeGlobals(options.globals ?? {}, this.defaultGlobals);
|
|
1176
|
+
return this.pool.withClient(async (client) => {
|
|
1177
|
+
return decodeRunCompletionPayload((await client.prefixRun({
|
|
1178
|
+
prefixId: this.id,
|
|
1179
|
+
code: options.code,
|
|
1180
|
+
filename: options.filename,
|
|
1181
|
+
limits: toWireLimits(options.limits),
|
|
1182
|
+
globals: bridgeGlobals
|
|
1183
|
+
})).result).result;
|
|
1184
|
+
});
|
|
1185
|
+
}
|
|
1186
|
+
async dispose() {
|
|
1187
|
+
if (!this._alive) return;
|
|
1188
|
+
this._alive = false;
|
|
1189
|
+
await this.pool.withClient((client) => client.disposePrefix(this.id));
|
|
1190
|
+
}
|
|
1191
|
+
async [Symbol.asyncDispose]() {
|
|
1192
|
+
await this.dispose();
|
|
1193
|
+
}
|
|
1194
|
+
};
|
|
1195
|
+
//#endregion
|
|
1196
|
+
export { createSandbox };
|