@iso4/sandbox 0.3.0 → 0.4.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.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:
@@ -398,6 +439,11 @@ var WireWriter = class {
398
439
  return this;
399
440
  }
400
441
  if (typeof value === "object") {
442
+ const proto = Object.getPrototypeOf(value);
443
+ if (proto !== null && proto !== Object.prototype) {
444
+ const name = value.constructor?.name ?? "(unknown)";
445
+ throw new TypeError(`[iso4] encodeWireValue: cannot encode ${name} instance; only primitives, bigint, string, Uint8Array, and plain objects/arrays cross the boundary — copy the data into a plain object`);
446
+ }
401
447
  if (this.visiting.has(value)) throw new TypeError("[iso4] encodeWireValue: cyclic or self-referential structure");
402
448
  this.visiting.add(value);
403
449
  const entries = Object.entries(value).filter(([k]) => k !== "__proto__");
@@ -545,6 +591,16 @@ function encodeAuthenticatePayload(auth) {
545
591
  token.copy(payload, 2);
546
592
  return payload;
547
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
+ };
548
604
  var PayloadWriter = class {
549
605
  parts = [];
550
606
  writeU8(n) {
@@ -577,23 +633,90 @@ var PayloadWriter = class {
577
633
  }
578
634
  return this;
579
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
+ }
580
665
  writeImports(imports) {
581
666
  this.writeU32(imports.length);
582
667
  for (const imp of imports) {
583
668
  this.writeString(imp.specifier);
584
- this.writeString(imp.source);
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);
585
708
  }
586
709
  return this;
587
710
  }
588
711
  writeResourceLimits(limits) {
589
- this.writeU32(limits.memoryMb ?? 0);
590
- this.writeU32(limits.cpuTimeMs ?? 0);
591
- this.writeU32(limits.wallTimeMs ?? 0);
592
- this.writeU32(limits.maxExportBytes ?? 0);
593
- this.writeU32(limits.maxStdoutBytes ?? 0);
594
- this.writeU32(limits.maxStderrBytes ?? 0);
595
- this.writeU32(limits.maxBridgeCallBytes ?? 0);
596
- this.writeU32(limits.maxBridgeCalls ?? 10);
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);
597
720
  return this;
598
721
  }
