@iso4/sandbox 0.3.1 → 0.4.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/README.md +29 -12
- package/dist/index.d.mts +160 -30
- package/dist/index.mjs +617 -449
- package/package.json +5 -5
package/dist/index.mjs
CHANGED
|
@@ -200,6 +200,8 @@ function decodeWireValueFromSlice(buf) {
|
|
|
200
200
|
* List<String> stdout
|
|
201
201
|
* List<String> stderr
|
|
202
202
|
* f64 durationMs
|
|
203
|
+
* f64 cpuTimeMs
|
|
204
|
+
* List<BridgeCallRecord> bridgeCalls
|
|
203
205
|
* u8 failurePresent (1 when ok = 0)
|
|
204
206
|
* String code
|
|
205
207
|
* String name
|
|
@@ -209,6 +211,8 @@ function decodeWireValueFromSlice(buf) {
|
|
|
209
211
|
* List<String> stdout
|
|
210
212
|
* List<String> stderr
|
|
211
213
|
* f64 durationMs
|
|
214
|
+
* f64 cpuTimeMs
|
|
215
|
+
* List<BridgeCallRecord> bridgeCalls
|
|
212
216
|
* ```
|
|
213
217
|
* @param buf
|
|
214
218
|
*/
|
|
@@ -221,6 +225,8 @@ function decodeRunCompletionPayload(buf) {
|
|
|
221
225
|
const stdout = reader.readStringList();
|
|
222
226
|
const stderr = reader.readStringList();
|
|
223
227
|
const durationMs = reader.readF64();
|
|
228
|
+
const cpuTimeMs = reader.readF64();
|
|
229
|
+
const bridgeCalls = readBridgeCallRecords(reader);
|
|
224
230
|
reader.readU8();
|
|
225
231
|
reader.assertDone();
|
|
226
232
|
return {
|
|
@@ -231,7 +237,9 @@ function decodeRunCompletionPayload(buf) {
|
|
|
231
237
|
exports: wireObjectToExports(exportsRaw),
|
|
232
238
|
stdout,
|
|
233
239
|
stderr,
|
|
234
|
-
durationMs
|
|
240
|
+
durationMs,
|
|
241
|
+
cpuTimeMs,
|
|
242
|
+
bridgeCalls
|
|
235
243
|
}
|
|
236
244
|
};
|
|
237
245
|
}
|
|
@@ -245,6 +253,8 @@ function decodeRunCompletionPayload(buf) {
|
|
|
245
253
|
const stdout = reader.readStringList();
|
|
246
254
|
const stderr = reader.readStringList();
|
|
247
255
|
const durationMs = reader.readF64();
|
|
256
|
+
const cpuTimeMs = reader.readF64();
|
|
257
|
+
const bridgeCalls = readBridgeCallRecords(reader);
|
|
248
258
|
reader.assertDone();
|
|
249
259
|
return {
|
|
250
260
|
runId,
|
|
@@ -260,11 +270,42 @@ function decodeRunCompletionPayload(buf) {
|
|
|
260
270
|
},
|
|
261
271
|
stdout,
|
|
262
272
|
stderr,
|
|
263
|
-
durationMs
|
|
273
|
+
durationMs,
|
|
274
|
+
cpuTimeMs,
|
|
275
|
+
bridgeCalls
|
|
264
276
|
}
|
|
265
277
|
};
|
|
266
278
|
}
|
|
267
279
|
/**
|
|
280
|
+
* Decode `List<BridgeCallRecord>` per `docs/protocol.md` §5.6. Names arrive
|
|
281
|
+
* already resolved — the runtime owns the import handle table and the shim
|
|
282
|
+
* naming convention, so no client-side mapping remains.
|
|
283
|
+
* @param reader
|
|
284
|
+
*/
|
|
285
|
+
function readBridgeCallRecords(reader) {
|
|
286
|
+
const count = reader.readU32();
|
|
287
|
+
const entries = [];
|
|
288
|
+
for (let i = 0; i < count; i++) {
|
|
289
|
+
const name = reader.readString();
|
|
290
|
+
const startMs = reader.readF64();
|
|
291
|
+
const durationMs = reader.readF64();
|
|
292
|
+
const argBytes = reader.readU32();
|
|
293
|
+
const responseBytes = reader.readU32();
|
|
294
|
+
const ok = reader.readBool();
|
|
295
|
+
const blocked = reader.readBool();
|
|
296
|
+
entries.push({
|
|
297
|
+
name,
|
|
298
|
+
startMs,
|
|
299
|
+
durationMs,
|
|
300
|
+
argBytes,
|
|
301
|
+
responseBytes,
|
|
302
|
+
ok,
|
|
303
|
+
blocked
|
|
304
|
+
});
|
|
305
|
+
}
|
|
306
|
+
return entries;
|
|
307
|
+
}
|
|
308
|
+
/**
|
|
268
309
|
* Decode a `PrecompileResultPayload` from a `PrecompileResult` frame.
|
|
269
310
|
*
|
|
270
311
|
* Wire layout per `docs/protocol.md` §5.6:
|
|
@@ -550,6 +591,16 @@ function encodeAuthenticatePayload(auth) {
|
|
|
550
591
|
token.copy(payload, 2);
|
|
551
592
|
return payload;
|
|
552
593
|
}
|
|
594
|
+
/**
|
|
595
|
+
* Wire tag for each `GlobalDefPayload` kind. Mirrors `HostGlobalDef` on the
|
|
596
|
+
* Rust side (`ipc.rs`).
|
|
597
|
+
*/
|
|
598
|
+
const GLOBAL_DEF_KIND = {
|
|
599
|
+
bridge: 0,
|
|
600
|
+
string: 1,
|
|
601
|
+
data: 2,
|
|
602
|
+
shim: 3
|
|
603
|
+
};
|
|
553
604
|
var PayloadWriter = class {
|
|
554
605
|
parts = [];
|
|
555
606
|
writeU8(n) {
|
|
@@ -582,23 +633,90 @@ var PayloadWriter = class {
|
|
|
582
633
|
}
|
|
583
634
|
return this;
|
|
584
635
|
}
|
|
636
|
+
writeOptionalU32(n) {
|
|
637
|
+
if (n === void 0) this.writeU8(0);
|
|
638
|
+
else {
|
|
639
|
+
this.writeU8(1);
|
|
640
|
+
this.writeU32(n);
|
|
641
|
+
}
|
|
642
|
+
return this;
|
|
643
|
+
}
|
|
644
|
+
writeGlobalDefs(defs) {
|
|
645
|
+
this.writeU32(defs.length);
|
|
646
|
+
for (const def of defs) {
|
|
647
|
+
this.writeU8(GLOBAL_DEF_KIND[def.kind]);
|
|
648
|
+
this.writeString(def.name);
|
|
649
|
+
switch (def.kind) {
|
|
650
|
+
case "bridge": break;
|
|
651
|
+
case "string":
|
|
652
|
+
this.writeString(def.expr);
|
|
653
|
+
break;
|
|
654
|
+
case "data":
|
|
655
|
+
this.writeBytes(encodeWireValue(def.value));
|
|
656
|
+
break;
|
|
657
|
+
case "shim":
|
|
658
|
+
this.writeString(def.shim);
|
|
659
|
+
this.writeString(def.handlerName);
|
|
660
|
+
break;
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
return this;
|
|
664
|
+
}
|
|
585
665
|
writeImports(imports) {
|
|
586
666
|
this.writeU32(imports.length);
|
|
587
667
|
for (const imp of imports) {
|
|
588
668
|
this.writeString(imp.specifier);
|
|
589
|
-
|
|
669
|
+
if ("source" in imp) {
|
|
670
|
+
this.writeU8(0);
|
|
671
|
+
this.writeString(imp.source);
|
|
672
|
+
} else {
|
|
673
|
+
this.writeU8(1);
|
|
674
|
+
this.writeU32(imp.module.length);
|
|
675
|
+
for (const [name, node] of imp.module) {
|
|
676
|
+
this.writeString(name);
|
|
677
|
+
this.writeHostModuleNode(node);
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
return this;
|
|
682
|
+
}
|
|
683
|
+
writeHostModuleNode(node) {
|
|
684
|
+
switch (node.kind) {
|
|
685
|
+
case "function":
|
|
686
|
+
this.writeU8(0);
|
|
687
|
+
break;
|
|
688
|
+
case "data":
|
|
689
|
+
this.writeU8(1);
|
|
690
|
+
this.writeBytes(encodeWireValue(node.value));
|
|
691
|
+
break;
|
|
692
|
+
case "object":
|
|
693
|
+
this.writeU8(2);
|
|
694
|
+
this.writeU32(node.entries.length);
|
|
695
|
+
for (const [key, child] of node.entries) {
|
|
696
|
+
this.writeString(key);
|
|
697
|
+
this.writeHostModuleNode(child);
|
|
698
|
+
}
|
|
699
|
+
break;
|
|
700
|
+
}
|
|
701
|
+
return this;
|
|
702
|
+
}
|
|
703
|
+
writeImportRebinds(rebinds) {
|
|
704
|
+
this.writeU32(rebinds.length);
|
|
705
|
+
for (const rebind of rebinds) {
|
|
706
|
+
this.writeString(rebind.specifier);
|
|
707
|
+
this.writeString(rebind.path);
|
|
590
708
|
}
|
|
591
709
|
return this;
|
|
592
710
|
}
|
|
593
711
|
writeResourceLimits(limits) {
|
|
594
|
-
this.
|
|
595
|
-
this.
|
|
596
|
-
this.
|
|
597
|
-
this.
|
|
598
|
-
this.
|
|
599
|
-
this.
|
|
600
|
-
this.
|
|
601
|
-
this.
|
|
712
|
+
this.writeOptionalU32(limits.memoryMb);
|
|
713
|
+
this.writeOptionalU32(limits.cpuTimeMs);
|
|
714
|
+
this.writeOptionalU32(limits.wallTimeMs);
|
|
715
|
+
this.writeOptionalU32(limits.maxExportBytes);
|
|
716
|
+
this.writeOptionalU32(limits.maxStdoutBytes);
|
|
717
|
+
this.writeOptionalU32(limits.maxStderrBytes);
|
|
718
|
+
this.writeOptionalU32(limits.maxBridgeCallBytes);
|
|
719
|
+
this.writeOptionalU32(limits.maxBridgeCalls);
|
|
602
720
|
return this;
|
|
603
721
|
}
|
|
604
722
|
toBuffer() {
|
|
@@ -610,12 +728,7 @@ var PayloadWriter = class {
|
|
|
610
728
|
* @param options
|
|
611
729
|
*/
|
|
612
730
|
function encodeRunPayload(options) {
|
|
613
|
-
|
|
614
|
-
const globals = options.globals ?? [];
|
|
615
|
-
w.writeU32(globals.length);
|
|
616
|
-
for (const name of globals) w.writeString(name);
|
|
617
|
-
w.writeImports(options.imports ?? []);
|
|
618
|
-
return w.toBuffer();
|
|
731
|
+
return new PayloadWriter().writeU32(options.runId).writeString(options.code).writeOptionalString(options.filename).writeResourceLimits(options.limits ?? {}).writeGlobalDefs(options.globals ?? []).writeImports(options.imports ?? []).toBuffer();
|
|
619
732
|
}
|
|
620
733
|
/**
|
|
621
734
|
* Encode a `PrecompilePayload` per `docs/protocol.md` §5.2.
|
|
@@ -623,12 +736,7 @@ function encodeRunPayload(options) {
|
|
|
623
736
|
* @param options
|
|
624
737
|
*/
|
|
625
738
|
function encodePrecompilePayload(options) {
|
|
626
|
-
|
|
627
|
-
const globals = options.globals ?? [];
|
|
628
|
-
w.writeU32(globals.length);
|
|
629
|
-
for (const name of globals) w.writeString(name);
|
|
630
|
-
w.writeImports(options.imports ?? []);
|
|
631
|
-
return w.toBuffer();
|
|
739
|
+
return new PayloadWriter().writeString(options.code).writeOptionalString(options.filename).writeResourceLimits(options.limits ?? {}).writeGlobalDefs(options.globals ?? []).writeImports(options.imports ?? []).toBuffer();
|
|
632
740
|
}
|
|
633
741
|
/**
|
|
634
742
|
* Encode a `PrefixRunPayload` per `docs/protocol.md` §5.2.
|
|
@@ -637,12 +745,7 @@ function encodePrecompilePayload(options) {
|
|
|
637
745
|
* @param options
|
|
638
746
|
*/
|
|
639
747
|
function encodePrefixRunPayload(options) {
|
|
640
|
-
|
|
641
|
-
const globals = options.globals ?? [];
|
|
642
|
-
w.writeU32(globals.length);
|
|
643
|
-
for (const name of globals) w.writeString(name);
|
|
644
|
-
w.writeImports(options.imports ?? []);
|
|
645
|
-
return w.toBuffer();
|
|
748
|
+
return new PayloadWriter().writeU32(options.runId).writeString(options.prefixId).writeString(options.code).writeOptionalString(options.filename).writeResourceLimits(options.limits ?? {}).writeGlobalDefs(options.globals ?? []).writeImportRebinds(options.importRebinds ?? []).toBuffer();
|
|
646
749
|
}
|
|
647
750
|
/**
|
|
648
751
|
* Encode a `DisposePrefix` payload — just the PrefixId string.
|
|
@@ -652,6 +755,15 @@ function encodeDisposePrefixPayload(prefixId) {
|
|
|
652
755
|
return new PayloadWriter().writeString(prefixId).toBuffer();
|
|
653
756
|
}
|
|
654
757
|
/**
|
|
758
|
+
* Encode a `Terminate` payload — just the RunId (u32) of the run to stop.
|
|
759
|
+
* Sent when an `AbortSignal` fires mid-run so Rust can gracefully abort the
|
|
760
|
+
* run and reply with a real `ERR_ABORTED` Result (see #36 / client.ts).
|
|
761
|
+
* @param runId
|
|
762
|
+
*/
|
|
763
|
+
function encodeTerminatePayload(runId) {
|
|
764
|
+
return new PayloadWriter().writeU32(runId).toBuffer();
|
|
765
|
+
}
|
|
766
|
+
/**
|
|
655
767
|
* Decode a `BridgeCallPayload` from a `BridgeCall` frame sent by Rust.
|
|
656
768
|
* Per `docs/protocol.md` §5.4.
|
|
657
769
|
* @param buf
|
|
@@ -794,13 +906,281 @@ function formatByte(byte) {
|
|
|
794
906
|
return `0x${byte.toString(16).padStart(2, "0")}`;
|
|
795
907
|
}
|
|
796
908
|
//#endregion
|
|
909
|
+
//#region src/imports.ts
|
|
910
|
+
/**
|
|
911
|
+
* The dispatch-map key for one host-module function leaf. The NUL separator
|
|
912
|
+
* cannot collide with anything a specifier or dot-joined path can contain in
|
|
913
|
+
* practice, so keys stay unambiguous.
|
|
914
|
+
* @param specifier
|
|
915
|
+
* @param path dot-joined function-leaf path
|
|
916
|
+
*/
|
|
917
|
+
function importHandlerKey(specifier, path) {
|
|
918
|
+
return `${specifier}\u0000${path}`;
|
|
919
|
+
}
|
|
920
|
+
/**
|
|
921
|
+
* Thrown when the host's import configuration is structurally invalid in a
|
|
922
|
+
* way only the client can see (a non-function rebind value, a source-module
|
|
923
|
+
* rebind attempt). `PrefixImpl.run` converts it into an
|
|
924
|
+
* `ERR_UNDECLARED_BINDING` `RunResult`, matching the runtime-side enforcement
|
|
925
|
+
* for undeclared locations.
|
|
926
|
+
*/
|
|
927
|
+
var UndeclaredImportBindingError = class extends Error {
|
|
928
|
+
code = "ERR_UNDECLARED_BINDING";
|
|
929
|
+
constructor(message) {
|
|
930
|
+
super(message);
|
|
931
|
+
this.name = "UndeclaredImportBindingError";
|
|
932
|
+
}
|
|
933
|
+
};
|
|
934
|
+
function processImports(imports) {
|
|
935
|
+
if (imports === void 0) return {
|
|
936
|
+
bindings: [],
|
|
937
|
+
handlers: /* @__PURE__ */ new Map()
|
|
938
|
+
};
|
|
939
|
+
const bindings = [];
|
|
940
|
+
const handlers = /* @__PURE__ */ new Map();
|
|
941
|
+
for (const [specifier, value] of Object.entries(imports)) {
|
|
942
|
+
if (typeof value === "string") {
|
|
943
|
+
bindings.push({
|
|
944
|
+
specifier,
|
|
945
|
+
source: value
|
|
946
|
+
});
|
|
947
|
+
continue;
|
|
948
|
+
}
|
|
949
|
+
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)}`);
|
|
950
|
+
const module = [];
|
|
951
|
+
for (const [name, child] of Object.entries(value)) {
|
|
952
|
+
if (child === void 0) continue;
|
|
953
|
+
if (!isValidExportIdentifier(name)) throw new Error(`[@iso4/sandbox] imports['${specifier}'] top-level key '${name}' is not a valid JavaScript identifier and cannot be exported as a named ESM export`);
|
|
954
|
+
module.push([name, lowerNode(specifier, child, [name], handlers)]);
|
|
955
|
+
}
|
|
956
|
+
bindings.push({
|
|
957
|
+
specifier,
|
|
958
|
+
module
|
|
959
|
+
});
|
|
960
|
+
}
|
|
961
|
+
return {
|
|
962
|
+
bindings,
|
|
963
|
+
handlers
|
|
964
|
+
};
|
|
965
|
+
}
|
|
966
|
+
/**
|
|
967
|
+
* Lower one host-module node to its wire shape, registering function leaves.
|
|
968
|
+
* @param specifier
|
|
969
|
+
* @param value
|
|
970
|
+
* @param path
|
|
971
|
+
* @param handlers
|
|
972
|
+
* @param seen
|
|
973
|
+
*/
|
|
974
|
+
function lowerNode(specifier, value, path, handlers, seen = /* @__PURE__ */ new Set()) {
|
|
975
|
+
if (typeof value === "function") {
|
|
976
|
+
handlers.set(importHandlerKey(specifier, path.join(".")), value);
|
|
977
|
+
return { kind: "function" };
|
|
978
|
+
}
|
|
979
|
+
if (isPlainObject(value)) {
|
|
980
|
+
if (seen.has(value)) throw new Error(`[@iso4/sandbox] imports['${specifier}'].${path.join(".")}: circular references are not supported in host-module shapes`);
|
|
981
|
+
seen.add(value);
|
|
982
|
+
const entries = [];
|
|
983
|
+
for (const [key, child] of Object.entries(value)) {
|
|
984
|
+
if (child === void 0) continue;
|
|
985
|
+
entries.push([key, lowerNode(specifier, child, [...path, key], handlers, seen)]);
|
|
986
|
+
}
|
|
987
|
+
seen.delete(value);
|
|
988
|
+
return {
|
|
989
|
+
kind: "object",
|
|
990
|
+
entries
|
|
991
|
+
};
|
|
992
|
+
}
|
|
993
|
+
validateDataLeaf(specifier, value, path);
|
|
994
|
+
return {
|
|
995
|
+
kind: "data",
|
|
996
|
+
value
|
|
997
|
+
};
|
|
998
|
+
}
|
|
999
|
+
/**
|
|
1000
|
+
* Validate a `HostExportData` value. Supports primitives, plain
|
|
1001
|
+
* objects/arrays, `BigInt`, `Uint8Array` — the same set the wire codec can
|
|
1002
|
+
* carry back out of the sandbox. `Date`, `Map`, `Set`, circular refs, and
|
|
1003
|
+
* class instances throw with a clear pointer.
|
|
1004
|
+
*
|
|
1005
|
+
* @param specifier
|
|
1006
|
+
* @param value
|
|
1007
|
+
* @param path
|
|
1008
|
+
* @param seen
|
|
1009
|
+
*/
|
|
1010
|
+
function validateDataLeaf(specifier, value, path, seen = /* @__PURE__ */ new Set()) {
|
|
1011
|
+
if (value === null || value === void 0) return;
|
|
1012
|
+
switch (typeof value) {
|
|
1013
|
+
case "boolean":
|
|
1014
|
+
case "number":
|
|
1015
|
+
case "bigint":
|
|
1016
|
+
case "string": return;
|
|
1017
|
+
}
|
|
1018
|
+
if (value instanceof Uint8Array) return;
|
|
1019
|
+
if (value instanceof Date || value instanceof Map || value instanceof Set) throw new Error(`[@iso4/sandbox] imports['${specifier}'].${path.join(".")}: ${value.constructor.name} values are not supported as data leaves; supported: primitives, bigint, string, Uint8Array, plain objects/arrays`);
|
|
1020
|
+
if (typeof value === "object") {
|
|
1021
|
+
if (seen.has(value)) throw new Error(`[@iso4/sandbox] imports['${specifier}'].${path.join(".")}: circular references in data leaves are not supported`);
|
|
1022
|
+
seen.add(value);
|
|
1023
|
+
if (Array.isArray(value)) {
|
|
1024
|
+
value.forEach((item, i) => {
|
|
1025
|
+
validateDataLeaf(specifier, item, [...path, String(i)], seen);
|
|
1026
|
+
});
|
|
1027
|
+
seen.delete(value);
|
|
1028
|
+
return;
|
|
1029
|
+
}
|
|
1030
|
+
const proto = Object.getPrototypeOf(value);
|
|
1031
|
+
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`);
|
|
1032
|
+
for (const [key, child] of Object.entries(value)) validateDataLeaf(specifier, child, [...path, key], seen);
|
|
1033
|
+
seen.delete(value);
|
|
1034
|
+
return;
|
|
1035
|
+
}
|
|
1036
|
+
throw new Error(`[@iso4/sandbox] imports['${specifier}'].${path.join(".")}: unsupported data value of type ${describeKind(value)}`);
|
|
1037
|
+
}
|
|
1038
|
+
/**
|
|
1039
|
+
* Merge the handlers behind a `Prefix`'s host-module function leaves with the
|
|
1040
|
+
* run's overrides and collect the rebind locations to send on the wire.
|
|
1041
|
+
*
|
|
1042
|
+
* Only client-visible shape problems throw here (a string value — source
|
|
1043
|
+
* modules are frozen; a non-function leaf value — there is nothing to
|
|
1044
|
+
* dispatch to). Whether each location was actually declared as a function
|
|
1045
|
+
* leaf at precompile time is enforced by the Rust runtime against the stored
|
|
1046
|
+
* prefix shape, which rejects violations with `ERR_UNDECLARED_BINDING`.
|
|
1047
|
+
*
|
|
1048
|
+
* @param runImports
|
|
1049
|
+
* @param defaults handler map captured at precompile time
|
|
1050
|
+
*/
|
|
1051
|
+
function mergeRebindImports(runImports, defaults) {
|
|
1052
|
+
if (runImports === void 0) return {
|
|
1053
|
+
rebinds: [],
|
|
1054
|
+
handlers: defaults
|
|
1055
|
+
};
|
|
1056
|
+
const handlers = new Map(defaults);
|
|
1057
|
+
const rebinds = [];
|
|
1058
|
+
for (const [specifier, value] of Object.entries(runImports)) {
|
|
1059
|
+
if (typeof value === "string") throw new UndeclaredImportBindingError(`import '${specifier}' is a source module — source imports are frozen in the snapshot and cannot be rebound at prefix.run() time`);
|
|
1060
|
+
if (!isPlainObject(value)) throw new Error(`[@iso4/sandbox] imports['${specifier}'] override must be a plain object; got ${describeKind(value)}`);
|
|
1061
|
+
walkRebind(specifier, value, [], handlers, rebinds);
|
|
1062
|
+
}
|
|
1063
|
+
return {
|
|
1064
|
+
rebinds,
|
|
1065
|
+
handlers
|
|
1066
|
+
};
|
|
1067
|
+
}
|
|
1068
|
+
function walkRebind(specifier, node, path, handlers, rebinds) {
|
|
1069
|
+
for (const [key, value] of Object.entries(node)) {
|
|
1070
|
+
if (value === void 0) continue;
|
|
1071
|
+
const newPath = [...path, key];
|
|
1072
|
+
if (typeof value === "function") {
|
|
1073
|
+
const joined = newPath.join(".");
|
|
1074
|
+
handlers.set(importHandlerKey(specifier, joined), value);
|
|
1075
|
+
rebinds.push({
|
|
1076
|
+
specifier,
|
|
1077
|
+
path: joined
|
|
1078
|
+
});
|
|
1079
|
+
continue;
|
|
1080
|
+
}
|
|
1081
|
+
if (isPlainObject(value)) {
|
|
1082
|
+
walkRebind(specifier, value, newPath, handlers, rebinds);
|
|
1083
|
+
continue;
|
|
1084
|
+
}
|
|
1085
|
+
throw new UndeclaredImportBindingError(`import '${specifier}'.${newPath.join(".")} can only be rebound with a function; got ${describeKind(value)}`);
|
|
1086
|
+
}
|
|
1087
|
+
}
|
|
1088
|
+
function isPlainObject(value) {
|
|
1089
|
+
if (value === null || typeof value !== "object") return false;
|
|
1090
|
+
if (Array.isArray(value)) return false;
|
|
1091
|
+
if (value instanceof Uint8Array || value instanceof Date) return false;
|
|
1092
|
+
if (value instanceof Map || value instanceof Set) return false;
|
|
1093
|
+
const proto = Object.getPrototypeOf(value);
|
|
1094
|
+
return proto === null || proto === Object.prototype;
|
|
1095
|
+
}
|
|
1096
|
+
const RESERVED_WORDS = new Set([
|
|
1097
|
+
"break",
|
|
1098
|
+
"case",
|
|
1099
|
+
"catch",
|
|
1100
|
+
"class",
|
|
1101
|
+
"const",
|
|
1102
|
+
"continue",
|
|
1103
|
+
"debugger",
|
|
1104
|
+
"default",
|
|
1105
|
+
"delete",
|
|
1106
|
+
"do",
|
|
1107
|
+
"else",
|
|
1108
|
+
"export",
|
|
1109
|
+
"extends",
|
|
1110
|
+
"finally",
|
|
1111
|
+
"for",
|
|
1112
|
+
"function",
|
|
1113
|
+
"if",
|
|
1114
|
+
"import",
|
|
1115
|
+
"in",
|
|
1116
|
+
"instanceof",
|
|
1117
|
+
"new",
|
|
1118
|
+
"return",
|
|
1119
|
+
"super",
|
|
1120
|
+
"switch",
|
|
1121
|
+
"this",
|
|
1122
|
+
"throw",
|
|
1123
|
+
"try",
|
|
1124
|
+
"typeof",
|
|
1125
|
+
"var",
|
|
1126
|
+
"void",
|
|
1127
|
+
"while",
|
|
1128
|
+
"with",
|
|
1129
|
+
"yield",
|
|
1130
|
+
"let",
|
|
1131
|
+
"static",
|
|
1132
|
+
"enum",
|
|
1133
|
+
"await",
|
|
1134
|
+
"implements",
|
|
1135
|
+
"package",
|
|
1136
|
+
"protected",
|
|
1137
|
+
"interface",
|
|
1138
|
+
"private",
|
|
1139
|
+
"public",
|
|
1140
|
+
"null",
|
|
1141
|
+
"true",
|
|
1142
|
+
"false"
|
|
1143
|
+
]);
|
|
1144
|
+
/**
|
|
1145
|
+
* Whether `name` can appear as a named ESM export. JS identifier rules plus
|
|
1146
|
+
* a reserved-word filter. `default` is allowed (the runtime emits it as
|
|
1147
|
+
* `export default`). Mirrored by `is_valid_export_identifier` in the Rust
|
|
1148
|
+
* runtime (`v8.rs`), which owns the final defensive check.
|
|
1149
|
+
* @param name
|
|
1150
|
+
*/
|
|
1151
|
+
function isValidExportIdentifier(name) {
|
|
1152
|
+
if (name === "default") return true;
|
|
1153
|
+
if (!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name)) return false;
|
|
1154
|
+
if (RESERVED_WORDS.has(name)) return false;
|
|
1155
|
+
return true;
|
|
1156
|
+
}
|
|
1157
|
+
function describeKind(value) {
|
|
1158
|
+
if (value === null) return "null";
|
|
1159
|
+
if (Array.isArray(value)) return "array";
|
|
1160
|
+
return typeof value;
|
|
1161
|
+
}
|
|
1162
|
+
//#endregion
|
|
797
1163
|
//#region src/client.ts
|
|
798
1164
|
/**
|
|
799
|
-
*
|
|
1165
|
+
* How long TS waits for Rust's graceful `ERR_ABORTED` Result after sending a
|
|
1166
|
+
* `Terminate` frame, before falling back to tearing the connection down (#36).
|
|
1167
|
+
*
|
|
1168
|
+
* The common case — a run suspended awaiting a bridge response — has the Rust
|
|
1169
|
+
* V8 thread parked on a socket read, so it consumes the `Terminate` and replies
|
|
1170
|
+
* in well under a millisecond; this window only bites when the sandbox is stuck
|
|
1171
|
+
* in a tight synchronous loop (Rust never reads the frame), where we fall back.
|
|
1172
|
+
* Kept comfortably under the abort-latency the runtime aims for.
|
|
1173
|
+
*/
|
|
1174
|
+
const TERMINATE_GRACE_MS = 100;
|
|
1175
|
+
/**
|
|
1176
|
+
* Thrown out of a run when its `AbortSignal` fires mid-flight and the graceful
|
|
1177
|
+
* `Terminate` path did not produce a Result within {@link TERMINATE_GRACE_MS}
|
|
1178
|
+
* (or when the pre-run abort race tears down before draining). The connection
|
|
800
1179
|
* is torn down (so the Rust isolate is reclaimed) before this propagates, and
|
|
801
1180
|
* the client is marked unusable so the pool replaces it rather than reusing a
|
|
802
1181
|
* half-dead slot. `index.ts` catches this and synthesizes the `ERR_ABORTED`
|
|
803
|
-
* `RunResult`.
|
|
1182
|
+
* `RunResult`. When the graceful path succeeds instead, no error is thrown —
|
|
1183
|
+
* the real `ERR_ABORTED` Result flows back through `drainFrames`.
|
|
804
1184
|
*/
|
|
805
1185
|
var RunAbortedError = class extends Error {
|
|
806
1186
|
/**
|
|
@@ -862,17 +1242,16 @@ var RuntimeIpcClient = class RuntimeIpcClient {
|
|
|
862
1242
|
}
|
|
863
1243
|
async runRawCode(code, options) {
|
|
864
1244
|
if (this.disposed) throw new Error("runtime IPC client is disposed");
|
|
865
|
-
const
|
|
866
|
-
const globalNames = Object.keys(globals);
|
|
1245
|
+
const runId = this.nextRunIdValue();
|
|
867
1246
|
await this.write(encodeTsToRustFrame(TsToRustMessageTypes.Run, encodeRunPayload({
|
|
868
|
-
runId
|
|
1247
|
+
runId,
|
|
869
1248
|
code,
|
|
870
1249
|
filename: options?.filename,
|
|
871
1250
|
limits: options?.limits,
|
|
872
|
-
globals:
|
|
1251
|
+
globals: options?.globals,
|
|
873
1252
|
imports: options?.imports
|
|
874
1253
|
})));
|
|
875
|
-
return this.drainUntilResult(makeDispatcher(
|
|
1254
|
+
return this.drainUntilResult(makeDispatcher(options?.dispatch ?? {}, options?.importDispatch), runId, options?.signal);
|
|
876
1255
|
}
|
|
877
1256
|
async precompile(options) {
|
|
878
1257
|
if (this.disposed) throw new Error("runtime IPC client is disposed");
|
|
@@ -880,7 +1259,7 @@ var RuntimeIpcClient = class RuntimeIpcClient {
|
|
|
880
1259
|
code: options.code,
|
|
881
1260
|
filename: options.filename,
|
|
882
1261
|
limits: options.limits,
|
|
883
|
-
globals:
|
|
1262
|
+
globals: options.globals,
|
|
884
1263
|
imports: options.imports
|
|
885
1264
|
})));
|
|
886
1265
|
for await (const frame of this.reader) {
|
|
@@ -891,18 +1270,17 @@ var RuntimeIpcClient = class RuntimeIpcClient {
|
|
|
891
1270
|
}
|
|
892
1271
|
async prefixRun(options) {
|
|
893
1272
|
if (this.disposed) throw new Error("runtime IPC client is disposed");
|
|
894
|
-
const
|
|
895
|
-
const globalNames = Object.keys(globals);
|
|
1273
|
+
const runId = this.nextRunIdValue();
|
|
896
1274
|
await this.write(encodeTsToRustFrame(TsToRustMessageTypes.PrefixRun, encodePrefixRunPayload({
|
|
897
1275
|
prefixId: options.prefixId,
|
|
898
1276
|
code: options.code,
|
|
899
1277
|
filename: options.filename,
|
|
900
1278
|
limits: options.limits,
|
|
901
|
-
globals:
|
|
902
|
-
|
|
903
|
-
runId
|
|
1279
|
+
globals: options.globals,
|
|
1280
|
+
importRebinds: options.importRebinds,
|
|
1281
|
+
runId
|
|
904
1282
|
})));
|
|
905
|
-
return this.drainUntilResult(makeDispatcher(
|
|
1283
|
+
return this.drainUntilResult(makeDispatcher(options.dispatch ?? {}, options.importDispatch), runId, options.signal);
|
|
906
1284
|
}
|
|
907
1285
|
async disposePrefix(prefixId) {
|
|
908
1286
|
if (this.disposed) return;
|
|
@@ -935,25 +1313,40 @@ var RuntimeIpcClient = class RuntimeIpcClient {
|
|
|
935
1313
|
* continue to completion. Rust silently ignores any late `BridgeResponse`
|
|
936
1314
|
* that arrives after the run has completed (see session.rs).
|
|
937
1315
|
*
|
|
938
|
-
* ── In-flight abort
|
|
1316
|
+
* ── In-flight abort (graceful terminate, #36) ─────────────────────────────
|
|
939
1317
|
* When `signal` fires mid-run — including while a bridge call is in flight —
|
|
940
|
-
* we
|
|
941
|
-
*
|
|
942
|
-
*
|
|
943
|
-
*
|
|
944
|
-
*
|
|
945
|
-
*
|
|
946
|
-
*
|
|
1318
|
+
* we first ask Rust to stop gracefully: send a `Terminate` frame (carrying
|
|
1319
|
+
* `runId`) and keep draining, leaving the socket open. In the common case the
|
|
1320
|
+
* Rust V8 thread is parked awaiting a bridge response, reads the frame, and
|
|
1321
|
+
* replies with a real `ERR_ABORTED` `Result` (carrying duration, CPU time,
|
|
1322
|
+
* and the bridge records collected so far). That Result flows back through
|
|
1323
|
+
* `drainFrames` and the connection stays healthy for reuse.
|
|
1324
|
+
*
|
|
1325
|
+
* If no Result arrives within {@link TERMINATE_GRACE_MS} — the sandbox is
|
|
1326
|
+
* stuck in a tight synchronous loop, so Rust never reaches the frame read —
|
|
1327
|
+
* we fall back to `abortConnection`: the reader is closed so this loop
|
|
1328
|
+
* throws, and the socket is destroyed so Rust observes EOF (its CPU guard
|
|
1329
|
+
* ultimately reclaims the busy isolate; see DESIGN.md §14.7). The loop then
|
|
1330
|
+
* throws `RunAbortedError`, which `index.ts` maps to a synthesized
|
|
1331
|
+
* `ERR_ABORTED` `RunResult`. Any late `BridgeResponse` from an orphaned
|
|
1332
|
+
* handler is harmless either way: on the graceful path the reused connection
|
|
1333
|
+
* discards it (stale callId), on the fallback path the socket is gone.
|
|
947
1334
|
* @param dispatcher
|
|
1335
|
+
* @param runId
|
|
948
1336
|
* @param signal
|
|
949
1337
|
*/
|
|
950
|
-
async drainUntilResult(dispatcher, signal) {
|
|
1338
|
+
async drainUntilResult(dispatcher, runId, signal) {
|
|
951
1339
|
if (signal?.aborted) {
|
|
952
1340
|
this.abortConnection();
|
|
953
1341
|
throw new RunAbortedError(signal.reason);
|
|
954
1342
|
}
|
|
1343
|
+
let graceTimer;
|
|
955
1344
|
const onAbort = () => {
|
|
956
|
-
this.
|
|
1345
|
+
this.write(encodeTsToRustFrame(TsToRustMessageTypes.Terminate, encodeTerminatePayload(runId))).catch(() => {});
|
|
1346
|
+
graceTimer = setTimeout(() => {
|
|
1347
|
+
this.abortConnection();
|
|
1348
|
+
}, TERMINATE_GRACE_MS);
|
|
1349
|
+
graceTimer.unref?.();
|
|
957
1350
|
};
|
|
958
1351
|
signal?.addEventListener("abort", onAbort, { once: true });
|
|
959
1352
|
try {
|
|
@@ -962,6 +1355,7 @@ var RuntimeIpcClient = class RuntimeIpcClient {
|
|
|
962
1355
|
if (signal?.aborted) throw new RunAbortedError(signal.reason);
|
|
963
1356
|
throw error;
|
|
964
1357
|
} finally {
|
|
1358
|
+
if (graceTimer !== void 0) clearTimeout(graceTimer);
|
|
965
1359
|
signal?.removeEventListener("abort", onAbort);
|
|
966
1360
|
}
|
|
967
1361
|
}
|
|
@@ -990,6 +1384,8 @@ var RuntimeIpcClient = class RuntimeIpcClient {
|
|
|
990
1384
|
else {
|
|
991
1385
|
const { callId } = call;
|
|
992
1386
|
dispatcher({
|
|
1387
|
+
targetKind: call.targetKind,
|
|
1388
|
+
specifier: call.specifier,
|
|
993
1389
|
exportName: call.exportName,
|
|
994
1390
|
args: call.args
|
|
995
1391
|
}).then((value) => {
|
|
@@ -1023,18 +1419,24 @@ var RuntimeIpcClient = class RuntimeIpcClient {
|
|
|
1023
1419
|
}
|
|
1024
1420
|
};
|
|
1025
1421
|
/**
|
|
1026
|
-
* Build a dispatcher
|
|
1027
|
-
*
|
|
1028
|
-
*
|
|
1029
|
-
*
|
|
1422
|
+
* Build a dispatcher over the two per-run handler maps: globals by
|
|
1423
|
+
* `exportName`, host-import function leaves by `(specifier, leaf path)` —
|
|
1424
|
+
* the runtime resolves import handle IDs before the frame is sent, so both
|
|
1425
|
+
* lookups are plain name-addressed.
|
|
1030
1426
|
*
|
|
1031
|
-
* Returns `undefined` when
|
|
1427
|
+
* Returns `undefined` when both maps are empty so the loop short-circuits to
|
|
1032
1428
|
* an "unconfigured bridge" error response.
|
|
1033
1429
|
* @param globals
|
|
1430
|
+
* @param imports
|
|
1034
1431
|
*/
|
|
1035
|
-
function makeDispatcher(globals) {
|
|
1036
|
-
if (Object.keys(globals).length === 0) return void 0;
|
|
1037
|
-
return async ({ exportName, args }) => {
|
|
1432
|
+
function makeDispatcher(globals, imports) {
|
|
1433
|
+
if (Object.keys(globals).length === 0 && (imports === void 0 || imports.size === 0)) return void 0;
|
|
1434
|
+
return async ({ targetKind, specifier, exportName, args }) => {
|
|
1435
|
+
if (targetKind === 1) {
|
|
1436
|
+
const handler = imports?.get(importHandlerKey(specifier ?? "", exportName));
|
|
1437
|
+
if (handler === void 0) throw new Error(`no handler configured for host import '${specifier}'.${exportName}`);
|
|
1438
|
+
return handler(...args);
|
|
1439
|
+
}
|
|
1038
1440
|
const handler = globals[exportName];
|
|
1039
1441
|
if (handler === void 0) throw new Error(`no handler configured for bridge global '${exportName}'`);
|
|
1040
1442
|
return handler(...args);
|
|
@@ -1133,353 +1535,113 @@ var ConnectionPool = class {
|
|
|
1133
1535
|
function isBridgeWithShim(v) {
|
|
1134
1536
|
return typeof v === "object" && v !== null && v.kind === "bridge-with-shim";
|
|
1135
1537
|
}
|
|
1538
|
+
function isDataGlobal(v) {
|
|
1539
|
+
return typeof v === "object" && v !== null && v.kind === "data";
|
|
1540
|
+
}
|
|
1136
1541
|
/**
|
|
1137
|
-
*
|
|
1138
|
-
*
|
|
1139
|
-
*
|
|
1140
|
-
*
|
|
1141
|
-
*
|
|
1142
|
-
*
|
|
1143
|
-
|
|
1144
|
-
|
|
1542
|
+
* Private bridge-dispatch name for a `BridgeWithShim` handler. This is a wire
|
|
1543
|
+
* dispatch key and an object-property key — never interpolated into generated
|
|
1544
|
+
* code — so any global name is safe. The runtime recognises the
|
|
1545
|
+
* `__iso4_<name>_h` convention (`public_record_name` in `v8.rs`) and reports
|
|
1546
|
+
* bridge records under the public `<name>`.
|
|
1547
|
+
* @param name public global name
|
|
1548
|
+
*/
|
|
1549
|
+
function shimHandlerName(name) {
|
|
1550
|
+
return `__iso4_${name}_h`;
|
|
1551
|
+
}
|
|
1552
|
+
/**
|
|
1553
|
+
* Lower a `HostGlobals` map into wire-shaped `defs` plus the bridge-dispatch
|
|
1554
|
+
* map. See the module comment for the split.
|
|
1555
|
+
* - `HostExportFunction` → `{ kind: 'bridge' }` + dispatch entry.
|
|
1556
|
+
* - `string` → `{ kind: 'string', expr }` (evaluated by Rust).
|
|
1557
|
+
* - `DataGlobal` → `{ kind: 'data', value }` (materialised by Rust).
|
|
1558
|
+
* - `BridgeWithShim` → `{ kind: 'shim', shim, handlerName }` + a dispatch
|
|
1559
|
+
* entry for the private handler under `handlerName`.
|
|
1145
1560
|
* @param globals
|
|
1146
1561
|
*/
|
|
1147
1562
|
function processGlobals(globals) {
|
|
1148
|
-
const
|
|
1149
|
-
const
|
|
1150
|
-
for (const [name, value] of Object.entries(globals)) if (typeof value === "function")
|
|
1151
|
-
|
|
1563
|
+
const defs = [];
|
|
1564
|
+
const dispatch = {};
|
|
1565
|
+
for (const [name, value] of Object.entries(globals)) if (typeof value === "function") {
|
|
1566
|
+
defs.push({
|
|
1567
|
+
kind: "bridge",
|
|
1568
|
+
name
|
|
1569
|
+
});
|
|
1570
|
+
dispatch[name] = value;
|
|
1571
|
+
} else if (typeof value === "string") defs.push({
|
|
1572
|
+
kind: "string",
|
|
1573
|
+
name,
|
|
1574
|
+
expr: value
|
|
1575
|
+
});
|
|
1576
|
+
else if (isDataGlobal(value)) defs.push({
|
|
1577
|
+
kind: "data",
|
|
1578
|
+
name,
|
|
1579
|
+
value: value.value
|
|
1580
|
+
});
|
|
1152
1581
|
else if (isBridgeWithShim(value)) {
|
|
1153
|
-
const
|
|
1154
|
-
|
|
1155
|
-
|
|
1582
|
+
const handlerName = shimHandlerName(name);
|
|
1583
|
+
defs.push({
|
|
1584
|
+
kind: "shim",
|
|
1585
|
+
name,
|
|
1586
|
+
shim: value.shim,
|
|
1587
|
+
handlerName
|
|
1588
|
+
});
|
|
1589
|
+
dispatch[handlerName] = value.handler;
|
|
1156
1590
|
}
|
|
1157
1591
|
return {
|
|
1158
|
-
|
|
1159
|
-
|
|
1592
|
+
defs,
|
|
1593
|
+
dispatch
|
|
1160
1594
|
};
|
|
1161
1595
|
}
|
|
1162
1596
|
/**
|
|
1163
1597
|
* Resolve bridge globals for a `prefix.run()` call.
|
|
1164
1598
|
*
|
|
1165
|
-
*
|
|
1166
|
-
*
|
|
1167
|
-
*
|
|
1168
|
-
*
|
|
1599
|
+
* String/data globals and shim *wrappers* are already compiled into the
|
|
1600
|
+
* snapshot — only the bridge *stubs* they call need re-installing per run
|
|
1601
|
+
* (bridge stubs are bound to the run's socket and are never snapshotted). So
|
|
1602
|
+
* every returned def is `kind: 'bridge'`, and shimmed globals are routed to
|
|
1603
|
+
* their private `__iso4_<name>_h` key so rebinding updates the handler the
|
|
1604
|
+
* shim calls, without touching the shim itself.
|
|
1169
1605
|
* @param runGlobals
|
|
1170
1606
|
* @param precompileGlobals
|
|
1171
1607
|
*/
|
|
1172
1608
|
function extractBridgeGlobals(runGlobals, precompileGlobals) {
|
|
1173
|
-
const
|
|
1609
|
+
const defs = [];
|
|
1610
|
+
const dispatch = {};
|
|
1174
1611
|
for (const [name, value] of Object.entries(precompileGlobals)) {
|
|
1175
|
-
if (typeof value === "string") continue;
|
|
1612
|
+
if (typeof value === "string" || isDataGlobal(value)) continue;
|
|
1176
1613
|
if (isBridgeWithShim(value)) {
|
|
1177
|
-
const
|
|
1614
|
+
const handlerName = shimHandlerName(name);
|
|
1178
1615
|
const override = runGlobals[name];
|
|
1179
|
-
|
|
1616
|
+
defs.push({
|
|
1617
|
+
kind: "bridge",
|
|
1618
|
+
name: handlerName
|
|
1619
|
+
});
|
|
1620
|
+
dispatch[handlerName] = typeof override === "function" ? override : value.handler;
|
|
1180
1621
|
} else if (typeof value === "function") {
|
|
1181
1622
|
const override = runGlobals[name];
|
|
1182
|
-
|
|
1623
|
+
defs.push({
|
|
1624
|
+
kind: "bridge",
|
|
1625
|
+
name
|
|
1626
|
+
});
|
|
1627
|
+
dispatch[name] = typeof override === "function" ? override : value;
|
|
1183
1628
|
}
|
|
1184
1629
|
}
|
|
1185
1630
|
for (const [name, override] of Object.entries(runGlobals)) {
|
|
1186
1631
|
if (name in precompileGlobals) continue;
|
|
1187
|
-
if (typeof override === "function")
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
//#endregion
|
|
1192
|
-
//#region src/imports.ts
|
|
1193
|
-
/**
|
|
1194
|
-
* The reserved global name of the bridge dispatcher. User globals may not
|
|
1195
|
-
* use this name. The generated host-module source calls it as
|
|
1196
|
-
* `globalThis.__iso4_call(id, ...args)`.
|
|
1197
|
-
*/
|
|
1198
|
-
const BRIDGE_DISPATCH_GLOBAL = "__iso4_call";
|
|
1199
|
-
/**
|
|
1200
|
-
* Thrown when the host's import configuration is structurally invalid
|
|
1201
|
-
* (mixed types, unsupported data values, undeclared rebindings, …).
|
|
1202
|
-
* `PrefixImpl.run` converts the undeclared-binding variant into an
|
|
1203
|
-
* `ERR_UNDECLARED_BINDING` `RunResult`, matching the globals path.
|
|
1204
|
-
*/
|
|
1205
|
-
var UndeclaredImportBindingError = class extends Error {
|
|
1206
|
-
code = "ERR_UNDECLARED_BINDING";
|
|
1207
|
-
constructor(message) {
|
|
1208
|
-
super(message);
|
|
1209
|
-
this.name = "UndeclaredImportBindingError";
|
|
1210
|
-
}
|
|
1211
|
-
};
|
|
1212
|
-
/**
|
|
1213
|
-
* Build the `__iso4_call` global handler that backs all host-module
|
|
1214
|
-
* function leaves for a run. It peels the leading handle ID and routes to
|
|
1215
|
-
* the registry.
|
|
1216
|
-
* @param registry
|
|
1217
|
-
*/
|
|
1218
|
-
function createDispatchGlobal(registry) {
|
|
1219
|
-
return (...args) => {
|
|
1220
|
-
const id = args[0];
|
|
1221
|
-
const fn = registry.get(id);
|
|
1222
|
-
if (fn === void 0) throw new Error(`[@iso4/sandbox] no host handler for import handle ${String(id)}`);
|
|
1223
|
-
return fn(...args.slice(1));
|
|
1224
|
-
};
|
|
1225
|
-
}
|
|
1226
|
-
function processImports(imports) {
|
|
1227
|
-
const shape = {
|
|
1228
|
-
sourceSpecifiers: /* @__PURE__ */ new Set(),
|
|
1229
|
-
hostFunctionIds: {},
|
|
1230
|
-
hostDataPaths: {}
|
|
1231
|
-
};
|
|
1232
|
-
if (imports === void 0) return {
|
|
1233
|
-
bindings: [],
|
|
1234
|
-
registry: /* @__PURE__ */ new Map(),
|
|
1235
|
-
shape
|
|
1236
|
-
};
|
|
1237
|
-
const bindings = [];
|
|
1238
|
-
const registry = /* @__PURE__ */ new Map();
|
|
1239
|
-
let nextId = 0;
|
|
1240
|
-
const allocId = () => nextId++;
|
|
1241
|
-
for (const [specifier, value] of Object.entries(imports)) {
|
|
1242
|
-
if (typeof value === "string") {
|
|
1243
|
-
bindings.push({
|
|
1244
|
-
specifier,
|
|
1245
|
-
source: value
|
|
1632
|
+
if (typeof override === "function") {
|
|
1633
|
+
defs.push({
|
|
1634
|
+
kind: "bridge",
|
|
1635
|
+
name
|
|
1246
1636
|
});
|
|
1247
|
-
|
|
1248
|
-
continue;
|
|
1637
|
+
dispatch[name] = override;
|
|
1249
1638
|
}
|
|
1250
|
-
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)}`);
|
|
1251
|
-
const fnIds = {};
|
|
1252
|
-
const dataPaths = /* @__PURE__ */ new Set();
|
|
1253
|
-
const source = generateHostModuleSource(specifier, value, registry, allocId, fnIds, dataPaths);
|
|
1254
|
-
bindings.push({
|
|
1255
|
-
specifier,
|
|
1256
|
-
source
|
|
1257
|
-
});
|
|
1258
|
-
shape.hostFunctionIds[specifier] = fnIds;
|
|
1259
|
-
shape.hostDataPaths[specifier] = dataPaths;
|
|
1260
1639
|
}
|
|
1261
1640
|
return {
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
shape
|
|
1641
|
+
defs,
|
|
1642
|
+
dispatch
|
|
1265
1643
|
};
|
|
1266
1644
|
}
|
|
1267
|
-
/**
|
|
1268
|
-
* Override the handlers behind a `Prefix`'s declared host-module function
|
|
1269
|
-
* leaves. Only declared paths may be rebound; everything else throws
|
|
1270
|
-
* `UndeclaredImportBindingError`. Source modules are frozen.
|
|
1271
|
-
*
|
|
1272
|
-
* Returns a fresh registry keyed by the same handle IDs the prefix assigned
|
|
1273
|
-
* at precompile time, with the new handler installed where provided.
|
|
1274
|
-
*
|
|
1275
|
-
* @param runImports
|
|
1276
|
-
* @param defaults
|
|
1277
|
-
* @param shape
|
|
1278
|
-
*/
|
|
1279
|
-
function extractRebindImports(runImports, defaults, shape) {
|
|
1280
|
-
if (runImports === void 0) return defaults;
|
|
1281
|
-
const merged = new Map(defaults);
|
|
1282
|
-
for (const [specifier, value] of Object.entries(runImports)) {
|
|
1283
|
-
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`);
|
|
1284
|
-
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)}`);
|
|
1285
|
-
if (shape.hostFunctionIds[specifier] === void 0) throw new UndeclaredImportBindingError(`import '${specifier}' was not declared at precompile time`);
|
|
1286
|
-
walkRebind(specifier, value, [], shape, merged);
|
|
1287
|
-
}
|
|
1288
|
-
return merged;
|
|
1289
|
-
}
|
|
1290
|
-
function walkRebind(specifier, node, path, shape, merged) {
|
|
1291
|
-
const fnIds = shape.hostFunctionIds[specifier];
|
|
1292
|
-
const dataPaths = shape.hostDataPaths[specifier];
|
|
1293
|
-
for (const [key, value] of Object.entries(node)) {
|
|
1294
|
-
if (value === void 0) continue;
|
|
1295
|
-
const newPath = [...path, key];
|
|
1296
|
-
const joined = newPath.join(".");
|
|
1297
|
-
if (typeof value === "function") {
|
|
1298
|
-
if (dataPaths.has(joined)) throw new UndeclaredImportBindingError(`import '${specifier}'.${joined} is a data leaf, not a function — data leaves cannot be rebound`);
|
|
1299
|
-
const id = fnIds[joined];
|
|
1300
|
-
if (id === void 0) throw new UndeclaredImportBindingError(`import '${specifier}'.${joined} was not declared at precompile time`);
|
|
1301
|
-
merged.set(id, value);
|
|
1302
|
-
continue;
|
|
1303
|
-
}
|
|
1304
|
-
if (isPlainObject(value)) {
|
|
1305
|
-
walkRebind(specifier, value, newPath, shape, merged);
|
|
1306
|
-
continue;
|
|
1307
|
-
}
|
|
1308
|
-
if (fnIds[joined] !== void 0 || dataPaths.has(joined)) throw new UndeclaredImportBindingError(`import '${specifier}'.${joined} can only be rebound with a function; got ${describeKind(value)}`);
|
|
1309
|
-
throw new UndeclaredImportBindingError(`import '${specifier}'.${joined} was not declared at precompile time`);
|
|
1310
|
-
}
|
|
1311
|
-
}
|
|
1312
|
-
/**
|
|
1313
|
-
* Generate the ESM source for a host module specifier. Walks `desc`
|
|
1314
|
-
* recursively and emits one `export const <name> = <expr>;` per top-level
|
|
1315
|
-
* entry. Function leaves become `__iso4_call(<id>, ...args)` stubs; data
|
|
1316
|
-
* leaves become JS literals.
|
|
1317
|
-
*
|
|
1318
|
-
* @param specifier
|
|
1319
|
-
* @param desc
|
|
1320
|
-
* @param registry
|
|
1321
|
-
* @param allocId
|
|
1322
|
-
* @param fnIds
|
|
1323
|
-
* @param dataPaths
|
|
1324
|
-
*/
|
|
1325
|
-
function generateHostModuleSource(specifier, desc, registry, allocId, fnIds, dataPaths) {
|
|
1326
|
-
const parts = [];
|
|
1327
|
-
for (const [key, value] of Object.entries(desc)) {
|
|
1328
|
-
if (value === void 0) continue;
|
|
1329
|
-
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`);
|
|
1330
|
-
const expr = emitValue(specifier, value, [key], registry, allocId, fnIds, dataPaths);
|
|
1331
|
-
if (key === "default") parts.push(`export default ${expr};`);
|
|
1332
|
-
else parts.push(`export const ${key} = ${expr};`);
|
|
1333
|
-
}
|
|
1334
|
-
return parts.join("\n");
|
|
1335
|
-
}
|
|
1336
|
-
function emitValue(specifier, value, path, registry, allocId, fnIds, dataPaths, seen = /* @__PURE__ */ new Set()) {
|
|
1337
|
-
if (typeof value === "function") {
|
|
1338
|
-
const id = allocId();
|
|
1339
|
-
registry.set(id, value);
|
|
1340
|
-
fnIds[path.join(".")] = id;
|
|
1341
|
-
return `(async (...args) => await globalThis.${BRIDGE_DISPATCH_GLOBAL}(${id}, ...args))`;
|
|
1342
|
-
}
|
|
1343
|
-
if (isPlainObject(value)) {
|
|
1344
|
-
if (seen.has(value)) throw new Error(`[@iso4/sandbox] imports['${specifier}'].${path.join(".")}: circular references are not supported in host-module shapes`);
|
|
1345
|
-
seen.add(value);
|
|
1346
|
-
const fields = [];
|
|
1347
|
-
for (const [key, child] of Object.entries(value)) {
|
|
1348
|
-
if (child === void 0) continue;
|
|
1349
|
-
const childExpr = emitValue(specifier, child, [...path, key], registry, allocId, fnIds, dataPaths, seen);
|
|
1350
|
-
fields.push(`${jsObjectKey(key)}: ${childExpr}`);
|
|
1351
|
-
}
|
|
1352
|
-
seen.delete(value);
|
|
1353
|
-
return `({ ${fields.join(", ")} })`;
|
|
1354
|
-
}
|
|
1355
|
-
dataPaths.add(path.join("."));
|
|
1356
|
-
return emitDataLiteral(specifier, value, path);
|
|
1357
|
-
}
|
|
1358
|
-
/**
|
|
1359
|
-
* Emit a `HostExportData` value as a JS expression that reproduces the
|
|
1360
|
-
* original value in the sandbox. Supports primitives, plain objects/arrays,
|
|
1361
|
-
* `BigInt`, `Uint8Array` — the same set the wire codec can carry back out.
|
|
1362
|
-
* `Date`, `Map`, `Set`, circular refs, and class instances throw with a
|
|
1363
|
-
* clear pointer.
|
|
1364
|
-
*
|
|
1365
|
-
* @param specifier
|
|
1366
|
-
* @param value
|
|
1367
|
-
* @param path
|
|
1368
|
-
* @param seen
|
|
1369
|
-
*/
|
|
1370
|
-
function emitDataLiteral(specifier, value, path, seen = /* @__PURE__ */ new Set()) {
|
|
1371
|
-
if (value === null) return "null";
|
|
1372
|
-
if (value === void 0) return "undefined";
|
|
1373
|
-
switch (typeof value) {
|
|
1374
|
-
case "boolean": return value ? "true" : "false";
|
|
1375
|
-
case "number":
|
|
1376
|
-
if (Number.isNaN(value)) return "NaN";
|
|
1377
|
-
if (!Number.isFinite(value)) return value > 0 ? "Infinity" : "-Infinity";
|
|
1378
|
-
return String(value);
|
|
1379
|
-
case "bigint": return `${value.toString()}n`;
|
|
1380
|
-
case "string": return JSON.stringify(value);
|
|
1381
|
-
}
|
|
1382
|
-
if (value instanceof Uint8Array) return `new Uint8Array([${Array.from(value).join(", ")}])`;
|
|
1383
|
-
if (value instanceof Date || value instanceof Map || value instanceof Set) throw new Error(`[@iso4/sandbox] imports['${specifier}'].${path.join(".")}: ${value.constructor.name} values are not supported as data leaves; supported: primitives, bigint, string, Uint8Array, plain objects/arrays`);
|
|
1384
|
-
if (typeof value === "object") {
|
|
1385
|
-
if (seen.has(value)) throw new Error(`[@iso4/sandbox] imports['${specifier}'].${path.join(".")}: circular references in data leaves are not supported`);
|
|
1386
|
-
seen.add(value);
|
|
1387
|
-
if (Array.isArray(value)) {
|
|
1388
|
-
const parts = value.map((item, i) => emitDataLiteral(specifier, item, [...path, String(i)], seen));
|
|
1389
|
-
seen.delete(value);
|
|
1390
|
-
return `[${parts.join(", ")}]`;
|
|
1391
|
-
}
|
|
1392
|
-
const proto = Object.getPrototypeOf(value);
|
|
1393
|
-
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`);
|
|
1394
|
-
const fields = [];
|
|
1395
|
-
for (const [key, child] of Object.entries(value)) fields.push(`${jsObjectKey(key)}: ${emitDataLiteral(specifier, child, [...path, key], seen)}`);
|
|
1396
|
-
seen.delete(value);
|
|
1397
|
-
return `({ ${fields.join(", ")} })`;
|
|
1398
|
-
}
|
|
1399
|
-
throw new Error(`[@iso4/sandbox] imports['${specifier}'].${path.join(".")}: unsupported data value of type ${describeKind(value)}`);
|
|
1400
|
-
}
|
|
1401
|
-
function isPlainObject(value) {
|
|
1402
|
-
if (value === null || typeof value !== "object") return false;
|
|
1403
|
-
if (Array.isArray(value)) return false;
|
|
1404
|
-
if (value instanceof Uint8Array || value instanceof Date) return false;
|
|
1405
|
-
if (value instanceof Map || value instanceof Set) return false;
|
|
1406
|
-
const proto = Object.getPrototypeOf(value);
|
|
1407
|
-
return proto === null || proto === Object.prototype;
|
|
1408
|
-
}
|
|
1409
|
-
const RESERVED_WORDS = new Set([
|
|
1410
|
-
"break",
|
|
1411
|
-
"case",
|
|
1412
|
-
"catch",
|
|
1413
|
-
"class",
|
|
1414
|
-
"const",
|
|
1415
|
-
"continue",
|
|
1416
|
-
"debugger",
|
|
1417
|
-
"default",
|
|
1418
|
-
"delete",
|
|
1419
|
-
"do",
|
|
1420
|
-
"else",
|
|
1421
|
-
"export",
|
|
1422
|
-
"extends",
|
|
1423
|
-
"finally",
|
|
1424
|
-
"for",
|
|
1425
|
-
"function",
|
|
1426
|
-
"if",
|
|
1427
|
-
"import",
|
|
1428
|
-
"in",
|
|
1429
|
-
"instanceof",
|
|
1430
|
-
"new",
|
|
1431
|
-
"return",
|
|
1432
|
-
"super",
|
|
1433
|
-
"switch",
|
|
1434
|
-
"this",
|
|
1435
|
-
"throw",
|
|
1436
|
-
"try",
|
|
1437
|
-
"typeof",
|
|
1438
|
-
"var",
|
|
1439
|
-
"void",
|
|
1440
|
-
"while",
|
|
1441
|
-
"with",
|
|
1442
|
-
"yield",
|
|
1443
|
-
"let",
|
|
1444
|
-
"static",
|
|
1445
|
-
"enum",
|
|
1446
|
-
"await",
|
|
1447
|
-
"implements",
|
|
1448
|
-
"package",
|
|
1449
|
-
"protected",
|
|
1450
|
-
"interface",
|
|
1451
|
-
"private",
|
|
1452
|
-
"public",
|
|
1453
|
-
"null",
|
|
1454
|
-
"true",
|
|
1455
|
-
"false"
|
|
1456
|
-
]);
|
|
1457
|
-
/**
|
|
1458
|
-
* Whether `name` can appear as a named ESM export. JS identifier rules plus
|
|
1459
|
-
* a reserved-word filter. `default` is handled separately by the emitter.
|
|
1460
|
-
* @param name
|
|
1461
|
-
*/
|
|
1462
|
-
function isValidExportIdentifier(name) {
|
|
1463
|
-
if (name === "default") return true;
|
|
1464
|
-
if (!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name)) return false;
|
|
1465
|
-
if (RESERVED_WORDS.has(name)) return false;
|
|
1466
|
-
return true;
|
|
1467
|
-
}
|
|
1468
|
-
/**
|
|
1469
|
-
* Emit `key` as a JS object property key: a bare identifier when possible,
|
|
1470
|
-
* otherwise a quoted string. Object keys (unlike export names) may be any
|
|
1471
|
-
* string, so this never rejects.
|
|
1472
|
-
* @param key
|
|
1473
|
-
*/
|
|
1474
|
-
function jsObjectKey(key) {
|
|
1475
|
-
if (/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key) && !RESERVED_WORDS.has(key)) return key;
|
|
1476
|
-
return JSON.stringify(key);
|
|
1477
|
-
}
|
|
1478
|
-
function describeKind(value) {
|
|
1479
|
-
if (value === null) return "null";
|
|
1480
|
-
if (Array.isArray(value)) return "array";
|
|
1481
|
-
return typeof value;
|
|
1482
|
-
}
|
|
1483
1645
|
//#endregion
|
|
1484
1646
|
//#region src/index.ts
|
|
1485
1647
|
/**
|
|
@@ -1526,30 +1688,21 @@ async function waitForSocket(socketPath, timeoutMs = 5e3) {
|
|
|
1526
1688
|
throw new Error(`[@iso4/sandbox] V8 process socket not available after ${timeoutMs}ms: ${socketPath}`);
|
|
1527
1689
|
}
|
|
1528
1690
|
/**
|
|
1529
|
-
* Map user-facing ResourceLimits to the wire-level encoding fields.
|
|
1530
|
-
* @param limits
|
|
1531
|
-
*/
|
|
1532
|
-
function toWireLimits(limits) {
|
|
1533
|
-
return {
|
|
1534
|
-
memoryMb: limits?.memoryMb ?? 64,
|
|
1535
|
-
cpuTimeMs: limits?.cpuTimeMs ?? 5e3,
|
|
1536
|
-
wallTimeMs: limits?.wallTimeMs ?? 3e4,
|
|
1537
|
-
maxExportBytes: limits?.maxExportBytes ?? 16 * 1024 * 1024,
|
|
1538
|
-
maxStdoutBytes: limits?.maxStdoutBytes ?? 1 * 1024 * 1024,
|
|
1539
|
-
maxStderrBytes: limits?.maxStderrBytes ?? 1 * 1024 * 1024,
|
|
1540
|
-
maxBridgeCallBytes: limits?.maxBridgeCallBytes ?? 16 * 1024 * 1024,
|
|
1541
|
-
maxBridgeCalls: limits?.maxBridgeCalls ?? 10
|
|
1542
|
-
};
|
|
1543
|
-
}
|
|
1544
|
-
/**
|
|
1545
1691
|
* The `RunResult` returned when a run is aborted — whether the signal was
|
|
1546
|
-
* already aborted at run entry or fired mid-flight (
|
|
1547
|
-
*
|
|
1548
|
-
*
|
|
1549
|
-
*
|
|
1692
|
+
* already aborted at run entry or fired mid-flight. `error` (code `ERR_ABORTED`)
|
|
1693
|
+
* is retained for backward compatibility; `reason` carries whatever was passed
|
|
1694
|
+
* to `abort(reason)`.
|
|
1695
|
+
*
|
|
1696
|
+
* When graceful termination (#36) succeeds, Rust sends a real `ERR_ABORTED`
|
|
1697
|
+
* Result and `from` carries its telemetry — duration, CPU time, bridge records,
|
|
1698
|
+
* and any logs produced before the abort landed — which is grafted onto the
|
|
1699
|
+
* aborted shape. When it falls back to socket teardown (or the signal was
|
|
1700
|
+
* already aborted at entry), no Result arrives from Rust, so `from` is omitted
|
|
1701
|
+
* and timings/`bridgeCalls` report zeros/empty.
|
|
1550
1702
|
* @param reason
|
|
1703
|
+
* @param from
|
|
1551
1704
|
*/
|
|
1552
|
-
function abortedResult(reason) {
|
|
1705
|
+
function abortedResult(reason, from) {
|
|
1553
1706
|
return {
|
|
1554
1707
|
status: "aborted",
|
|
1555
1708
|
ok: false,
|
|
@@ -1559,9 +1712,11 @@ function abortedResult(reason) {
|
|
|
1559
1712
|
message: "run was aborted"
|
|
1560
1713
|
},
|
|
1561
1714
|
reason,
|
|
1562
|
-
stdout: [],
|
|
1563
|
-
stderr: [],
|
|
1564
|
-
durationMs: 0
|
|
1715
|
+
stdout: from?.stdout ?? [],
|
|
1716
|
+
stderr: from?.stderr ?? [],
|
|
1717
|
+
durationMs: from?.durationMs ?? 0,
|
|
1718
|
+
cpuTimeMs: from?.cpuTimeMs ?? 0,
|
|
1719
|
+
bridgeCalls: from?.bridgeCalls ?? []
|
|
1565
1720
|
};
|
|
1566
1721
|
}
|
|
1567
1722
|
var SandboxImpl = class {
|
|
@@ -1582,22 +1737,21 @@ var SandboxImpl = class {
|
|
|
1582
1737
|
}
|
|
1583
1738
|
async run(options) {
|
|
1584
1739
|
if (options.signal?.aborted) return abortedResult(options.signal.reason);
|
|
1585
|
-
const {
|
|
1586
|
-
const { bindings,
|
|
1587
|
-
const allGlobals = registry.size > 0 ? {
|
|
1588
|
-
...bridgeGlobals,
|
|
1589
|
-
[BRIDGE_DISPATCH_GLOBAL]: createDispatchGlobal(registry)
|
|
1590
|
-
} : bridgeGlobals;
|
|
1591
|
-
const code = preamble ? `${preamble}\n${options.code}` : options.code;
|
|
1740
|
+
const { defs, dispatch } = processGlobals(options.globals ?? {});
|
|
1741
|
+
const { bindings, handlers } = processImports(options.imports);
|
|
1592
1742
|
try {
|
|
1593
1743
|
return await this.pool.withClient(async (client) => {
|
|
1594
|
-
|
|
1744
|
+
const decoded = decodeRunCompletionPayload((await client.runRawCode(options.code, {
|
|
1595
1745
|
filename: options.filename,
|
|
1596
|
-
limits:
|
|
1597
|
-
globals:
|
|
1746
|
+
limits: options.limits,
|
|
1747
|
+
globals: defs,
|
|
1748
|
+
dispatch,
|
|
1598
1749
|
imports: bindings,
|
|
1750
|
+
importDispatch: handlers,
|
|
1599
1751
|
signal: options.signal
|
|
1600
1752
|
})).result).result;
|
|
1753
|
+
if (options.signal?.aborted && decoded.status === "failed" && decoded.error.code === "ERR_ABORTED") return abortedResult(options.signal.reason, decoded);
|
|
1754
|
+
return decoded;
|
|
1601
1755
|
});
|
|
1602
1756
|
} catch (error) {
|
|
1603
1757
|
if (error instanceof RunAbortedError) return abortedResult(error.reason);
|
|
@@ -1605,23 +1759,27 @@ var SandboxImpl = class {
|
|
|
1605
1759
|
}
|
|
1606
1760
|
}
|
|
1607
1761
|
/**
|
|
1762
|
+
* @deprecated Renamed to {@link SandboxImpl.prepare}; kept as an alias.
|
|
1608
1763
|
* @param options
|
|
1609
1764
|
*/
|
|
1610
1765
|
async precompile(options) {
|
|
1766
|
+
return this.prepare(options);
|
|
1767
|
+
}
|
|
1768
|
+
/**
|
|
1769
|
+
* Pre-compile a prefix of code into a V8 startup snapshot. See
|
|
1770
|
+
* {@link Sandbox.prepare}.
|
|
1771
|
+
* @param options
|
|
1772
|
+
*/
|
|
1773
|
+
async prepare(options) {
|
|
1611
1774
|
return this.pool.withClient(async (client) => {
|
|
1612
1775
|
const rawGlobals = options.globals ?? {};
|
|
1613
|
-
const {
|
|
1614
|
-
const { bindings,
|
|
1615
|
-
const allGlobals = registry.size > 0 ? {
|
|
1616
|
-
...bridgeGlobals,
|
|
1617
|
-
[BRIDGE_DISPATCH_GLOBAL]: createDispatchGlobal(registry)
|
|
1618
|
-
} : bridgeGlobals;
|
|
1619
|
-
const code = preamble ? `${preamble}\n${options.code}` : options.code;
|
|
1776
|
+
const { defs } = processGlobals(rawGlobals);
|
|
1777
|
+
const { bindings, handlers } = processImports(options.imports);
|
|
1620
1778
|
const result = decodePrecompileResultPayload(await client.precompile({
|
|
1621
|
-
code,
|
|
1779
|
+
code: options.code,
|
|
1622
1780
|
filename: options.filename,
|
|
1623
|
-
limits:
|
|
1624
|
-
globals:
|
|
1781
|
+
limits: options.limits,
|
|
1782
|
+
globals: defs,
|
|
1625
1783
|
imports: bindings
|
|
1626
1784
|
}));
|
|
1627
1785
|
if (!result.ok) {
|
|
@@ -1631,7 +1789,7 @@ var SandboxImpl = class {
|
|
|
1631
1789
|
if (result.error.stack) err.stack = result.error.stack;
|
|
1632
1790
|
throw err;
|
|
1633
1791
|
}
|
|
1634
|
-
return new PrefixImpl(result.prefixId, this.pool, rawGlobals,
|
|
1792
|
+
return new PrefixImpl(result.prefixId, this.pool, rawGlobals, handlers);
|
|
1635
1793
|
});
|
|
1636
1794
|
}
|
|
1637
1795
|
async dispose() {
|
|
@@ -1658,30 +1816,35 @@ var PrefixImpl = class {
|
|
|
1658
1816
|
*/
|
|
1659
1817
|
defaultGlobals;
|
|
1660
1818
|
/**
|
|
1661
|
-
*
|
|
1662
|
-
* Same rebinding rules as `defaultGlobals` — a
|
|
1663
|
-
* a subset of function leaves; everything else
|
|
1664
|
-
* modules and data leaves are frozen in the
|
|
1665
|
-
* here.
|
|
1819
|
+
* Host-import function-leaf handlers declared at precompile time, keyed by
|
|
1820
|
+
* `(specifier, path)`. Same rebinding rules as `defaultGlobals` — a
|
|
1821
|
+
* `prefix.run()` may override a subset of function leaves; everything else
|
|
1822
|
+
* falls back to these. Source modules and data leaves are frozen in the
|
|
1823
|
+
* snapshot and not represented here. The declared shape itself lives with
|
|
1824
|
+
* the prefix in the Rust runtime, which enforces `ERR_UNDECLARED_BINDING`
|
|
1825
|
+
* for rebind attempts outside it.
|
|
1666
1826
|
*/
|
|
1667
|
-
|
|
1668
|
-
/**
|
|
1669
|
-
* Declared shape captured at precompile time. Drives type-level rebinding
|
|
1670
|
-
* via `RebindImports<M>` and runtime `ERR_UNDECLARED_BINDING` enforcement
|
|
1671
|
-
* inside `extractRebindImports`.
|
|
1672
|
-
*/
|
|
1673
|
-
declaredImportShape;
|
|
1827
|
+
defaultImportHandlers;
|
|
1674
1828
|
_alive = true;
|
|
1675
|
-
constructor(id, pool, defaultGlobals,
|
|
1829
|
+
constructor(id, pool, defaultGlobals, defaultImportHandlers) {
|
|
1676
1830
|
this.id = id;
|
|
1677
1831
|
this.pool = pool;
|
|
1678
1832
|
this.defaultGlobals = defaultGlobals;
|
|
1679
|
-
this.
|
|
1680
|
-
this.declaredImportShape = declaredImportShape;
|
|
1833
|
+
this.defaultImportHandlers = defaultImportHandlers;
|
|
1681
1834
|
}
|
|
1682
1835
|
get alive() {
|
|
1683
1836
|
return this._alive;
|
|
1684
1837
|
}
|
|
1838
|
+
/**
|
|
1839
|
+
* Execute dynamic code against this prefix's snapshot. See
|
|
1840
|
+
* {@link Prefix.execute}.
|
|
1841
|
+
*/
|
|
1842
|
+
async execute(options) {
|
|
1843
|
+
return this.run(options);
|
|
1844
|
+
}
|
|
1845
|
+
/**
|
|
1846
|
+
* @deprecated Renamed to {@link PrefixImpl.execute}; kept as an alias.
|
|
1847
|
+
*/
|
|
1685
1848
|
async run(options) {
|
|
1686
1849
|
if (!this._alive) return {
|
|
1687
1850
|
status: "failed",
|
|
@@ -1693,13 +1856,15 @@ var PrefixImpl = class {
|
|
|
1693
1856
|
},
|
|
1694
1857
|
stdout: [],
|
|
1695
1858
|
stderr: [],
|
|
1696
|
-
durationMs: 0
|
|
1859
|
+
durationMs: 0,
|
|
1860
|
+
cpuTimeMs: 0,
|
|
1861
|
+
bridgeCalls: []
|
|
1697
1862
|
};
|
|
1698
1863
|
if (options.signal?.aborted) return abortedResult(options.signal.reason);
|
|
1699
|
-
const
|
|
1700
|
-
let
|
|
1864
|
+
const { defs, dispatch } = extractBridgeGlobals(options.globals ?? {}, this.defaultGlobals);
|
|
1865
|
+
let merged;
|
|
1701
1866
|
try {
|
|
1702
|
-
|
|
1867
|
+
merged = mergeRebindImports(options.imports, this.defaultImportHandlers);
|
|
1703
1868
|
} catch (e) {
|
|
1704
1869
|
if (e instanceof UndeclaredImportBindingError) return {
|
|
1705
1870
|
status: "failed",
|
|
@@ -1711,24 +1876,27 @@ var PrefixImpl = class {
|
|
|
1711
1876
|
},
|
|
1712
1877
|
stdout: [],
|
|
1713
1878
|
stderr: [],
|
|
1714
|
-
durationMs: 0
|
|
1879
|
+
durationMs: 0,
|
|
1880
|
+
cpuTimeMs: 0,
|
|
1881
|
+
bridgeCalls: []
|
|
1715
1882
|
};
|
|
1716
1883
|
throw e;
|
|
1717
1884
|
}
|
|
1718
|
-
const allGlobals = registry.size > 0 ? {
|
|
1719
|
-
...bridgeGlobals,
|
|
1720
|
-
[BRIDGE_DISPATCH_GLOBAL]: createDispatchGlobal(registry)
|
|
1721
|
-
} : bridgeGlobals;
|
|
1722
1885
|
try {
|
|
1723
1886
|
return await this.pool.withClient(async (client) => {
|
|
1724
|
-
|
|
1887
|
+
const decoded = decodeRunCompletionPayload((await client.prefixRun({
|
|
1725
1888
|
prefixId: this.id,
|
|
1726
1889
|
code: options.code,
|
|
1727
1890
|
filename: options.filename,
|
|
1728
|
-
limits:
|
|
1729
|
-
globals:
|
|
1891
|
+
limits: options.limits,
|
|
1892
|
+
globals: defs,
|
|
1893
|
+
dispatch,
|
|
1894
|
+
importRebinds: merged.rebinds,
|
|
1895
|
+
importDispatch: merged.handlers,
|
|
1730
1896
|
signal: options.signal
|
|
1731
1897
|
})).result).result;
|
|
1898
|
+
if (options.signal?.aborted && decoded.status === "failed" && decoded.error.code === "ERR_ABORTED") return abortedResult(options.signal.reason, decoded);
|
|
1899
|
+
return decoded;
|
|
1732
1900
|
});
|
|
1733
1901
|
} catch (error) {
|
|
1734
1902
|
if (error instanceof RunAbortedError) return abortedResult(error.reason);
|