@secure-exec/core 0.1.0-rc.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.
Files changed (81) hide show
  1. package/LICENSE +191 -0
  2. package/README.md +7 -0
  3. package/dist/bridge/active-handles.d.ts +21 -0
  4. package/dist/bridge/active-handles.js +60 -0
  5. package/dist/bridge/child-process.d.ts +90 -0
  6. package/dist/bridge/child-process.js +606 -0
  7. package/dist/bridge/fs.d.ts +281 -0
  8. package/dist/bridge/fs.js +2151 -0
  9. package/dist/bridge/index.d.ts +10 -0
  10. package/dist/bridge/index.js +41 -0
  11. package/dist/bridge/module.d.ts +75 -0
  12. package/dist/bridge/module.js +308 -0
  13. package/dist/bridge/network.d.ts +249 -0
  14. package/dist/bridge/network.js +1416 -0
  15. package/dist/bridge/os.d.ts +13 -0
  16. package/dist/bridge/os.js +256 -0
  17. package/dist/bridge/polyfills.d.ts +2 -0
  18. package/dist/bridge/polyfills.js +11 -0
  19. package/dist/bridge/process.d.ts +86 -0
  20. package/dist/bridge/process.js +938 -0
  21. package/dist/bridge-setup.d.ts +6 -0
  22. package/dist/bridge-setup.js +9 -0
  23. package/dist/bridge.js +11538 -0
  24. package/dist/esm-compiler.d.ts +14 -0
  25. package/dist/esm-compiler.js +68 -0
  26. package/dist/fs-helpers.d.ts +23 -0
  27. package/dist/fs-helpers.js +41 -0
  28. package/dist/generated/isolate-runtime.d.ts +19 -0
  29. package/dist/generated/isolate-runtime.js +21 -0
  30. package/dist/generated/polyfills.d.ts +82 -0
  31. package/dist/generated/polyfills.js +82 -0
  32. package/dist/index.d.ts +30 -0
  33. package/dist/index.js +25 -0
  34. package/dist/isolate-runtime/apply-custom-global-policy.js +54 -0
  35. package/dist/isolate-runtime/apply-timing-mitigation-freeze.js +44 -0
  36. package/dist/isolate-runtime/apply-timing-mitigation-off.js +14 -0
  37. package/dist/isolate-runtime/bridge-attach.js +29 -0
  38. package/dist/isolate-runtime/bridge-initial-globals.js +246 -0
  39. package/dist/isolate-runtime/eval-script-result.js +8 -0
  40. package/dist/isolate-runtime/global-exposure-helpers.js +36 -0
  41. package/dist/isolate-runtime/init-commonjs-module-globals.js +28 -0
  42. package/dist/isolate-runtime/override-process-cwd.js +8 -0
  43. package/dist/isolate-runtime/override-process-env.js +8 -0
  44. package/dist/isolate-runtime/require-setup.js +650 -0
  45. package/dist/isolate-runtime/set-commonjs-file-globals.js +36 -0
  46. package/dist/isolate-runtime/set-stdin-data.js +10 -0
  47. package/dist/isolate-runtime/setup-dynamic-import.js +64 -0
  48. package/dist/isolate-runtime/setup-fs-facade.js +48 -0
  49. package/dist/module-resolver.d.ts +25 -0
  50. package/dist/module-resolver.js +264 -0
  51. package/dist/package-bundler.d.ts +36 -0
  52. package/dist/package-bundler.js +497 -0
  53. package/dist/python-runtime.d.ts +16 -0
  54. package/dist/python-runtime.js +45 -0
  55. package/dist/runtime-driver.d.ts +62 -0
  56. package/dist/runtime-driver.js +1 -0
  57. package/dist/runtime.d.ts +31 -0
  58. package/dist/runtime.js +69 -0
  59. package/dist/shared/api-types.d.ts +71 -0
  60. package/dist/shared/api-types.js +1 -0
  61. package/dist/shared/bridge-contract.d.ts +302 -0
  62. package/dist/shared/bridge-contract.js +82 -0
  63. package/dist/shared/console-formatter.d.ts +22 -0
  64. package/dist/shared/console-formatter.js +157 -0
  65. package/dist/shared/constants.d.ts +3 -0
  66. package/dist/shared/constants.js +3 -0
  67. package/dist/shared/errors.d.ts +16 -0
  68. package/dist/shared/errors.js +21 -0
  69. package/dist/shared/esm-utils.d.ts +28 -0
  70. package/dist/shared/esm-utils.js +97 -0
  71. package/dist/shared/global-exposure.d.ts +38 -0
  72. package/dist/shared/global-exposure.js +406 -0
  73. package/dist/shared/in-memory-fs.d.ts +42 -0
  74. package/dist/shared/in-memory-fs.js +341 -0
  75. package/dist/shared/permissions.d.ts +38 -0
  76. package/dist/shared/permissions.js +283 -0
  77. package/dist/shared/require-setup.d.ts +6 -0
  78. package/dist/shared/require-setup.js +9 -0
  79. package/dist/types.d.ts +206 -0
  80. package/dist/types.js +1 -0
  81. package/package.json +107 -0