599
722
  toBuffer() {
@@ -605,12 +728,7 @@ var PayloadWriter = class {
605
728
  * @param options
606
729
  */
607
730
  function encodeRunPayload(options) {
608
- const w = new PayloadWriter().writeU32(options.runId).writeString(options.code).writeOptionalString(options.filename).writeResourceLimits(options.limits ?? {});
609
- const globals = options.globals ?? [];
610
- w.writeU32(globals.length);
611
- for (const name of globals) w.writeString(name);
612
- w.writeImports(options.imports ?? []);
613
- 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();
614
732
  }
615
733
  /**
616
734
  * Encode a `PrecompilePayload` per `docs/protocol.md` §5.2.
@@ -618,12 +736,7 @@ function encodeRunPayload(options) {
618
736
  * @param options
619
737
  */
620
738
  function encodePrecompilePayload(options) {
621
- const w = new PayloadWriter().writeString(options.code).writeOptionalString(options.filename).writeResourceLimits(options.limits ?? {});
622
- const globals = options.globals ?? [];
623
- w.writeU32(globals.length);
624
- for (const name of globals) w.writeString(name);
625
- w.writeImports(options.imports ?? []);
626
- return w.toBuffer();
739
+ return new PayloadWriter().writeString(options.code).writeOptionalString(options.filename).writeResourceLimits(options.limits ?? {}).writeGlobalDefs(options.globals ?? []).writeImports(options.imports ?? []).toBuffer();
627
740
  }
628
741
  /**
629
742
  * Encode a `PrefixRunPayload` per `docs/protocol.md` §5.2.
@@ -632,12 +745,7 @@ function encodePrecompilePayload(options) {
632
745
  * @param options
633
746
  */
634
747
  function encodePrefixRunPayload(options) {
635
- const w = new PayloadWriter().writeU32(options.runId).writeString(options.prefixId).writeString(options.code).writeOptionalString(options.filename).writeResourceLimits(options.limits ?? {});
636
- const globals = options.globals ?? [];
637
- w.writeU32(globals.length);
638
- for (const name of globals) w.writeString(name);
639
- w.writeImports(options.imports ?? []);
640
- 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();
641
749
  }
642
750
  /**
643
751
  * Encode a `DisposePrefix` payload — just the PrefixId string.
@@ -647,6 +755,15 @@ function encodeDisposePrefixPayload(prefixId) {
647
755
  return new PayloadWriter().writeString(prefixId).toBuffer();
648
756
  }
649
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
+ /**
650
767
  * Decode a `BridgeCallPayload` from a `BridgeCall` frame sent by Rust.
651
768
  * Per `docs/protocol.md` §5.4.
652
769
  * @param buf
@@ -789,13 +906,281 @@ function formatByte(byte) {
789
906
  return `0x${byte.toString(16).padStart(2, "0")}`;
790
907
  }
791
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
792
1163
  //#region src/client.ts
793
1164
  /**
794
- * Thrown out of a run when its `AbortSignal` fires mid-flight. The connection
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
795
1179
  * is torn down (so the Rust isolate is reclaimed) before this propagates, and
796
1180
  * the client is marked unusable so the pool replaces it rather than reusing a
797
1181
  * half-dead slot. `index.ts` catches this and synthesizes the `ERR_ABORTED`
798
- * `RunResult`.
1182
+ * `RunResult`. When the graceful path succeeds instead, no error is thrown —
1183
+ * the real `ERR_ABORTED` Result flows back through `drainFrames`.
799
1184
  */
800
1185
  var RunAbortedError = class extends Error {
801
1186
  /**
@@ -857,17 +1242,16 @@ var RuntimeIpcClient = class RuntimeIpcClient {
857
1242
  }
858
1243
  async runRawCode(code, options) {
859
1244
  if (this.disposed) throw new Error("runtime IPC client is disposed");
860
- const globals = options?.globals ?? {};
861
- const globalNames = Object.keys(globals);
1245
+ const runId = this.nextRunIdValue();
862
1246
  await this.write(encodeTsToRustFrame(TsToRustMessageTypes.Run, encodeRunPayload({
863
- runId: this.nextRunIdValue(),
1247
+ runId,
864
1248
  code,
865
1249
  filename: options?.filename,
866
1250
  limits: options?.limits,
867
- globals: globalNames,
1251
+ globals: options?.globals,
868
1252
  imports: options?.imports
869
1253
  })));
870
- return this.drainUntilResult(makeDispatcher(globals), options?.signal);
1254
+ return this.drainUntilResult(makeDispatcher(options?.dispatch ?? {}, options?.importDispatch), runId, options?.signal);
871
1255
  }
872
1256
  async precompile(options) {
873
1257
  if (this.disposed) throw new Error("runtime IPC client is disposed");
@@ -875,7 +1259,7 @@ var RuntimeIpcClient = class RuntimeIpcClient {
875
1259
  code: options.code,
876
1260
  filename: options.filename,
877
1261
  limits: options.limits,
878
- globals: Object.keys(options.globals ?? {}),
1262
+ globals: options.globals,
879
1263
  imports: options.imports
880
1264
  })));
881
1265
  for await (const frame of this.reader) {
@@ -886,18 +1270,17 @@ var RuntimeIpcClient = class RuntimeIpcClient {
886
1270
  }
887
1271
  async prefixRun(options) {
888
1272
  if (this.disposed) throw new Error("runtime IPC client is disposed");
889
- const globals = options.globals ?? {};
890
- const globalNames = Object.keys(globals);
1273
+ const runId = this.nextRunIdValue();
891
1274
  await this.write(encodeTsToRustFrame(TsToRustMessageTypes.PrefixRun, encodePrefixRunPayload({
892
1275
  prefixId: options.prefixId,
893
1276
  code: options.code,
894
1277
  filename: options.filename,
895
1278
  limits: options.limits,
896
- globals: globalNames,
897
- imports: options.imports,
898
- runId: this.nextRunIdValue()
1279
+ globals: options.globals,
1280
+ importRebinds: options.importRebinds,
1281
+ runId
899
1282
  })));
900
- return this.drainUntilResult(makeDispatcher(globals), options.signal);
1283
+ return this.drainUntilResult(makeDispatcher(options.dispatch ?? {}, options.importDispatch), runId, options.signal);
901
1284
  }
902
1285
  async disposePrefix(prefixId) {
903
1286
  if (this.disposed) return;
@@ -930,25 +1313,40 @@ var RuntimeIpcClient = class RuntimeIpcClient {
930
1313
  * continue to completion. Rust silently ignores any late `BridgeResponse`
931
1314
  * that arrives after the run has completed (see session.rs).
932
1315
  *
933
- * ── In-flight abort ──────────────────────────────────────────────────────
1316
+ * ── In-flight abort (graceful terminate, #36) ─────────────────────────────
934
1317
  * When `signal` fires mid-run — including while a bridge call is in flight —
935
- * we tear the connection down immediately (`abortConnection`): the reader is
936
- * closed so this loop throws, and the socket is destroyed so the Rust side
937
- * observes EOF and reclaims the isolate promptly (rather than waiting for
938
- * `wallTimeMs`). The loop then throws `RunAbortedError`, which `index.ts`
939
- * maps to an `ERR_ABORTED` `RunResult`. Any late `BridgeResponse` written by
940
- * an orphaned handler after this point fails silently (the socket is gone),
941
- * so the sandbox never observes a return value for the in-flight call.
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.
942
1334
  * @param dispatcher
1335
+ * @param runId
943
1336
  * @param signal
944
1337
  */
945
- async drainUntilResult(dispatcher, signal) {
1338
+ async drainUntilResult(dispatcher, runId, signal) {
946
1339
  if (signal?.aborted) {
947
1340
  this.abortConnection();
948
1341
  throw new RunAbortedError(signal.reason);
949
1342
  }
1343
+ let graceTimer;
950
1344
  const onAbort = () => {
951
- this.abortConnection();
1345
+ this.write(encodeTsToRustFrame(TsToRustMessageTypes.Terminate, encodeTerminatePayload(runId))).catch(() => {});
1346
+ graceTimer = setTimeout(() => {
1347
+ this.abortConnection();
1348
+ }, TERMINATE_GRACE_MS);
1349
+ graceTimer.unref?.();
952
1350
  };
953
1351
  signal?.addEventListener("abort", onAbort, { once: true });
954
1352
  try {
@@ -957,6 +1355,7 @@ var RuntimeIpcClient = class RuntimeIpcClient {
957
1355
  if (signal?.aborted) throw new RunAbortedError(signal.reason);
958
1356
  throw error;
959
1357
  } finally {
1358
+ if (graceTimer !== void 0) clearTimeout(graceTimer);
960
1359
  signal?.removeEventListener("abort", onAbort);
961
1360
  }
962
1361
  }
@@ -985,6 +1384,8 @@ var RuntimeIpcClient = class RuntimeIpcClient {
985
1384
  else {
986
1385
  const { callId } = call;
987
1386
  dispatcher({
1387
+ targetKind: call.targetKind,
1388
+ specifier: call.specifier,
988
1389
  exportName: call.exportName,
989
1390
  args: call.args
990
1391
  }).then((value) => {
@@ -1018,18 +1419,24 @@ var RuntimeIpcClient = class RuntimeIpcClient {
1018
1419
  }
1019
1420
  };
1020
1421
  /**
1021
- * Build a dispatcher that looks up a handler by `exportName` in the
1022
- * per-run globals map. Host-module imports are bridged through the same
1023
- * map via the reserved `__iso4_call` global, so a single lookup table
1024
- * handles every bridge call.
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.
1025
1426
  *
1026
- * Returns `undefined` when the map is empty so the loop short-circuits to
1427
+ * Returns `undefined` when both maps are empty so the loop short-circuits to
1027
1428
  * an "unconfigured bridge" error response.
1028
1429
  * @param globals
1430
+ * @param imports
1029
1431
  */
1030
- function makeDispatcher(globals) {
1031
- if (Object.keys(globals).length === 0) return void 0;
1032
- 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
+ }
1033
1440
  const handler = globals[exportName];
1034
1441
  if (handler === void 0) throw new Error(`no handler configured for bridge global '${exportName}'`);
1035
1442
  return handler(...args);
@@ -1128,353 +1535,113 @@ var ConnectionPool = class {
1128
1535
  function isBridgeWithShim(v) {
1129
1536
  return typeof v === "object" && v !== null && v.kind === "bridge-with-shim";
1130
1537
  }
1538
+ function isDataGlobal(v) {
1539
+ return typeof v === "object" && v !== null && v.kind === "data";
1540
+ }
1131
1541
  /**
1132
- * Split a `HostGlobals` map into:
1133
- * - `bridgeGlobals`: plain functions sent to Rust as bridge stubs.
1134
- * - `HostExportFunction` → registered under its own name.
1135
- * - `BridgeWithShim` handler → registered under `__iso4_<name>_h`.
1136
- * - `preamble`: JS source prepended to the user's code.
1137
- * - `string` → `globalThis["name"] = (<expr>)`
1138
- * - `BridgeWithShim` → wrapper that calls the private stub and passes the
1139
- * result through the shim: `async (...args) => await (shim)(await __iso4_<name>_h(...args))`
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`.
1140
1560
  * @param globals
1141
1561
  */
1142
1562
  function processGlobals(globals) {
1143
- const bridgeGlobals = {};
1144
- const parts = [];
1145
- for (const [name, value] of Object.entries(globals)) if (typeof value === "function") bridgeGlobals[name] = value;
1146
- else if (typeof value === "string") parts.push(`globalThis[${JSON.stringify(name)}] = (${value})`);
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
+ });
1147
1581
  else if (isBridgeWithShim(value)) {
1148
- const privateKey = `__iso4_${name}_h`;
1149
- bridgeGlobals[privateKey] = value.handler;
1150
- parts.push(`globalThis[${JSON.stringify(name)}] = async (...args) => await (${value.shim})(await ${privateKey}(...args))`);
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;
1151
1590
  }
1152
1591
  return {
1153
- bridgeGlobals,
1154
- preamble: parts.length > 0 ? parts.join("\n") : void 0
1592
+ defs,
1593
+ dispatch
1155
1594
  };
1156
1595
  }
1157
1596
  /**
1158
1597
  * Resolve bridge globals for a `prefix.run()` call.
1159
1598
  *
1160
- * The preamble is already compiled into the snapshot — only the bridge
1161
- * function pointers need resolving. Shimmed globals are routed to their
1162
- * private `__iso4_<name>_h` key so rebinding updates the handler the shim
1163
- * calls, without touching the shim itself.
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.
1164
1605
  * @param runGlobals
1165
1606
  * @param precompileGlobals
1166
1607
  */
1167
1608
  function extractBridgeGlobals(runGlobals, precompileGlobals) {
1168
- const out = {};
1609
+ const defs = [];
1610
+ const dispatch = {};
1169
1611
  for (const [name, value] of Object.entries(precompileGlobals)) {
1170
- if (typeof value === "string") continue;
1612
+ if (typeof value === "string" || isDataGlobal(value)) continue;
1171
1613
  if (isBridgeWithShim(value)) {
1172
- const privateKey = `__iso4_${name}_h`;
1614
+ const handlerName = shimHandlerName(name);
1173
1615
  const override = runGlobals[name];
1174
- out[privateKey] = typeof override === "function" ? override : value.handler;
1616
+ defs.push({
1617
+ kind: "bridge",
1618
+ name: handlerName
1619
+ });
1620
+ dispatch[handlerName] = typeof override === "function" ? override : value.handler;
1175
1621
  } else if (typeof value === "function") {
1176
1622
  const override = runGlobals[name];
1177
- out[name] = typeof override === "function" ? override : value;
1623
+ defs.push({
1624
+ kind: "bridge",
1625
+ name
1626
+ });
1627
+ dispatch[name] = typeof override === "function" ? override : value;
1178
1628
  }
1179
1629
  }
1180
1630
  for (const [name, override] of Object.entries(runGlobals)) {
1181
1631
  if (name in precompileGlobals) continue;
1182
- if (typeof override === "function") out[name] = override;
1183
- }
1184
- return out;
1185
- }
1186
- //#endregion
1187
- //#region src/imports.ts
1188
- /**
1189
- * The reserved global name of the bridge dispatcher. User globals may not
1190
- * use this name. The generated host-module source calls it as
1191
- * `globalThis.__iso4_call(id, ...args)`.
1192
- */
1193
- const BRIDGE_DISPATCH_GLOBAL = "__iso4_call";
1194
- /**
1195
- * Thrown when the host's import configuration is structurally invalid
1196
- * (mixed types, unsupported data values, undeclared rebindings, …).
1197
- * `PrefixImpl.run` converts the undeclared-binding variant into an
1198
- * `ERR_UNDECLARED_BINDING` `RunResult`, matching the globals path.
1199
- */
1200
- var UndeclaredImportBindingError = class extends Error {
1201
- code = "ERR_UNDECLARED_BINDING";
1202
- constructor(message) {
1203
- super(message);
1204
- this.name = "UndeclaredImportBindingError";
1205
- }
1206
- };
1207
- /**
1208
- * Build the `__iso4_call` global handler that backs all host-module
1209
- * function leaves for a run. It peels the leading handle ID and routes to
1210
- * the registry.
1211
- * @param registry
1212
- */
1213
- function createDispatchGlobal(registry) {
1214
- return (...args) => {
1215
- const id = args[0];
1216
- const fn = registry.get(id);
1217
- if (fn === void 0) throw new Error(`[@iso4/sandbox] no host handler for import handle ${String(id)}`);
1218
- return fn(...args.slice(1));
1219
- };
1220
- }
1221
- function processImports(imports) {
1222
- const shape = {
1223
- sourceSpecifiers: /* @__PURE__ */ new Set(),
1224
- hostFunctionIds: {},
1225
- hostDataPaths: {}
1226
- };
1227
- if (imports === void 0) return {
1228
- bindings: [],
1229
- registry: /* @__PURE__ */ new Map(),
1230
- shape
1231
- };
1232
- const bindings = [];
1233
- const registry = /* @__PURE__ */ new Map();
1234
- let nextId = 0;
1235
- const allocId = () => nextId++;
1236
- for (const [specifier, value] of Object.entries(imports)) {
1237
- if (typeof value === "string") {
1238
- bindings.push({
1239
- specifier,
1240
- source: value
1632
+ if (typeof override === "function") {
1633
+ defs.push({
1634
+ kind: "bridge",
1635
+ name
1241
1636
  });
1242
- shape.sourceSpecifiers.add(specifier);
1243
- continue;
1637
+ dispatch[name] = override;
1244
1638
  }
1245
- 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)}`);
1246
- const fnIds = {};
1247
- const dataPaths = /* @__PURE__ */ new Set();
1248
- const source = generateHostModuleSource(specifier, value, registry, allocId, fnIds, dataPaths);
1249
- bindings.push({
1250
- specifier,
1251
- source
1252
- });
1253
- shape.hostFunctionIds[specifier] = fnIds;
1254
- shape.hostDataPaths[specifier] = dataPaths;
1255
1639
  }
1256
1640
  return {
1257
- bindings,
1258
- registry,
1259
- shape
1641
+ defs,
1642
+ dispatch
1260
1643
  };
1261
1644
  }
1262
- /**
1263
- * Override the handlers behind a `Prefix`'s declared host-module function
1264
- * leaves. Only declared paths may be rebound; everything else throws
1265
- * `UndeclaredImportBindingError`. Source modules are frozen.
1266
- *
1267
- * Returns a fresh registry keyed by the same handle IDs the prefix assigned
1268
- * at precompile time, with the new handler installed where provided.
1269
- *
1270
- * @param runImports
1271
- * @param defaults
1272
- * @param shape
1273
- */
1274
- function extractRebindImports(runImports, defaults, shape) {
1275
- if (runImports === void 0) return defaults;
1276
- const merged = new Map(defaults);
1277
- for (const [specifier, value] of Object.entries(runImports)) {
1278
- 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`);
1279
- 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)}`);
1280
- if (shape.hostFunctionIds[specifier] === void 0) throw new UndeclaredImportBindingError(`import '${specifier}' was not declared at precompile time`);
1281
- walkRebind(specifier, value, [], shape, merged);
1282
- }
1283
- return merged;
1284
- }
1285
- function walkRebind(specifier, node, path, shape, merged) {
1286
- const fnIds = shape.hostFunctionIds[specifier];
1287
- const dataPaths = shape.hostDataPaths[specifier];
1288
- for (const [key, value] of Object.entries(node)) {
1289
- if (value === void 0) continue;
1290
- const newPath = [...path, key];
1291
- const joined = newPath.join(".");
1292
- if (typeof value === "function") {
1293
- if (dataPaths.has(joined)) throw new UndeclaredImportBindingError(`import '${specifier}'.${joined} is a data leaf, not a function — data leaves cannot be rebound`);
1294
- const id = fnIds[joined];
1295
- if (id === void 0) throw new UndeclaredImportBindingError(`import '${specifier}'.${joined} was not declared at precompile time`);
1296
- merged.set(id, value);
1297
- continue;
1298
- }
1299
- if (isPlainObject(value)) {
1300
- walkRebind(specifier, value, newPath, shape, merged);
1301
- continue;
1302
- }
1303
- if (fnIds[joined] !== void 0 || dataPaths.has(joined)) throw new UndeclaredImportBindingError(`import '${specifier}'.${joined} can only be rebound with a function; got ${describeKind(value)}`);
1304
- throw new UndeclaredImportBindingError(`import '${specifier}'.${joined} was not declared at precompile time`);
1305
- }
1306
- }
1307
- /**
1308
- * Generate the ESM source for a host module specifier. Walks `desc`
1309
- * recursively and emits one `export const <name> = <expr>;` per top-level
1310
- * entry. Function leaves become `__iso4_call(<id>, ...args)` stubs; data
1311
- * leaves become JS literals.
1312
- *
1313
- * @param specifier
1314
- * @param desc
1315
- * @param registry
1316
- * @param allocId
1317
- * @param fnIds
1318
- * @param dataPaths
1319
- */
1320
- function generateHostModuleSource(specifier, desc, registry, allocId, fnIds, dataPaths) {
1321
- const parts = [];
1322
- for (const [key, value] of Object.entries(desc)) {
1323
- if (value === void 0) continue;
1324
- 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`);
1325
- const expr = emitValue(specifier, value, [key], registry, allocId, fnIds, dataPaths);
1326
- if (key === "default") parts.push(`export default ${expr};`);
1327
- else parts.push(`export const ${key} = ${expr};`);
1328
- }
1329
- return parts.join("\n");
1330
- }
1331
- function emitValue(specifier, value, path, registry, allocId, fnIds, dataPaths, seen = /* @__PURE__ */ new Set()) {
1332
- if (typeof value === "function") {
1333
- const id = allocId();
1334
- registry.set(id, value);
1335
- fnIds[path.join(".")] = id;
1336
- return `(async (...args) => await globalThis.${BRIDGE_DISPATCH_GLOBAL}(${id}, ...args))`;
1337
- }
1338
- if (isPlainObject(value)) {
1339
- if (seen.has(value)) throw new Error(`[@iso4/sandbox] imports['${specifier}'].${path.join(".")}: circular references are not supported in host-module shapes`);
1340
- seen.add(value);
1341
- const fields = [];
1342
- for (const [key, child] of Object.entries(value)) {
1343
- if (child === void 0) continue;
1344
- const childExpr = emitValue(specifier, child, [...path, key], registry, allocId, fnIds, dataPaths, seen);
1345
- fields.push(`${jsObjectKey(key)}: ${childExpr}`);
1346
- }
1347
- seen.delete(value);
1348
- return `({ ${fields.join(", ")} })`;
1349
- }
1350
- dataPaths.add(path.join("."));
1351
- return emitDataLiteral(specifier, value, path);
1352
- }
1353
- /**
1354
- * Emit a `HostExportData` value as a JS expression that reproduces the
1355
- * original value in the sandbox. Supports primitives, plain objects/arrays,
1356
- * `Date`, `BigInt`, `Uint8Array`. `Map`, `Set`, circular refs, and class
1357
- * instances throw with a clear pointer.
1358
- *
1359
- * @param specifier
1360
- * @param value
1361
- * @param path
1362
- * @param seen
1363
- */
1364
- function emitDataLiteral(specifier, value, path, seen = /* @__PURE__ */ new Set()) {
1365
- if (value === null) return "null";
1366
- if (value === void 0) return "undefined";
1367
- switch (typeof value) {
1368
- case "boolean": return value ? "true" : "false";
1369
- case "number":
1370
- if (Number.isNaN(value)) return "NaN";
1371
- if (!Number.isFinite(value)) return value > 0 ? "Infinity" : "-Infinity";
1372
- return String(value);
1373
- case "bigint": return `${value.toString()}n`;
1374
- case "string": return JSON.stringify(value);
1375
- }
1376
- if (value instanceof Uint8Array) return `new Uint8Array([${Array.from(value).join(", ")}])`;
1377
- if (value instanceof Date) return `new Date(${value.getTime()})`;
1378
- 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`);
1379
- if (typeof value === "object") {
1380
- if (seen.has(value)) throw new Error(`[@iso4/sandbox] imports['${specifier}'].${path.join(".")}: circular references in data leaves are not supported`);
1381
- seen.add(value);
1382
- if (Array.isArray(value)) {
1383
- const parts = value.map((item, i) => emitDataLiteral(specifier, item, [...path, String(i)], seen));
1384
- seen.delete(value);
1385
- return `[${parts.join(", ")}]`;
1386
- }
1387
- const proto = Object.getPrototypeOf(value);
1388
- 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`);
1389
- const fields = [];
1390
- for (const [key, child] of Object.entries(value)) fields.push(`${jsObjectKey(key)}: ${emitDataLiteral(specifier, child, [...path, key], seen)}`);
1391
- seen.delete(value);
1392
- return `({ ${fields.join(", ")} })`;
1393
- }
1394
- throw new Error(`[@iso4/sandbox] imports['${specifier}'].${path.join(".")}: unsupported data value of type ${describeKind(value)}`);
1395
- }
1396
- function isPlainObject(value) {
1397
- if (value === null || typeof value !== "object") return false;
1398
- if (Array.isArray(value)) return false;
1399
- if (value instanceof Uint8Array || value instanceof Date) return false;
1400
- if (value instanceof Map || value instanceof Set) return false;
1401
- const proto = Object.getPrototypeOf(value);
1402
- return proto === null || proto === Object.prototype;
1403
- }
1404
- const RESERVED_WORDS = new Set([
1405
- "break",
1406
- "case",
1407
- "catch",
1408
- "class",
1409
- "const",
1410
- "continue",
1411
- "debugger",
1412
- "default",
1413
- "delete",
1414
- "do",
1415
- "else",
1416
- "export",
1417
- "extends",
1418
- "finally",
1419
- "for",
1420
- "function",
1421
- "if",
1422
- "import",
1423
- "in",
1424
- "instanceof",
1425
- "new",
1426
- "return",
1427
- "super",
1428
- "switch",
1429
- "this",
1430
- "throw",
1431
- "try",
1432
- "typeof",
1433
- "var",
1434
- "void",
1435
- "while",
1436
- "with",
1437
- "yield",
1438
- "let",
1439
- "static",
1440
- "enum",
1441
- "await",
1442
- "implements",
1443
- "package",
1444
- "protected",
1445
- "interface",
1446
- "private",
1447
- "public",
1448
- "null",
1449
- "true",
1450
- "false"
1451
- ]);
1452
- /**
1453
- * Whether `name` can appear as a named ESM export. JS identifier rules plus
1454
- * a reserved-word filter. `default` is handled separately by the emitter.
1455
- * @param name
1456
- */
1457
- function isValidExportIdentifier(name) {
1458
- if (name === "default") return true;
1459
- if (!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name)) return false;
1460
- if (RESERVED_WORDS.has(name)) return false;
1461
- return true;
1462
- }
1463
- /**
1464
- * Emit `key` as a JS object property key: a bare identifier when possible,
1465
- * otherwise a quoted string. Object keys (unlike export names) may be any
1466
- * string, so this never rejects.
1467
- * @param key
1468
- */
1469
- function jsObjectKey(key) {
1470
- if (/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key) && !RESERVED_WORDS.has(key)) return key;
1471
- return JSON.stringify(key);
1472
- }
1473
- function describeKind(value) {
1474
- if (value === null) return "null";
1475
- if (Array.isArray(value)) return "array";
1476
- return typeof value;
1477
- }
1478
1645
  //#endregion
