@iso4/sandbox 0.6.3 → 0.8.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/README.md CHANGED
@@ -70,7 +70,7 @@ await sandbox.dispose()
70
70
 
71
71
  ## How globals work
72
72
 
73
- `globals` wires any non-reserved name directly into the sandbox's global
73
+ `globals` wires any non-reserved identifier directly into the sandbox's global
74
74
  object as a bridge stub. The bridge is fully generic — `fetch` is not
75
75
  special-cased:
76
76
 
@@ -88,6 +88,17 @@ const options = {
88
88
  Functions in bridge return values are currently dropped — return plain data,
89
89
  not class instances with methods.
90
90
 
91
+ Global names must be usable by bare name: iso4 refuses one that is not a
92
+ JavaScript identifier (`my-tool`) or is a reserved word (`class`, `true`)
93
+ with `ERR_INVALID_GLOBAL_NAME`. Unicode identifiers (`café`) and `eval` and
94
+ `arguments` are allowed.
95
+
96
+ `SANDBOX_GLOBALS` is a `Set` of every name a fresh sandbox already defines.
97
+ Check generated names against it before installing them. `RESERVED_WORDS`
98
+ is a `Set` of names that cannot be a binding in module source, such as
99
+ `class` or `eval`; iso4 refuses host-module export names in it, and global
100
+ names in it other than `eval` and `arguments`.
101
+
91
102
  ## TypeScript-checked rebinding
92
103
 
93
104
  `prepare()` infers the globals shape `G` from what you pass, and the
package/dist/index.d.mts CHANGED
@@ -161,8 +161,9 @@ interface ResourceLimits {
161
161
  graceMs?: number;
162
162
  }
163
163
  /**
164
- * Host-provided globals. Any name not reserved by V8 or the runtime is
165
- * permitted. Each value becomes a bridge stub in the sandbox global object.
164
+ * Host-provided globals. Any name not reserved by the runtime that sandbox
165
+ * code can reference by bare name is permitted. Each value becomes a bridge
166
+ * stub in the sandbox global object.
166
167
  *
167
168
  * Reserved names (rejected with `ERR_RESERVED_NAME`): `console`,
168
169
  * `waitUntil`, `setTimeout`, `clearTimeout`, `Headers`, `Request`,
@@ -170,6 +171,15 @@ interface ResourceLimits {
170
171
  * are owned by the runtime; shadowing `Response` would silently break
171
172
  * serialization.
172
173
  *
174
+ * A name sandbox code cannot reference by bare name is rejected with
175
+ * `ERR_INVALID_GLOBAL_NAME`: one that is not a JavaScript identifier
176
+ * (`my-tool`, `1abc`; Unicode identifiers such as `café` are fine), or one in
177
+ * {@link RESERVED_WORDS} other than `eval` and `arguments`. Keys nested inside
178
+ * a global's value are unrestricted.
179
+ *
180
+ * {@link SANDBOX_GLOBALS} holds every name a fresh sandbox defines, V8
181
+ * built-ins included.
182
+ *
173
183
  * Common usage:
174
184
  * ```ts
175
185
  * globals: {
@@ -898,7 +908,8 @@ interface Prefix<G extends HostGlobals = {}, M extends Imports = {}> {
898
908
  * `G` is the declared-globals shape from the matching `precompile()` call.
899
909
  * The `globals` field is typed as `Partial<G>` — only names present in `G`
900
910
  * may be overridden. Passing any other name is a TypeScript error at compile
901
- * time and `ERR_UNDECLARED_BINDING` at runtime.
911
+ * time and `ERR_UNDECLARED_BINDING` at runtime (`ERR_INVALID_GLOBAL_NAME`
912
+ * first, for a name sandbox code cannot reference by bare name).
902
913
  */
903
914
  interface PrefixRunOptions<G extends HostGlobals, M extends Imports> {
904
915
  /**
@@ -908,7 +919,8 @@ interface PrefixRunOptions<G extends HostGlobals, M extends Imports> {
908
919
  /**
909
920
  * Override implementations for a **subset** of globals declared at
910
921
  * precompile time. Only names present in `G` are accepted (TypeScript
911
- * error + runtime `ERR_UNDECLARED_BINDING` for anything else), but the
922
+ * error + runtime `ERR_UNDECLARED_BINDING` for anything else, or
923
+ * `ERR_INVALID_GLOBAL_NAME` for a name unusable by bare name), but the
912
924
  * function signature does not need to match the precompile-time handler
913
925
  * exactly — any `HostExportFunction`-compatible value is accepted.
914
926
  */
@@ -1461,9 +1473,28 @@ interface RunError {
1461
1473
  * `RunError.resetCause`.
1462
1474
  */
1463
1475
  type ResetCause = "cpu" | "memory" | "wall" | "abort" | "internal";
1464
- type RunErrorCode = "ERR_USER_CODE" | "ERR_MEMORY_LIMIT" | "ERR_CPU_TIMEOUT" | "ERR_WALL_TIMEOUT" | "ERR_ABORTED" | "ERR_MODULE_NOT_FOUND" | "ERR_COMPILE" | "ERR_FUNCTION_ARGUMENT_NOT_SUPPORTED" | "ERR_EXPORT_NOT_SERIALIZABLE" | "ERR_TYPE_NOT_SERIALIZABLE" | "ERR_EXPORT_TOO_LARGE" | "ERR_CALL_TARGET_NOT_FOUND" | "ERR_HOST_BRIDGE" | "ERR_BRIDGE_PAYLOAD_TOO_LARGE" | "ERR_BRIDGE_CALL_LIMIT_EXCEEDED" | "ERR_INSTANCE_RESET" | "ERR_CAPACITY_MEMORY" | "ERR_QUEUE_FULL" | "ERR_UNDECLARED_BINDING" | "ERR_RESERVED_NAME" | "ERR_FROZEN_BINDING" | "ERR_INVALID_REBIND" | "ERR_PREFIX_DID_NOT_SETTLE" | "ERR_PREFIX_BRIDGE_CALL" | "ERR_WARMUP_LIMIT" | "ERR_PREFIX_DISPOSED" | "ERR_PROTOCOL_DESYNC" | "ERR_INTERNAL";
1476
+ type RunErrorCode = "ERR_USER_CODE" | "ERR_MEMORY_LIMIT" | "ERR_CPU_TIMEOUT" | "ERR_WALL_TIMEOUT" | "ERR_ABORTED" | "ERR_MODULE_NOT_FOUND" | "ERR_COMPILE" | "ERR_FUNCTION_ARGUMENT_NOT_SUPPORTED" | "ERR_EXPORT_NOT_SERIALIZABLE" | "ERR_TYPE_NOT_SERIALIZABLE" | "ERR_EXPORT_TOO_LARGE" | "ERR_CALL_TARGET_NOT_FOUND" | "ERR_HOST_BRIDGE" | "ERR_BRIDGE_PAYLOAD_TOO_LARGE" | "ERR_BRIDGE_CALL_LIMIT_EXCEEDED" | "ERR_INSTANCE_RESET" | "ERR_CAPACITY_MEMORY" | "ERR_QUEUE_FULL" | "ERR_UNDECLARED_BINDING" | "ERR_RESERVED_NAME" | "ERR_INVALID_GLOBAL_NAME" | "ERR_FROZEN_BINDING" | "ERR_INVALID_REBIND" | "ERR_PREFIX_DID_NOT_SETTLE" | "ERR_PREFIX_BRIDGE_CALL" | "ERR_WARMUP_LIMIT" | "ERR_PREFIX_DISPOSED" | "ERR_PROTOCOL_DESYNC" | "ERR_INTERNAL";
1477
+ //#endregion
1478
+ //#region src/globals.d.ts
1479
+ /**
1480
+ * Every global name a fresh sandbox defines: the JS built-ins of the bundled
1481
+ * V8 plus the runtime's own (`console`, `waitUntil`, timers, web classes).
1482
+ * A host global under one of these names replaces the built-in, or is
1483
+ * silently ignored for `undefined`, `NaN` and `Infinity`. Names the grammar
1484
+ * forbids outright are in {@link RESERVED_WORDS}.
1485
+ */
1486
+ declare const SANDBOX_GLOBALS: ReadonlySet<string>;
1487
+ /**
1488
+ * Every name that cannot be a binding in module source, so it cannot be a
1489
+ * host-module export name. As host global names, all but `eval` and
1490
+ * `arguments` are refused with `ERR_INVALID_GLOBAL_NAME`. `default` is
1491
+ * included, though iso4 itself accepts it as a host-module export (emitted as
1492
+ * `export default`). Unlike {@link SANDBOX_GLOBALS}, which lists names that
1493
+ * are taken, these are names the grammar forbids.
1494
+ */
1495
+ declare const RESERVED_WORDS: ReadonlySet<string>;
1465
1496
  //#endregion
1466
1497
  //#region src/index.d.ts
1467
1498
  declare function createSandbox(options?: SandboxOptions): Promise<Sandbox>;
1468
1499
  //#endregion
1469
- export { type BridgeCallEntry, type BridgeCallEntryBase, type BridgeCallFailureReason, type BridgeGlobal, type BridgeWithShim, type CallResult, type CallSuccess, type CallTarget, type CreateSandbox, type DataGlobal, type GlobalOptions, type HostExportData, type HostExportFunction, type HostGlobalValue, type HostGlobals, type HostModuleObject, type HostModuleValue, type ImportValue, type Imports, type MemoryLimit, type OneOffResourceLimits, type PrecompileOptions, type Prefix, type PrefixCallOptions, type PrefixRunOptions, type ReadExportsOptions, type ReadExportsResult, type RebindGlobals, type RebindHostModule, type RebindImports, type RebindValue, type ResetCause, type ResourceLimits, type RunCallOptions, type RunError, type RunErrorCode, type RunFailure, type RunOptions, type RunResult, type RunSuccess, type Sandbox, type SandboxExports, type SandboxOptions, type SandboxStats, type StringGlobal, type WaitUntilResult, createSandbox };
1500
+ export { type BridgeCallEntry, type BridgeCallEntryBase, type BridgeCallFailureReason, type BridgeGlobal, type BridgeWithShim, type CallResult, type CallSuccess, type CallTarget, type CreateSandbox, type DataGlobal, type GlobalOptions, type HostExportData, type HostExportFunction, type HostGlobalValue, type HostGlobals, type HostModuleObject, type HostModuleValue, type ImportValue, type Imports, type MemoryLimit, type OneOffResourceLimits, type PrecompileOptions, type Prefix, type PrefixCallOptions, type PrefixRunOptions, RESERVED_WORDS, type ReadExportsOptions, type ReadExportsResult, type RebindGlobals, type RebindHostModule, type RebindImports, type RebindValue, type ResetCause, type ResourceLimits, type RunCallOptions, type RunError, type RunErrorCode, type RunFailure, type RunOptions, type RunResult, type RunSuccess, SANDBOX_GLOBALS, type Sandbox, type SandboxExports, type SandboxOptions, type SandboxStats, type StringGlobal, type WaitUntilResult, createSandbox };
package/dist/index.mjs CHANGED
@@ -655,7 +655,11 @@ const TsToRustMessageTypes = {
655
655
  * The host dropped an outbound streamed body (consumer cancel, dispose);
656
656
  * the runtime cancels the guest source.
657
657
  */
658
- StreamCancel: 12
658
+ StreamCancel: 12,
659
+ /**
660
+ * Orderly close: the host is done with this connection. Empty payload.
661
+ */
662
+ Close: 13
659
663
  };
660
664
  const RustToTsMessageTypes = {
661
665
  BridgeCall: 1,
@@ -1878,6 +1882,337 @@ function parseRustToTsMessageType(byte) {
1878
1882
  function formatByte(byte) {
1879
1883
  return `0x${byte.toString(16).padStart(2, "0")}`;
1880
1884
  }
1885
+ //#endregion
1886
+ //#region src/globals.ts
1887
+ /**
1888
+ * Every global name a fresh sandbox defines: the JS built-ins of the bundled
1889
+ * V8 plus the runtime's own (`console`, `waitUntil`, timers, web classes).
1890
+ * A host global under one of these names replaces the built-in, or is
1891
+ * silently ignored for `undefined`, `NaN` and `Infinity`. Names the grammar
1892
+ * forbids outright are in {@link RESERVED_WORDS}.
1893
+ */
1894
+ const SANDBOX_GLOBALS = new Set([
1895
+ "AggregateError",
1896
+ "Array",
1897
+ "ArrayBuffer",
1898
+ "AsyncDisposableStack",
1899
+ "Atomics",
1900
+ "BigInt",
1901
+ "BigInt64Array",
1902
+ "BigUint64Array",
1903
+ "Boolean",
1904
+ "DataView",
1905
+ "Date",
1906
+ "DisposableStack",
1907
+ "Error",
1908
+ "EvalError",
1909
+ "FinalizationRegistry",
1910
+ "Float16Array",
1911
+ "Float32Array",
1912
+ "Float64Array",
1913
+ "Function",
1914
+ "Headers",
1915
+ "Infinity",
1916
+ "Int16Array",
1917
+ "Int32Array",
1918
+ "Int8Array",
1919
+ "Intl",
1920
+ "Iterator",
1921
+ "JSON",
1922
+ "Map",
1923
+ "Math",
1924
+ "NaN",
1925
+ "Number",
1926
+ "Object",
1927
+ "Promise",
1928
+ "Proxy",
1929
+ "RangeError",
1930
+ "ReferenceError",
1931
+ "Reflect",
1932
+ "RegExp",
1933
+ "Request",
1934
+ "Response",
1935
+ "Set",
1936
+ "String",
1937
+ "SuppressedError",
1938
+ "Symbol",
1939
+ "SyntaxError",
1940
+ "Temporal",
1941
+ "TextDecoder",
1942
+ "TextEncoder",
1943
+ "TypeError",
1944
+ "URIError",
1945
+ "URL",
1946
+ "URLSearchParams",
1947
+ "Uint16Array",
1948
+ "Uint32Array",
1949
+ "Uint8Array",
1950
+ "Uint8ClampedArray",
1951
+ "WeakMap",
1952
+ "WeakRef",
1953
+ "WeakSet",
1954
+ "clearTimeout",
1955
+ "console",
1956
+ "decodeURI",
1957
+ "decodeURIComponent",
1958
+ "encodeURI",
1959
+ "encodeURIComponent",
1960
+ "escape",
1961
+ "eval",
1962
+ "globalThis",
1963
+ "isFinite",
1964
+ "isNaN",
1965
+ "parseFloat",
1966
+ "parseInt",
1967
+ "setTimeout",
1968
+ "undefined",
1969
+ "unescape",
1970
+ "waitUntil"
1971
+ ]);
1972
+ /**
1973
+ * Every name that cannot be a binding in module source, so it cannot be a
1974
+ * host-module export name. As host global names, all but `eval` and
1975
+ * `arguments` are refused with `ERR_INVALID_GLOBAL_NAME`. `default` is
1976
+ * included, though iso4 itself accepts it as a host-module export (emitted as
1977
+ * `export default`). Unlike {@link SANDBOX_GLOBALS}, which lists names that
1978
+ * are taken, these are names the grammar forbids.
1979
+ */
1980
+ const RESERVED_WORDS = new Set([
1981
+ "break",
1982
+ "case",
1983
+ "catch",
1984
+ "class",
1985
+ "const",
1986
+ "continue",
1987
+ "debugger",
1988
+ "default",
1989
+ "delete",
1990
+ "do",
1991
+ "else",
1992
+ "export",
1993
+ "extends",
1994
+ "finally",
1995
+ "for",
1996
+ "function",
1997
+ "if",
1998
+ "import",
1999
+ "in",
2000
+ "instanceof",
2001
+ "new",
2002
+ "return",
2003
+ "super",
2004
+ "switch",
2005
+ "this",
2006
+ "throw",
2007
+ "try",
2008
+ "typeof",
2009
+ "var",
2010
+ "void",
2011
+ "while",
2012
+ "with",
2013
+ "yield",
2014
+ "let",
2015
+ "static",
2016
+ "enum",
2017
+ "await",
2018
+ "implements",
2019
+ "package",
2020
+ "protected",
2021
+ "interface",
2022
+ "private",
2023
+ "public",
2024
+ "null",
2025
+ "true",
2026
+ "false",
2027
+ "eval",
2028
+ "arguments"
2029
+ ]);
2030
+ /**
2031
+ * A JavaScript identifier name, Unicode included: ID_Start/ID_Continue plus
2032
+ * `$`, `_`, ZWNJ and ZWJ.
2033
+ */
2034
+ const IDENTIFIER_NAME = /^[\p{ID_Start}$_][\p{ID_Continue}$\u200C\u200D]*$/u;
2035
+ /**
2036
+ * A host global name sandbox code cannot reference by bare name. Carries the
2037
+ * same code and message the runtime reports for it.
2038
+ */
2039
+ var GlobalNameError = class extends Error {
2040
+ code = "ERR_INVALID_GLOBAL_NAME";
2041
+ };
2042
+ function isBridgeWithShim(v) {
2043
+ return typeof v === "object" && v !== null && v.kind === "bridge-with-shim";
2044
+ }
2045
+ function isDataGlobal(v) {
2046
+ return typeof v === "object" && v !== null && v.kind === "data";
2047
+ }
2048
+ function isBridgeGlobal(v) {
2049
+ return typeof v === "object" && v !== null && v.kind === "bridge";
2050
+ }
2051
+ function isStringGlobal(v) {
2052
+ return typeof v === "object" && v !== null && v.kind === "string";
2053
+ }
2054
+ /**
2055
+ * Private bridge-dispatch name for a `BridgeWithShim` handler. This is a wire
2056
+ * dispatch key and an object-property key — never interpolated into generated
2057
+ * code — so any global name is safe. The runtime recognises the
2058
+ * `__iso4_<name>_h` convention (`public_record_name` in `v8.rs`) and reports
2059
+ * bridge records under the public `<name>`.
2060
+ * @param name public global name
2061
+ */
2062
+ function shimHandlerName(name) {
2063
+ return `__iso4_${name}_h`;
2064
+ }
2065
+ /**
2066
+ * Throw {@link GlobalNameError} unless sandbox code can reference `name` by
2067
+ * bare name. Mirrored by `check_bare_global_name` in `v8.rs`.
2068
+ * @param name host global name
2069
+ */
2070
+ function checkGlobalName(name) {
2071
+ if (name !== "eval" && name !== "arguments" && (!IDENTIFIER_NAME.test(name) || RESERVED_WORDS.has(name))) throw new GlobalNameError(`global '${name}' cannot be referenced by bare name in sandbox code`);
2072
+ }
2073
+ /**
2074
+ * Lower a `HostGlobals` map into wire-shaped `defs` plus the bridge-dispatch
2075
+ * map. See the module comment for the split. Throws {@link GlobalNameError}
2076
+ * for a name sandbox code cannot reference by bare name.
2077
+ * - `HostExportFunction` → `{ kind: 'bridge' }` + dispatch entry.
2078
+ * - `string` → `{ kind: 'string', expr }` (evaluated by Rust).
2079
+ * - `DataGlobal` → `{ kind: 'data', value }` (materialised by Rust).
2080
+ * - `BridgeWithShim` → `{ kind: 'shim', shim, handlerName }` + a dispatch
2081
+ * entry for the private handler under `handlerName`.
2082
+ * @param globals
2083
+ */
2084
+ function processGlobals(globals) {
2085
+ const defs = [];
2086
+ const dispatch = {};
2087
+ for (const [name, value] of Object.entries(globals)) {
2088
+ checkGlobalName(name);
2089
+ if (typeof value === "function") {
2090
+ defs.push({
2091
+ kind: "bridge",
2092
+ name,
2093
+ enumerable: true
2094
+ });
2095
+ dispatch[name] = value;
2096
+ } else if (typeof value === "string") defs.push({
2097
+ kind: "string",
2098
+ name,
2099
+ expr: value,
2100
+ enumerable: true
2101
+ });
2102
+ else if (isBridgeGlobal(value)) {
2103
+ defs.push({
2104
+ kind: "bridge",
2105
+ name,
2106
+ enumerable: value.enumerable ?? true
2107
+ });
2108
+ dispatch[name] = value.handler;
2109
+ } else if (isStringGlobal(value)) defs.push({
2110
+ kind: "string",
2111
+ name,
2112
+ expr: value.expr,
2113
+ enumerable: value.enumerable ?? true
2114
+ });
2115
+ else if (isDataGlobal(value)) defs.push({
2116
+ kind: "data",
2117
+ name,
2118
+ value: value.value,
2119
+ enumerable: value.enumerable ?? true
2120
+ });
2121
+ else if (isBridgeWithShim(value)) {
2122
+ const handlerName = shimHandlerName(name);
2123
+ defs.push({
2124
+ kind: "shim",
2125
+ name,
2126
+ shim: value.shim,
2127
+ handlerName,
2128
+ enumerable: value.enumerable ?? true
2129
+ });
2130
+ dispatch[handlerName] = value.handler;
2131
+ }
2132
+ }
2133
+ return {
2134
+ defs,
2135
+ dispatch
2136
+ };
2137
+ }
2138
+ /**
2139
+ * Resolve bridge globals for a `prefix.run()` call.
2140
+ *
2141
+ * String/data globals and shim *wrappers* are already compiled into the
2142
+ * declared prefix state, replayed by the runtime when the prefix evaluates —
2143
+ * only the bridge *stubs* they call need re-installing per run (bridge stubs
2144
+ * are bound to the run's socket). So
2145
+ * every returned def is `kind: 'bridge'`, and shimmed globals are routed to
2146
+ * their private `__iso4_<name>_h` key so rebinding updates the handler the
2147
+ * shim calls, without touching the shim itself.
2148
+ * @param runGlobals
2149
+ * @param precompileGlobals
2150
+ */
2151
+ /**
2152
+ * Resolve a per-run override for a declared bridge global.
2153
+ *
2154
+ * An omitted key falls back to the precompile-time handler (the intended
2155
+ * default). But a key that IS supplied yet is not a function — the runtime
2156
+ * shape TypeScript cannot catch, e.g. a tenant handler that resolves to
2157
+ * `undefined` — throws instead of silently reusing the (often broader) default,
2158
+ * which would be a fail-open exactly where the API is used to narrow privilege.
2159
+ * This matches the imports side, which already rejects a non-function rebind.
2160
+ * @param runGlobals the per-run rebind map
2161
+ * @param name the declared global's name
2162
+ * @param fallback the precompile-time handler used when no override is supplied
2163
+ */
2164
+ function resolveOverride(runGlobals, name, fallback) {
2165
+ if (!Object.hasOwn(runGlobals, name)) return fallback;
2166
+ const override = runGlobals[name];
2167
+ if (typeof override !== "function") throw new TypeError(`[iso4] global override "${name}" must be a function, got ${override === null ? "null" : typeof override}`);
2168
+ return override;
2169
+ }
2170
+ function extractBridgeGlobals(runGlobals, precompileGlobals) {
2171
+ const defs = [];
2172
+ const dispatch = {};
2173
+ for (const [name, value] of Object.entries(precompileGlobals)) {
2174
+ if (typeof value === "string" || isStringGlobal(value) || isDataGlobal(value)) continue;
2175
+ if (isBridgeWithShim(value)) {
2176
+ const handlerName = shimHandlerName(name);
2177
+ defs.push({
2178
+ kind: "bridge",
2179
+ name: handlerName,
2180
+ enumerable: true
2181
+ });
2182
+ dispatch[handlerName] = resolveOverride(runGlobals, name, value.handler);
2183
+ } else if (isBridgeGlobal(value)) {
2184
+ defs.push({
2185
+ kind: "bridge",
2186
+ name,
2187
+ enumerable: value.enumerable ?? true
2188
+ });
2189
+ dispatch[name] = resolveOverride(runGlobals, name, value.handler);
2190
+ } else if (typeof value === "function") {
2191
+ defs.push({
2192
+ kind: "bridge",
2193
+ name,
2194
+ enumerable: true
2195
+ });
2196
+ dispatch[name] = resolveOverride(runGlobals, name, value);
2197
+ }
2198
+ }
2199
+ for (const [name, override] of Object.entries(runGlobals)) {
2200
+ if (name in precompileGlobals) continue;
2201
+ checkGlobalName(name);
2202
+ if (typeof override === "function") {
2203
+ defs.push({
2204
+ kind: "bridge",
2205
+ name,
2206
+ enumerable: true
2207
+ });
2208
+ dispatch[name] = override;
2209
+ }
2210
+ }
2211
+ return {
2212
+ defs,
2213
+ dispatch
2214
+ };
2215
+ }
1881
2216
  /**
1882
2217
  * The dispatch-map key for one host-module function leaf. The NUL separator
1883
2218
  * cannot collide with anything a specifier or dot-joined path can contain in
@@ -2025,54 +2360,6 @@ function isPlainObject(value) {
2025
2360
  const proto = Object.getPrototypeOf(value);
2026
2361
  return proto === null || proto === Object.prototype;
2027
2362
  }
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
2363
  /**
2077
2364
  * Whether `name` can appear as a named ESM export. JS identifier rules plus
2078
2365
  * a reserved-word filter. `default` is allowed (the runtime emits it as
@@ -2082,7 +2369,7 @@ const RESERVED_WORDS = new Set([
2082
2369
  */
2083
2370
  function isValidExportIdentifier(name) {
2084
2371
  if (name === "default") return true;
2085
- if (!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name)) return false;
2372
+ if (!IDENTIFIER_NAME.test(name)) return false;
2086
2373
  if (RESERVED_WORDS.has(name)) return false;
2087
2374
  return true;
2088
2375
  }
@@ -2291,6 +2578,7 @@ var RuntimeIpcClient = class RuntimeIpcClient {
2291
2578
  })));
2292
2579
  await client.awaitHello();
2293
2580
  } catch (error) {
2581
+ client.broken = true;
2294
2582
  await client.dispose();
2295
2583
  throw error;
2296
2584
  }
