@iso4/sandbox 0.7.0 → 0.8.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/dist/index.mjs CHANGED
@@ -1,3 +1,4 @@
1
+ import { a as isValidExportName, r as RUNTIME_OWNED_GLOBALS } from "./names-BY-6pKkh.mjs";
1
2
  import { access, mkdtemp, rm } from "node:fs/promises";
2
3
  import { existsSync, rmSync } from "node:fs";
3
4
  import { availableParallelism, tmpdir, totalmem } from "node:os";
@@ -655,7 +656,11 @@ const TsToRustMessageTypes = {
655
656
  * The host dropped an outbound streamed body (consumer cancel, dispose);
656
657
  * the runtime cancels the guest source.
657
658
  */
658
- StreamCancel: 12
659
+ StreamCancel: 12,
660
+ /**
661
+ * Orderly close: the host is done with this connection. Empty payload.
662
+ */
663
+ Close: 13
659
664
  };
660
665
  const RustToTsMessageTypes = {
661
666
  BridgeCall: 1,
@@ -1041,7 +1046,8 @@ var PayloadWriter = class {
1041
1046
  this.writeU32(rebinds.length);
1042
1047
  for (const rebind of rebinds) {
1043
1048
  this.writeString(rebind.specifier);
1044
- this.writeString(rebind.path);
1049
+ this.writeU32(rebind.path.length);
1050
+ for (const segment of rebind.path) this.writeString(segment);
1045
1051
  }
1046
1052
  return this;
1047
1053
  }
@@ -1143,6 +1149,14 @@ var PayloadReader = class {
1143
1149
  this.offset += len;
1144
1150
  return slice;
1145
1151
  }
1152
+ /**
1153
+ * Advance past `len` bytes with the same bounds check as {@link readRawBytes}.
1154
+ * @param len
1155
+ */
1156
+ skipBytes(len) {
1157
+ if (this.remaining < len) throw new PayloadDecodeError(`unexpected end of payload: need ${len} bytes, have ${this.remaining}`);
1158
+ this.offset += len;
1159
+ }
1146
1160
  readString() {
1147
1161
  return Buffer.from(this.readRawBytes(this.readU32())).toString("utf8");
1148
1162
  }
@@ -1153,6 +1167,17 @@ var PayloadReader = class {
1153
1167
  return items;
1154
1168
  }
1155
1169
  /**
1170
+ * Read a `String specifier` + `List<String> path` and return exactly those
1171
+ * validated bytes as a latin1 string: the import key, see {@link encodeImportKey}.
1172
+ */
1173
+ readImportKey() {
1174
+ const start = this.offset;
1175
+ this.skipBytes(this.readU32());
1176
+ const count = this.readU32();
1177
+ for (let i = 0; i < count; i++) this.skipBytes(this.readU32());
1178
+ return Buffer.from(this.view.buffer, this.view.byteOffset + start, this.offset - start).toString("latin1");
1179
+ }
1180
+ /**
1156
1181
  * Read a value slot: `u32 byteLength` + V8 serialization blob.
1157
1182
  */
1158
1183
  readValueBlob() {
@@ -1213,6 +1238,29 @@ function encodeTerminatePayload(runId, hard) {
1213
1238
  return new PayloadWriter().writeU32(runId).writeU8(hard ? 1 : 0).toBuffer();
1214
1239
  }
1215
1240
  /**
1241
+ * The handler-map key of a host-module function leaf: its specifier and path
1242
+ * in wire encoding (`String` + `List<String>`), as latin1. Unambiguous, and
1243
+ * equal to the bytes a `BridgeCall` carries, so dispatch needs no decoding.
1244
+ * @param specifier
1245
+ * @param path the leaf's key segments
1246
+ */
1247
+ function encodeImportKey(specifier, path) {
1248
+ const writer = new PayloadWriter().writeString(specifier).writeU32(path.length);
1249
+ for (const segment of path) writer.writeString(segment);
1250
+ return writer.toBuffer().toString("latin1");
1251
+ }
1252
+ /**
1253
+ * Decode an import key back to its specifier and path, for messages.
1254
+ * @param key a key from {@link encodeImportKey} or a `BridgeCall`
1255
+ */
1256
+ function decodeImportKey(key) {
1257
+ const reader = new PayloadReader(Buffer.from(key, "latin1"));
1258
+ return {
1259
+ specifier: reader.readString(),
1260
+ path: reader.readStringList()
1261
+ };
1262
+ }
1263
+ /**
1216
1264
  * Decode a `BridgeCallPayload` from a `BridgeCall` frame sent by Rust.
1217
1265
  * Per `docs/protocol.md` §5.4.
1218
1266
  *
@@ -1252,17 +1300,20 @@ function decodeBridgeCallPayload(buf) {
1252
1300
  const callId = reader.readU32();
1253
1301
  const targetKindRaw = reader.readU8();
1254
1302
  if (targetKindRaw !== 0 && targetKindRaw !== 1) throw new Error(`invalid bridge targetKind: ${targetKindRaw}`);
1255
- const targetKind = targetKindRaw;
1256
- const specifier = reader.readU8() === 1 ? reader.readString() : void 0;
1257
- const exportName = reader.readString();
1303
+ if (reader.readU8() === 1 !== (targetKindRaw === 1)) throw new PayloadDecodeError("BridgeCall specifier must be present exactly for an import target");
1304
+ const target = targetKindRaw === 0 ? {
1305
+ targetKind: 0,
1306
+ exportName: reader.readString()
1307
+ } : {
1308
+ targetKind: 1,
1309
+ key: reader.readImportKey()
1310
+ };
1258
1311
  const decoded = reader.readValueBlob();
1259
1312
  if (!Array.isArray(decoded)) throw new PayloadDecodeError(`BridgeCall args must decode to an array, got ${decoded === null ? "null" : typeof decoded}`);
1260
1313
  return {
1261
1314
  runId,
1262
1315
  callId,
1263
- targetKind,
1264
- specifier,
1265
- exportName,
1316
+ target,
1266
1317
  args: decoded
1267
1318
  };
1268
1319
  }
@@ -1878,219 +1929,6 @@ function parseRustToTsMessageType(byte) {
1878
1929
  function formatByte(byte) {
1879
1930
  return `0x${byte.toString(16).padStart(2, "0")}`;
1880
1931
  }
1881
- /**
1882
- * The dispatch-map key for one host-module function leaf. The NUL separator
1883
- * cannot collide with anything a specifier or dot-joined path can contain in
1884
- * practice, so keys stay unambiguous.
1885
- * @param specifier
1886
- * @param path dot-joined function-leaf path
1887
- */
1888
- function importHandlerKey(specifier, path) {
1889
- return `${specifier}\u0000${path}`;
1890
- }
1891
- /**
1892
- * Thrown when the host's import configuration is structurally invalid in a
1893
- * way only the client can see. `PrefixImpl.run` converts it into a failed
1894
- * `RunResult` carrying `code`: `ERR_FROZEN_BINDING` for a rebind of a frozen
1895
- * location (a source module), `ERR_INVALID_REBIND` for a non-function rebind
1896
- * value. Matches the runtime-side enforcement for locations only Rust can see.
1897
- */
1898
- var ImportRebindError = class extends Error {
1899
- code;
1900
- constructor(code, message) {
1901
- super(message);
1902
- this.name = "ImportRebindError";
1903
- this.code = code;
1904
- }
1905
- };
1906
- function processImports(imports) {
1907
- if (imports === void 0) return {
1908
- bindings: [],
1909
- handlers: /* @__PURE__ */ new Map()
1910
- };
1911
- const bindings = [];
1912
- const handlers = /* @__PURE__ */ new Map();
1913
- for (const [specifier, value] of Object.entries(imports)) {
1914
- if (typeof value === "string") {
1915
- bindings.push({
1916
- specifier,
1917
- source: value
1918
- });
1919
- continue;
1920
- }
1921
- 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)}`);
1922
- const module = [];
1923
- for (const [name, child] of Object.entries(value)) {
1924
- if (child === void 0) continue;
1925
- 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`);
1926
- module.push([name, lowerNode(specifier, child, [name], handlers)]);
1927
- }
1928
- bindings.push({
1929
- specifier,
1930
- module
1931
- });
1932
- }
1933
- return {
1934
- bindings,
1935
- handlers
1936
- };
1937
- }
1938
- /**
1939
- * Lower one host-module node to its wire shape, registering function leaves.
1940
- * @param specifier
1941
- * @param value
1942
- * @param path
1943
- * @param handlers
1944
- * @param seen
1945
- */
1946
- function lowerNode(specifier, value, path, handlers, seen = /* @__PURE__ */ new Set()) {
1947
- if (path.length > 64) throw new Error(`[@iso4/sandbox] imports['${specifier}'].${path.join(".")}: host-module shapes may nest at most 64 levels deep`);
1948
- if (typeof value === "function") {
1949
- handlers.set(importHandlerKey(specifier, path.join(".")), value);
1950
- return { kind: "function" };
1951
- }
1952
- if (isPlainObject(value)) {
1953
- if (seen.has(value)) throw new Error(`[@iso4/sandbox] imports['${specifier}'].${path.join(".")}: circular references are not supported in host-module shapes`);
1954
- seen.add(value);
1955
- const entries = [];
1956
- for (const [key, child] of Object.entries(value)) {
1957
- if (child === void 0) continue;
1958
- entries.push([key, lowerNode(specifier, child, [...path, key], handlers, seen)]);
1959
- }
1960
- seen.delete(value);
1961
- return {
1962
- kind: "object",
1963
- entries
1964
- };
1965
- }
1966
- return {
1967
- kind: "data",
1968
- value
1969
- };
1970
- }
1971
- /**
1972
- * Merge the handlers behind a `Prefix`'s host-module function leaves with the
1973
- * run's overrides and collect the rebind locations to send on the wire.
1974
- *
1975
- * Only client-visible shape problems throw here (a string value — source
1976
- * modules are frozen; a non-function leaf value — there is nothing to
1977
- * dispatch to). Whether each location was actually declared as a function
1978
- * leaf at precompile time is enforced by the Rust runtime against the stored
1979
- * prefix shape (`ERR_UNDECLARED_BINDING` for undeclared locations,
1980
- * `ERR_FROZEN_BINDING` for frozen ones).
1981
- *
1982
- * @param runImports
1983
- * @param defaults handler map captured at precompile time
1984
- */
1985
- function mergeRebindImports(runImports, defaults) {
1986
- if (runImports === void 0) return {
1987
- rebinds: [],
1988
- handlers: defaults
1989
- };
1990
- const handlers = new Map(defaults);
1991
- const rebinds = [];
1992
- for (const [specifier, value] of Object.entries(runImports)) {
1993
- if (typeof value === "string") throw new ImportRebindError("ERR_FROZEN_BINDING", `import '${specifier}' is a source module — source imports are frozen with the prefix and cannot be rebound at prefix.run() time`);
1994
- if (!isPlainObject(value)) throw new Error(`[@iso4/sandbox] imports['${specifier}'] override must be a plain object; got ${describeKind(value)}`);
1995
- walkRebind(specifier, value, [], handlers, rebinds);
1996
- }
1997
- return {
1998
- rebinds,
1999
- handlers
2000
- };
2001
- }
2002
- function walkRebind(specifier, node, path, handlers, rebinds) {
2003
- for (const [key, value] of Object.entries(node)) {
2004
- if (value === void 0) continue;
2005
- const newPath = [...path, key];
2006
- if (typeof value === "function") {
2007
- const joined = newPath.join(".");
2008
- handlers.set(importHandlerKey(specifier, joined), value);
2009
- rebinds.push({
2010
- specifier,
2011
- path: joined
2012
- });
2013
- continue;
2014
- }
2015
- if (isPlainObject(value)) {
2016
- walkRebind(specifier, value, newPath, handlers, rebinds);
2017
- continue;
2018
- }
2019
- throw new ImportRebindError("ERR_INVALID_REBIND", `import '${specifier}'.${newPath.join(".")} can only be rebound with a function; got ${describeKind(value)}`);
2020
- }
2021
- }
2022
- function isPlainObject(value) {
2023
- if (value === null || typeof value !== "object") return false;
2024
- if (Array.isArray(value)) return false;
2025
- const proto = Object.getPrototypeOf(value);
2026
- return proto === null || proto === Object.prototype;
2027
- }
2028
- const RESERVED_WORDS = new Set([
2029
- "break",
2030
- "case",
2031
- "catch",
2032
- "class",
2033
- "const",
2034
- "continue",
2035
- "debugger",
2036
- "default",
2037
- "delete",
2038
- "do",
2039
- "else",
2040
- "export",
2041
- "extends",
2042
- "finally",
2043
- "for",
2044
- "function",
2045
- "if",
2046
- "import",
2047
- "in",
2048
- "instanceof",
2049
- "new",
2050
- "return",
2051
- "super",
2052
- "switch",
2053
- "this",
2054
- "throw",
2055
- "try",
2056
- "typeof",
2057
- "var",
2058
- "void",
2059
- "while",
2060
- "with",
2061
- "yield",
2062
- "let",
2063
- "static",
2064
- "enum",
2065
- "await",
2066
- "implements",
2067
- "package",
2068
- "protected",
2069
- "interface",
2070
- "private",
2071
- "public",
2072
- "null",
2073
- "true",
2074
- "false"
2075
- ]);
2076
- /**
2077
- * Whether `name` can appear as a named ESM export. JS identifier rules plus
2078
- * a reserved-word filter. `default` is allowed (the runtime emits it as
2079
- * `export default`). Mirrored by `is_valid_export_identifier` in the Rust
2080
- * runtime (`v8.rs`), which owns the final defensive check.
2081
- * @param name
2082
- */
2083
- function isValidExportIdentifier(name) {
2084
- if (name === "default") return true;
2085
- if (!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name)) return false;
2086
- if (RESERVED_WORDS.has(name)) return false;
2087
- return true;
2088
- }
2089
- function describeKind(value) {
2090
- if (value === null) return "null";
2091
- if (Array.isArray(value)) return "array";
2092
- return typeof value;
2093
- }
2094
1932
  //#endregion