1479
1646
  //#region src/index.ts
1480
1647
  /**
@@ -1521,30 +1688,21 @@ async function waitForSocket(socketPath, timeoutMs = 5e3) {
1521
1688
  throw new Error(`[@iso4/sandbox] V8 process socket not available after ${timeoutMs}ms: ${socketPath}`);
1522
1689
  }
1523
1690
  /**
1524
- * Map user-facing ResourceLimits to the wire-level encoding fields.
1525
- * @param limits
1526
- */
1527
- function toWireLimits(limits) {
1528
- return {
1529
- memoryMb: limits?.memoryMb ?? 64,
1530
- cpuTimeMs: limits?.cpuTimeMs ?? 5e3,
1531
- wallTimeMs: limits?.wallTimeMs ?? 3e4,
1532
- maxExportBytes: limits?.maxExportBytes ?? 16 * 1024 * 1024,
1533
- maxStdoutBytes: limits?.maxStdoutBytes ?? 1 * 1024 * 1024,
1534
- maxStderrBytes: limits?.maxStderrBytes ?? 1 * 1024 * 1024,
1535
- maxBridgeCallBytes: limits?.maxBridgeCallBytes ?? 16 * 1024 * 1024,
1536
- maxBridgeCalls: limits?.maxBridgeCalls ?? 10
1537
- };
1538
- }
1539
- /**
1540
1691
  * The `RunResult` returned when a run is aborted — whether the signal was
1541
- * already aborted at run entry or fired mid-flight (surfaced as a
1542
- * `RunAbortedError` from the client). Shared so both paths produce an
1543
- * identical shape. `error` (code `ERR_ABORTED`) is retained for backward
1544
- * compatibility; `reason` carries whatever was passed to `abort(reason)`.
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.
1545
1702
  * @param reason
1703
+ * @param from
1546
1704
  */