@@ -2539,6 +2827,7 @@ var RuntimeIpcClient = class RuntimeIpcClient {
2539
2827
  async dispose() {
2540
2828
  if (this.disposed) return;
2541
2829
  this.disposed = true;
2830
+ if (!this.broken && !this.socket.destroyed) this.socket.write(encodeTsToRustFrame(TsToRustMessageTypes.Close, new Uint8Array(0)));
2542
2831
  this.socket.end();
2543
2832
  await new Promise((resolve) => {
2544
2833
  if (this.socket.destroyed) {
@@ -3300,169 +3589,6 @@ var RunPool = class {
3300
3589
  }
3301
3590
  };
3302
3591
  //#endregion
3303
- //#region src/globals.ts
3304
- function isBridgeWithShim(v) {
3305
- return typeof v === "object" && v !== null && v.kind === "bridge-with-shim";
3306
- }
3307
- function isDataGlobal(v) {
3308
- return typeof v === "object" && v !== null && v.kind === "data";
3309
- }
3310
- function isBridgeGlobal(v) {
3311
- return typeof v === "object" && v !== null && v.kind === "bridge";
3312
- }
3313
- function isStringGlobal(v) {
3314
- return typeof v === "object" && v !== null && v.kind === "string";
3315
- }
3316
- /**
3317
- * Private bridge-dispatch name for a `BridgeWithShim` handler. This is a wire
3318
- * dispatch key and an object-property key — never interpolated into generated
3319
- * code — so any global name is safe. The runtime recognises the
3320
- * `__iso4_<name>_h` convention (`public_record_name` in `v8.rs`) and reports
3321
- * bridge records under the public `<name>`.
3322
- * @param name public global name
3323
- */
3324
- function shimHandlerName(name) {
3325
- return `__iso4_${name}_h`;
3326
- }
3327
- /**
3328
- * Lower a `HostGlobals` map into wire-shaped `defs` plus the bridge-dispatch
3329
- * map. See the module comment for the split.
3330
- * - `HostExportFunction` → `{ kind: 'bridge' }` + dispatch entry.
3331
- * - `string` → `{ kind: 'string', expr }` (evaluated by Rust).
3332
- * - `DataGlobal` → `{ kind: 'data', value }` (materialised by Rust).
3333
- * - `BridgeWithShim` → `{ kind: 'shim', shim, handlerName }` + a dispatch
3334
- * entry for the private handler under `handlerName`.
3335
- * @param globals
3336
- */
3337
- function processGlobals(globals) {
3338
- const defs = [];
3339
- const dispatch = {};
3340
- for (const [name, value] of Object.entries(globals)) if (typeof value === "function") {
3341
- defs.push({
3342
- kind: "bridge",
3343
- name,
3344
- enumerable: true
3345
- });
3346
- dispatch[name] = value;
3347
- } else if (typeof value === "string") defs.push({
3348
- kind: "string",
3349
- name,
3350
- expr: value,
3351
- enumerable: true
3352
- });
3353
- else if (isBridgeGlobal(value)) {
3354
- defs.push({
3355
- kind: "bridge",
3356
- name,
3357
- enumerable: value.enumerable ?? true
3358
- });
3359
- dispatch[name] = value.handler;
3360
- } else if (isStringGlobal(value)) defs.push({
3361
- kind: "string",
3362
- name,
3363
- expr: value.expr,
3364
- enumerable: value.enumerable ?? true
3365
- });
3366
- else if (isDataGlobal(value)) defs.push({
3367
- kind: "data",
3368
- name,
3369
- value: value.value,
3370
- enumerable: value.enumerable ?? true
3371
- });
3372
- else if (isBridgeWithShim(value)) {
3373
- const handlerName = shimHandlerName(name);
3374
- defs.push({
3375
- kind: "shim",
3376
- name,
3377
- shim: value.shim,
3378
- handlerName,
3379
- enumerable: value.enumerable ?? true
3380
- });
3381
- dispatch[handlerName] = value.handler;
3382
- }
3383
- return {
3384
- defs,
3385
- dispatch
3386
- };
3387
- }
3388
- /**
3389
- * Resolve bridge globals for a `prefix.run()` call.
3390
- *
3391
- * String/data globals and shim *wrappers* are already compiled into the
3392
- * declared prefix state, replayed by the runtime when the prefix evaluates —
3393
- * only the bridge *stubs* they call need re-installing per run (bridge stubs
3394
- * are bound to the run's socket). So
3395
- * every returned def is `kind: 'bridge'`, and shimmed globals are routed to
3396
- * their private `__iso4_<name>_h` key so rebinding updates the handler the
3397
- * shim calls, without touching the shim itself.
3398
- * @param runGlobals
3399
- * @param precompileGlobals
3400
- */
3401
- /**
3402
- * Resolve a per-run override for a declared bridge global.
3403
- *
3404
- * An omitted key falls back to the precompile-time handler (the intended
3405
- * default). But a key that IS supplied yet is not a function — the runtime
3406
- * shape TypeScript cannot catch, e.g. a tenant handler that resolves to
3407
- * `undefined` — throws instead of silently reusing the (often broader) default,
3408
- * which would be a fail-open exactly where the API is used to narrow privilege.
3409
- * This matches the imports side, which already rejects a non-function rebind.
3410
- * @param runGlobals the per-run rebind map
3411
- * @param name the declared global's name
3412
- * @param fallback the precompile-time handler used when no override is supplied
3413
- */
3414
- function resolveOverride(runGlobals, name, fallback) {
3415
- if (!Object.hasOwn(runGlobals, name)) return fallback;
3416
- const override = runGlobals[name];
3417
- if (typeof override !== "function") throw new TypeError(`[iso4] global override "${name}" must be a function, got ${override === null ? "null" : typeof override}`);
3418
- return override;
3419
- }
3420
- function extractBridgeGlobals(runGlobals, precompileGlobals) {
3421
- const defs = [];
3422
- const dispatch = {};
3423
- for (const [name, value] of Object.entries(precompileGlobals)) {
3424
- if (typeof value === "string" || isStringGlobal(value) || isDataGlobal(value)) continue;
3425
- if (isBridgeWithShim(value)) {
3426
- const handlerName = shimHandlerName(name);
3427
- defs.push({
3428
- kind: "bridge",
3429
- name: handlerName,
3430
- enumerable: true
3431
- });
3432
- dispatch[handlerName] = resolveOverride(runGlobals, name, value.handler);
3433
- } else if (isBridgeGlobal(value)) {
3434
- defs.push({
3435
- kind: "bridge",
3436
- name,
3437
- enumerable: value.enumerable ?? true
3438
- });
3439
- dispatch[name] = resolveOverride(runGlobals, name, value.handler);
3440
- } else if (typeof value === "function") {
3441
- defs.push({
3442
- kind: "bridge",
3443
- name,
3444
- enumerable: true
3445
- });
3446
- dispatch[name] = resolveOverride(runGlobals, name, value);
3447
- }
3448
- }
3449
- for (const [name, override] of Object.entries(runGlobals)) {
3450
- if (name in precompileGlobals) continue;
3451
- if (typeof override === "function") {
3452
- defs.push({
3453
- kind: "bridge",
3454
- name,
3455
- enumerable: true
3456
- });
3457
- dispatch[name] = override;
3458
- }
3459
- }
3460
- return {
3461
- defs,
3462
- dispatch
3463
- };
3464
- }
3465
- //#endregion
3466
3592
  //#region src/index.ts
3467
3593
  /**
3468
3594
  * \@iso4/sandbox - public entry point.
@@ -3878,7 +4004,28 @@ var SandboxImpl = class {
3878
4004
  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");
3879
4005
  validateMemoryMb(options.limits?.memoryMb, "limits.memoryMb");
3880
4006
  const runMemoryMb = options.limits?.memoryMb ?? this.memoryMb;
3881
- const { defs, dispatch } = processGlobals(options.globals ?? {});
4007
+ let processed;
4008
+ try {
4009
+ processed = processGlobals(options.globals ?? {});
4010
+ } catch (e) {
4011
+ if (e instanceof GlobalNameError) return {
4012
+ status: "failed",
4013
+ ok: false,
4014
+ error: {
4015
+ code: e.code,
4016
+ name: "Error",
4017
+ message: e.message
4018
+ },
4019
+ stdout: [],
4020
+ stderr: [],
4021
+ durationMs: 0,
4022
+ wallTimeMs: 0,
4023
+ cpuTimeMs: 0,
4024
+ bridgeCalls: []
4025
+ };
4026
+ throw e;
4027
+ }
4028
+ const { defs, dispatch } = processed;
3882
4029
  await materializeHostTypesInGlobals(defs, this.brandKey);
3883
4030
  const { bindings, handlers } = processImports(options.imports);
3884
4031
  const streams = new StreamSourceRegistry();
@@ -3983,9 +4130,9 @@ var SandboxImpl = class {
3983
4130
  async prepare(options) {
3984
4131
  validateMemoryMb(options.memoryMb, "memoryMb");
3985
4132
  const prefixMemoryMb = options.memoryMb ?? this.memoryMb;
4133
+ const rawGlobals = options.globals ?? {};
4134
+ const { defs } = processGlobals(rawGlobals);
3986
4135
  return this.pool.withClient(async (client) => {
3987
- const rawGlobals = options.globals ?? {};
3988
- const { defs } = processGlobals(rawGlobals);
3989
4136
  await materializeHostTypesInGlobals(defs, this.brandKey);
3990
4137
  const { bindings, handlers } = processImports(options.imports);
3991
4138
  const result = decodePrecompileResultPayload(await client.precompile({
@@ -4133,12 +4280,14 @@ var PrefixImpl = class {
4133
4280
  if (options.signal?.aborted) return abortedResult(options.signal.reason);
4134
4281
  if (options.hardAbortSignal?.aborted) return abortedResult(options.hardAbortSignal.reason);
4135
4282
  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 })");
4136
- const { defs, dispatch } = extractBridgeGlobals(options.globals ?? {}, this.defaultGlobals);
4283
+ let defs;
4284
+ let dispatch;
4137
4285
  let merged;
4138
4286
  try {
4287
+ ({defs, dispatch} = extractBridgeGlobals(options.globals ?? {}, this.defaultGlobals));
4139
4288
  merged = mergeRebindImports(options.imports, this.defaultImportHandlers);
4140
4289
  } catch (e) {
4141
- if (e instanceof ImportRebindError) return {
4290
+ if (e instanceof ImportRebindError || e instanceof GlobalNameError) return {
4142
4291
  status: "failed",
4143
4292
  ok: false,
4144
4293
  error: {
@@ -4201,4 +4350,4 @@ var PrefixImpl = class {
4201
4350
  }
4202
4351
  };
4203
4352
  //#endregion
4204
- export { createSandbox };
4353
+ export { RESERVED_WORDS, SANDBOX_GLOBALS, createSandbox };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@iso4/sandbox",
3
- "version": "0.6.3",
3
+ "version": "0.8.0",
4
4
  "type": "module",
5
5
  "description": "Fast, sandboxed V8 isolate runtime for agent-generated JavaScript. Two-process architecture for crash isolation.",
6
6
  "keywords": [
@@ -49,10 +49,10 @@
49
49
  "vitest": "^4.1.5"
50
50
  },
51
51
  "optionalDependencies": {
52
- "@iso4/v8-darwin-arm64": "^0.6.3",
53
- "@iso4/v8-darwin-x64": "^0.6.3",
54
- "@iso4/v8-linux-arm64-gnu": "^0.6.3",
55
- "@iso4/v8-linux-x64-gnu": "^0.6.3"
52
+ "@iso4/v8-darwin-arm64": "^0.8.0",
53
+ "@iso4/v8-darwin-x64": "^0.8.0",
54
+ "@iso4/v8-linux-arm64-gnu": "^0.8.0",
55
+ "@iso4/v8-linux-x64-gnu": "^0.8.0"
56
56
  },
57
57
  "engines": {
58
58
  "node": ">=24.0.0"