@@ -0,0 +1,938 @@
1
+ // Process module polyfill for isolated-vm
2
+ // Provides Node.js process object and global polyfills for sandbox compatibility
3
+ // Re-export TextEncoder/TextDecoder from polyfills (polyfills.ts is imported first in index.ts)
4
+ import { TextEncoder, TextDecoder } from "./polyfills.js";
5
+ // Use whatwg-url for spec-compliant URL implementation
6
+ import { URL as WhatwgURL, URLSearchParams as WhatwgURLSearchParams } from "whatwg-url";
7
+ // Use buffer package for spec-compliant Buffer implementation
8
+ import { Buffer as BufferPolyfill } from "buffer";
9
+ import { exposeCustomGlobal, exposeMutableRuntimeStateGlobal, } from "../shared/global-exposure.js";
10
+ // Get config with defaults
11
+ const config = {
12
+ platform: (typeof _processConfig !== "undefined" && _processConfig.platform) ||
13
+ "linux",
14
+ arch: (typeof _processConfig !== "undefined" && _processConfig.arch) || "x64",
15
+ version: (typeof _processConfig !== "undefined" && _processConfig.version) ||
16
+ "v22.0.0",
17
+ cwd: (typeof _processConfig !== "undefined" && _processConfig.cwd) || "/root",
18
+ env: (typeof _processConfig !== "undefined" && _processConfig.env) || {},
19
+ argv: (typeof _processConfig !== "undefined" && _processConfig.argv) || [
20
+ "node",
21
+ "script.js",
22
+ ],
23
+ execPath: (typeof _processConfig !== "undefined" && _processConfig.execPath) ||
24
+ "/usr/bin/node",
25
+ pid: (typeof _processConfig !== "undefined" && _processConfig.pid) || 1,
26
+ ppid: (typeof _processConfig !== "undefined" && _processConfig.ppid) || 0,
27
+ uid: (typeof _processConfig !== "undefined" && _processConfig.uid) || 0,
28
+ gid: (typeof _processConfig !== "undefined" && _processConfig.gid) || 0,
29
+ timingMitigation: (typeof _processConfig !== "undefined" && _processConfig.timingMitigation) ||
30
+ "off",
31
+ frozenTimeMs: typeof _processConfig !== "undefined" ? _processConfig.frozenTimeMs : undefined,
32
+ };
33
+ /** Get the current timestamp, returning a frozen value when timing mitigation is active. */
34
+ function getNowMs() {
35
+ if (config.timingMitigation === "freeze" &&
36
+ typeof config.frozenTimeMs === "number") {
37
+ return config.frozenTimeMs;
38
+ }
39
+ return typeof performance !== "undefined" && performance.now
40
+ ? performance.now()
41
+ : Date.now();
42
+ }
43
+ // Start time for uptime calculation
44
+ const _processStartTime = getNowMs();
45
+ const BUFFER_MAX_LENGTH = typeof BufferPolyfill.kMaxLength ===
46
+ "number"
47
+ ? BufferPolyfill.kMaxLength
48
+ : 2147483647;
49
+ const BUFFER_MAX_STRING_LENGTH = typeof BufferPolyfill.kStringMaxLength ===
50
+ "number"
51
+ ? BufferPolyfill.kStringMaxLength
52
+ : 536870888;
53
+ const BUFFER_CONSTANTS = Object.freeze({
54
+ MAX_LENGTH: BUFFER_MAX_LENGTH,
55
+ MAX_STRING_LENGTH: BUFFER_MAX_STRING_LENGTH,
56
+ });
57
+ const bufferPolyfillMutable = BufferPolyfill;
58
+ if (typeof bufferPolyfillMutable.kMaxLength !== "number") {
59
+ bufferPolyfillMutable.kMaxLength = BUFFER_MAX_LENGTH;
60
+ }
61
+ if (typeof bufferPolyfillMutable.kStringMaxLength !== "number") {
62
+ bufferPolyfillMutable.kStringMaxLength = BUFFER_MAX_STRING_LENGTH;
63
+ }
64
+ if (typeof bufferPolyfillMutable.constants !== "object" ||
65
+ bufferPolyfillMutable.constants === null) {
66
+ bufferPolyfillMutable.constants = {
67
+ MAX_LENGTH: BUFFER_MAX_LENGTH,
68
+ MAX_STRING_LENGTH: BUFFER_MAX_STRING_LENGTH,
69
+ };
70
+ }
71
+ // Exit code tracking
72
+ let _exitCode = 0;
73
+ let _exited = false;
74
+ /**
75
+ * Thrown by `process.exit()` to unwind the sandbox call stack. The host
76
+ * catches this to extract the exit code without killing the isolate.
77
+ */
78
+ export class ProcessExitError extends Error {
79
+ code;
80
+ constructor(code) {
81
+ super("process.exit(" + code + ")");
82
+ this.name = "ProcessExitError";
83
+ this.code = code;
84
+ }
85
+ }
86
+ // Make available globally
87
+ exposeCustomGlobal("ProcessExitError", ProcessExitError);
88
+ const _processListeners = {};
89
+ const _processOnceListeners = {};
90
+ function _addListener(event, listener, once = false) {
91
+ const target = once ? _processOnceListeners : _processListeners;
92
+ if (!target[event]) {
93
+ target[event] = [];
94
+ }
95
+ target[event].push(listener);
96
+ return process;
97
+ }
98
+ function _removeListener(event, listener) {
99
+ if (_processListeners[event]) {
100
+ const idx = _processListeners[event].indexOf(listener);
101
+ if (idx !== -1)
102
+ _processListeners[event].splice(idx, 1);
103
+ }
104
+ if (_processOnceListeners[event]) {
105
+ const idx = _processOnceListeners[event].indexOf(listener);
106
+ if (idx !== -1)
107
+ _processOnceListeners[event].splice(idx, 1);
108
+ }
109
+ return process;
110
+ }
111
+ function _emit(event, ...args) {
112
+ let handled = false;
113
+ // Regular listeners
114
+ if (_processListeners[event]) {
115
+ for (const listener of _processListeners[event]) {
116
+ listener(...args);
117
+ handled = true;
118
+ }
119
+ }
120
+ // Once listeners (remove after calling)
121
+ if (_processOnceListeners[event]) {
122
+ const listeners = _processOnceListeners[event].slice();
123
+ _processOnceListeners[event] = [];
124
+ for (const listener of listeners) {
125
+ listener(...args);
126
+ handled = true;
127
+ }
128
+ }
129
+ return handled;
130
+ }
131
+ // Stdout stream
132
+ const _stdout = {
133
+ write(data) {
134
+ if (typeof _log !== "undefined") {
135
+ _log.applySync(undefined, [String(data).replace(/\n$/, "")]);
136
+ }
137
+ return true;
138
+ },
139
+ end() {
140
+ return this;
141
+ },
142
+ on() {
143
+ return this;
144
+ },
145
+ once() {
146
+ return this;
147
+ },
148
+ emit() {
149
+ return false;
150
+ },
151
+ writable: true,
152
+ isTTY: false,
153
+ columns: 80,
154
+ rows: 24,
155
+ };
156
+ // Stderr stream
157
+ const _stderr = {
158
+ write(data) {
159
+ if (typeof _error !== "undefined") {
160
+ _error.applySync(undefined, [String(data).replace(/\n$/, "")]);
161
+ }
162
+ return true;
163
+ },
164
+ end() {
165
+ return this;
166
+ },
167
+ on() {
168
+ return this;
169
+ },
170
+ once() {
171
+ return this;
172
+ },
173
+ emit() {
174
+ return false;
175
+ },
176
+ writable: true,
177
+ isTTY: false,
178
+ columns: 80,
179
+ rows: 24,
180
+ };
181
+ const _stdinListeners = {};
182
+ const _stdinOnceListeners = {};
183
+ // Initialize stdin state as globals for external access
184
+ exposeMutableRuntimeStateGlobal("_stdinData", (typeof _processConfig !== "undefined" && _processConfig.stdin) || "");
185
+ exposeMutableRuntimeStateGlobal("_stdinPosition", 0);
186
+ exposeMutableRuntimeStateGlobal("_stdinEnded", false);
187
+ exposeMutableRuntimeStateGlobal("_stdinFlowMode", false);
188
+ // Getters for the globals
189
+ function getStdinData() { return globalThis._stdinData; }
190
+ function setStdinDataValue(v) { globalThis._stdinData = v; }
191
+ function getStdinPosition() { return globalThis._stdinPosition; }
192
+ function setStdinPosition(v) { globalThis._stdinPosition = v; }
193
+ function getStdinEnded() { return globalThis._stdinEnded; }
194
+ function setStdinEnded(v) { globalThis._stdinEnded = v; }
195
+ function getStdinFlowMode() { return globalThis._stdinFlowMode; }
196
+ function setStdinFlowMode(v) { globalThis._stdinFlowMode = v; }
197
+ function _emitStdinData() {
198
+ if (getStdinEnded() || !getStdinData())
199
+ return;
200
+ // In flowing mode, emit all remaining data
201
+ if (getStdinFlowMode() && getStdinPosition() < getStdinData().length) {
202
+ const chunk = getStdinData().slice(getStdinPosition());
203
+ setStdinPosition(getStdinData().length);
204
+ // Emit data event
205
+ const dataListeners = [...(_stdinListeners["data"] || []), ...(_stdinOnceListeners["data"] || [])];
206
+ _stdinOnceListeners["data"] = [];
207
+ for (const listener of dataListeners) {
208
+ listener(chunk);
209
+ }
210
+ // Emit end after all data
211
+ setStdinEnded(true);
212
+ const endListeners = [...(_stdinListeners["end"] || []), ...(_stdinOnceListeners["end"] || [])];
213
+ _stdinOnceListeners["end"] = [];
214
+ for (const listener of endListeners) {
215
+ listener();
216
+ }
217
+ // Emit close
218
+ const closeListeners = [...(_stdinListeners["close"] || []), ...(_stdinOnceListeners["close"] || [])];
219
+ _stdinOnceListeners["close"] = [];
220
+ for (const listener of closeListeners) {
221
+ listener();
222
+ }
223
+ }
224
+ }
225
+ const _stdin = {
226
+ readable: true,
227
+ paused: true,
228
+ encoding: null,
229
+ read(size) {
230
+ if (getStdinPosition() >= getStdinData().length)
231
+ return null;
232
+ const chunk = size ? getStdinData().slice(getStdinPosition(), getStdinPosition() + size) : getStdinData().slice(getStdinPosition());
233
+ setStdinPosition(getStdinPosition() + chunk.length);
234
+ return chunk;
235
+ },
236
+ on(event, listener) {
237
+ if (!_stdinListeners[event])
238
+ _stdinListeners[event] = [];
239
+ _stdinListeners[event].push(listener);
240
+ // When 'end' listener is added and we have data, emit everything synchronously
241
+ // This works because typical patterns register 'data' then 'end' listeners
242
+ if (event === "end" && getStdinData() && !getStdinEnded()) {
243
+ setStdinFlowMode(true);
244
+ // Emit synchronously - all listeners should be registered by now
245
+ _emitStdinData();
246
+ }
247
+ return this;
248
+ },
249
+ once(event, listener) {
250
+ if (!_stdinOnceListeners[event])
251
+ _stdinOnceListeners[event] = [];
252
+ _stdinOnceListeners[event].push(listener);
253
+ return this;
254
+ },
255
+ off(event, listener) {
256
+ if (_stdinListeners[event]) {
257
+ const idx = _stdinListeners[event].indexOf(listener);
258
+ if (idx !== -1)
259
+ _stdinListeners[event].splice(idx, 1);
260
+ }
261
+ return this;
262
+ },
263
+ removeListener(event, listener) {
264
+ return this.off(event, listener);
265
+ },
266
+ emit(event, ...args) {
267
+ const listeners = [...(_stdinListeners[event] || []), ...(_stdinOnceListeners[event] || [])];
268
+ _stdinOnceListeners[event] = [];
269
+ for (const listener of listeners) {
270
+ listener(args[0]);
271
+ }
272
+ return listeners.length > 0;
273
+ },
274
+ pause() {
275
+ this.paused = true;
276
+ setStdinFlowMode(false);
277
+ return this;
278
+ },
279
+ resume() {
280
+ this.paused = false;
281
+ setStdinFlowMode(true);
282
+ _emitStdinData();
283
+ return this;
284
+ },
285
+ setEncoding(enc) {
286
+ this.encoding = enc;
287
+ return this;
288
+ },
289
+ isTTY: false,
290
+ // For readline compatibility
291
+ [Symbol.asyncIterator]: async function* () {
292
+ const lines = getStdinData().split("\n");
293
+ for (const line of lines) {
294
+ if (line)
295
+ yield line;
296
+ }
297
+ },
298
+ };
299
+ // hrtime function with bigint method
300
+ function hrtime(prev) {
301
+ const now = getNowMs();
302
+ const seconds = Math.floor(now / 1000);
303
+ const nanoseconds = Math.floor((now % 1000) * 1e6);
304
+ if (prev) {
305
+ let diffSec = seconds - prev[0];
306
+ let diffNano = nanoseconds - prev[1];
307
+ if (diffNano < 0) {
308
+ diffSec -= 1;
309
+ diffNano += 1e9;
310
+ }
311
+ return [diffSec, diffNano];
312
+ }
313
+ return [seconds, nanoseconds];
314
+ }
315
+ hrtime.bigint = function () {
316
+ const now = getNowMs();
317
+ return BigInt(Math.floor(now * 1e6));
318
+ };
319
+ // Internal state
320
+ let _cwd = config.cwd;
321
+ let _umask = 0o022;
322
+ // The process object — typed loosely as a polyfill, cast to typeof nodeProcess on export
323
+ const process = {
324
+ // Static properties
325
+ platform: config.platform,
326
+ arch: config.arch,
327
+ version: config.version,
328
+ versions: {
329
+ node: config.version.replace(/^v/, ""),
330
+ v8: "11.3.244.8",
331
+ uv: "1.44.2",
332
+ zlib: "1.2.13",
333
+ brotli: "1.0.9",
334
+ ares: "1.19.0",
335
+ modules: "108",
336
+ nghttp2: "1.52.0",
337
+ napi: "8",
338
+ llhttp: "8.1.0",
339
+ openssl: "3.0.8",
340
+ cldr: "42.0",
341
+ icu: "72.1",
342
+ tz: "2022g",
343
+ unicode: "15.0",
344
+ },
345
+ pid: config.pid,
346
+ ppid: config.ppid,
347
+ execPath: config.execPath,
348
+ execArgv: [],
349
+ argv: config.argv,
350
+ argv0: config.argv[0] || "node",
351
+ title: "node",
352
+ env: config.env,
353
+ // Config stubs
354
+ config: {
355
+ target_defaults: {
356
+ cflags: [],
357
+ default_configuration: "Release",
358
+ defines: [],
359
+ include_dirs: [],
360
+ libraries: [],
361
+ },
362
+ variables: {
363
+ node_prefix: "/usr",
364
+ node_shared_libuv: false,
365
+ },
366
+ },
367
+ release: {
368
+ name: "node",
369
+ sourceUrl: "https://nodejs.org/download/release/v20.0.0/node-v20.0.0.tar.gz",
370
+ headersUrl: "https://nodejs.org/download/release/v20.0.0/node-v20.0.0-headers.tar.gz",
371
+ },
372
+ // Feature flags
373
+ features: {
374
+ inspector: false,
375
+ debug: false,
376
+ uv: true,
377
+ ipv6: true,
378
+ tls_alpn: true,
379
+ tls_sni: true,
380
+ tls_ocsp: true,
381
+ tls: true,
382
+ },
383
+ // Methods
384
+ cwd() {
385
+ return _cwd;
386
+ },
387
+ chdir(dir) {
388
+ _cwd = dir;
389
+ },
390
+ get exitCode() {
391
+ return _exitCode;
392
+ },
393
+ set exitCode(code) {
394
+ _exitCode = code ?? 0;
395
+ },
396
+ exit(code) {
397
+ const exitCode = code !== undefined ? code : _exitCode;
398
+ _exitCode = exitCode;
399
+ _exited = true;
400
+ // Fire exit event
401
+ try {
402
+ _emit("exit", exitCode);
403
+ }
404
+ catch (_e) {
405
+ // Ignore errors in exit handlers
406
+ }
407
+ // Throw to stop execution
408
+ throw new ProcessExitError(exitCode);
409
+ },
410
+ abort() {
411
+ return process.exit(1);
412
+ },
413
+ nextTick(callback, ...args) {
414
+ if (typeof queueMicrotask === "function") {
415
+ queueMicrotask(() => callback(...args));
416
+ }
417
+ else {
418
+ Promise.resolve().then(() => callback(...args));
419
+ }
420
+ },
421
+ hrtime: hrtime,
422
+ getuid() {
423
+ return config.uid;
424
+ },
425
+ getgid() {
426
+ return config.gid;
427
+ },
428
+ geteuid() {
429
+ return config.uid;
430
+ },
431
+ getegid() {
432
+ return config.gid;
433
+ },
434
+ getgroups() {
435
+ return [config.gid];
436
+ },
437
+ setuid() { },
438
+ setgid() { },
439
+ seteuid() { },
440
+ setegid() { },
441
+ setgroups() { },
442
+ umask(mask) {
443
+ const oldMask = _umask;
444
+ if (mask !== undefined) {
445
+ _umask = mask;
446
+ }
447
+ return oldMask;
448
+ },
449
+ uptime() {
450
+ return (getNowMs() - _processStartTime) / 1000;
451
+ },
452
+ memoryUsage() {
453
+ return {
454
+ rss: 50 * 1024 * 1024,
455
+ heapTotal: 20 * 1024 * 1024,
456
+ heapUsed: 10 * 1024 * 1024,
457
+ external: 1 * 1024 * 1024,
458
+ arrayBuffers: 500 * 1024,
459
+ };
460
+ },
461
+ cpuUsage(prev) {
462
+ const usage = {
463
+ user: 1000000,
464
+ system: 500000,
465
+ };
466
+ if (prev) {
467
+ return {
468
+ user: usage.user - prev.user,
469
+ system: usage.system - prev.system,
470
+ };
471
+ }
472
+ return usage;
473
+ },
474
+ resourceUsage() {
475
+ return {
476
+ userCPUTime: 1000000,
477
+ systemCPUTime: 500000,
478
+ maxRSS: 50 * 1024,
479
+ sharedMemorySize: 0,
480
+ unsharedDataSize: 0,
481
+ unsharedStackSize: 0,
482
+ minorPageFault: 0,
483
+ majorPageFault: 0,
484
+ swappedOut: 0,
485
+ fsRead: 0,
486
+ fsWrite: 0,
487
+ ipcSent: 0,
488
+ ipcReceived: 0,
489
+ signalsCount: 0,
490
+ voluntaryContextSwitches: 0,
491
+ involuntaryContextSwitches: 0,
492
+ };
493
+ },
494
+ kill(pid, signal) {
495
+ if (pid !== process.pid) {
496
+ const err = new Error("Operation not permitted");
497
+ err.code = "EPERM";
498
+ err.errno = -1;
499
+ err.syscall = "kill";
500
+ throw err;
501
+ }
502
+ // Self-kill - treat as exit
503
+ if (!signal || signal === "SIGTERM" || signal === 15) {
504
+ process.exit(143);
505
+ }
506
+ return true;
507
+ },
508
+ // EventEmitter methods
509
+ on(event, listener) {
510
+ return _addListener(event, listener);
511
+ },
512
+ once(event, listener) {
513
+ return _addListener(event, listener, true);
514
+ },
515
+ removeListener(event, listener) {
516
+ return _removeListener(event, listener);
517
+ },
518
+ // off is an alias for removeListener (assigned below to be same reference)
519
+ off: null,
520
+ removeAllListeners(event) {
521
+ if (event) {
522
+ delete _processListeners[event];
523
+ delete _processOnceListeners[event];
524
+ }
525
+ else {
526
+ Object.keys(_processListeners).forEach((k) => delete _processListeners[k]);
527
+ Object.keys(_processOnceListeners).forEach((k) => delete _processOnceListeners[k]);
528
+ }
529
+ return process;
530
+ },
531
+ addListener(event, listener) {
532
+ return _addListener(event, listener);
533
+ },
534
+ emit(event, ...args) {
535
+ return _emit(event, ...args);
536
+ },
537
+ listeners(event) {
538
+ return [
539
+ ...(_processListeners[event] || []),
540
+ ...(_processOnceListeners[event] || []),
541
+ ];
542
+ },
543
+ listenerCount(event) {
544
+ return ((_processListeners[event] || []).length +
545
+ (_processOnceListeners[event] || []).length);
546
+ },
547
+ prependListener(event, listener) {
548
+ if (!_processListeners[event]) {
549
+ _processListeners[event] = [];
550
+ }
551
+ _processListeners[event].unshift(listener);
552
+ return process;
553
+ },
554
+ prependOnceListener(event, listener) {
555
+ if (!_processOnceListeners[event]) {
556
+ _processOnceListeners[event] = [];
557
+ }
558
+ _processOnceListeners[event].unshift(listener);
559
+ return process;
560
+ },
561
+ eventNames() {
562
+ return [
563
+ ...new Set([
564
+ ...Object.keys(_processListeners),
565
+ ...Object.keys(_processOnceListeners),
566
+ ]),
567
+ ];
568
+ },
569
+ setMaxListeners() {
570
+ return process;
571
+ },
572
+ getMaxListeners() {
573
+ return 10;
574
+ },
575
+ rawListeners(event) {
576
+ return process.listeners(event);
577
+ },
578
+ // Stdio streams
579
+ stdout: _stdout,
580
+ stderr: _stderr,
581
+ stdin: _stdin,
582
+ // Process state
583
+ connected: false,
584
+ // Module info (will be set by createRequire)
585
+ mainModule: undefined,
586
+ // No-op methods for compatibility
587
+ emitWarning(warning) {
588
+ const msg = typeof warning === "string" ? warning : warning.message;
589
+ _emit("warning", { message: msg, name: "Warning" });
590
+ },
591
+ binding(name) {
592
+ // Return stub implementations for common bindings
593
+ const stubs = {
594
+ fs: {},
595
+ buffer: {
596
+ Buffer: globalThis.Buffer,
597
+ constants: BUFFER_CONSTANTS,
598
+ kMaxLength: BUFFER_MAX_LENGTH,
599
+ kStringMaxLength: BUFFER_MAX_STRING_LENGTH,
600
+ },
601
+ process_wrap: {},
602
+ natives: {},
603
+ config: {},
604
+ uv: { UV_UDP_REUSEADDR: 4 },
605
+ constants: {
606
+ MAX_LENGTH: BUFFER_MAX_LENGTH,
607
+ MAX_STRING_LENGTH: BUFFER_MAX_STRING_LENGTH,
608
+ buffer: BUFFER_CONSTANTS,
609
+ },
610
+ crypto: {},
611
+ string_decoder: {},
612
+ os: {},
613
+ };
614
+ return stubs[name] || {};
615
+ },
616
+ _linkedBinding(name) {
617
+ return process.binding(name);
618
+ },
619
+ dlopen() {
620
+ throw new Error("process.dlopen is not supported");
621
+ },
622
+ hasUncaughtExceptionCaptureCallback() {
623
+ return false;
624
+ },
625
+ setUncaughtExceptionCaptureCallback() { },
626
+ // Send for IPC (no-op)
627
+ send() {
628
+ return false;
629
+ },
630
+ disconnect() { },
631
+ // Report
632
+ report: {
633
+ directory: "",
634
+ filename: "",
635
+ compact: false,
636
+ signal: "SIGUSR2",
637
+ reportOnFatalError: false,
638
+ reportOnSignal: false,
639
+ reportOnUncaughtException: false,
640
+ getReport() {
641
+ return {};
642
+ },
643
+ writeReport() {
644
+ return "";
645
+ },
646
+ },
647
+ // Debug port
648
+ debugPort: 9229,
649
+ // Internal state
650
+ _cwd: config.cwd,
651
+ _umask: 0o022,
652
+ };
653
+ // Make process.off === process.removeListener (same function reference)
654
+ process.off = process.removeListener;
655
+ // Add memoryUsage.rss
656
+ process.memoryUsage.rss =
657
+ function () {
658
+ return 50 * 1024 * 1024;
659
+ };
660
+ export default process;
661
+ // ============================================================================
662
+ // Global polyfills
663
+ // ============================================================================
664
+ // Timer implementation
665
+ let _timerId = 0;
666
+ const _timers = new Map();
667
+ const _intervals = new Map();
668
+ /** Check timer budget. _maxTimers is injected by the host when resourceBudgets.maxTimers is set. */
669
+ function _checkTimerBudget() {
670
+ if (typeof _maxTimers !== "undefined" && (_timers.size + _intervals.size) >= _maxTimers) {
671
+ throw new Error("ERR_RESOURCE_BUDGET_EXCEEDED: maximum number of timers exceeded");
672
+ }
673
+ }
674
+ // queueMicrotask fallback
675
+ const _queueMicrotask = typeof queueMicrotask === "function"
676
+ ? queueMicrotask
677
+ : function (fn) {
678
+ Promise.resolve().then(fn);
679
+ };
680
+ /**
681
+ * Timer handle that mimics Node.js Timeout (ref/unref/Symbol.toPrimitive).
682
+ * Timers with delay > 0 use the host's `_scheduleTimer` bridge to sleep
683
+ * without blocking the isolate's event loop.
684
+ */
685
+ class TimerHandle {
686
+ _id;
687
+ _destroyed;
688
+ constructor(id) {
689
+ this._id = id;
690
+ this._destroyed = false;
691
+ }
692
+ ref() {
693
+ return this;
694
+ }
695
+ unref() {
696
+ return this;
697
+ }
698
+ hasRef() {
699
+ return true;
700
+ }
701
+ refresh() {
702
+ return this;
703
+ }
704
+ [Symbol.toPrimitive]() {
705
+ return this._id;
706
+ }
707
+ }
708
+ export function setTimeout(callback, delay, ...args) {
709
+ _checkTimerBudget();
710
+ const id = ++_timerId;
711
+ const handle = new TimerHandle(id);
712
+ _timers.set(id, handle);
713
+ const actualDelay = delay ?? 0;
714
+ // Use host timer for actual delays if available and delay > 0
715
+ if (typeof _scheduleTimer !== "undefined" && actualDelay > 0) {
716
+ // _scheduleTimer.apply() returns a Promise that resolves after the delay
717
+ // Using { result: { promise: true } } tells isolated-vm to wait for the
718
+ // host Promise to resolve before resolving the apply() Promise
719
+ _scheduleTimer
720
+ .apply(undefined, [actualDelay], { result: { promise: true } })
721
+ .then(() => {
722
+ if (_timers.has(id)) {
723
+ _timers.delete(id);
724
+ try {
725
+ callback(...args);
726
+ }
727
+ catch (_e) {
728
+ // Ignore timer callback errors
729
+ }
730
+ }
731
+ });
732
+ }
733
+ else {
734
+ // Use microtask for zero delay or when host timer is unavailable
735
+ _queueMicrotask(() => {
736
+ if (_timers.has(id)) {
737
+ _timers.delete(id);
738
+ try {
739
+ callback(...args);
740
+ }
741
+ catch (_e) {
742
+ // Ignore timer callback errors
743
+ }
744
+ }
745
+ });
746
+ }
747
+ return handle;
748
+ }
749
+ export function clearTimeout(timer) {
750
+ const id = timer && typeof timer === "object" && timer._id !== undefined
751
+ ? timer._id
752
+ : timer;
753
+ _timers.delete(id);
754
+ }
755
+ export function setInterval(callback, delay, ...args) {
756
+ _checkTimerBudget();
757
+ const id = ++_timerId;
758
+ const handle = new TimerHandle(id);
759
+ _intervals.set(id, handle);
760
+ const actualDelay = delay ?? 0;
761
+ // Schedule interval execution
762
+ const scheduleNext = () => {
763
+ if (!_intervals.has(id))
764
+ return; // Interval was cleared
765
+ if (typeof _scheduleTimer !== "undefined" && actualDelay > 0) {
766
+ // Use host timer for actual delays
767
+ _scheduleTimer
768
+ .apply(undefined, [actualDelay], { result: { promise: true } })
769
+ .then(() => {
770
+ if (_intervals.has(id)) {
771
+ try {
772
+ callback(...args);
773
+ }
774
+ catch (_e) {
775
+ // Ignore timer callback errors
776
+ }
777
+ // Schedule next iteration
778
+ scheduleNext();
779
+ }
780
+ });
781
+ }
782
+ else {
783
+ // Use microtask for zero delay or when host timer unavailable
784
+ _queueMicrotask(() => {
785
+ if (_intervals.has(id)) {
786
+ try {
787
+ callback(...args);
788
+ }
789
+ catch (_e) {
790
+ // Ignore timer callback errors
791
+ }
792
+ // Schedule next iteration
793
+ scheduleNext();
794
+ }
795
+ });
796
+ }
797
+ };
798
+ // Start the interval
799
+ scheduleNext();
800
+ return handle;
801
+ }
802
+ export function clearInterval(timer) {
803
+ const id = timer && typeof timer === "object" && timer._id !== undefined
804
+ ? timer._id
805
+ : timer;
806
+ _intervals.delete(id);
807
+ }
808
+ export function setImmediate(callback, ...args) {
809
+ return setTimeout(callback, 0, ...args);
810
+ }
811
+ export function clearImmediate(id) {
812
+ clearTimeout(id);
813
+ }
814
+ // URL and URLSearchParams - use whatwg-url for spec-compliant implementation
815
+ export const URL = WhatwgURL;
816
+ export const URLSearchParams = WhatwgURLSearchParams;
817
+ // TextEncoder and TextDecoder - re-export from polyfills
818
+ export { TextEncoder, TextDecoder };
819
+ // Buffer - use buffer package polyfill
820
+ export const Buffer = BufferPolyfill;
821
+ function throwUnsupportedCryptoApi(api) {
822
+ throw new Error(`crypto.${api} is not supported in sandbox`);
823
+ }
824
+ /**
825
+ * Crypto polyfill that delegates to the host for entropy. `getRandomValues`
826
+ * calls the host's `_cryptoRandomFill` bridge to get cryptographically secure
827
+ * random bytes. Subtle crypto operations are unsupported.
828
+ */
829
+ export const cryptoPolyfill = {
830
+ getRandomValues(array) {
831
+ if (typeof _cryptoRandomFill === "undefined") {
832
+ throwUnsupportedCryptoApi("getRandomValues");
833
+ }
834
+ const bytes = new Uint8Array(array.buffer, array.byteOffset, array.byteLength);
835
+ try {
836
+ const base64 = _cryptoRandomFill.applySync(undefined, [bytes.byteLength]);
837
+ const hostBytes = BufferPolyfill.from(base64, "base64");
838
+ if (hostBytes.byteLength !== bytes.byteLength) {
839
+ throw new Error("invalid host entropy size");
840
+ }
841
+ bytes.set(hostBytes);
842
+ return array;
843
+ }
844
+ catch {
845
+ throwUnsupportedCryptoApi("getRandomValues");
846
+ }
847
+ },
848
+ randomUUID() {
849
+ if (typeof _cryptoRandomUUID === "undefined") {
850
+ throwUnsupportedCryptoApi("randomUUID");
851
+ }
852
+ try {
853
+ const uuid = _cryptoRandomUUID.applySync(undefined, []);
854
+ if (typeof uuid !== "string") {
855
+ throw new Error("invalid host uuid");
856
+ }
857
+ return uuid;
858
+ }
859
+ catch {
860
+ throwUnsupportedCryptoApi("randomUUID");
861
+ }
862
+ },
863
+ subtle: {
864
+ digest() {
865
+ throw new Error("crypto.subtle.digest is not supported in sandbox");
866
+ },
867
+ encrypt() {
868
+ throw new Error("crypto.subtle.encrypt is not supported in sandbox");
869
+ },
870
+ decrypt() {
871
+ throw new Error("crypto.subtle.decrypt is not supported in sandbox");
872
+ },
873
+ },
874
+ };
875
+ /**
876
+ * Install all process/timer/URL/Buffer/crypto polyfills onto `globalThis`.
877
+ * Called once during bridge initialization before user code runs.
878
+ */
879
+ export function setupGlobals() {
880
+ const g = globalThis;
881
+ // Process - simple assignment is sufficient since we use external: ["process"]
882
+ // in polyfills.ts, which prevents node-stdlib-browser's process shim from being
883
+ // bundled and overwriting our process object.
884
+ g.process = process;
885
+ // Timers
886
+ g.setTimeout = setTimeout;
887
+ g.clearTimeout = clearTimeout;
888
+ g.setInterval = setInterval;
889
+ g.clearInterval = clearInterval;
890
+ g.setImmediate = setImmediate;
891
+ g.clearImmediate = clearImmediate;
892
+ // queueMicrotask
893
+ if (typeof g.queueMicrotask === "undefined") {
894
+ g.queueMicrotask = _queueMicrotask;
895
+ }
896
+ // URL
897
+ if (typeof g.URL === "undefined") {
898
+ g.URL = URL;
899
+ }
900
+ if (typeof g.URLSearchParams === "undefined") {
901
+ g.URLSearchParams = URLSearchParams;
902
+ }
903
+ // TextEncoder/TextDecoder
904
+ if (typeof g.TextEncoder === "undefined") {
905
+ g.TextEncoder = TextEncoder;
906
+ }
907
+ if (typeof g.TextDecoder === "undefined") {
908
+ g.TextDecoder = TextDecoder;
909
+ }
910
+ // Buffer
911
+ if (typeof g.Buffer === "undefined") {
912
+ g.Buffer = Buffer;
913
+ }
914
+ const globalBuffer = g.Buffer;
915
+ if (typeof globalBuffer.kMaxLength !== "number") {
916
+ globalBuffer.kMaxLength = BUFFER_MAX_LENGTH;
917
+ }
918
+ if (typeof globalBuffer.kStringMaxLength !== "number") {
919
+ globalBuffer.kStringMaxLength = BUFFER_MAX_STRING_LENGTH;
920
+ }
921
+ if (typeof globalBuffer.constants !== "object" ||
922
+ globalBuffer.constants === null) {
923
+ globalBuffer.constants = BUFFER_CONSTANTS;
924
+ }
925
+ // Crypto
926
+ if (typeof g.crypto === "undefined") {
927
+ g.crypto = cryptoPolyfill;
928
+ }
929
+ else {
930
+ const cryptoObj = g.crypto;
931
+ if (typeof cryptoObj.getRandomValues === "undefined") {
932
+ cryptoObj.getRandomValues = cryptoPolyfill.getRandomValues;
933
+ }
934
+ if (typeof cryptoObj.randomUUID === "undefined") {
935
+ cryptoObj.randomUUID = cryptoPolyfill.randomUUID;
936
+ }
937
+ }
938
+ }