1547
- function abortedResult(reason) {
1705
+ function abortedResult(reason, from) {
1548
1706
  return {
1549
1707
  status: "aborted",
1550
1708
  ok: false,
@@ -1554,9 +1712,11 @@ function abortedResult(reason) {
1554
1712
  message: "run was aborted"
1555
1713
  },
1556
1714
  reason,
1557
- stdout: [],
1558
- stderr: [],
1559
- durationMs: 0
1715
+ stdout: from?.stdout ?? [],
1716
+ stderr: from?.stderr ?? [],
1717
+ durationMs: from?.durationMs ?? 0,
1718
+ cpuTimeMs: from?.cpuTimeMs ?? 0,
1719
+ bridgeCalls: from?.bridgeCalls ?? []
1560
1720
  };
1561
1721
  }
1562
1722
  var SandboxImpl = class {
@@ -1577,22 +1737,21 @@ var SandboxImpl = class {
1577
1737
  }
1578
1738
  async run(options) {
1579
1739
  if (options.signal?.aborted) return abortedResult(options.signal.reason);
1580
- const { bridgeGlobals, preamble } = processGlobals(options.globals ?? {});
1581
- const { bindings, registry, shape: _shape } = processImports(options.imports);
1582
- const allGlobals = registry.size > 0 ? {
1583
- ...bridgeGlobals,
1584
- [BRIDGE_DISPATCH_GLOBAL]: createDispatchGlobal(registry)
1585
- } : bridgeGlobals;
1586
- const code = preamble ? `${preamble}\n${options.code}` : options.code;
1740
+ const { defs, dispatch } = processGlobals(options.globals ?? {});
1741
+ const { bindings, handlers } = processImports(options.imports);
1587
1742
  try {
1588
1743
  return await this.pool.withClient(async (client) => {
1589
- return decodeRunCompletionPayload((await client.runRawCode(code, {
1744
+ const decoded = decodeRunCompletionPayload((await client.runRawCode(options.code, {
1590
1745
  filename: options.filename,
1591
- limits: toWireLimits(options.limits),
1592
- globals: allGlobals,
1746
+ limits: options.limits,
1747
+ globals: defs,
1748
+ dispatch,
1593
1749
  imports: bindings,
1750
+ importDispatch: handlers,
1594
1751
  signal: options.signal
1595
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;
1596
1755
  });
1597
1756
  } catch (error) {
1598
1757
  if (error instanceof RunAbortedError) return abortedResult(error.reason);
@@ -1605,18 +1764,13 @@ var SandboxImpl = class {
1605
1764
  async precompile(options) {
1606
1765
  return this.pool.withClient(async (client) => {
1607
1766
  const rawGlobals = options.globals ?? {};
1608
- const { bridgeGlobals, preamble } = processGlobals(rawGlobals);
1609
- const { bindings, registry, shape } = processImports(options.imports);
1610
- const allGlobals = registry.size > 0 ? {
1611
- ...bridgeGlobals,
1612
- [BRIDGE_DISPATCH_GLOBAL]: createDispatchGlobal(registry)
1613
- } : bridgeGlobals;
1614
- const code = preamble ? `${preamble}\n${options.code}` : options.code;
1767
+ const { defs } = processGlobals(rawGlobals);
1768
+ const { bindings, handlers } = processImports(options.imports);
1615
1769
  const result = decodePrecompileResultPayload(await client.precompile({
1616
- code,
1770
+ code: options.code,
1617
1771
  filename: options.filename,
1618
- limits: toWireLimits(options.limits),
1619
- globals: allGlobals,
1772
+ limits: options.limits,
1773
+ globals: defs,
1620
1774
  imports: bindings
1621
1775
  }));
1622
1776
  if (!result.ok) {
@@ -1626,7 +1780,7 @@ var SandboxImpl = class {
1626
1780
  if (result.error.stack) err.stack = result.error.stack;
1627
1781
  throw err;
1628
1782
  }
1629
- return new PrefixImpl(result.prefixId, this.pool, rawGlobals, registry, shape);
1783
+ return new PrefixImpl(result.prefixId, this.pool, rawGlobals, handlers);
1630
1784
  });
1631
1785
  }
1632
1786
  async dispose() {
@@ -1653,26 +1807,21 @@ var PrefixImpl = class {
1653
1807
  */
1654
1808
  defaultGlobals;
1655
1809
  /**
1656
- * Handle registry declared at precompile time: handle ID → host function.
1657
- * Same rebinding rules as `defaultGlobals` — a `prefix.run()` may override
1658
- * a subset of function leaves; everything else falls back to these. Source
1659
- * modules and data leaves are frozen in the snapshot and not represented
1660
- * here.
1661
- */
1662
- defaultRegistry;
1663
- /**
1664
- * Declared shape captured at precompile time. Drives type-level rebinding
1665
- * via `RebindImports<M>` and runtime `ERR_UNDECLARED_BINDING` enforcement
1666
- * inside `extractRebindImports`.
1810
+ * Host-import function-leaf handlers declared at precompile time, keyed by
1811
+ * `(specifier, path)`. Same rebinding rules as `defaultGlobals` — a
1812
+ * `prefix.run()` may override a subset of function leaves; everything else
1813
+ * falls back to these. Source modules and data leaves are frozen in the
1814
+ * snapshot and not represented here. The declared shape itself lives with
1815
+ * the prefix in the Rust runtime, which enforces `ERR_UNDECLARED_BINDING`
1816
+ * for rebind attempts outside it.
1667
1817
  */
1668
- declaredImportShape;
1818
+ defaultImportHandlers;
1669
1819
  _alive = true;
1670
- constructor(id, pool, defaultGlobals, defaultRegistry, declaredImportShape) {
1820
+ constructor(id, pool, defaultGlobals, defaultImportHandlers) {
1671
1821
  this.id = id;
1672
1822
  this.pool = pool;
1673
1823
  this.defaultGlobals = defaultGlobals;
1674
- this.defaultRegistry = defaultRegistry;
1675
- this.declaredImportShape = declaredImportShape;
1824
+ this.defaultImportHandlers = defaultImportHandlers;
1676
1825
  }
1677
1826
  get alive() {
1678
1827
  return this._alive;
@@ -1688,13 +1837,15 @@ var PrefixImpl = class {
1688
1837
  },
1689
1838
  stdout: [],
1690
1839
  stderr: [],
1691
- durationMs: 0
1840
+ durationMs: 0,
1841
+ cpuTimeMs: 0,
1842
+ bridgeCalls: []
1692
1843
  };
1693
1844
  if (options.signal?.aborted) return abortedResult(options.signal.reason);
1694
- const bridgeGlobals = extractBridgeGlobals(options.globals ?? {}, this.defaultGlobals);
1695
- let registry;
1845
+ const { defs, dispatch } = extractBridgeGlobals(options.globals ?? {}, this.defaultGlobals);
1846
+ let merged;
1696
1847
  try {
1697
- registry = extractRebindImports(options.imports, this.defaultRegistry, this.declaredImportShape);
1848
+ merged = mergeRebindImports(options.imports, this.defaultImportHandlers);
1698
1849
  } catch (e) {
1699
1850
  if (e instanceof UndeclaredImportBindingError) return {
1700
1851
  status: "failed",
@@ -1706,24 +1857,27 @@ var PrefixImpl = class {
1706
1857
  },
1707
1858
  stdout: [],
1708
1859
  stderr: [],
1709
- durationMs: 0
1860
+ durationMs: 0,
1861
+ cpuTimeMs: 0,
1862
+ bridgeCalls: []
1710
1863
  };
1711
1864
  throw e;
1712
1865
  }
1713
- const allGlobals = registry.size > 0 ? {
1714
- ...bridgeGlobals,
1715
- [BRIDGE_DISPATCH_GLOBAL]: createDispatchGlobal(registry)
1716
- } : bridgeGlobals;
1717
1866
  try {
1718
1867
  return await this.pool.withClient(async (client) => {
1719
- return decodeRunCompletionPayload((await client.prefixRun({
1868
+ const decoded = decodeRunCompletionPayload((await client.prefixRun({
1720
1869
  prefixId: this.id,
1721
1870
  code: options.code,
1722
1871
  filename: options.filename,
1723
- limits: toWireLimits(options.limits),
1724
- globals: allGlobals,
1872
+ limits: options.limits,
1873
+ globals: defs,
1874
+ dispatch,
1875
+ importRebinds: merged.rebinds,
1876
+ importDispatch: merged.handlers,
1725
1877
  signal: options.signal
1726
1878
  })).result).result;
1879
+ if (options.signal?.aborted && decoded.status === "failed" && decoded.error.code === "ERR_ABORTED") return abortedResult(options.signal.reason, decoded);
1880
+ return decoded;
1727
1881
  });
1728
1882
  } catch (error) {
1729
1883
  if (error instanceof RunAbortedError) return abortedResult(error.reason);