@iso4/sandbox 0.0.3 → 0.1.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.mts +91 -40
- package/dist/index.mjs +533 -58
- package/package.json +5 -5
package/dist/index.d.mts
CHANGED
|
@@ -181,51 +181,86 @@ type RebindValue<V extends HostGlobalValue> = V extends BridgeWithShim<infer H>
|
|
|
181
181
|
*/
|
|
182
182
|
type RebindGlobals<G extends HostGlobals> = { [K in keyof G as G[K] extends string ? never : K]?: RebindValue<G[K]> };
|
|
183
183
|
/**
|
|
184
|
-
*
|
|
184
|
+
* Top-level `imports` shape. Keys are import specifiers; values are either
|
|
185
|
+
* a source string or a host-module description object.
|
|
186
|
+
*
|
|
187
|
+
* `M` is the literal shape of the map. `precompile()` infers it from the
|
|
188
|
+
* object literal so the declared specifiers and their value shapes flow
|
|
189
|
+
* into `Prefix<G, M>` and feed `RebindImports<M>`.
|
|
185
190
|
*/
|
|
186
|
-
|
|
187
|
-
static?: Record<string, ImportDefinition>;
|
|
188
|
-
resolve?: (specifier: string, importer: string | null) => Promise<ImportDefinition | null> | ImportDefinition | null;
|
|
189
|
-
}
|
|
190
|
-
type ImportDefinition = SourceImport | HostImport;
|
|
191
|
+
type Imports<M extends Record<string, ImportValue> = Record<string, ImportValue>> = M;
|
|
191
192
|
/**
|
|
192
|
-
*
|
|
193
|
+
* A single import value. String = source module. Object = host module
|
|
194
|
+
* description (the recursive walker handles all nesting).
|
|
193
195
|
*/
|
|
194
|
-
|
|
195
|
-
kind: "source";
|
|
196
|
-
source: string;
|
|
197
|
-
}
|
|
196
|
+
type ImportValue = string | HostModuleObject;
|
|
198
197
|
/**
|
|
199
|
-
*
|
|
198
|
+
* A host-module description object. Each property is either:
|
|
199
|
+
*
|
|
200
|
+
* - A function — becomes an async bridge stub in the generated module.
|
|
201
|
+
* - A plain data value (primitive, plain object/array, `Date`, `BigInt`,
|
|
202
|
+
* `Uint8Array`) — becomes a JS literal in the generated module.
|
|
203
|
+
* - A nested object that itself contains a mix of functions and data —
|
|
204
|
+
* walked recursively.
|
|
205
|
+
*
|
|
206
|
+
* `Map`, `Set`, circular references, class instances with prototype
|
|
207
|
+
* methods, and stateful handles (streams, sockets) are rejected at
|
|
208
|
+
* registration with a clear error.
|
|
200
209
|
*/
|
|
201
|
-
interface
|
|
202
|
-
|
|
203
|
-
exports: HostExports;
|
|
204
|
-
}
|
|
205
|
-
interface HostExports {
|
|
206
|
-
default?: HostExportValue;
|
|
207
|
-
[name: string]: HostExportValue | undefined;
|
|
210
|
+
interface HostModuleObject {
|
|
211
|
+
[name: string]: HostModuleValue;
|
|
208
212
|
}
|
|
209
|
-
type HostExportValue = HostExportData | HostExportFunction;
|
|
210
213
|
/**
|
|
211
|
-
*
|
|
212
|
-
* Kept for `HostExports` / import system typing.
|
|
214
|
+
* Any node the recursive walker may encounter inside a `HostModuleObject`.
|
|
213
215
|
*/
|
|
214
|
-
type
|
|
216
|
+
type HostModuleValue = HostExportFunction | HostExportData | HostModuleObject;
|
|
217
|
+
/**
|
|
218
|
+
* The set of plain-data values supported as data leaves in the host-module
|
|
219
|
+
* shape. The JS-literal emitter knows how to emit each of these.
|
|
220
|
+
*/
|
|
221
|
+
type HostExportData = null | undefined | boolean | number | bigint | string | Uint8Array | Date | HostExportData[] | {
|
|
215
222
|
[key: string]: HostExportData;
|
|
216
223
|
};
|
|
217
224
|
/**
|
|
218
|
-
* A host-side function exposed as a global or import
|
|
225
|
+
* A host-side function exposed as a global or import-tree leaf.
|
|
219
226
|
*
|
|
220
227
|
* Args and return are `unknown` — the bridge serialises/deserialises values
|
|
221
228
|
* with V8 ValueSerializer; we don't try to model that at the type level.
|
|
222
|
-
* The one invariant that matters (functions cannot cross the boundary
|
|
223
|
-
* enforced at runtime by the V8 layer, not here.
|
|
229
|
+
* The one invariant that matters (functions cannot cross the boundary as
|
|
230
|
+
* argument values) is enforced at runtime by the V8 layer, not here.
|
|
224
231
|
*
|
|
225
232
|
* Use specific function types for your handlers and let TypeScript infer
|
|
226
|
-
* them through `HostGlobals` and `
|
|
233
|
+
* them through `HostGlobals`, `RebindGlobals<G>`, and `RebindImports<M>`.
|
|
227
234
|
*/
|
|
228
235
|
type HostExportFunction = (...args: unknown[]) => unknown;
|
|
236
|
+
/**
|
|
237
|
+
* The rebindable subset of an `Imports<M>` declared at precompile time.
|
|
238
|
+
*
|
|
239
|
+
* Mirrors `RebindGlobals<G>` over the recursive host-module shape:
|
|
240
|
+
*
|
|
241
|
+
* - **Source imports** (string values) are compiled into the snapshot and
|
|
242
|
+
* cannot be rebound — their keys are excluded from the result.
|
|
243
|
+
* - **Host imports** (object values) are walked recursively. Only function
|
|
244
|
+
* leaves survive; data leaves are excluded because their values are
|
|
245
|
+
* emitted as JS literals into the generated module.
|
|
246
|
+
*
|
|
247
|
+
* Passing a specifier or export name that was not declared at precompile
|
|
248
|
+
* is a TypeScript error at compile time and `ERR_UNDECLARED_BINDING` at
|
|
249
|
+
* runtime.
|
|
250
|
+
*
|
|
251
|
+
* When `M` is left at its wide default (no `imports` declared, or no
|
|
252
|
+
* literal shape inferred), the rebind keyspace collapses to
|
|
253
|
+
* `Record<string, never>` — the walker only kicks in for literal shapes,
|
|
254
|
+
* which have finite depth.
|
|
255
|
+
*/
|
|
256
|
+
type RebindImports<M extends Record<string, ImportValue>> = Record<string, ImportValue> extends M ? Record<string, never> : { [K in keyof M as M[K] extends string ? never : K]?: M[K] extends HostModuleObject ? RebindHostModule<M[K]> : never };
|
|
257
|
+
/**
|
|
258
|
+
* Recursive walker over a `HostModuleObject`. Function leaves keep
|
|
259
|
+
* their declared signature; nested objects recurse; data leaves drop out
|
|
260
|
+
* entirely. Only used against literal shapes inferred by `precompile`, so
|
|
261
|
+
* the recursion is always finite.
|
|
262
|
+
*/
|
|
263
|
+
type RebindHostModule<T> = T extends HostExportFunction ? T : T extends HostModuleObject ? { [K in keyof T as T[K] extends HostExportFunction ? K : T[K] extends HostModuleObject ? K : never]?: T[K] extends HostExportFunction ? T[K] : T[K] extends HostModuleObject ? RebindHostModule<T[K]> : never } : never;
|
|
229
264
|
interface SandboxOptions {
|
|
230
265
|
/**
|
|
231
266
|
* Maximum number of isolates (UDS connection slots) running concurrently.
|
|
@@ -270,7 +305,10 @@ interface Sandbox {
|
|
|
270
305
|
* Globals declared here serve as **default** implementations for all runs.
|
|
271
306
|
* `prefix.run()` may override any subset; omitted names reuse the default.
|
|
272
307
|
*/
|
|
273
|
-
|
|
308
|
+
/**
|
|
309
|
+
* eslint-disable \@typescript-eslint/no-empty-object-type
|
|
310
|
+
*/
|
|
311
|
+
precompile: <G extends HostGlobals = {}, M extends Imports = {}>(options: PrecompileOptions<G, M>) => Promise<Prefix<G, M>>;
|
|
274
312
|
/**
|
|
275
313
|
* Tear down the Rust process. Outstanding prefixes are invalidated.
|
|
276
314
|
*/
|
|
@@ -289,7 +327,7 @@ type CreateSandbox = (options?: SandboxOptions) => Promise<Sandbox>;
|
|
|
289
327
|
* from the `globals` field, so the returned `Prefix<G>` is typed to allow
|
|
290
328
|
* only those names to be rebound in subsequent `prefix.run()` calls.
|
|
291
329
|
*/
|
|
292
|
-
interface PrecompileOptions<G extends HostGlobals> {
|
|
330
|
+
interface PrecompileOptions<G extends HostGlobals, M extends Imports> {
|
|
293
331
|
/**
|
|
294
332
|
* ESM source code to evaluate before snapshotting. Top-level await works.
|
|
295
333
|
*
|
|
@@ -313,7 +351,13 @@ interface PrecompileOptions<G extends HostGlobals> {
|
|
|
313
351
|
* any `prefix.run()` call that does not override them.
|
|
314
352
|
*/
|
|
315
353
|
globals?: G;
|
|
316
|
-
|
|
354
|
+
/**
|
|
355
|
+
* Declares the imports the sandbox code may resolve.
|
|
356
|
+
*
|
|
357
|
+
* The inferred shape feeds `Prefix<G, M>` so `prefix.run()` knows which
|
|
358
|
+
* specifiers exist and which exports may be rebound.
|
|
359
|
+
*/
|
|
360
|
+
imports?: M;
|
|
317
361
|
/**
|
|
318
362
|
* Resource limits applied to prefix code evaluation.
|
|
319
363
|
*
|
|
@@ -337,21 +381,22 @@ interface PrecompileOptions<G extends HostGlobals> {
|
|
|
337
381
|
* declared global's implementation per run, but you cannot add names that
|
|
338
382
|
* were not declared at precompile time.
|
|
339
383
|
*/
|
|
340
|
-
interface Prefix<G extends HostGlobals> {
|
|
384
|
+
interface Prefix<G extends HostGlobals, M extends Imports> {
|
|
341
385
|
readonly id: string;
|
|
342
386
|
/**
|
|
343
387
|
* Execute dynamic code against this prefix's snapshot state.
|
|
344
388
|
*
|
|
345
389
|
* Globals declared at precompile time are active. You may rebind any subset
|
|
346
390
|
* of them via `options.globals`; the precompile-time handler is used for
|
|
347
|
-
* any name not overridden here.
|
|
391
|
+
* any name not overridden here. Same rule for `imports`, restricted to
|
|
392
|
+
* host-import function exports declared in `I`.
|
|
348
393
|
*
|
|
349
394
|
* @example
|
|
350
395
|
* const result = await prefix.run({
|
|
351
396
|
* code: `export default await (${agentFn})()`,
|
|
352
397
|
* })
|
|
353
398
|
*/
|
|
354
|
-
run: (options: PrefixRunOptions<G>) => Promise<RunResult>;
|
|
399
|
+
run: (options: PrefixRunOptions<G, M>) => Promise<RunResult>;
|
|
355
400
|
/**
|
|
356
401
|
* Release the snapshot. Subsequent run() calls reject. Idempotent.
|
|
357
402
|
*/
|
|
@@ -370,7 +415,7 @@ interface Prefix<G extends HostGlobals> {
|
|
|
370
415
|
* may be overridden. Passing any other name is a TypeScript error at compile
|
|
371
416
|
* time and `ERR_UNDECLARED_BINDING` at runtime.
|
|
372
417
|
*/
|
|
373
|
-
interface PrefixRunOptions<G extends HostGlobals> {
|
|
418
|
+
interface PrefixRunOptions<G extends HostGlobals, M extends Imports> {
|
|
374
419
|
/**
|
|
375
420
|
* Dynamic ESM source code to compile and run against the prefix state.
|
|
376
421
|
*/
|
|
@@ -384,11 +429,13 @@ interface PrefixRunOptions<G extends HostGlobals> {
|
|
|
384
429
|
*/
|
|
385
430
|
globals?: RebindGlobals<G>;
|
|
386
431
|
/**
|
|
387
|
-
* Rebind host-module
|
|
388
|
-
* Source module imports are frozen in the snapshot and cannot be rebound
|
|
389
|
-
*
|
|
432
|
+
* Rebind host-module function exports declared at precompile time.
|
|
433
|
+
* Source module imports are frozen in the snapshot and cannot be rebound;
|
|
434
|
+
* data exports are baked into the synthetic module. TypeScript enforces
|
|
435
|
+
* this at the type level via `RebindImports<M>`; the runtime rejects
|
|
436
|
+
* anything that slips through with `ERR_UNDECLARED_BINDING`.
|
|
390
437
|
*/
|
|
391
|
-
imports?:
|
|
438
|
+
imports?: RebindImports<M>;
|
|
392
439
|
limits?: Partial<ResourceLimits>;
|
|
393
440
|
signal?: AbortSignal;
|
|
394
441
|
filename?: string;
|
|
@@ -397,7 +444,7 @@ interface RunOptions {
|
|
|
397
444
|
code: string;
|
|
398
445
|
limits?: Partial<ResourceLimits>;
|
|
399
446
|
globals?: HostGlobals;
|
|
400
|
-
imports?:
|
|
447
|
+
imports?: Imports;
|
|
401
448
|
signal?: AbortSignal;
|
|
402
449
|
filename?: string;
|
|
403
450
|
}
|
|
@@ -432,10 +479,14 @@ interface RunError {
|
|
|
432
479
|
name: string;
|
|
433
480
|
message: string;
|
|
434
481
|
stack?: string;
|
|
482
|
+
/**
|
|
483
|
+
* Own enumerable properties of the thrown error, excluding name/message/stack. Present only for ERR_USER_CODE when the thrown value is an object with serializable own properties.
|
|
484
|
+
*/
|
|
485
|
+
data?: unknown;
|
|
435
486
|
}
|
|
436
487
|
type RunErrorCode = "ERR_USER_CODE" | "ERR_MEMORY_LIMIT" | "ERR_CPU_TIMEOUT" | "ERR_WALL_TIMEOUT" | "ERR_ABORTED" | "ERR_MODULE_NOT_FOUND" | "ERR_COMPILE" | "ERR_FUNCTION_ARGUMENT_NOT_SUPPORTED" | "ERR_EXPORT_NOT_SERIALIZABLE" | "ERR_EXPORT_TOO_LARGE" | "ERR_EXPORT_UNRESOLVED_PROMISE" | "ERR_HOST_BRIDGE" | "ERR_BRIDGE_PAYLOAD_TOO_LARGE" | "ERR_BRIDGE_CALL_LIMIT_EXCEEDED" | "ERR_UNDECLARED_BINDING" | "ERR_PREFIX_DISPOSED" | "ERR_INTERNAL";
|
|
437
488
|
//#endregion
|
|
438
489
|
//#region src/index.d.ts
|
|
439
490
|
declare function createSandbox(options?: SandboxOptions): Promise<Sandbox>;
|
|
440
491
|
//#endregion
|
|
441
|
-
export { type BridgeWithShim, type CreateSandbox, type HostExportData, type HostExportFunction, type
|
|
492
|
+
export { type BridgeWithShim, type CreateSandbox, type HostExportData, type HostExportFunction, type HostGlobalValue, type HostGlobals, type HostModuleObject, type HostModuleValue, type ImportValue, type Imports, type PrecompileOptions, type Prefix, type PrefixRunOptions, type RebindGlobals, type RebindHostModule, type RebindImports, type RebindValue, type ResourceLimits, type RunError, type RunErrorCode, type RunFailure, type RunOptions, type RunResult, type RunSuccess, type Sandbox, type SandboxExports, type SandboxOptions, createSandbox };
|
package/dist/index.mjs
CHANGED
|
@@ -239,6 +239,7 @@ function decodeRunCompletionPayload(buf) {
|
|
|
239
239
|
const name = reader.readString();
|
|
240
240
|
const message = reader.readString();
|
|
241
241
|
const stack = reader.readU8() === 1 ? reader.readString() : void 0;
|
|
242
|
+
const data = reader.readU8() === 1 ? decodeWireValueFromReader(reader) : void 0;
|
|
242
243
|
const stdout = reader.readStringList();
|
|
243
244
|
const stderr = reader.readStringList();
|
|
244
245
|
const durationMs = reader.readF64();
|
|
@@ -251,7 +252,8 @@ function decodeRunCompletionPayload(buf) {
|
|
|
251
252
|
code,
|
|
252
253
|
name,
|
|
253
254
|
message,
|
|
254
|
-
stack
|
|
255
|
+
stack,
|
|
256
|
+
data
|
|
255
257
|
},
|
|
256
258
|
stdout,
|
|
257
259
|
stderr,
|
|
@@ -290,6 +292,7 @@ function decodePrecompileResultPayload(buf) {
|
|
|
290
292
|
const name = reader.readString();
|
|
291
293
|
const message = reader.readString();
|
|
292
294
|
const stack = reader.readU8() === 1 ? reader.readString() : void 0;
|
|
295
|
+
if (reader.readU8() === 1) decodeWireValueFromReader(reader);
|
|
293
296
|
reader.assertDone();
|
|
294
297
|
return {
|
|
295
298
|
ok: false,
|
|
@@ -571,6 +574,14 @@ var PayloadWriter = class {
|
|
|
571
574
|
}
|
|
572
575
|
return this;
|
|
573
576
|
}
|
|
577
|
+
writeImports(imports) {
|
|
578
|
+
this.writeU32(imports.length);
|
|
579
|
+
for (const imp of imports) {
|
|
580
|
+
this.writeString(imp.specifier);
|
|
581
|
+
this.writeString(imp.source);
|
|
582
|
+
}
|
|
583
|
+
return this;
|
|
584
|
+
}
|
|
574
585
|
writeResourceLimits(limits) {
|
|
575
586
|
this.writeU32(limits.memoryMb ?? 0);
|
|
576
587
|
this.writeU32(limits.cpuTimeMs ?? 0);
|
|
@@ -595,7 +606,7 @@ function encodeRunPayload(options) {
|
|
|
595
606
|
const globals = options.globals ?? [];
|
|
596
607
|
w.writeU32(globals.length);
|
|
597
608
|
for (const name of globals) w.writeString(name);
|
|
598
|
-
w.
|
|
609
|
+
w.writeImports(options.imports ?? []);
|
|
599
610
|
return w.toBuffer();
|
|
600
611
|
}
|
|
601
612
|
/**
|
|
@@ -608,7 +619,7 @@ function encodePrecompilePayload(options) {
|
|
|
608
619
|
const globals = options.globals ?? [];
|
|
609
620
|
w.writeU32(globals.length);
|
|
610
621
|
for (const name of globals) w.writeString(name);
|
|
611
|
-
w.
|
|
622
|
+
w.writeImports(options.imports ?? []);
|
|
612
623
|
return w.toBuffer();
|
|
613
624
|
}
|
|
614
625
|
/**
|
|
@@ -622,7 +633,7 @@ function encodePrefixRunPayload(options) {
|
|
|
622
633
|
const globals = options.globals ?? [];
|
|
623
634
|
w.writeU32(globals.length);
|
|
624
635
|
for (const name of globals) w.writeString(name);
|
|
625
|
-
w.
|
|
636
|
+
w.writeImports(options.imports ?? []);
|
|
626
637
|
return w.toBuffer();
|
|
627
638
|
}
|
|
628
639
|
/**
|
|
@@ -724,10 +735,29 @@ function formatByte(byte) {
|
|
|
724
735
|
}
|
|
725
736
|
//#endregion
|
|
726
737
|
//#region src/client.ts
|
|
738
|
+
/**
|
|
739
|
+
* Thrown out of a run when its `AbortSignal` fires mid-flight. The connection
|
|
740
|
+
* is torn down (so the Rust isolate is reclaimed) before this propagates, and
|
|
741
|
+
* the client is marked unusable so the pool replaces it rather than reusing a
|
|
742
|
+
* half-dead slot. `index.ts` catches this and synthesizes the `ERR_ABORTED`
|
|
743
|
+
* `RunResult`.
|
|
744
|
+
*/
|
|
745
|
+
var RunAbortedError = class extends Error {
|
|
746
|
+
constructor(message = "run was aborted") {
|
|
747
|
+
super(message);
|
|
748
|
+
this.name = "RunAbortedError";
|
|
749
|
+
}
|
|
750
|
+
};
|
|
727
751
|
var RuntimeIpcClient = class RuntimeIpcClient {
|
|
728
752
|
socket;
|
|
729
753
|
reader;
|
|
730
754
|
disposed = false;
|
|
755
|
+
/**
|
|
756
|
+
* Set when an in-flight abort tore this connection down. A broken client
|
|
757
|
+
* must not be returned to the pool's free list — `ConnectionPool.release`
|
|
758
|
+
* checks `usable` and replaces it with a fresh connection instead.
|
|
759
|
+
*/
|
|
760
|
+
broken = false;
|
|
731
761
|
constructor(socket) {
|
|
732
762
|
this.socket = socket;
|
|
733
763
|
this.reader = new FrameReader();
|
|
@@ -744,6 +774,14 @@ var RuntimeIpcClient = class RuntimeIpcClient {
|
|
|
744
774
|
this.reader.close(/* @__PURE__ */ new Error("socket closed"));
|
|
745
775
|
});
|
|
746
776
|
}
|
|
777
|
+
/**
|
|
778
|
+
* A client is usable while its connection is intact. Once an in-flight abort
|
|
779
|
+
* (or a dispose) tears the socket down it becomes unusable and the pool must
|
|
780
|
+
* replace it.
|
|
781
|
+
*/
|
|
782
|
+
get usable() {
|
|
783
|
+
return !this.disposed && !this.broken;
|
|
784
|
+
}
|
|
747
785
|
static async connect(options) {
|
|
748
786
|
const client = new RuntimeIpcClient(await connectSocket(options.socketPath));
|
|
749
787
|
await client.write(encodeTsToRustFrame(TsToRustMessageTypes.Authenticate, encodeAuthenticatePayload({
|
|
@@ -766,9 +804,10 @@ var RuntimeIpcClient = class RuntimeIpcClient {
|
|
|
766
804
|
code,
|
|
767
805
|
filename: options?.filename,
|
|
768
806
|
limits: options?.limits,
|
|
769
|
-
globals: globalNames
|
|
807
|
+
globals: globalNames,
|
|
808
|
+
imports: options?.imports
|
|
770
809
|
})));
|
|
771
|
-
return this.drainUntilResult(makeDispatcher(globals));
|
|
810
|
+
return this.drainUntilResult(makeDispatcher(globals), options?.signal);
|
|
772
811
|
}
|
|
773
812
|
async precompile(options) {
|
|
774
813
|
if (this.disposed) throw new Error("runtime IPC client is disposed");
|
|
@@ -776,7 +815,8 @@ var RuntimeIpcClient = class RuntimeIpcClient {
|
|
|
776
815
|
code: options.code,
|
|
777
816
|
filename: options.filename,
|
|
778
817
|
limits: options.limits,
|
|
779
|
-
globals: Object.keys(options.globals ?? {})
|
|
818
|
+
globals: Object.keys(options.globals ?? {}),
|
|
819
|
+
imports: options.imports
|
|
780
820
|
})));
|
|
781
821
|
for await (const frame of this.reader) {
|
|
782
822
|
if (frame.messageType === RustToTsMessageTypes.PrecompileResult) return frame.payload;
|
|
@@ -794,9 +834,10 @@ var RuntimeIpcClient = class RuntimeIpcClient {
|
|
|
794
834
|
filename: options.filename,
|
|
795
835
|
limits: options.limits,
|
|
796
836
|
globals: globalNames,
|
|
837
|
+
imports: options.imports,
|
|
797
838
|
runId: this.nextRunIdValue()
|
|
798
839
|
})));
|
|
799
|
-
return this.drainUntilResult(makeDispatcher(globals));
|
|
840
|
+
return this.drainUntilResult(makeDispatcher(globals), options.signal);
|
|
800
841
|
}
|
|
801
842
|
async disposePrefix(prefixId) {
|
|
802
843
|
if (this.disposed) return;
|
|
@@ -828,9 +869,50 @@ var RuntimeIpcClient = class RuntimeIpcClient {
|
|
|
828
869
|
* garbage-collected when it eventually settles. Any in-flight I/O or timers
|
|
829
870
|
* continue to completion. Rust silently ignores any late `BridgeResponse`
|
|
830
871
|
* that arrives after the run has completed (see session.rs).
|
|
872
|
+
*
|
|
873
|
+
* ── In-flight abort ──────────────────────────────────────────────────────
|
|
874
|
+
* When `signal` fires mid-run — including while a bridge call is in flight —
|
|
875
|
+
* we tear the connection down immediately (`abortConnection`): the reader is
|
|
876
|
+
* closed so this loop throws, and the socket is destroyed so the Rust side
|
|
877
|
+
* observes EOF and reclaims the isolate promptly (rather than waiting for
|
|
878
|
+
* `wallTimeMs`). The loop then throws `RunAbortedError`, which `index.ts`
|
|
879
|
+
* maps to an `ERR_ABORTED` `RunResult`. Any late `BridgeResponse` written by
|
|
880
|
+
* an orphaned handler after this point fails silently (the socket is gone),
|
|
881
|
+
* so the sandbox never observes a return value for the in-flight call.
|
|
831
882
|
* @param dispatcher
|
|
883
|
+
* @param signal
|
|
832
884
|
*/
|
|
833
|
-
async drainUntilResult(dispatcher) {
|
|
885
|
+
async drainUntilResult(dispatcher, signal) {
|
|
886
|
+
if (signal?.aborted) {
|
|
887
|
+
this.abortConnection();
|
|
888
|
+
throw new RunAbortedError();
|
|
889
|
+
}
|
|
890
|
+
const onAbort = () => {
|
|
891
|
+
this.abortConnection();
|
|
892
|
+
};
|
|
893
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
894
|
+
try {
|
|
895
|
+
return await this.drainFrames(dispatcher);
|
|
896
|
+
} catch (error) {
|
|
897
|
+
if (signal?.aborted) throw new RunAbortedError();
|
|
898
|
+
throw error;
|
|
899
|
+
} finally {
|
|
900
|
+
signal?.removeEventListener("abort", onAbort);
|
|
901
|
+
}
|
|
902
|
+
}
|
|
903
|
+
/**
|
|
904
|
+
* Tear down the connection in response to an in-flight abort. Idempotent.
|
|
905
|
+
* Marks the client `broken` (so the pool replaces it), closes the frame
|
|
906
|
+
* reader (so `drainFrames` stops awaiting), and destroys the socket (so the
|
|
907
|
+
* Rust session sees EOF and drops the isolate).
|
|
908
|
+
*/
|
|
909
|
+
abortConnection() {
|
|
910
|
+
if (this.broken) return;
|
|
911
|
+
this.broken = true;
|
|
912
|
+
this.reader.close(new RunAbortedError());
|
|
913
|
+
this.socket.destroy();
|
|
914
|
+
}
|
|
915
|
+
async drainFrames(dispatcher) {
|
|
834
916
|
for await (const frame of this.reader) switch (frame.messageType) {
|
|
835
917
|
case RustToTsMessageTypes.Result: return { result: frame.payload };
|
|
836
918
|
case RustToTsMessageTypes.Log: break;
|
|
@@ -839,7 +921,10 @@ var RuntimeIpcClient = class RuntimeIpcClient {
|
|
|
839
921
|
if (dispatcher === void 0) await this.write(encodeTsToRustFrame(TsToRustMessageTypes.BridgeResponse, encodeBridgeResponsePayload(call.callId, false, void 0, "no bridge dispatcher configured")));
|
|
840
922
|
else {
|
|
841
923
|
const { callId } = call;
|
|
842
|
-
dispatcher(
|
|
924
|
+
dispatcher({
|
|
925
|
+
exportName: call.exportName,
|
|
926
|
+
args: call.args
|
|
927
|
+
}).then((value) => {
|
|
843
928
|
let encoded;
|
|
844
929
|
try {
|
|
845
930
|
encoded = encodeWireValue(value);
|
|
@@ -867,14 +952,20 @@ var RuntimeIpcClient = class RuntimeIpcClient {
|
|
|
867
952
|
}
|
|
868
953
|
};
|
|
869
954
|
/**
|
|
870
|
-
* Build a dispatcher
|
|
955
|
+
* Build a dispatcher that looks up a handler by `exportName` in the
|
|
956
|
+
* per-run globals map. Host-module imports are bridged through the same
|
|
957
|
+
* map via the reserved `__iso4_call` global, so a single lookup table
|
|
958
|
+
* handles every bridge call.
|
|
959
|
+
*
|
|
960
|
+
* Returns `undefined` when the map is empty so the loop short-circuits to
|
|
961
|
+
* an "unconfigured bridge" error response.
|
|
871
962
|
* @param globals
|
|
872
963
|
*/
|
|
873
964
|
function makeDispatcher(globals) {
|
|
874
965
|
if (Object.keys(globals).length === 0) return void 0;
|
|
875
|
-
return async (
|
|
876
|
-
const handler = globals[
|
|
877
|
-
if (handler === void 0) throw new Error(`no handler configured for global '${
|
|
966
|
+
return async ({ exportName, args }) => {
|
|
967
|
+
const handler = globals[exportName];
|
|
968
|
+
if (handler === void 0) throw new Error(`no handler configured for bridge global '${exportName}'`);
|
|
878
969
|
return handler(...args);
|
|
879
970
|
};
|
|
880
971
|
}
|
|
@@ -893,9 +984,11 @@ function connectSocket(socketPath) {
|
|
|
893
984
|
var ConnectionPool = class {
|
|
894
985
|
free;
|
|
895
986
|
waiters = [];
|
|
987
|
+
connect;
|
|
896
988
|
disposed = false;
|
|
897
|
-
constructor(clients) {
|
|
989
|
+
constructor(clients, connect) {
|
|
898
990
|
this.free = [...clients];
|
|
991
|
+
this.connect = connect;
|
|
899
992
|
}
|
|
900
993
|
/**
|
|
901
994
|
* Borrow a client, run `fn`, then unconditionally return the client.
|
|
@@ -933,10 +1026,36 @@ var ConnectionPool = class {
|
|
|
933
1026
|
client.dispose();
|
|
934
1027
|
return;
|
|
935
1028
|
}
|
|
1029
|
+
if (!client.usable) {
|
|
1030
|
+
this.replace(client).catch(() => {});
|
|
1031
|
+
return;
|
|
1032
|
+
}
|
|
936
1033
|
const next = this.waiters.shift();
|
|
937
1034
|
if (next !== void 0) next.resolve(client);
|
|
938
1035
|
else this.free.push(client);
|
|
939
1036
|
}
|
|
1037
|
+
/**
|
|
1038
|
+
* Dispose a dead slot and connect a fresh one in its place. If reconnection
|
|
1039
|
+
* fails (or no factory was supplied) the pool simply runs with one fewer
|
|
1040
|
+
* slot rather than handing back a broken connection; any waiter still gets
|
|
1041
|
+
* served by other slots as they free up.
|
|
1042
|
+
* @param dead
|
|
1043
|
+
*/
|
|
1044
|
+
async replace(dead) {
|
|
1045
|
+
await dead.dispose().catch(() => {});
|
|
1046
|
+
if (this.connect === void 0) return;
|
|
1047
|
+
let fresh;
|
|
1048
|
+
try {
|
|
1049
|
+
fresh = await this.connect();
|
|
1050
|
+
} catch {
|
|
1051
|
+
return;
|
|
1052
|
+
}
|
|
1053
|
+
if (this.disposed) {
|
|
1054
|
+
await fresh.dispose().catch(() => {});
|
|
1055
|
+
return;
|
|
1056
|
+
}
|
|
1057
|
+
this.release(fresh);
|
|
1058
|
+
}
|
|
940
1059
|
};
|
|
941
1060
|
//#endregion
|
|
942
1061
|
//#region src/globals.ts
|
|
@@ -999,6 +1118,298 @@ function extractBridgeGlobals(runGlobals, precompileGlobals) {
|
|
|
999
1118
|
return out;
|
|
1000
1119
|
}
|
|
1001
1120
|
//#endregion
|
|
1121
|
+
//#region src/imports.ts
|
|
1122
|
+
/**
|
|
1123
|
+
* The reserved global name of the bridge dispatcher. User globals may not
|
|
1124
|
+
* use this name. The generated host-module source calls it as
|
|
1125
|
+
* `globalThis.__iso4_call(id, ...args)`.
|
|
1126
|
+
*/
|
|
1127
|
+
const BRIDGE_DISPATCH_GLOBAL = "__iso4_call";
|
|
1128
|
+
/**
|
|
1129
|
+
* Thrown when the host's import configuration is structurally invalid
|
|
1130
|
+
* (mixed types, unsupported data values, undeclared rebindings, …).
|
|
1131
|
+
* `PrefixImpl.run` converts the undeclared-binding variant into an
|
|
1132
|
+
* `ERR_UNDECLARED_BINDING` `RunResult`, matching the globals path.
|
|
1133
|
+
*/
|
|
1134
|
+
var UndeclaredImportBindingError = class extends Error {
|
|
1135
|
+
code = "ERR_UNDECLARED_BINDING";
|
|
1136
|
+
constructor(message) {
|
|
1137
|
+
super(message);
|
|
1138
|
+
this.name = "UndeclaredImportBindingError";
|
|
1139
|
+
}
|
|
1140
|
+
};
|
|
1141
|
+
/**
|
|
1142
|
+
* Build the `__iso4_call` global handler that backs all host-module
|
|
1143
|
+
* function leaves for a run. It peels the leading handle ID and routes to
|
|
1144
|
+
* the registry.
|
|
1145
|
+
* @param registry
|
|
1146
|
+
*/
|
|
1147
|
+
function createDispatchGlobal(registry) {
|
|
1148
|
+
return (...args) => {
|
|
1149
|
+
const id = args[0];
|
|
1150
|
+
const fn = registry.get(id);
|
|
1151
|
+
if (fn === void 0) throw new Error(`[@iso4/sandbox] no host handler for import handle ${String(id)}`);
|
|
1152
|
+
return fn(...args.slice(1));
|
|
1153
|
+
};
|
|
1154
|
+
}
|
|
1155
|
+
function processImports(imports) {
|
|
1156
|
+
const shape = {
|
|
1157
|
+
sourceSpecifiers: /* @__PURE__ */ new Set(),
|
|
1158
|
+
hostFunctionIds: {},
|
|
1159
|
+
hostDataPaths: {}
|
|
1160
|
+
};
|
|
1161
|
+
if (imports === void 0) return {
|
|
1162
|
+
bindings: [],
|
|
1163
|
+
registry: /* @__PURE__ */ new Map(),
|
|
1164
|
+
shape
|
|
1165
|
+
};
|
|
1166
|
+
const bindings = [];
|
|
1167
|
+
const registry = /* @__PURE__ */ new Map();
|
|
1168
|
+
let nextId = 0;
|
|
1169
|
+
const allocId = () => nextId++;
|
|
1170
|
+
for (const [specifier, value] of Object.entries(imports)) {
|
|
1171
|
+
if (typeof value === "string") {
|
|
1172
|
+
bindings.push({
|
|
1173
|
+
specifier,
|
|
1174
|
+
source: value
|
|
1175
|
+
});
|
|
1176
|
+
shape.sourceSpecifiers.add(specifier);
|
|
1177
|
+
continue;
|
|
1178
|
+
}
|
|
1179
|
+
if (!isPlainObject(value)) throw new Error(`[@iso4/sandbox] imports['${specifier}'] must be a string (source module) or a plain object (host module); got ${describeKind(value)}`);
|
|
1180
|
+
const fnIds = {};
|
|
1181
|
+
const dataPaths = /* @__PURE__ */ new Set();
|
|
1182
|
+
const source = generateHostModuleSource(specifier, value, registry, allocId, fnIds, dataPaths);
|
|
1183
|
+
bindings.push({
|
|
1184
|
+
specifier,
|
|
1185
|
+
source
|
|
1186
|
+
});
|
|
1187
|
+
shape.hostFunctionIds[specifier] = fnIds;
|
|
1188
|
+
shape.hostDataPaths[specifier] = dataPaths;
|
|
1189
|
+
}
|
|
1190
|
+
return {
|
|
1191
|
+
bindings,
|
|
1192
|
+
registry,
|
|
1193
|
+
shape
|
|
1194
|
+
};
|
|
1195
|
+
}
|
|
1196
|
+
/**
|
|
1197
|
+
* Override the handlers behind a `Prefix`'s declared host-module function
|
|
1198
|
+
* leaves. Only declared paths may be rebound; everything else throws
|
|
1199
|
+
* `UndeclaredImportBindingError`. Source modules are frozen.
|
|
1200
|
+
*
|
|
1201
|
+
* Returns a fresh registry keyed by the same handle IDs the prefix assigned
|
|
1202
|
+
* at precompile time, with the new handler installed where provided.
|
|
1203
|
+
*
|
|
1204
|
+
* @param runImports
|
|
1205
|
+
* @param defaults
|
|
1206
|
+
* @param shape
|
|
1207
|
+
*/
|
|
1208
|
+
function extractRebindImports(runImports, defaults, shape) {
|
|
1209
|
+
if (runImports === void 0) return defaults;
|
|
1210
|
+
const merged = new Map(defaults);
|
|
1211
|
+
for (const [specifier, value] of Object.entries(runImports)) {
|
|
1212
|
+
if (typeof value === "string" || shape.sourceSpecifiers.has(specifier)) throw new UndeclaredImportBindingError(`import '${specifier}' is a source module — source imports are frozen in the snapshot and cannot be rebound at prefix.run() time`);
|
|
1213
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error(`[@iso4/sandbox] imports['${specifier}'] override must be a plain object; got ${describeKind(value)}`);
|
|
1214
|
+
if (shape.hostFunctionIds[specifier] === void 0) throw new UndeclaredImportBindingError(`import '${specifier}' was not declared at precompile time`);
|
|
1215
|
+
walkRebind(specifier, value, [], shape, merged);
|
|
1216
|
+
}
|
|
1217
|
+
return merged;
|
|
1218
|
+
}
|
|
1219
|
+
function walkRebind(specifier, node, path, shape, merged) {
|
|
1220
|
+
const fnIds = shape.hostFunctionIds[specifier];
|
|
1221
|
+
const dataPaths = shape.hostDataPaths[specifier];
|
|
1222
|
+
for (const [key, value] of Object.entries(node)) {
|
|
1223
|
+
if (value === void 0) continue;
|
|
1224
|
+
const newPath = [...path, key];
|
|
1225
|
+
const joined = newPath.join(".");
|
|
1226
|
+
if (typeof value === "function") {
|
|
1227
|
+
if (dataPaths.has(joined)) throw new UndeclaredImportBindingError(`import '${specifier}'.${joined} is a data leaf, not a function — data leaves cannot be rebound`);
|
|
1228
|
+
const id = fnIds[joined];
|
|
1229
|
+
if (id === void 0) throw new UndeclaredImportBindingError(`import '${specifier}'.${joined} was not declared at precompile time`);
|
|
1230
|
+
merged.set(id, value);
|
|
1231
|
+
continue;
|
|
1232
|
+
}
|
|
1233
|
+
if (isPlainObject(value)) {
|
|
1234
|
+
walkRebind(specifier, value, newPath, shape, merged);
|
|
1235
|
+
continue;
|
|
1236
|
+
}
|
|
1237
|
+
if (fnIds[joined] !== void 0 || dataPaths.has(joined)) throw new UndeclaredImportBindingError(`import '${specifier}'.${joined} can only be rebound with a function; got ${describeKind(value)}`);
|
|
1238
|
+
throw new UndeclaredImportBindingError(`import '${specifier}'.${joined} was not declared at precompile time`);
|
|
1239
|
+
}
|
|
1240
|
+
}
|
|
1241
|
+
/**
|
|
1242
|
+
* Generate the ESM source for a host module specifier. Walks `desc`
|
|
1243
|
+
* recursively and emits one `export const <name> = <expr>;` per top-level
|
|
1244
|
+
* entry. Function leaves become `__iso4_call(<id>, ...args)` stubs; data
|
|
1245
|
+
* leaves become JS literals.
|
|
1246
|
+
*
|
|
1247
|
+
* @param specifier
|
|
1248
|
+
* @param desc
|
|
1249
|
+
* @param registry
|
|
1250
|
+
* @param allocId
|
|
1251
|
+
* @param fnIds
|
|
1252
|
+
* @param dataPaths
|
|
1253
|
+
*/
|
|
1254
|
+
function generateHostModuleSource(specifier, desc, registry, allocId, fnIds, dataPaths) {
|
|
1255
|
+
const parts = [];
|
|
1256
|
+
for (const [key, value] of Object.entries(desc)) {
|
|
1257
|
+
if (value === void 0) continue;
|
|
1258
|
+
if (!isValidExportIdentifier(key)) throw new Error(`[@iso4/sandbox] imports['${specifier}'] top-level key '${key}' is not a valid JavaScript identifier and cannot be exported as a named ESM export`);
|
|
1259
|
+
const expr = emitValue(specifier, value, [key], registry, allocId, fnIds, dataPaths);
|
|
1260
|
+
if (key === "default") parts.push(`export default ${expr};`);
|
|
1261
|
+
else parts.push(`export const ${key} = ${expr};`);
|
|
1262
|
+
}
|
|
1263
|
+
return parts.join("\n");
|
|
1264
|
+
}
|
|
1265
|
+
function emitValue(specifier, value, path, registry, allocId, fnIds, dataPaths, seen = /* @__PURE__ */ new Set()) {
|
|
1266
|
+
if (typeof value === "function") {
|
|
1267
|
+
const id = allocId();
|
|
1268
|
+
registry.set(id, value);
|
|
1269
|
+
fnIds[path.join(".")] = id;
|
|
1270
|
+
return `(async (...args) => await globalThis.${BRIDGE_DISPATCH_GLOBAL}(${id}, ...args))`;
|
|
1271
|
+
}
|
|
1272
|
+
if (isPlainObject(value)) {
|
|
1273
|
+
if (seen.has(value)) throw new Error(`[@iso4/sandbox] imports['${specifier}'].${path.join(".")}: circular references are not supported in host-module shapes`);
|
|
1274
|
+
seen.add(value);
|
|
1275
|
+
const fields = [];
|
|
1276
|
+
for (const [key, child] of Object.entries(value)) {
|
|
1277
|
+
if (child === void 0) continue;
|
|
1278
|
+
const childExpr = emitValue(specifier, child, [...path, key], registry, allocId, fnIds, dataPaths, seen);
|
|
1279
|
+
fields.push(`${jsObjectKey(key)}: ${childExpr}`);
|
|
1280
|
+
}
|
|
1281
|
+
seen.delete(value);
|
|
1282
|
+
return `({ ${fields.join(", ")} })`;
|
|
1283
|
+
}
|
|
1284
|
+
dataPaths.add(path.join("."));
|
|
1285
|
+
return emitDataLiteral(specifier, value, path);
|
|
1286
|
+
}
|
|
1287
|
+
/**
|
|
1288
|
+
* Emit a `HostExportData` value as a JS expression that reproduces the
|
|
1289
|
+
* original value in the sandbox. Supports primitives, plain objects/arrays,
|
|
1290
|
+
* `Date`, `BigInt`, `Uint8Array`. `Map`, `Set`, circular refs, and class
|
|
1291
|
+
* instances throw with a clear pointer.
|
|
1292
|
+
*
|
|
1293
|
+
* @param specifier
|
|
1294
|
+
* @param value
|
|
1295
|
+
* @param path
|
|
1296
|
+
* @param seen
|
|
1297
|
+
*/
|
|
1298
|
+
function emitDataLiteral(specifier, value, path, seen = /* @__PURE__ */ new Set()) {
|
|
1299
|
+
if (value === null) return "null";
|
|
1300
|
+
if (value === void 0) return "undefined";
|
|
1301
|
+
switch (typeof value) {
|
|
1302
|
+
case "boolean": return value ? "true" : "false";
|
|
1303
|
+
case "number":
|
|
1304
|
+
if (Number.isNaN(value)) return "NaN";
|
|
1305
|
+
if (!Number.isFinite(value)) return value > 0 ? "Infinity" : "-Infinity";
|
|
1306
|
+
return String(value);
|
|
1307
|
+
case "bigint": return `${value.toString()}n`;
|
|
1308
|
+
case "string": return JSON.stringify(value);
|
|
1309
|
+
}
|
|
1310
|
+
if (value instanceof Uint8Array) return `new Uint8Array([${Array.from(value).join(", ")}])`;
|
|
1311
|
+
if (value instanceof Date) return `new Date(${value.getTime()})`;
|
|
1312
|
+
if (value instanceof Map || value instanceof Set) throw new Error(`[@iso4/sandbox] imports['${specifier}'].${path.join(".")}: Map / Set values are not yet supported as data leaves`);
|
|
1313
|
+
if (typeof value === "object") {
|
|
1314
|
+
if (seen.has(value)) throw new Error(`[@iso4/sandbox] imports['${specifier}'].${path.join(".")}: circular references in data leaves are not supported`);
|
|
1315
|
+
seen.add(value);
|
|
1316
|
+
if (Array.isArray(value)) {
|
|
1317
|
+
const parts = value.map((item, i) => emitDataLiteral(specifier, item, [...path, String(i)], seen));
|
|
1318
|
+
seen.delete(value);
|
|
1319
|
+
return `[${parts.join(", ")}]`;
|
|
1320
|
+
}
|
|
1321
|
+
const proto = Object.getPrototypeOf(value);
|
|
1322
|
+
if (proto !== null && proto !== Object.prototype) throw new Error(`[@iso4/sandbox] imports['${specifier}'].${path.join(".")}: class instances are not supported as data leaves; copy the data into a plain object explicitly`);
|
|
1323
|
+
const fields = [];
|
|
1324
|
+
for (const [key, child] of Object.entries(value)) fields.push(`${jsObjectKey(key)}: ${emitDataLiteral(specifier, child, [...path, key], seen)}`);
|
|
1325
|
+
seen.delete(value);
|
|
1326
|
+
return `({ ${fields.join(", ")} })`;
|
|
1327
|
+
}
|
|
1328
|
+
throw new Error(`[@iso4/sandbox] imports['${specifier}'].${path.join(".")}: unsupported data value of type ${describeKind(value)}`);
|
|
1329
|
+
}
|
|
1330
|
+
function isPlainObject(value) {
|
|
1331
|
+
if (value === null || typeof value !== "object") return false;
|
|
1332
|
+
if (Array.isArray(value)) return false;
|
|
1333
|
+
if (value instanceof Uint8Array || value instanceof Date) return false;
|
|
1334
|
+
if (value instanceof Map || value instanceof Set) return false;
|
|
1335
|
+
const proto = Object.getPrototypeOf(value);
|
|
1336
|
+
return proto === null || proto === Object.prototype;
|
|
1337
|
+
}
|
|
1338
|
+
const RESERVED_WORDS = new Set([
|
|
1339
|
+
"break",
|
|
1340
|
+
"case",
|
|
1341
|
+
"catch",
|
|
1342
|
+
"class",
|
|
1343
|
+
"const",
|
|
1344
|
+
"continue",
|
|
1345
|
+
"debugger",
|
|
1346
|
+
"default",
|
|
1347
|
+
"delete",
|
|
1348
|
+
"do",
|
|
1349
|
+
"else",
|
|
1350
|
+
"export",
|
|
1351
|
+
"extends",
|
|
1352
|
+
"finally",
|
|
1353
|
+
"for",
|
|
1354
|
+
"function",
|
|
1355
|
+
"if",
|
|
1356
|
+
"import",
|
|
1357
|
+
"in",
|
|
1358
|
+
"instanceof",
|
|
1359
|
+
"new",
|
|
1360
|
+
"return",
|
|
1361
|
+
"super",
|
|
1362
|
+
"switch",
|
|
1363
|
+
"this",
|
|
1364
|
+
"throw",
|
|
1365
|
+
"try",
|
|
1366
|
+
"typeof",
|
|
1367
|
+
"var",
|
|
1368
|
+
"void",
|
|
1369
|
+
"while",
|
|
1370
|
+
"with",
|
|
1371
|
+
"yield",
|
|
1372
|
+
"let",
|
|
1373
|
+
"static",
|
|
1374
|
+
"enum",
|
|
1375
|
+
"await",
|
|
1376
|
+
"implements",
|
|
1377
|
+
"package",
|
|
1378
|
+
"protected",
|
|
1379
|
+
"interface",
|
|
1380
|
+
"private",
|
|
1381
|
+
"public",
|
|
1382
|
+
"null",
|
|
1383
|
+
"true",
|
|
1384
|
+
"false"
|
|
1385
|
+
]);
|
|
1386
|
+
/**
|
|
1387
|
+
* Whether `name` can appear as a named ESM export. JS identifier rules plus
|
|
1388
|
+
* a reserved-word filter. `default` is handled separately by the emitter.
|
|
1389
|
+
* @param name
|
|
1390
|
+
*/
|
|
1391
|
+
function isValidExportIdentifier(name) {
|
|
1392
|
+
if (name === "default") return true;
|
|
1393
|
+
if (!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name)) return false;
|
|
1394
|
+
if (RESERVED_WORDS.has(name)) return false;
|
|
1395
|
+
return true;
|
|
1396
|
+
}
|
|
1397
|
+
/**
|
|
1398
|
+
* Emit `key` as a JS object property key: a bare identifier when possible,
|
|
1399
|
+
* otherwise a quoted string. Object keys (unlike export names) may be any
|
|
1400
|
+
* string, so this never rejects.
|
|
1401
|
+
* @param key
|
|
1402
|
+
*/
|
|
1403
|
+
function jsObjectKey(key) {
|
|
1404
|
+
if (/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key) && !RESERVED_WORDS.has(key)) return key;
|
|
1405
|
+
return JSON.stringify(key);
|
|
1406
|
+
}
|
|
1407
|
+
function describeKind(value) {
|
|
1408
|
+
if (value === null) return "null";
|
|
1409
|
+
if (Array.isArray(value)) return "array";
|
|
1410
|
+
return typeof value;
|
|
1411
|
+
}
|
|
1412
|
+
//#endregion
|
|
1002
1413
|
//#region src/index.ts
|
|
1003
1414
|
/**
|
|
1004
1415
|
* \@iso4/sandbox - public entry point.
|
|
@@ -1025,10 +1436,11 @@ async function createSandbox(options) {
|
|
|
1025
1436
|
process.stderr.write(`[@iso4/sandbox] failed to start V8 process: ${err.message}\n`);
|
|
1026
1437
|
});
|
|
1027
1438
|
await waitForSocket(socketPath);
|
|
1028
|
-
|
|
1439
|
+
const connect = () => RuntimeIpcClient.connect({
|
|
1029
1440
|
socketPath,
|
|
1030
1441
|
token
|
|
1031
|
-
})
|
|
1442
|
+
});
|
|
1443
|
+
return new SandboxImpl(proc, new ConnectionPool(await Promise.all(Array.from({ length: maxIsolates }, () => connect())), connect), socketPath);
|
|
1032
1444
|
}
|
|
1033
1445
|
async function waitForSocket(socketPath, timeoutMs = 5e3) {
|
|
1034
1446
|
const deadline = Date.now() + timeoutMs;
|
|
@@ -1058,6 +1470,25 @@ function toWireLimits(limits) {
|
|
|
1058
1470
|
maxBridgeCalls: limits?.maxBridgeCalls ?? 10
|
|
1059
1471
|
};
|
|
1060
1472
|
}
|
|
1473
|
+
/**
|
|
1474
|
+
* The `RunResult` returned when a run is aborted — whether the signal was
|
|
1475
|
+
* already aborted at run entry or fired mid-flight (surfaced as a
|
|
1476
|
+
* `RunAbortedError` from the client). Shared so both paths produce an
|
|
1477
|
+
* identical shape.
|
|
1478
|
+
*/
|
|
1479
|
+
function abortedResult() {
|
|
1480
|
+
return {
|
|
1481
|
+
ok: false,
|
|
1482
|
+
error: {
|
|
1483
|
+
code: "ERR_ABORTED",
|
|
1484
|
+
name: "AbortError",
|
|
1485
|
+
message: "run was aborted"
|
|
1486
|
+
},
|
|
1487
|
+
stdout: [],
|
|
1488
|
+
stderr: [],
|
|
1489
|
+
durationMs: 0
|
|
1490
|
+
};
|
|
1491
|
+
}
|
|
1061
1492
|
var SandboxImpl = class {
|
|
1062
1493
|
proc;
|
|
1063
1494
|
pool;
|
|
@@ -1075,37 +1506,48 @@ var SandboxImpl = class {
|
|
|
1075
1506
|
return this._alive;
|
|
1076
1507
|
}
|
|
1077
1508
|
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
|
-
};
|
|
1509
|
+
if (options.signal?.aborted) return abortedResult();
|
|
1089
1510
|
const { bridgeGlobals, preamble } = processGlobals(options.globals ?? {});
|
|
1511
|
+
const { bindings, registry, shape: _shape } = processImports(options.imports);
|
|
1512
|
+
const allGlobals = registry.size > 0 ? {
|
|
1513
|
+
...bridgeGlobals,
|
|
1514
|
+
[BRIDGE_DISPATCH_GLOBAL]: createDispatchGlobal(registry)
|
|
1515
|
+
} : bridgeGlobals;
|
|
1090
1516
|
const code = preamble ? `${preamble}\n${options.code}` : options.code;
|
|
1091
|
-
|
|
1092
|
-
return
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1517
|
+
try {
|
|
1518
|
+
return await this.pool.withClient(async (client) => {
|
|
1519
|
+
return decodeRunCompletionPayload((await client.runRawCode(code, {
|
|
1520
|
+
filename: options.filename,
|
|
1521
|
+
limits: toWireLimits(options.limits),
|
|
1522
|
+
globals: allGlobals,
|
|
1523
|
+
imports: bindings,
|
|
1524
|
+
signal: options.signal
|
|
1525
|
+
})).result).result;
|
|
1526
|
+
});
|
|
1527
|
+
} catch (error) {
|
|
1528
|
+
if (error instanceof RunAbortedError) return abortedResult();
|
|
1529
|
+
throw error;
|
|
1530
|
+
}
|
|
1098
1531
|
}
|
|
1532
|
+
/**
|
|
1533
|
+
* @param options
|
|
1534
|
+
*/
|
|
1099
1535
|
async precompile(options) {
|
|
1100
1536
|
return this.pool.withClient(async (client) => {
|
|
1101
1537
|
const rawGlobals = options.globals ?? {};
|
|
1102
1538
|
const { bridgeGlobals, preamble } = processGlobals(rawGlobals);
|
|
1539
|
+
const { bindings, registry, shape } = processImports(options.imports);
|
|
1540
|
+
const allGlobals = registry.size > 0 ? {
|
|
1541
|
+
...bridgeGlobals,
|
|
1542
|
+
[BRIDGE_DISPATCH_GLOBAL]: createDispatchGlobal(registry)
|
|
1543
|
+
} : bridgeGlobals;
|
|
1103
1544
|
const code = preamble ? `${preamble}\n${options.code}` : options.code;
|
|
1104
1545
|
const result = decodePrecompileResultPayload(await client.precompile({
|
|
1105
1546
|
code,
|
|
1106
1547
|
filename: options.filename,
|
|
1107
1548
|
limits: toWireLimits(options.limits),
|
|
1108
|
-
globals:
|
|
1549
|
+
globals: allGlobals,
|
|
1550
|
+
imports: bindings
|
|
1109
1551
|
}));
|
|
1110
1552
|
if (!result.ok) {
|
|
1111
1553
|
const err = new Error(result.error.message);
|
|
@@ -1114,7 +1556,7 @@ var SandboxImpl = class {
|
|
|
1114
1556
|
if (result.error.stack) err.stack = result.error.stack;
|
|
1115
1557
|
throw err;
|
|
1116
1558
|
}
|
|
1117
|
-
return new PrefixImpl(result.prefixId, this.pool, rawGlobals);
|
|
1559
|
+
return new PrefixImpl(result.prefixId, this.pool, rawGlobals, registry, shape);
|
|
1118
1560
|
});
|
|
1119
1561
|
}
|
|
1120
1562
|
async dispose() {
|
|
@@ -1140,11 +1582,27 @@ var PrefixImpl = class {
|
|
|
1140
1582
|
* precompile-time implementation is reused."
|
|
1141
1583
|
*/
|
|
1142
1584
|
defaultGlobals;
|
|
1585
|
+
/**
|
|
1586
|
+
* Handle registry declared at precompile time: handle ID → host function.
|
|
1587
|
+
* Same rebinding rules as `defaultGlobals` — a `prefix.run()` may override
|
|
1588
|
+
* a subset of function leaves; everything else falls back to these. Source
|
|
1589
|
+
* modules and data leaves are frozen in the snapshot and not represented
|
|
1590
|
+
* here.
|
|
1591
|
+
*/
|
|
1592
|
+
defaultRegistry;
|
|
1593
|
+
/**
|
|
1594
|
+
* Declared shape captured at precompile time. Drives type-level rebinding
|
|
1595
|
+
* via `RebindImports<M>` and runtime `ERR_UNDECLARED_BINDING` enforcement
|
|
1596
|
+
* inside `extractRebindImports`.
|
|
1597
|
+
*/
|
|
1598
|
+
declaredImportShape;
|
|
1143
1599
|
_alive = true;
|
|
1144
|
-
constructor(id, pool, defaultGlobals) {
|
|
1600
|
+
constructor(id, pool, defaultGlobals, defaultRegistry, declaredImportShape) {
|
|
1145
1601
|
this.id = id;
|
|
1146
1602
|
this.pool = pool;
|
|
1147
1603
|
this.defaultGlobals = defaultGlobals;
|
|
1604
|
+
this.defaultRegistry = defaultRegistry;
|
|
1605
|
+
this.declaredImportShape = declaredImportShape;
|
|
1148
1606
|
}
|
|
1149
1607
|
get alive() {
|
|
1150
1608
|
return this._alive;
|
|
@@ -1161,27 +1619,44 @@ var PrefixImpl = class {
|
|
|
1161
1619
|
stderr: [],
|
|
1162
1620
|
durationMs: 0
|
|
1163
1621
|
};
|
|
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
|
-
};
|
|
1622
|
+
if (options.signal?.aborted) return abortedResult();
|
|
1175
1623
|
const bridgeGlobals = extractBridgeGlobals(options.globals ?? {}, this.defaultGlobals);
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1624
|
+
let registry;
|
|
1625
|
+
try {
|
|
1626
|
+
registry = extractRebindImports(options.imports, this.defaultRegistry, this.declaredImportShape);
|
|
1627
|
+
} catch (e) {
|
|
1628
|
+
if (e instanceof UndeclaredImportBindingError) return {
|
|
1629
|
+
ok: false,
|
|
1630
|
+
error: {
|
|
1631
|
+
code: "ERR_UNDECLARED_BINDING",
|
|
1632
|
+
name: "Error",
|
|
1633
|
+
message: e.message
|
|
1634
|
+
},
|
|
1635
|
+
stdout: [],
|
|
1636
|
+
stderr: [],
|
|
1637
|
+
durationMs: 0
|
|
1638
|
+
};
|
|
1639
|
+
throw e;
|
|
1640
|
+
}
|
|
1641
|
+
const allGlobals = registry.size > 0 ? {
|
|
1642
|
+
...bridgeGlobals,
|
|
1643
|
+
[BRIDGE_DISPATCH_GLOBAL]: createDispatchGlobal(registry)
|
|
1644
|
+
} : bridgeGlobals;
|
|
1645
|
+
try {
|
|
1646
|
+
return await this.pool.withClient(async (client) => {
|
|
1647
|
+
return decodeRunCompletionPayload((await client.prefixRun({
|
|
1648
|
+
prefixId: this.id,
|
|
1649
|
+
code: options.code,
|
|
1650
|
+
filename: options.filename,
|
|
1651
|
+
limits: toWireLimits(options.limits),
|
|
1652
|
+
globals: allGlobals,
|
|
1653
|
+
signal: options.signal
|
|
1654
|
+
})).result).result;
|
|
1655
|
+
});
|
|
1656
|
+
} catch (error) {
|
|
1657
|
+
if (error instanceof RunAbortedError) return abortedResult();
|
|
1658
|
+
throw error;
|
|
1659
|
+
}
|
|
1185
1660
|
}
|
|
1186
1661
|
async dispose() {
|
|
1187
1662
|
if (!this._alive) return;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@iso4/sandbox",
|
|
3
|
-
"version": "0.0
|
|
3
|
+
"version": "0.1.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Fast, sandboxed V8 isolate runtime for agent-generated JavaScript. Two-process architecture for crash isolation.",
|
|
6
6
|
"keywords": [
|
|
@@ -47,10 +47,10 @@
|
|
|
47
47
|
"vitest": "^4.1.5"
|
|
48
48
|
},
|
|
49
49
|
"optionalDependencies": {
|
|
50
|
-
"@iso4/v8-darwin-arm64": "^0.0
|
|
51
|
-
"@iso4/v8-darwin-x64": "^0.0
|
|
52
|
-
"@iso4/v8-linux-arm64-gnu": "^0.0
|
|
53
|
-
"@iso4/v8-linux-x64-gnu": "^0.0
|
|
50
|
+
"@iso4/v8-darwin-arm64": "^0.1.0",
|
|
51
|
+
"@iso4/v8-darwin-x64": "^0.1.0",
|
|
52
|
+
"@iso4/v8-linux-arm64-gnu": "^0.1.0",
|
|
53
|
+
"@iso4/v8-linux-x64-gnu": "^0.1.0"
|
|
54
54
|
},
|
|
55
55
|
"engines": {
|
|
56
56
|
"node": ">=24.0.0"
|