2095
1933
  //#region src/client.ts
2096
1934
  /**
@@ -2291,6 +2129,7 @@ var RuntimeIpcClient = class RuntimeIpcClient {
2291
2129
  })));
2292
2130
  await client.awaitHello();
2293
2131
  } catch (error) {
2132
+ client.broken = true;
2294
2133
  await client.dispose();
2295
2134
  throw error;
2296
2135
  }
@@ -2539,6 +2378,7 @@ var RuntimeIpcClient = class RuntimeIpcClient {
2539
2378
  async dispose() {
2540
2379
  if (this.disposed) return;
2541
2380
  this.disposed = true;
2381
+ if (!this.broken && !this.socket.destroyed) this.socket.write(encodeTsToRustFrame(TsToRustMessageTypes.Close, new Uint8Array(0)));
2542
2382
  this.socket.end();
2543
2383
  await new Promise((resolve) => {
2544
2384
  if (this.socket.destroyed) {
@@ -2876,12 +2716,7 @@ var RuntimeIpcClient = class RuntimeIpcClient {
2876
2716
  })));
2877
2717
  else {
2878
2718
  const { runId: frameRunId, callId } = call;
2879
- dispatcher({
2880
- targetKind: call.targetKind,
2881
- specifier: call.specifier,
2882
- exportName: call.exportName,
2883
- args: call.args
2884
- }).then(async (value) => {
2719
+ dispatcher(call.target, call.args).then(async (value) => {
2885
2720
  let encoded;
2886
2721
  try {
2887
2722
  encoded = await serializeHostValue(value, this.brandKey, streams);
@@ -2928,14 +2763,17 @@ var RuntimeIpcClient = class RuntimeIpcClient {
2928
2763
  */
2929
2764
  function makeDispatcher(globals, imports) {
2930
2765
  if (Object.keys(globals).length === 0 && (imports === void 0 || imports.size === 0)) return void 0;
2931
- return async ({ targetKind, specifier, exportName, args }) => {
2932
- if (targetKind === 1) {
2933
- const handler = imports?.get(importHandlerKey(specifier ?? "", exportName));
2934
- if (handler === void 0) throw new Error(`no handler configured for host import '${specifier}'.${exportName}`);
2766
+ return async (target, args) => {
2767
+ if (target.targetKind === 1) {
2768
+ const handler = imports?.get(target.key);
2769
+ if (handler === void 0) {
2770
+ const { specifier, path } = decodeImportKey(target.key);
2771
+ throw new Error(`no handler configured for host import '${specifier}'.${path.join(".")}`);
2772
+ }
2935
2773
  return handler(...args);
2936
2774
  }
2937
- const handler = globals[exportName];
2938
- if (handler === void 0) throw new Error(`no handler configured for bridge global '${exportName}'`);
2775
+ const handler = globals[target.exportName];
2776
+ if (handler === void 0) throw new Error(`no handler configured for bridge global '${target.exportName}'`);
2939
2777
  return handler(...args);
2940
2778
  };
2941
2779
  }
@@ -3302,89 +3140,17 @@ var RunPool = class {
3302
3140
  //#endregion
3303
3141
  //#region src/globals.ts
3304
3142
  /**
3305
- * Every global name a fresh sandbox defines: the JS built-ins of the bundled
3306
- * V8 plus the runtime's own (`console`, `waitUntil`, timers, web classes).
3307
- * A host global under one of these names replaces the built-in, or is
3308
- * silently ignored for `undefined`, `NaN` and `Infinity`.
3143
+ * The error every setup refusal is thrown as, whichever side detects it: a
3144
+ * plain `Error` carrying the runtime's code.
3145
+ * @param code the setup code
3146
+ * @param message the runtime's message for it
3309
3147
  */
3310
- const SANDBOX_GLOBALS = new Set([
3311
- "AggregateError",
3312
- "Array",
3313
- "ArrayBuffer",
3314
- "AsyncDisposableStack",
3315
- "Atomics",
3316
- "BigInt",
3317
- "BigInt64Array",
3318
- "BigUint64Array",
3319
- "Boolean",
3320
- "DataView",
3321
- "Date",
3322
- "DisposableStack",
3323
- "Error",
3324
- "EvalError",
3325
- "FinalizationRegistry",
3326
- "Float16Array",
3327
- "Float32Array",
3328
- "Float64Array",
3329
- "Function",
3330
- "Headers",
3331
- "Infinity",
3332
- "Int16Array",
3333
- "Int32Array",
3334
- "Int8Array",
3335
- "Intl",
3336
- "Iterator",
3337
- "JSON",
3338
- "Map",
3339
- "Math",
3340
- "NaN",
3341
- "Number",
3342
- "Object",
3343
- "Promise",
3344
- "Proxy",
3345
- "RangeError",
3346
- "ReferenceError",
3347
- "Reflect",
3348
- "RegExp",
3349
- "Request",
3350
- "Response",
3351
- "Set",
3352
- "String",
3353
- "SuppressedError",
3354
- "Symbol",
3355
- "SyntaxError",
3356
- "Temporal",
3357
- "TextDecoder",
3358
- "TextEncoder",
3359
- "TypeError",
3360
- "URIError",
3361
- "URL",
3362
- "URLSearchParams",
3363
- "Uint16Array",
3364
- "Uint32Array",
3365
- "Uint8Array",
3366
- "Uint8ClampedArray",
3367
- "WeakMap",
3368
- "WeakRef",
3369
- "WeakSet",
3370
- "clearTimeout",
3371
- "console",
3372
- "decodeURI",
3373
- "decodeURIComponent",
3374
- "encodeURI",
3375
- "encodeURIComponent",
3376
- "escape",
3377
- "eval",
3378
- "globalThis",
3379
- "isFinite",
3380
- "isNaN",
3381
- "parseFloat",
3382
- "parseInt",
3383
- "setTimeout",
3384
- "undefined",
3385
- "unescape",
3386
- "waitUntil"
3387
- ]);
3148
+ function setupError(code, message) {
3149
+ const err = new Error(message);
3150
+ err.name = "Error";
3151
+ err.code = code;
3152
+ return err;
3153
+ }
3388
3154
  function isBridgeWithShim(v) {
3389
3155
  return typeof v === "object" && v !== null && v.kind === "bridge-with-shim";
3390
3156
  }
@@ -3410,7 +3176,9 @@ function shimHandlerName(name) {
3410
3176
  }
3411
3177
  /**
3412
3178
  * Lower a `HostGlobals` map into wire-shaped `defs` plus the bridge-dispatch
3413
- * map. See the module comment for the split.
3179
+ * map. See the module comment for the split. Throws a `TypeError` for a name
3180
+ * that is not a well-formed string and `ERR_RESERVED_NAME` for a runtime-owned
3181
+ * one.
3414
3182
  * - `HostExportFunction` → `{ kind: 'bridge' }` + dispatch entry.
3415
3183
  * - `string` → `{ kind: 'string', expr }` (evaluated by Rust).
3416
3184
  * - `DataGlobal` → `{ kind: 'data', value }` (materialised by Rust).
@@ -3421,48 +3189,52 @@ function shimHandlerName(name) {
3421
3189
  function processGlobals(globals) {
3422
3190
  const defs = [];
3423
3191
  const dispatch = {};
3424
- for (const [name, value] of Object.entries(globals)) if (typeof value === "function") {
3425
- defs.push({
3426
- kind: "bridge",
3192
+ for (const [name, value] of Object.entries(globals)) {
3193
+ if (!name.isWellFormed()) throw new TypeError(`[@iso4/sandbox] global name '${name}' is not a well-formed string`);
3194
+ if (RUNTIME_OWNED_GLOBALS.has(name)) throw setupError("ERR_RESERVED_NAME", `global '${name}' is reserved by the runtime and cannot be provided by the host`);
3195
+ if (typeof value === "function") {
3196
+ defs.push({
3197
+ kind: "bridge",
3198
+ name,
3199
+ enumerable: true
3200
+ });
3201
+ dispatch[name] = value;
3202
+ } else if (typeof value === "string") defs.push({
3203
+ kind: "string",
3427
3204
  name,
3205
+ expr: value,
3428
3206
  enumerable: true
3429
3207
  });
3430
- dispatch[name] = value;
3431
- } else if (typeof value === "string") defs.push({
3432
- kind: "string",
3433
- name,
3434
- expr: value,
3435
- enumerable: true
3436
- });
3437
- else if (isBridgeGlobal(value)) {
3438
- defs.push({
3439
- kind: "bridge",
3208
+ else if (isBridgeGlobal(value)) {
3209
+ defs.push({
3210
+ kind: "bridge",
3211
+ name,
3212
+ enumerable: value.enumerable ?? true
3213
+ });
3214
+ dispatch[name] = value.handler;
3215
+ } else if (isStringGlobal(value)) defs.push({
3216
+ kind: "string",
3440
3217
  name,
3218
+ expr: value.expr,
3441
3219
  enumerable: value.enumerable ?? true
3442
3220
  });
3443
- dispatch[name] = value.handler;
3444
- } else if (isStringGlobal(value)) defs.push({
3445
- kind: "string",
3446
- name,
3447
- expr: value.expr,
3448
- enumerable: value.enumerable ?? true
3449
- });
3450
- else if (isDataGlobal(value)) defs.push({
3451
- kind: "data",
3452
- name,
3453
- value: value.value,
3454
- enumerable: value.enumerable ?? true
3455
- });
3456
- else if (isBridgeWithShim(value)) {
3457
- const handlerName = shimHandlerName(name);
3458
- defs.push({
3459
- kind: "shim",
3221
+ else if (isDataGlobal(value)) defs.push({
3222
+ kind: "data",
3460
3223
  name,
3461
- shim: value.shim,
3462
- handlerName,
3224
+ value: value.value,
3463
3225
  enumerable: value.enumerable ?? true
3464
3226
  });
3465
- dispatch[handlerName] = value.handler;
3227
+ else if (isBridgeWithShim(value)) {
3228
+ const handlerName = shimHandlerName(name);
3229
+ defs.push({
3230
+ kind: "shim",
3231
+ name,
3232
+ shim: value.shim,
3233
+ handlerName,
3234
+ enumerable: value.enumerable ?? true
3235
+ });
3236
+ dispatch[handlerName] = value.handler;
3237
+ }
3466
3238
  }
3467
3239
  return {
3468
3240
  defs,
@@ -3470,82 +3242,240 @@ function processGlobals(globals) {
3470
3242
  };
3471
3243
  }
3472
3244
  /**
3473
- * Resolve bridge globals for a `prefix.run()` call.
3474
- *
3475
- * String/data globals and shim *wrappers* are already compiled into the
3476
- * declared prefix state, replayed by the runtime when the prefix evaluates —
3477
- * only the bridge *stubs* they call need re-installing per run (bridge stubs
3478
- * are bound to the run's socket). So
3479
- * every returned def is `kind: 'bridge'`, and shimmed globals are routed to
3480
- * their private `__iso4_<name>_h` key so rebinding updates the handler the
3481
- * shim calls, without touching the shim itself.
3482
- * @param runGlobals
3483
- * @param precompileGlobals
3245
+ * Copy the declared global shape at `prepare()`, so later changes to the
3246
+ * caller's object change nothing. Kinds `processGlobals` ignores are left out.
3247
+ * @param globals the `globals` passed to `prepare()`
3484
3248
  */
3249
+ function declareGlobals(globals) {
3250
+ const declared = /* @__PURE__ */ new Map();
3251
+ for (const [name, value] of Object.entries(globals)) if (typeof value === "function") declared.set(name, {
3252
+ kind: "bridge",
3253
+ handler: value,
3254
+ enumerable: true
3255
+ });
3256
+ else if (typeof value === "string" || isStringGlobal(value) || isDataGlobal(value)) declared.set(name, { kind: "value" });
3257
+ else if (isBridgeWithShim(value)) declared.set(name, {
3258
+ kind: "shim",
3259
+ handler: value.handler
3260
+ });
3261
+ else if (isBridgeGlobal(value)) declared.set(name, {
3262
+ kind: "bridge",
3263
+ handler: value.handler,
3264
+ enumerable: value.enumerable ?? true
3265
+ });
3266
+ return declared;
3267
+ }
3485
3268
  /**
3486
- * Resolve a per-run override for a declared bridge global.
3269
+ * Resolve bridge globals for a `prefix.run()` call.
3487
3270
  *
3488
- * An omitted key falls back to the precompile-time handler (the intended
3489
- * default). But a key that IS supplied yet is not a function — the runtime
3490
- * shape TypeScript cannot catch, e.g. a tenant handler that resolves to
3491
- * `undefined` — throws instead of silently reusing the (often broader) default,
3492
- * which would be a fail-open exactly where the API is used to narrow privilege.
3493
- * This matches the imports side, which already rejects a non-function rebind.
3494
- * @param runGlobals the per-run rebind map
3495
- * @param name the declared global's name
3496
- * @param fallback the precompile-time handler used when no override is supplied
3271
+ * Value globals and shim wrappers are replayed from the declared prefix
3272
+ * state, so every returned def is `kind: 'bridge'`; a shim override is routed
3273
+ * to its private `__iso4_<name>_h` key. Throws the setup error the runtime
3274
+ * would send for an undeclared or frozen name, and `ERR_INVALID_REBIND` for a
3275
+ * non-function override.
3276
+ * @param runGlobals the run's `globals` option
3277
+ * @param declared the shape kept from `prepare()` by {@link declareGlobals}
3497
3278
  */
3498
- function resolveOverride(runGlobals, name, fallback) {
3499
- if (!Object.hasOwn(runGlobals, name)) return fallback;
3500
- const override = runGlobals[name];
3501
- if (typeof override !== "function") throw new TypeError(`[iso4] global override "${name}" must be a function, got ${override === null ? "null" : typeof override}`);
3502
- return override;
3503
- }
3504
- function extractBridgeGlobals(runGlobals, precompileGlobals) {
3279
+ function extractBridgeGlobals(runGlobals, declared) {
3280
+ const overrides = runGlobals;
3281
+ for (const [name, override] of Object.entries(overrides)) {
3282
+ if (!name.isWellFormed()) throw new TypeError(`[@iso4/sandbox] global name '${name}' is not a well-formed string`);
3283
+ const shape = declared.get(name);
3284
+ if (shape === void 0) throw setupError("ERR_UNDECLARED_BINDING", `global '${name}' was not declared at precompile time`);
3285
+ if (shape.kind === "value") throw setupError("ERR_FROZEN_BINDING", `global '${name}' is a value global, frozen with the prefix — only function globals can be rebound`);
3286
+ if (typeof override !== "function") throw setupError("ERR_INVALID_REBIND", `global '${name}' can only be rebound with a function; got ${override === null ? "null" : typeof override}`);
3287
+ }
3505
3288
  const defs = [];
3506
3289
  const dispatch = {};
3507
- for (const [name, value] of Object.entries(precompileGlobals)) {
3508
- if (typeof value === "string" || isStringGlobal(value) || isDataGlobal(value)) continue;
3509
- if (isBridgeWithShim(value)) {
3510
- const handlerName = shimHandlerName(name);
3511
- defs.push({
3512
- kind: "bridge",
3513
- name: handlerName,
3514
- enumerable: true
3515
- });
3516
- dispatch[handlerName] = resolveOverride(runGlobals, name, value.handler);
3517
- } else if (isBridgeGlobal(value)) {
3518
- defs.push({
3519
- kind: "bridge",
3520
- name,
3521
- enumerable: value.enumerable ?? true
3522
- });
3523
- dispatch[name] = resolveOverride(runGlobals, name, value.handler);
3524
- } else if (typeof value === "function") {
3525
- defs.push({
3526
- kind: "bridge",
3527
- name,
3528
- enumerable: true
3290
+ for (const [name, shape] of declared) {
3291
+ if (shape.kind === "value") continue;
3292
+ const override = Object.hasOwn(overrides, name) ? overrides[name] : void 0;
3293
+ const stub = shape.kind === "shim" ? shimHandlerName(name) : name;
3294
+ defs.push({
3295
+ kind: "bridge",
3296
+ name: stub,
3297
+ enumerable: shape.kind === "shim" || shape.enumerable
3298
+ });
3299
+ dispatch[stub] = override ?? shape.handler;
3300
+ }
3301
+ return {
3302
+ defs,
3303
+ dispatch
3304
+ };
3305
+ }
3306
+ /**
3307
+ * The dispatch-map key for one host-module function leaf: the wire bytes of
3308
+ * its specifier and key segments, so `{ 'a.b': f }` and `{ a: { b: f } }` differ.
3309
+ * @param specifier
3310
+ * @param path the leaf's key segments
3311
+ */
3312
+ const importHandlerKey = encodeImportKey;
3313
+ /**
3314
+ * Thrown for an import rebind the prefix does not allow. `PrefixImpl.run`
3315
+ * rethrows it as the same coded `Error` the runtime's refusals become.
3316
+ */
3317
+ var ImportRebindError = class extends Error {
3318
+ code;
3319
+ constructor(code, message) {
3320
+ super(message);
3321
+ this.name = "ImportRebindError";
3322
+ this.code = code;
3323
+ }
3324
+ };
3325
+ function processImports(imports) {
3326
+ if (imports === void 0) return {
3327
+ bindings: [],
3328
+ handlers: /* @__PURE__ */ new Map()
3329
+ };
3330
+ const bindings = [];
3331
+ const handlers = /* @__PURE__ */ new Map();
3332
+ for (const [specifier, value] of Object.entries(imports)) {
3333
+ if (!specifier.isWellFormed()) throw new TypeError(`[@iso4/sandbox] import specifier '${specifier}' is not a well-formed string`);
3334
+ if (typeof value === "string") {
3335
+ bindings.push({
3336
+ specifier,
3337
+ source: value
3529
3338
  });
3530
- dispatch[name] = resolveOverride(runGlobals, name, value);
3339
+ continue;
3531
3340
  }
3341
+ 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)}`);
3342
+ const module = [];
3343
+ for (const [name, child] of Object.entries(value)) {
3344
+ if (child === void 0) continue;
3345
+ if (!isValidExportName(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`);
3346
+ module.push([name, lowerNode(specifier, child, [name], handlers)]);
3347
+ }
3348
+ bindings.push({
3349
+ specifier,
3350
+ module
3351
+ });
3532
3352
  }
3533
- for (const [name, override] of Object.entries(runGlobals)) {
3534
- if (name in precompileGlobals) continue;
3535
- if (typeof override === "function") {
3536
- defs.push({
3537
- kind: "bridge",
3538
- name,
3539
- enumerable: true
3540
- });
3541
- dispatch[name] = override;
3353
+ return {
3354
+ bindings,
3355
+ handlers
3356
+ };
3357
+ }
3358
+ /**
3359
+ * Lower one host-module node to its wire shape, registering function leaves.
3360
+ * @param specifier
3361
+ * @param value
3362
+ * @param path
3363
+ * @param handlers
3364
+ * @param seen
3365
+ */
3366
+ function lowerNode(specifier, value, path, handlers, seen = /* @__PURE__ */ new Set()) {
3367
+ if (path.length > 64) throw new Error(`[@iso4/sandbox] imports['${specifier}'].${path.join(".")}: host-module shapes may nest at most 64 levels deep`);
3368
+ if (typeof value === "function") {
3369
+ handlers.set(importHandlerKey(specifier, path), value);
3370
+ return { kind: "function" };
3371
+ }
3372
+ if (isPlainObject(value)) {
3373
+ if (seen.has(value)) throw new Error(`[@iso4/sandbox] imports['${specifier}'].${path.join(".")}: circular references are not supported in host-module shapes`);
3374
+ seen.add(value);
3375
+ const entries = [];
3376
+ for (const [key, child] of Object.entries(value)) {
3377
+ if (child === void 0) continue;
3378
+ if (!key.isWellFormed()) throw new TypeError(`[@iso4/sandbox] import key '${key}' is not a well-formed string`);
3379
+ entries.push([key, lowerNode(specifier, child, [...path, key], handlers, seen)]);
3542
3380
  }
3381
+ seen.delete(value);
3382
+ return {
3383
+ kind: "object",
3384
+ entries
3385
+ };
3543
3386
  }
3544
3387
  return {
3545
- defs,
3546
- dispatch
3388
+ kind: "data",
3389
+ value
3547
3390
  };
3548
3391
  }
3392
+ /**
3393
+ * The declared import shape without data-leaf values or source text, kept by a
3394
+ * prefix for {@link mergeRebindImports} so it does not pin large data.
3395
+ * @param bindings the bindings sent at `prepare()`
3396
+ */
3397
+ function declaredImportShape(bindings) {
3398
+ const strip = (entries) => entries.map(([key, node]) => [key, node.kind === "object" ? {
3399
+ kind: "object",
3400
+ entries: strip(node.entries)
3401
+ } : node.kind === "data" ? {
3402
+ kind: "data",
3403
+ value: void 0
3404
+ } : node]);
3405
+ return bindings.map((b) => "source" in b ? {
3406
+ specifier: b.specifier,
3407
+ source: ""
3408
+ } : {
3409
+ specifier: b.specifier,
3410
+ module: strip(b.module)
3411
+ });
3412
+ }
3413
+ /**
3414
+ * Merge the handlers behind a `Prefix`'s host-module function leaves with the
3415
+ * run's overrides and collect the rebind locations to send on the wire.
3416
+ *
3417
+ * Every location is looked up in the declared shape before its value is
3418
+ * looked at, with the same codes and messages as `validate_import_rebinds` in
3419
+ * the runtime, which repeats the check: undeclared is `ERR_UNDECLARED_BINDING`,
3420
+ * a source module or data leaf `ERR_FROZEN_BINDING`. A declared location
3421
+ * given the wrong kind of value is `ERR_INVALID_REBIND`.
3422
+ *
3423
+ * @param runImports the run's `imports` option
3424
+ * @param defaults handler map captured at precompile time
3425
+ * @param declared the import shape declared at `prepare()`
3426
+ */
3427
+ function mergeRebindImports(runImports, defaults, declared) {
3428
+ if (runImports === void 0) return {
3429
+ rebinds: [],
3430
+ handlers: defaults
3431
+ };
3432
+ const handlers = new Map(defaults);
3433
+ const rebinds = [];
3434
+ for (const [specifier, value] of Object.entries(runImports)) {
3435
+ if (!specifier.isWellFormed()) throw new TypeError(`[@iso4/sandbox] import specifier '${specifier}' is not a well-formed string`);
3436
+ const binding = declared.find((b) => b.specifier === specifier);
3437
+ if (binding === void 0) throw new ImportRebindError("ERR_UNDECLARED_BINDING", `import '${specifier}' was not declared at precompile time`);
3438
+ if ("source" in binding) throw new ImportRebindError("ERR_FROZEN_BINDING", `import '${specifier}' is a source module — source imports are frozen with the prefix and cannot be rebound at prefix.run() time`);
3439
+ if (!isPlainObject(value)) throw new ImportRebindError("ERR_INVALID_REBIND", `import '${specifier}' can only be rebound with a plain object; got ${describeKind(value)}`);
3440
+ walkRebind(specifier, value, binding.module, [], handlers, rebinds);
3441
+ }
3442
+ return {
3443
+ rebinds,
3444
+ handlers
3445
+ };
3446
+ }
3447
+ function walkRebind(specifier, node, declared, path, handlers, rebinds) {
3448
+ for (const [key, value] of Object.entries(node)) {
3449
+ if (!key.isWellFormed()) throw new TypeError(`[@iso4/sandbox] import key '${key}' is not a well-formed string`);
3450
+ const segments = [...path, key];
3451
+ const joined = segments.join(".");
3452
+ const shape = declared.find(([name]) => name === key)?.[1];
3453
+ if (shape === void 0) throw new ImportRebindError("ERR_UNDECLARED_BINDING", `import '${specifier}'.${joined} was not declared at precompile time`);
3454
+ if (shape.kind === "data") throw new ImportRebindError("ERR_FROZEN_BINDING", `import '${specifier}'.${joined} is a data leaf, not a function — data leaves cannot be rebound`);
3455
+ if (shape.kind === "object") {
3456
+ if (!isPlainObject(value)) throw new ImportRebindError("ERR_INVALID_REBIND", `import '${specifier}'.${joined} can only be rebound with a plain object; got ${describeKind(value)}`);
3457
+ walkRebind(specifier, value, shape.entries, segments, handlers, rebinds);
3458
+ continue;
3459
+ }
3460
+ if (typeof value !== "function") throw new ImportRebindError("ERR_INVALID_REBIND", `import '${specifier}'.${joined} can only be rebound with a function; got ${describeKind(value)}`);
3461
+ handlers.set(importHandlerKey(specifier, segments), value);
3462
+ rebinds.push({
3463
+ specifier,
3464
+ path: segments
3465
+ });
3466
+ }
3467
+ }
3468
+ function isPlainObject(value) {
3469
+ if (value === null || typeof value !== "object") return false;
3470
+ if (Array.isArray(value)) return false;
3471
+ const proto = Object.getPrototypeOf(value);
3472
+ return proto === null || proto === Object.prototype;
3473
+ }
3474
+ function describeKind(value) {
3475
+ if (value === null) return "null";
3476
+ if (Array.isArray(value)) return "array";
3477
+ return typeof value;
3478
+ }
3549
3479
  //#endregion
3550
3480
  //#region src/index.ts
3551
3481
  /**
@@ -3780,6 +3710,43 @@ function waitUntilResultFrom(report) {
3780
3710
  return out;
3781
3711
  }
3782
3712
  /**
3713
+ * The `ResourceLimits` fields the wire carries as a `u32`; `0` disables each.
3714
+ */
3715
+ const U32_LIMIT_FIELDS = [
3716
+ "cpuTimeMs",
3717
+ "wallTimeMs",
3718
+ "maxBridgeCallBytes",
3719
+ "maxExportBytes",
3720
+ "maxStdoutBytes",
3721
+ "maxStderrBytes",
3722
+ "maxBridgeCalls",
3723
+ "graceMs"
3724
+ ];
3725
+ const U32_MAX = 4294967295;
3726
+ /**
3727
+ * Refuse a limit the wire cannot carry as a `u32` instead of letting the
3728
+ * encoder throw a `RangeError` or silently truncate a fraction.
3729
+ * @param limits the caller's `limits` option
3730
+ */
3731
+ function validateLimits(limits) {
3732
+ if (limits === void 0) return;
3733
+ if (limits === null || typeof limits !== "object") throw new TypeError("[@iso4/sandbox] limits must be an object");
3734
+ for (const field of U32_LIMIT_FIELDS) {
3735
+ const value = limits[field];
3736
+ if (value !== void 0 && !(Number.isInteger(value) && value >= 0 && value <= U32_MAX)) throw new TypeError(`[@iso4/sandbox] limits.${field} must be an integer from 0 to ${U32_MAX}`);
3737
+ }
3738
+ }
3739
+ /**
3740
+ * Only the public `u32` fields; heap caps come from `heapCapsForWire`, so an
3741
+ * untyped caller cannot smuggle `memoryMb`/`hardMemoryMb` onto the wire.
3742
+ * @param limits the validated `limits` option
3743
+ */
3744
+ function wireLimits(limits) {
3745
+ const out = {};
3746
+ for (const field of U32_LIMIT_FIELDS) if (limits?.[field] !== void 0) out[field] = limits[field];
3747
+ return out;
3748
+ }
3749
+ /**
3783
3750
  * A heap cap must be an integer number of megabytes ≥ 0 (0 = uncapped):
3784
3751
  * the wire carries it as a u32, and a fractional or negative value would
3785
3752
  * silently misencode instead of capping.
@@ -3789,11 +3756,11 @@ function waitUntilResultFrom(report) {
3789
3756
  function validateMemoryMb(value, where) {
3790
3757
  if (value === void 0) return;
3791
3758
  if (typeof value === "number") {
3792
- if (!Number.isInteger(value) || value < 0) throw new TypeError(`[@iso4/sandbox] ${where} must be an integer >= 0 (megabytes; 0 = uncapped)`);
3759
+ if (!Number.isInteger(value) || value < 0 || value > U32_MAX) throw new TypeError(`[@iso4/sandbox] ${where} must be an integer from 0 to ${U32_MAX} (megabytes; 0 = uncapped)`);
3793
3760
  return;
3794
3761
  }
3795
3762
  if (value === null || typeof value !== "object") throw new TypeError(`[@iso4/sandbox] ${where} must be a number of megabytes or { soft?, hard }`);
3796
- if (!Number.isInteger(value.hard) || value.hard < 1) throw new TypeError(`[@iso4/sandbox] ${where}.hard must be an integer >= 1 (megabytes) — write memoryMb: 0 for uncapped`);
3763
+ if (!Number.isInteger(value.hard) || value.hard < 1 || value.hard > U32_MAX) throw new TypeError(`[@iso4/sandbox] ${where}.hard must be an integer from 1 to ${U32_MAX} (megabytes) — write memoryMb: 0 for uncapped`);
3797
3764
  if (value.soft === void 0) return;
3798
3765
  if (!Number.isInteger(value.soft) || value.soft < 1) throw new TypeError(`[@iso4/sandbox] ${where}.soft must be an integer >= 1 (megabytes) — omit it for a hard line only`);
3799
3766
  if (value.soft >= value.hard) throw new TypeError(`[@iso4/sandbox] ${where}.soft (${value.soft}) must be below ${where}.hard (${value.hard})`);
@@ -3885,6 +3852,30 @@ function desyncResult(error) {
3885
3852
  bridgeCalls: []
3886
3853
  };
3887
3854
  }
3855
+ /**
3856
+ * Codes the runtime reports for a run whose options are invalid. The client
3857
+ * checks first; this catches what it cannot know, such as a prefix the
3858
+ * runtime dropped. Runs throw these, like `prepare()`, instead of returning them.
3859
+ */
3860
+ const SETUP_ERROR_CODES = new Set([
3861
+ "ERR_RESERVED_NAME",
3862
+ "ERR_UNDECLARED_BINDING",
3863
+ "ERR_FROZEN_BINDING",
3864
+ "ERR_INVALID_REBIND",
3865
+ "ERR_PREFIX_DISPOSED"
3866
+ ]);
3867
+ /**
3868
+ * The error `prepare()`, `readExports()` and `run()` throw for a failure the
3869
+ * runtime reported: an `Error` carrying the runtime's `code`, `name`, `stack`.
3870
+ * @param error the reported failure
3871
+ */
3872
+ function thrownRunError(error) {
3873
+ const err = new Error(error.message);
3874
+ err.name = error.name;
3875
+ err.code = error.code;
3876
+ if (error.stack) err.stack = error.stack;
3877
+ return err;
3878
+ }
3888
3879
  function abortedResult(reason, from) {
3889
3880
  return {
3890
3881
  status: "aborted",
@@ -3959,6 +3950,7 @@ var SandboxImpl = class {
3959
3950
  async run(options) {
3960
3951
  if (options.signal?.aborted) return abortedResult(options.signal.reason);
3961
3952
  if (options.hardAbortSignal?.aborted) return abortedResult(options.hardAbortSignal.reason);
3953
+ validateLimits(options.limits);
3962
3954
  if (typeof options.limits?.memoryMb === "object") throw new TypeError("[@iso4/sandbox] limits.memoryMb takes a number of megabytes — the { soft, hard } form belongs on createSandbox or prepare, whose instances are reused");
3963
3955
  validateMemoryMb(options.limits?.memoryMb, "limits.memoryMb");
3964
3956
  const runMemoryMb = options.limits?.memoryMb ?? this.memoryMb;
@@ -3966,16 +3958,16 @@ var SandboxImpl = class {
3966
3958
  await materializeHostTypesInGlobals(defs, this.brandKey);
3967
3959
  const { bindings, handlers } = processImports(options.imports);
3968
3960
  const streams = new StreamSourceRegistry();
3969
- const call = options.call === void 0 ? void 0 : {
3970
- exportPath: options.call.export,
3971
- argsBlob: await serializeHostValue(options.call.args ?? [], this.brandKey, streams)
3972
- };
3973
3961
  try {
3962
+ const call = options.call === void 0 ? void 0 : {
3963
+ exportPath: options.call.export,
3964
+ argsBlob: await serializeHostValue(options.call.args ?? [], this.brandKey, streams)
3965
+ };
3974
3966
  return await this.pool.withClient(async (client, queueWaitMs) => {
3975
3967
  const raw = await client.runRawCode(options.code, {
3976
3968
  filename: options.filename,
3977
3969
  limits: {
3978
- ...options.limits,
3970
+ ...wireLimits(options.limits),
3979
3971
  ...heapCapsForWire(runMemoryMb)
3980
3972
  },
3981
3973
  globals: defs,
@@ -3988,6 +3980,10 @@ var SandboxImpl = class {
3988
3980
  streams
3989
3981
  });
3990
3982
  const decoded = withBodyStreamBinder((id) => raw.outStreams.attach(id), () => call === void 0 ? decodeRunCompletionPayload(raw.result, void 0, raw.droppedCallIds).result : decodeRunCompletionPayload(raw.result, "call", raw.droppedCallIds).result);
3983
+ if (decoded.status === "failed" && SETUP_ERROR_CODES.has(decoded.error.code)) throw thrownRunError({
3984
+ ...decoded.error,
3985
+ code: decoded.error.code
3986
+ });
3991
3987
  if (raw.epilogue !== void 0 && raw.graceWork && decoded.ok) decoded.waitUntil = raw.epilogue.then(waitUntilResultFrom);
3992
3988
  if (decoded.status === "failed" && decoded.error.code === "ERR_ABORTED") {
3993
3989
  if (options.signal?.aborted) return abortedResult(options.signal.reason, decoded);
@@ -4040,13 +4036,7 @@ var SandboxImpl = class {
4040
4036
  filename: options.filename,
4041
4037
  limits: options.limits
4042
4038
  });
4043
- if (result.status !== "completed") {
4044
- const err = new Error(result.error.message);
4045
- err.name = result.error.name;
4046
- err.code = result.error.code;
4047
- if (result.error.stack) err.stack = result.error.stack;
4048
- throw err;
4049
- }
4039
+ if (result.status !== "completed") throw thrownRunError(result.error);
4050
4040
  return {
4051
4041
  exports: result.exports,
4052
4042
  skippedExports: result.skippedExports
@@ -4066,30 +4056,26 @@ var SandboxImpl = class {
4066
4056
  */
4067
4057
  async prepare(options) {
4068
4058
  validateMemoryMb(options.memoryMb, "memoryMb");
4059
+ validateLimits(options.limits);
4069
4060
  const prefixMemoryMb = options.memoryMb ?? this.memoryMb;
4061
+ const rawGlobals = options.globals ?? {};
4062
+ const { defs } = processGlobals(rawGlobals);
4063
+ const declaredGlobals = declareGlobals(rawGlobals);
4070
4064
  return this.pool.withClient(async (client) => {
4071
- const rawGlobals = options.globals ?? {};
4072
- const { defs } = processGlobals(rawGlobals);
4073
4065
  await materializeHostTypesInGlobals(defs, this.brandKey);
4074
4066
  const { bindings, handlers } = processImports(options.imports);
4075
4067
  const result = decodePrecompileResultPayload(await client.precompile({
4076
4068
  code: options.code,
4077
4069
  filename: options.filename,
4078
4070
  limits: {
4079
- ...options.limits,
4071
+ ...wireLimits(options.limits),
4080
4072
  ...heapCapsForWire(prefixMemoryMb)
4081
4073
  },
4082
4074
  globals: defs,
4083
4075
  imports: bindings
4084
4076
  }));
4085
- if (!result.ok) {
4086
- const err = new Error(result.error.message);
4087
- err.name = result.error.name;
4088
- err.code = result.error.code;
4089
- if (result.error.stack) err.stack = result.error.stack;
4090
- throw err;
4091
- }
4092
- return new PrefixImpl(result.prefixId, this.pool, rawGlobals, handlers, this.brandKey, prefixMemoryMb);
4077
+ if (!result.ok) throw thrownRunError(result.error);
4078
+ return new PrefixImpl(result.prefixId, this.pool, declaredGlobals, handlers, declaredImportShape(bindings), this.brandKey, prefixMemoryMb);
4093
4079
  });
4094
4080
  }
4095
4081
  async dispose() {
@@ -4114,23 +4100,20 @@ var PrefixImpl = class {
4114
4100
  id;
4115
4101
  pool;
4116
4102
  /**
4117
- * Handlers declared at precompile time. Used as defaults for any run that
4118
- * does not supply its own override, per DESIGN.md §11.4 "Rebinding rules":
4119
- * "If the prefix declared a global the run doesn't supply, the
4120
- * precompile-time implementation is reused."
4103
+ * The global shape declared at `prepare()`, with the default handlers a run
4104
+ * falls back to when it does not override them (DESIGN.md §11.4).
4121
4105
  */
4122
- defaultGlobals;
4106
+ declaredGlobals;
4123
4107
  /**
4124
- * Host-import function-leaf handlers declared at precompile time, keyed by
4125
- * `(specifier, path)`. Same rebinding rules as `defaultGlobals` — a
4126
- * `prefix.run()` may override a subset of function leaves; everything else
4127
- * falls back to these. Source modules and data leaves are frozen in the
4128
- * declared prefix state and not represented here. The declared shape itself lives with
4129
- * the prefix in the Rust runtime, which rejects rebind attempts outside it
4130
- * (`ERR_UNDECLARED_BINDING`) or at frozen locations (`ERR_FROZEN_BINDING`).
4108
+ * Host-import function-leaf handlers declared at `prepare()`, keyed by
4109
+ * `(specifier, path)`; a run's overrides apply on top.
4131
4110
  */
4132
4111
  defaultImportHandlers;
4133
4112
  /**
4113
+ * The import shape declared at `prepare()`, for client-side rebind checks.
4114
+ */
4115
+ declaredImports;
4116
+ /**
4134
4117
  * THIS prefix's heap cap (`prepare({ memoryMb })`, falling back to the
4135
4118
  * sandbox default). Warm instances serving the prefix are created with
4136
4119
  * it; a per-run value stays impossible — the cap is baked into the
@@ -4142,11 +4125,12 @@ var PrefixImpl = class {
4142
4125
  */
4143
4126
  brandKey;
4144
4127
  _alive = true;
4145
- constructor(id, pool, defaultGlobals, defaultImportHandlers, brandKey, memoryMb) {
4128
+ constructor(id, pool, declaredGlobals, defaultImportHandlers, declaredImports, brandKey, memoryMb) {
4146
4129
  this.id = id;
4147
4130
  this.pool = pool;
4148
- this.defaultGlobals = defaultGlobals;
4131
+ this.declaredGlobals = declaredGlobals;
4149
4132
  this.defaultImportHandlers = defaultImportHandlers;
4133
+ this.declaredImports = declaredImports;
4150
4134
  this.brandKey = brandKey;
4151
4135
  this.memoryMb = memoryMb;
4152
4136
  }
@@ -4166,7 +4150,7 @@ var PrefixImpl = class {
4166
4150
  * @deprecated Renamed to {@link PrefixImpl.execute}; kept as an alias.
4167
4151
  */
4168
4152
  async run(options) {
4169
- return await this.dispatch(options, { code: options.code });
4153
+ return await this.dispatch(options, async () => ({ code: options.code }));
4170
4154
  }
4171
4155
  /**
4172
4156
  * Call a function exported by this prefix's module — no postfix compiled.
@@ -4174,21 +4158,17 @@ var PrefixImpl = class {
4174
4158
  * @param options
4175
4159
  */
4176
4160
  async call(options) {
4177
- const streams = new StreamSourceRegistry();
4178
- const call = {
4161
+ return await this.dispatch(options, async (streams) => ({ call: {
4179
4162
  exportPath: options.export,
4180
4163
  argsBlob: await serializeHostValue(options.args ?? [], this.brandKey, streams)
4181
- };
4182
- return await this.dispatch(options, {
4183
- call,
4184
- streams
4185
- });
4164
+ } }));
4186
4165
  }
4187
4166
  /**
4188
4167
  * Shared body of {@link run} and {@link call}: disposal/abort guards,
4189
4168
  * bridge-global extraction, import-rebind merging, and the PrefixRun round
4190
- * trip. `payload` carries the postfix source or the call — exactly one, as
4191
- * the wire demands; it also selects how the result blob decodes.
4169
+ * trip. `buildPayload` yields the postfix source or the call — exactly one,
4170
+ * as the wire demands; it also selects how the result blob decodes. It runs
4171
+ * after the checks, so a refused run never registers a stream source.
4192
4172
  * @param options
4193
4173
  * @param options.globals
4194
4174
  * @param options.imports
@@ -4196,58 +4176,32 @@ var PrefixImpl = class {
4196
4176
  * @param options.signal
4197
4177
  * @param options.hardAbortSignal
4198
4178
  * @param options.filename
4199
- * @param payload
4179
+ * @param buildPayload
4200
4180
  */
4201
- async dispatch(options, payload) {
4202
- if (!this._alive) return {
4203
- status: "failed",
4204
- ok: false,
4205
- error: {
4206
- code: "ERR_PREFIX_DISPOSED",
4207
- name: "Error",
4208
- message: `prefix '${this.id}' has been disposed`
4209
- },
4210
- stdout: [],
4211
- stderr: [],
4212
- durationMs: 0,
4213
- wallTimeMs: 0,
4214
- cpuTimeMs: 0,
4215
- bridgeCalls: []
4216
- };
4181
+ async dispatch(options, buildPayload) {
4182
+ if (!this._alive) throw setupError("ERR_PREFIX_DISPOSED", `prefix '${this.id}' has been disposed or never existed`);
4217
4183
  if (options.signal?.aborted) return abortedResult(options.signal.reason);
4218
4184
  if (options.hardAbortSignal?.aborted) return abortedResult(options.hardAbortSignal.reason);
4185
+ validateLimits(options.limits);
4219
4186
  if (options.limits !== void 0 && "memoryMb" in options.limits) throw new TypeError("[@iso4/sandbox] limits.memoryMb is not a per-run option for prefix runs: the cap is baked into the shared warm isolates at creation — set it per prefix via prepare({ memoryMb }), or the sandbox default via createSandbox({ memoryMb })");
4220
- const { defs, dispatch } = extractBridgeGlobals(options.globals ?? {}, this.defaultGlobals);
4187
+ const { defs, dispatch } = extractBridgeGlobals(options.globals ?? {}, this.declaredGlobals);
4221
4188
  let merged;
4222
4189
  try {
4223
- merged = mergeRebindImports(options.imports, this.defaultImportHandlers);
4190
+ merged = mergeRebindImports(options.imports, this.defaultImportHandlers, this.declaredImports);
4224
4191
  } catch (e) {
4225
- if (e instanceof ImportRebindError) return {
4226
- status: "failed",
4227
- ok: false,
4228
- error: {
4229
- code: e.code,
4230
- name: "Error",
4231
- message: e.message
4232
- },
4233
- stdout: [],
4234
- stderr: [],
4235
- durationMs: 0,
4236
- wallTimeMs: 0,
4237
- cpuTimeMs: 0,
4238
- bridgeCalls: []
4239
- };
4192
+ if (e instanceof ImportRebindError) throw setupError(e.code, e.message);
4240
4193
  throw e;
4241
4194
  }
4242
- const streams = payload.streams ?? new StreamSourceRegistry();
4195
+ const streams = new StreamSourceRegistry();
4243
4196
  try {
4197
+ const payload = await buildPayload(streams);
4244
4198
  return await this.pool.withClient(async (client, queueWaitMs) => {
4245
4199
  const raw = await client.prefixRun({
4246
4200
  prefixId: this.id,
4247
4201
  code: payload.code,
4248
4202
  filename: options.filename,
4249
4203
  limits: {
4250
- ...options.limits,
4204
+ ...wireLimits(options.limits),
4251
4205
  ...heapCapsForWire(this.memoryMb)
4252
4206
  },
4253
4207
  globals: defs,
@@ -4260,6 +4214,10 @@ var PrefixImpl = class {
4260
4214
  streams
4261
4215
  });
4262
4216
  const decoded = withBodyStreamBinder((id) => raw.outStreams.attach(id), () => payload.call === void 0 ? decodeRunCompletionPayload(raw.result, void 0, raw.droppedCallIds).result : decodeRunCompletionPayload(raw.result, "call", raw.droppedCallIds).result);
4217
+ if (decoded.status === "failed" && SETUP_ERROR_CODES.has(decoded.error.code)) throw thrownRunError({
4218
+ ...decoded.error,
4219
+ code: decoded.error.code
4220
+ });
4263
4221
  if (raw.epilogue !== void 0 && raw.graceWork && decoded.ok) decoded.waitUntil = raw.epilogue.then(waitUntilResultFrom);
4264
4222
  if (decoded.status === "failed" && decoded.error.code === "ERR_ABORTED") {
4265
4223
  if (options.signal?.aborted) return abortedResult(options.signal.reason, decoded);
@@ -4278,6 +4236,9 @@ var PrefixImpl = class {
4278
4236
  async dispose() {
4279
4237
  if (!this._alive) return;
4280
4238
  this._alive = false;
4239
+ this.declaredGlobals = /* @__PURE__ */ new Map();
4240
+ this.defaultImportHandlers = /* @__PURE__ */ new Map();
4241
+ this.declaredImports = [];
4281
4242
  await this.pool.withClient((client) => client.disposePrefix(this.id));
4282
4243
  }
4283
4244
  async [Symbol.asyncDispose]() {
@@ -4285,4 +4246,4 @@ var PrefixImpl = class {
4285
4246
  }
4286
4247
  };
4287
4248
  //#endregion
4288
- export { SANDBOX_GLOBALS, createSandbox };
4249
+ export { createSandbox };