@ccheever/exact-ibex-runtime 0.1.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.
Files changed (161) hide show
  1. package/package.json +63 -0
  2. package/src/abort/AbortController.ts +23 -0
  3. package/src/abort/AbortSignal.ts +152 -0
  4. package/src/abort/index.ts +2 -0
  5. package/src/accessibility.ts +12 -0
  6. package/src/arraybuffer-detach.ts +109 -0
  7. package/src/base64/base64.ts +168 -0
  8. package/src/base64/index.ts +1 -0
  9. package/src/blob/Blob.ts +259 -0
  10. package/src/blob/File.ts +59 -0
  11. package/src/blob/FormData.ts +323 -0
  12. package/src/blob/index.ts +3 -0
  13. package/src/bootstrap.ts +1946 -0
  14. package/src/broadcast/BroadcastChannel.ts +280 -0
  15. package/src/broadcast/index.ts +5 -0
  16. package/src/cache/Cache.ts +349 -0
  17. package/src/cache/CacheStorage.ts +89 -0
  18. package/src/cache/index.ts +27 -0
  19. package/src/camera/index.ts +6202 -0
  20. package/src/camera/processor.worker.ts +194 -0
  21. package/src/camera/scene.ts +195 -0
  22. package/src/clipboard/Clipboard.ts +129 -0
  23. package/src/clipboard/ClipboardItem.ts +97 -0
  24. package/src/clipboard/index.ts +6 -0
  25. package/src/clone/index.ts +1 -0
  26. package/src/clone/structuredClone.ts +389 -0
  27. package/src/clone/transferableSymbols.ts +2 -0
  28. package/src/compression/CompressionStream.ts +146 -0
  29. package/src/compression/DecompressionStream.ts +342 -0
  30. package/src/compression/index.ts +4 -0
  31. package/src/console/Console.ts +341 -0
  32. package/src/console/index.ts +2 -0
  33. package/src/core/accessibility-state.ts +263 -0
  34. package/src/core/accessibility.ts +184 -0
  35. package/src/core/agent-state.ts +37 -0
  36. package/src/core/diagnostics-logs.ts +144 -0
  37. package/src/core/host-call-bridge.ts +16 -0
  38. package/src/core/i18n-helpers.ts +189 -0
  39. package/src/core/locale-state.ts +253 -0
  40. package/src/core/locale.ts +95 -0
  41. package/src/crypto/Crypto.ts +2743 -0
  42. package/src/crypto/index.ts +1 -0
  43. package/src/diagnostics/logs.ts +7 -0
  44. package/src/encoding/TextDecoder.ts +1181 -0
  45. package/src/encoding/TextDecoderStream.ts +58 -0
  46. package/src/encoding/TextEncoder.ts +180 -0
  47. package/src/encoding/TextEncoderStream.ts +39 -0
  48. package/src/encoding/index.ts +8 -0
  49. package/src/events/CloseEvent.ts +91 -0
  50. package/src/events/DOMException.ts +409 -0
  51. package/src/events/ErrorEvent.ts +39 -0
  52. package/src/events/Event.ts +151 -0
  53. package/src/events/EventTarget.ts +280 -0
  54. package/src/events/FocusEvent.ts +27 -0
  55. package/src/events/KeyboardEvent.ts +46 -0
  56. package/src/events/MessageEvent.ts +61 -0
  57. package/src/events/ProgressEvent.ts +33 -0
  58. package/src/events/PromiseRejectionEvent.ts +31 -0
  59. package/src/events/index.ts +52 -0
  60. package/src/eventsource/EventSource.ts +371 -0
  61. package/src/eventsource/index.ts +2 -0
  62. package/src/fetch/Headers.ts +642 -0
  63. package/src/fetch/Request.ts +760 -0
  64. package/src/fetch/Response.ts +543 -0
  65. package/src/fetch/body.ts +1256 -0
  66. package/src/fetch/cookie-jar.ts +566 -0
  67. package/src/fetch/demo.ts +207 -0
  68. package/src/fetch/errors.ts +101 -0
  69. package/src/fetch/fetch.ts +2610 -0
  70. package/src/fetch/index.ts +101 -0
  71. package/src/fetch/native-bridge.ts +65 -0
  72. package/src/fetch/types.ts +258 -0
  73. package/src/filereader/FileReader.ts +236 -0
  74. package/src/filereader/index.ts +1 -0
  75. package/src/fs/Dirent.ts +39 -0
  76. package/src/fs/ExactFile.ts +450 -0
  77. package/src/fs/Stats.ts +80 -0
  78. package/src/fs/index.ts +944 -0
  79. package/src/fs/promises.ts +386 -0
  80. package/src/fs/shared.ts +328 -0
  81. package/src/http-server/index.js +697 -0
  82. package/src/http-server/index.ts +27 -0
  83. package/src/identity.generated.ts +14 -0
  84. package/src/index.ts +283 -0
  85. package/src/indexeddb/IDBCursor.ts +188 -0
  86. package/src/indexeddb/IDBDatabase.ts +343 -0
  87. package/src/indexeddb/IDBFactory.ts +269 -0
  88. package/src/indexeddb/IDBIndex.ts +194 -0
  89. package/src/indexeddb/IDBKeyRange.ts +109 -0
  90. package/src/indexeddb/IDBObjectStore.ts +468 -0
  91. package/src/indexeddb/IDBRequest.ts +163 -0
  92. package/src/indexeddb/IDBTransaction.ts +207 -0
  93. package/src/indexeddb/index.ts +34 -0
  94. package/src/indexeddb/utils.ts +52 -0
  95. package/src/inspect/index.ts +1 -0
  96. package/src/inspect/inspect.ts +465 -0
  97. package/src/internal/detect.ts +104 -0
  98. package/src/locale.ts +10 -0
  99. package/src/location/index.ts +1059 -0
  100. package/src/locks/LockManager.ts +460 -0
  101. package/src/locks/index.ts +12 -0
  102. package/src/media/VideoFrame.ts +58 -0
  103. package/src/messaging/MessageChannel.ts +31 -0
  104. package/src/messaging/MessagePort.ts +180 -0
  105. package/src/messaging/index.ts +2 -0
  106. package/src/messaging.ts +247 -0
  107. package/src/native/NativeModules.ts +354 -0
  108. package/src/native/index.ts +1 -0
  109. package/src/navigator/Navigator.ts +351 -0
  110. package/src/navigator/index.ts +1 -0
  111. package/src/node/Buffer.ts +1786 -0
  112. package/src/node/index.ts +4 -0
  113. package/src/node/path.ts +495 -0
  114. package/src/node/process.ts +2528 -0
  115. package/src/performance/Performance.ts +532 -0
  116. package/src/performance/index.ts +21 -0
  117. package/src/polyfills/array.ts +236 -0
  118. package/src/polyfills/arraybuffer.ts +172 -0
  119. package/src/polyfills/groupby.ts +85 -0
  120. package/src/polyfills/index.ts +85 -0
  121. package/src/polyfills/intl.ts +1956 -0
  122. package/src/polyfills/iterator.ts +479 -0
  123. package/src/polyfills/promise.ts +37 -0
  124. package/src/polyfills/set.ts +245 -0
  125. package/src/polyfills/string.ts +85 -0
  126. package/src/polyfills/typedarray.ts +110 -0
  127. package/src/promise-rejection-tracking.ts +464 -0
  128. package/src/react-native/index.ts +388 -0
  129. package/src/runtime-entry.ts +55 -0
  130. package/src/scheduling/AnimationFrame.ts +105 -0
  131. package/src/scheduling/IdleCallback.ts +167 -0
  132. package/src/scheduling/index.ts +13 -0
  133. package/src/security/Capabilities.ts +1146 -0
  134. package/src/security/Permissions.ts +392 -0
  135. package/src/security/capability-bits.generated.ts +63 -0
  136. package/src/security/index.ts +16 -0
  137. package/src/sqlite/Database.ts +456 -0
  138. package/src/sqlite/Statement.ts +206 -0
  139. package/src/sqlite/constants.ts +79 -0
  140. package/src/sqlite/errors.ts +25 -0
  141. package/src/sqlite/index.ts +34 -0
  142. package/src/sqlite/module.js +438 -0
  143. package/src/storage/Storage.ts +291 -0
  144. package/src/storage/StorageManager.ts +91 -0
  145. package/src/storage/index.ts +3 -0
  146. package/src/stream-compat.ts +47 -0
  147. package/src/streams/ReadableStream.ts +4131 -0
  148. package/src/streams/TransformStream.ts +375 -0
  149. package/src/streams/WritableStream.ts +866 -0
  150. package/src/streams/index.ts +41 -0
  151. package/src/timers/Timers.ts +296 -0
  152. package/src/timers/index.ts +11 -0
  153. package/src/url/URL.ts +656 -0
  154. package/src/url/URLPattern.ts +850 -0
  155. package/src/url/URLSearchParams.ts +244 -0
  156. package/src/url/index.ts +9 -0
  157. package/src/websocket/WebSocket.ts +770 -0
  158. package/src/websocket/WebSocketError.ts +52 -0
  159. package/src/websocket/WebSocketStream.ts +628 -0
  160. package/src/websocket/index.ts +7 -0
  161. package/src/window/index.ts +872 -0
@@ -0,0 +1,2528 @@
1
+ // @ts-nocheck
2
+ /**
3
+ * process object implementation for Ibex runtime (Node.js compatibility)
4
+ *
5
+ * Provides a subset of Node.js process API for compatibility with
6
+ * libraries that check for Node.js environment.
7
+ */
8
+
9
+ import { getRuntimeVersion, runtimeInfo } from '../bootstrap';
10
+ import {
11
+ BUN_COMPAT_VERSION,
12
+ RELEASE_NAME,
13
+ RUNTIME_VERSIONS,
14
+ } from '../identity.generated';
15
+
16
+ // Declare the global functions from native bridge
17
+ declare global {
18
+ var __exactGetEnv: ((name: string) => string | undefined) | undefined;
19
+ var __exactGetAllEnv: (() => Record<string, string>) | undefined;
20
+ var __exactGetCwd: (() => string) | undefined;
21
+ var __exactSetCwd: ((path: string) => void) | undefined;
22
+ var __exactArgv: string[] | undefined;
23
+ var __exactExecArgv: string[] | undefined;
24
+ var __exactExecPath: string | undefined;
25
+ }
26
+
27
+ var _processCwd = "/";
28
+ const _nextTickQueue: Array<{ callback: (...args: any[]) => void; args: any[] }> = [];
29
+ let _nextTickScheduled = false;
30
+ let _nextTickHooksInstalled = false;
31
+ const _nativeGlobalNextTick:
32
+ | ((callback: (...args: any[]) => void, ...args: any[]) => void)
33
+ | undefined =
34
+ typeof (globalThis as any).nextTick === 'function'
35
+ ? (globalThis as any).nextTick.bind(globalThis)
36
+ : undefined;
37
+ const _nativeProcessNextTick:
38
+ | ((callback: (...args: any[]) => void, ...args: any[]) => void)
39
+ | undefined =
40
+ typeof (globalThis as any).process?.nextTick === 'function'
41
+ ? (globalThis as any).process.nextTick.bind((globalThis as any).process)
42
+ : undefined;
43
+ const _nativeProcessHrtime: ((time?: [number, number]) => [number, number]) | undefined =
44
+ typeof (globalThis as any).process?.hrtime === 'function'
45
+ ? (globalThis as any).process.hrtime.bind((globalThis as any).process)
46
+ : undefined;
47
+ const _nativeProcessHrtimeBigint: (() => bigint) | undefined =
48
+ typeof (globalThis as any).process?.hrtime?.bigint === 'function'
49
+ ? (globalThis as any).process.hrtime.bigint.bind((globalThis as any).process.hrtime)
50
+ : undefined;
51
+ const _nativeProcessKill:
52
+ | ((pid: number, signal?: string | number) => true)
53
+ | undefined =
54
+ typeof (globalThis as any).process?.kill === 'function'
55
+ ? (globalThis as any).process.kill.bind((globalThis as any).process)
56
+ : undefined;
57
+ const _nativeArch: string | undefined =
58
+ typeof (globalThis as any).process?.arch === 'string'
59
+ ? (globalThis as any).process.arch
60
+ : undefined;
61
+ const _nativeGetuid: (() => number) | undefined =
62
+ typeof (globalThis as any).process?.getuid === 'function'
63
+ ? (globalThis as any).process.getuid.bind((globalThis as any).process)
64
+ : undefined;
65
+ const _nativeGetgid: (() => number) | undefined =
66
+ typeof (globalThis as any).process?.getgid === 'function'
67
+ ? (globalThis as any).process.getgid.bind((globalThis as any).process)
68
+ : undefined;
69
+ const _nativeGeteuid: (() => number) | undefined =
70
+ typeof (globalThis as any).process?.geteuid === 'function'
71
+ ? (globalThis as any).process.geteuid.bind((globalThis as any).process)
72
+ : undefined;
73
+ const _nativeGetegid: (() => number) | undefined =
74
+ typeof (globalThis as any).process?.getegid === 'function'
75
+ ? (globalThis as any).process.getegid.bind((globalThis as any).process)
76
+ : undefined;
77
+ const _nativePromiseThen = Promise.prototype.then;
78
+ const _nativeQueueMicrotask =
79
+ typeof queueMicrotask === 'function' ? queueMicrotask.bind(globalThis) : undefined;
80
+ const _nativeBigInt = typeof BigInt === 'function' ? BigInt : undefined;
81
+
82
+ const SIGNAL_NAME_TO_NUMBER: Record<string, number> = {
83
+ SIGHUP: 1,
84
+ SIGINT: 2,
85
+ SIGQUIT: 3,
86
+ SIGILL: 4,
87
+ SIGTRAP: 5,
88
+ SIGABRT: 6,
89
+ SIGIOT: 6,
90
+ SIGBUS: 7,
91
+ SIGFPE: 8,
92
+ SIGKILL: 9,
93
+ SIGUSR1: 10,
94
+ SIGSEGV: 11,
95
+ SIGUSR2: 12,
96
+ SIGPIPE: 13,
97
+ SIGALRM: 14,
98
+ SIGTERM: 15,
99
+ SIGCHLD: 17,
100
+ SIGCONT: 18,
101
+ SIGSTOP: 19,
102
+ SIGTSTP: 20,
103
+ SIGTTIN: 21,
104
+ SIGTTOU: 22,
105
+ SIGURG: 23,
106
+ SIGXCPU: 24,
107
+ SIGXFSZ: 25,
108
+ SIGVTALRM: 26,
109
+ SIGPROF: 27,
110
+ SIGWINCH: 28,
111
+ SIGIO: 29,
112
+ SIGPOLL: 29,
113
+ SIGPWR: 30,
114
+ SIGSYS: 31,
115
+ };
116
+
117
+ const USER_CREDENTIALS: Record<string, number> = {
118
+ root: 0,
119
+ nobody: 65534,
120
+ };
121
+
122
+ const GROUP_CREDENTIALS: Record<string, number> = {
123
+ root: 0,
124
+ nobody: 65534,
125
+ nogroup: 65534,
126
+ };
127
+
128
+ const CANONICAL_ALLOWED_NODE_ENVIRONMENT_FLAGS = [
129
+ '--perf-basic-prof',
130
+ '--stack-trace-limit',
131
+ '-r',
132
+ '--debug-arraybuffer-allocations',
133
+ '--no-debug-arraybuffer-allocations',
134
+ '--es-module-specifier-resolution',
135
+ '--experimental-fetch',
136
+ '--experimental-global-customevent',
137
+ '--experimental-global-webcrypto',
138
+ '--experimental-quic',
139
+ '--experimental-report',
140
+ '--experimental-wasm-modules',
141
+ '--experimental-worker',
142
+ '--loader',
143
+ '--no-node-snapshot',
144
+ '--node-snapshot',
145
+ '--no-trace-promises',
146
+ '--no-verify-base-objects',
147
+ '--trace-promises',
148
+ '--verify-base-objects',
149
+ ] as const;
150
+
151
+ const _nativeSetAdd = Set.prototype.add;
152
+ const _nativeSetClear = Set.prototype.clear;
153
+ const _nativeSetDelete = Set.prototype.delete;
154
+ const _nativeSetHas = Set.prototype.has;
155
+ let _immutableAllowedNodeEnvironmentFlags: Set<string> | null = null;
156
+ let _dateToStringPatched = false;
157
+ const _nativeDateToString = Date.prototype.toString;
158
+
159
+ function makeInvalidObjectDefinePropertyError(message: string): TypeError & { code: string } {
160
+ const err = new TypeError(message) as TypeError & { code: string };
161
+ err.code = 'ERR_INVALID_OBJECT_DEFINE_PROPERTY';
162
+ return err;
163
+ }
164
+
165
+ function normalizeAllowedNodeEnvironmentFlag(flag: unknown): string | null {
166
+ if (typeof flag !== 'string' || flag.length === 0) {
167
+ return null;
168
+ }
169
+
170
+ let dashCount = 0;
171
+ while (dashCount < flag.length && flag.charCodeAt(dashCount) === 0x2d) {
172
+ dashCount += 1;
173
+ }
174
+
175
+ let name = flag.slice(dashCount);
176
+ if (name.length === 0) {
177
+ return null;
178
+ }
179
+
180
+ const equalsIndex = name.indexOf('=');
181
+ if (equalsIndex !== -1) {
182
+ name = name.slice(0, equalsIndex);
183
+ }
184
+ name = name.replace(/_/g, '-');
185
+
186
+ if (dashCount === 0) {
187
+ return name.length === 1 ? `-${name}` : `--${name}`;
188
+ }
189
+ if (dashCount === 1) {
190
+ return `-${name}`;
191
+ }
192
+ if (dashCount === 2) {
193
+ return `--${name}`;
194
+ }
195
+ return `${'-'.repeat(dashCount)}${name}`;
196
+ }
197
+
198
+ function createAllowedNodeEnvironmentFlags(): Set<string> {
199
+ if (!_immutableAllowedNodeEnvironmentFlags) {
200
+ const allowedFlags = new Set<string>(CANONICAL_ALLOWED_NODE_ENVIRONMENT_FLAGS);
201
+ if (!(Set.prototype as any).__exactImmutableAllowedFlagsPatched) {
202
+ Object.defineProperty(Set.prototype, 'add', {
203
+ value(this: Set<unknown>, value: unknown) {
204
+ if (this === _immutableAllowedNodeEnvironmentFlags) {
205
+ return this;
206
+ }
207
+ return _nativeSetAdd.call(this, value);
208
+ },
209
+ writable: true,
210
+ configurable: true,
211
+ });
212
+ Object.defineProperty(Set.prototype, 'delete', {
213
+ value(this: Set<unknown>, value: unknown) {
214
+ if (this === _immutableAllowedNodeEnvironmentFlags) {
215
+ return false;
216
+ }
217
+ return _nativeSetDelete.call(this, value);
218
+ },
219
+ writable: true,
220
+ configurable: true,
221
+ });
222
+ Object.defineProperty(Set.prototype, 'clear', {
223
+ value(this: Set<unknown>) {
224
+ if (this === _immutableAllowedNodeEnvironmentFlags) {
225
+ return undefined;
226
+ }
227
+ return _nativeSetClear.call(this);
228
+ },
229
+ writable: true,
230
+ configurable: true,
231
+ });
232
+ Object.defineProperty(Set.prototype, '__exactImmutableAllowedFlagsPatched', {
233
+ value: true,
234
+ writable: false,
235
+ configurable: true,
236
+ });
237
+ }
238
+
239
+ Object.defineProperty(allowedFlags, 'has', {
240
+ value(this: Set<string>, value: unknown): boolean {
241
+ const normalized = normalizeAllowedNodeEnvironmentFlag(value);
242
+ if (normalized === null) {
243
+ return false;
244
+ }
245
+ return _nativeSetHas.call(this, normalized);
246
+ },
247
+ writable: false,
248
+ configurable: false,
249
+ });
250
+
251
+ _immutableAllowedNodeEnvironmentFlags = Object.freeze(allowedFlags);
252
+ }
253
+
254
+ return _immutableAllowedNodeEnvironmentFlags;
255
+ }
256
+
257
+ function _normalizeResolvedPath(path: string): string {
258
+ let rest = path;
259
+ let prefix = '';
260
+ let absolute = false;
261
+
262
+ if (/^[A-Za-z]:[\\/]/.test(rest)) {
263
+ prefix = rest.slice(0, 2);
264
+ rest = rest.slice(2);
265
+ absolute = true;
266
+ } else if (rest.startsWith('/')) {
267
+ rest = rest.slice(1);
268
+ absolute = true;
269
+ }
270
+
271
+ const parts = rest.split(/[\\/]+/);
272
+ const normalized: string[] = [];
273
+ for (const part of parts) {
274
+ if (!part || part === '.') {
275
+ continue;
276
+ }
277
+ if (part === '..') {
278
+ if (normalized.length > 0) {
279
+ normalized.pop();
280
+ } else if (!absolute) {
281
+ normalized.push(part);
282
+ }
283
+ continue;
284
+ }
285
+ normalized.push(part);
286
+ }
287
+
288
+ const joined = normalized.join('/');
289
+ if (prefix) {
290
+ return joined ? `${prefix}/${joined}` : `${prefix}/`;
291
+ }
292
+ if (absolute) {
293
+ return joined ? `/${joined}` : '/';
294
+ }
295
+ return joined || '.';
296
+ }
297
+
298
+ function _drainNextTickQueue(): void {
299
+ if (_nextTickQueue.length === 0) {
300
+ _nextTickScheduled = false;
301
+ return;
302
+ }
303
+
304
+ _nextTickScheduled = false;
305
+ while (_nextTickQueue.length > 0) {
306
+ const batch = _nextTickQueue.splice(0, _nextTickQueue.length);
307
+ for (const entry of batch) {
308
+ entry.callback(...entry.args);
309
+ }
310
+ }
311
+ }
312
+
313
+ function _wrapNextTickAwareCallback<TArgs extends any[], TResult>(
314
+ callback?: ((...args: TArgs) => TResult) | null
315
+ ): ((...args: TArgs) => TResult) | undefined {
316
+ if (typeof callback !== 'function') {
317
+ return undefined;
318
+ }
319
+
320
+ return function(this: unknown, ...args: TArgs): TResult {
321
+ _drainNextTickQueue();
322
+ return callback.apply(this, args);
323
+ };
324
+ }
325
+
326
+ function _installNextTickHooks(): void {
327
+ if (_nextTickHooksInstalled || _nativeProcessNextTick || _nativeGlobalNextTick) {
328
+ return;
329
+ }
330
+ _nextTickHooksInstalled = true;
331
+
332
+ Promise.prototype.then = function then(
333
+ onFulfilled?: ((value: any) => any) | null,
334
+ onRejected?: ((reason: any) => any) | null
335
+ ) {
336
+ return _nativePromiseThen.call(
337
+ this,
338
+ _wrapNextTickAwareCallback(onFulfilled),
339
+ _wrapNextTickAwareCallback(onRejected)
340
+ );
341
+ };
342
+
343
+ if (_nativeQueueMicrotask) {
344
+ try {
345
+ (globalThis as any).queueMicrotask = (callback: () => void): void => {
346
+ _nativeQueueMicrotask(() => {
347
+ _drainNextTickQueue();
348
+ callback();
349
+ });
350
+ };
351
+ } catch (_err) {}
352
+ }
353
+ }
354
+
355
+ function _scheduleNextTickDrain(): void {
356
+ if (_nextTickScheduled) {
357
+ return;
358
+ }
359
+ _nextTickScheduled = true;
360
+ _installNextTickHooks();
361
+ if (_nativeQueueMicrotask) {
362
+ _nativeQueueMicrotask(_drainNextTickQueue);
363
+ return;
364
+ }
365
+ Promise.resolve().then(_drainNextTickQueue);
366
+ }
367
+
368
+ function _monotonicTimeNs(): bigint {
369
+ if (!_nativeBigInt) {
370
+ throw new TypeError('BigInt is not supported by this JavaScript engine');
371
+ }
372
+ const perf = (globalThis as any).performance;
373
+ if (perf && typeof perf.now === 'function') {
374
+ const originMs =
375
+ typeof perf.timeOrigin === 'number' && Number.isFinite(perf.timeOrigin)
376
+ ? perf.timeOrigin
377
+ : Date.now();
378
+ return _nativeBigInt(Math.floor((originMs + perf.now()) * 1e6));
379
+ }
380
+ return _nativeBigInt(Date.now()) * _nativeBigInt(1000000);
381
+ }
382
+
383
+ function _monotonicHrtimeTuple(): [number, number] {
384
+ if (_nativeProcessHrtime) {
385
+ const nativeNow = _nativeProcessHrtime();
386
+ if (
387
+ Array.isArray(nativeNow) &&
388
+ typeof nativeNow[0] === 'number' &&
389
+ typeof nativeNow[1] === 'number'
390
+ ) {
391
+ return [nativeNow[0], nativeNow[1]];
392
+ }
393
+ }
394
+
395
+ const perf = (globalThis as any).performance;
396
+ const nowMs =
397
+ perf && typeof perf.now === 'function'
398
+ ? (typeof perf.timeOrigin === 'number' && Number.isFinite(perf.timeOrigin)
399
+ ? perf.timeOrigin
400
+ : Date.now()) + perf.now()
401
+ : Date.now();
402
+ const seconds = Math.floor(nowMs / 1000);
403
+ const nanoseconds = Math.floor((nowMs - seconds * 1000) * 1e6);
404
+ return [seconds, nanoseconds];
405
+ }
406
+
407
+ function _stringifyPathPart(path: any): string {
408
+ if (typeof path === 'string') return path;
409
+ if (typeof Buffer !== 'undefined' && Buffer.isBuffer?.(path)) return path.toString();
410
+ return String(path);
411
+ }
412
+
413
+ function _normalizeCwdPath(value: any): string {
414
+ const path = _stringifyPathPart(value);
415
+ if (path.length === 0) return "/";
416
+ if (path.charAt(0) === "/" || /^[A-Za-z]:[\\/]/.test(path)) {
417
+ return _normalizeResolvedPath(path);
418
+ }
419
+ return _normalizeResolvedPath(`/${path}`);
420
+ }
421
+
422
+ function _resolveCwd(path: string): string {
423
+ if (path.charAt(0) === '/' || /^[A-Za-z]:[\\/]/.test(path)) {
424
+ return _normalizeResolvedPath(path);
425
+ }
426
+ const cwd = typeof process === 'object' && process && typeof process.cwd === 'function' ? process.cwd() : "/";
427
+ if (cwd.charAt(cwd.length - 1) !== '/') {
428
+ return _normalizeResolvedPath(`${cwd}/${path}`);
429
+ }
430
+ return _normalizeResolvedPath(`${cwd}${path}`);
431
+ }
432
+
433
+ function _readNativeCwd(): string | null {
434
+ if (typeof __exactGetCwd !== 'function') {
435
+ return null;
436
+ }
437
+ try {
438
+ const value = __exactGetCwd();
439
+ if (typeof value === 'string' && value.length > 0) {
440
+ return _normalizeCwdPath(value);
441
+ }
442
+ } catch (_err) {}
443
+ return null;
444
+ }
445
+
446
+ function _coerceChdirError(err: unknown, origArg: string): Error & { code?: string; errno?: number; syscall?: string; path?: string; dest?: string } {
447
+ const fallbackErrorMap: Record<string, number> = {
448
+ EACCES: 13,
449
+ EINVAL: 22,
450
+ ENOENT: 2,
451
+ ENOTDIR: 20,
452
+ };
453
+ // Use native cwd if available, fall back to _processCwd
454
+ const currentCwd = (typeof __exactGetCwd === 'function' ? __exactGetCwd() : null) || _processCwd;
455
+ if (err && typeof err === 'object' && typeof (err as any).message === 'string') {
456
+ const message = (err as any).message as string;
457
+ const lower = message.toLowerCase();
458
+ let code: string | undefined;
459
+ if (lower.includes('no such file') || lower.includes('does not exist')) {
460
+ code = 'ENOENT';
461
+ } else if (lower.includes('permission denied')) {
462
+ code = 'EACCES';
463
+ } else if (lower.includes('not a directory')) {
464
+ code = 'ENOTDIR';
465
+ }
466
+ if (code) {
467
+ const codeStr: Record<string, string> = { ENOENT: 'no such file or directory', EACCES: 'permission denied', ENOTDIR: 'not a directory' };
468
+ const errMsg = `${code}: ${codeStr[code] || message}, chdir '${currentCwd}' -> '${origArg}'`;
469
+ const mapped = new Error(errMsg) as Error & { code?: string; errno?: number; syscall?: string; path?: string; dest?: string };
470
+ mapped.code = code;
471
+ const errno = fallbackErrorMap[code];
472
+ if (errno !== undefined) {
473
+ mapped.errno = -errno;
474
+ }
475
+ mapped.syscall = 'chdir';
476
+ mapped.path = currentCwd;
477
+ mapped.dest = origArg;
478
+ return mapped;
479
+ }
480
+ }
481
+ const fallback = new Error('process.chdir failed') as Error & { code?: string; errno?: number; syscall?: string; path?: string; dest?: string };
482
+ fallback.code = 'EINVAL';
483
+ fallback.syscall = 'chdir';
484
+ fallback.path = currentCwd;
485
+ fallback.dest = origArg;
486
+ return fallback;
487
+ }
488
+
489
+ function _deepFreeze<T>(value: T): T {
490
+ if (!value || (typeof value !== 'object' && typeof value !== 'function') || Object.isFrozen(value)) {
491
+ return value;
492
+ }
493
+
494
+ Object.freeze(value);
495
+ for (const key of Object.getOwnPropertyNames(value)) {
496
+ _deepFreeze((value as Record<string, unknown>)[key] as T);
497
+ }
498
+ return value;
499
+ }
500
+
501
+ function _getConfiguredTimeZone(): string | undefined {
502
+ const env = (globalThis as any).process?.env;
503
+ const timeZone = env?.TZ;
504
+ return typeof timeZone === 'string' && timeZone.length > 0 ? timeZone : undefined;
505
+ }
506
+
507
+ function _getTimeZoneOffsetMinutes(date: Date, timeZone: string): number {
508
+ const parts = new Intl.DateTimeFormat('en-CA', {
509
+ timeZone,
510
+ year: 'numeric',
511
+ month: '2-digit',
512
+ day: '2-digit',
513
+ hour: '2-digit',
514
+ minute: '2-digit',
515
+ second: '2-digit',
516
+ hourCycle: 'h23',
517
+ }).formatToParts(date);
518
+
519
+ const values: Record<string, number> = {};
520
+ for (const part of parts) {
521
+ if (part.type === 'literal') {
522
+ continue;
523
+ }
524
+ values[part.type] = Number(part.value);
525
+ }
526
+
527
+ const zonedAsUtc = Date.UTC(
528
+ values.year,
529
+ (values.month ?? 1) - 1,
530
+ values.day ?? 1,
531
+ values.hour ?? 0,
532
+ values.minute ?? 0,
533
+ values.second ?? 0,
534
+ );
535
+ return Math.round((zonedAsUtc - date.getTime()) / 60000);
536
+ }
537
+
538
+ function _formatDateForConfiguredTimeZone(date: Date, timeZone: string): string | null {
539
+ if (Number.isNaN(date.getTime()) || typeof Intl === 'undefined' || typeof Intl.DateTimeFormat !== 'function') {
540
+ return null;
541
+ }
542
+
543
+ try {
544
+ const formatted = new Intl.DateTimeFormat('en-US', {
545
+ timeZone,
546
+ weekday: 'short',
547
+ month: 'short',
548
+ day: '2-digit',
549
+ year: 'numeric',
550
+ hour: '2-digit',
551
+ minute: '2-digit',
552
+ second: '2-digit',
553
+ hourCycle: 'h23',
554
+ }).format(date);
555
+ const match = formatted.match(/^([A-Za-z]{3}), ([A-Za-z]{3}) (\d{2}), (\d{4}) at (\d{2}:\d{2}:\d{2})$/);
556
+ if (!match) {
557
+ return null;
558
+ }
559
+
560
+ const timeZoneNameFormatted = new Intl.DateTimeFormat('en-US', {
561
+ timeZone,
562
+ timeZoneName: 'long',
563
+ }).format(date);
564
+ const timeZoneName = timeZoneNameFormatted.split(', ').slice(1).join(', ') || timeZone;
565
+
566
+ const totalOffsetMinutes = _getTimeZoneOffsetMinutes(date, timeZone);
567
+ const absoluteOffsetMinutes = Math.abs(totalOffsetMinutes);
568
+ const offsetHours = Math.floor(absoluteOffsetMinutes / 60).toString().padStart(2, '0');
569
+ const offsetMinutes = (absoluteOffsetMinutes % 60).toString().padStart(2, '0');
570
+ const sign = totalOffsetMinutes >= 0 ? '+' : '-';
571
+
572
+ return `${match[1]} ${match[2]} ${match[3]} ${match[4]} ${match[5]} ` +
573
+ `GMT${sign}${offsetHours}${offsetMinutes} (${timeZoneName})`;
574
+ } catch {
575
+ return null;
576
+ }
577
+ }
578
+
579
+ function _installTimeZoneAwareDateToString(): void {
580
+ if (_dateToStringPatched) {
581
+ return;
582
+ }
583
+ _dateToStringPatched = true;
584
+
585
+ Date.prototype.toString = function exactToString(this: Date): string {
586
+ const timeZone = _getConfiguredTimeZone();
587
+ if (!timeZone) {
588
+ return _nativeDateToString.call(this);
589
+ }
590
+
591
+ const formatted = _formatDateForConfiguredTimeZone(this, timeZone);
592
+ return formatted ?? _nativeDateToString.call(this);
593
+ };
594
+ }
595
+
596
+ export interface ProcessVersions {
597
+ node?: string;
598
+ acorn?: string;
599
+ ada?: string;
600
+ amaro?: string;
601
+ ares?: string;
602
+ brotli?: string;
603
+ cjs_module_lexer?: string;
604
+ cldr?: string;
605
+ icu?: string;
606
+ llhttp?: string;
607
+ modules?: string;
608
+ napi?: string;
609
+ nbytes?: string;
610
+ ncrypto?: string;
611
+ nghttp2?: string;
612
+ nghttp3?: string;
613
+ ngtcp2?: string;
614
+ openssl?: string;
615
+ simdjson?: string;
616
+ simdutf?: string;
617
+ sqlite?: string;
618
+ tz?: string;
619
+ undici?: string;
620
+ unicode?: string;
621
+ v8?: string;
622
+ uv?: string;
623
+ uvwasi?: string;
624
+ zlib?: string;
625
+ zstd?: string;
626
+ [key: string]: string | undefined;
627
+ }
628
+
629
+ const PROCESS_DEFAULT_CONFIG = _deepFreeze({
630
+ target_defaults: {
631
+ cflags: [] as string[],
632
+ default_configuration: 'Release',
633
+ defines: [] as string[],
634
+ include_dirs: [] as string[],
635
+ libraries: [] as string[],
636
+ },
637
+ variables: {
638
+ asan: 0,
639
+ coverage: false,
640
+ debug_nghttp2: false,
641
+ enable_lto: false,
642
+ enable_pgo_generate: false,
643
+ enable_pgo_use: false,
644
+ error_on_warn: false,
645
+ force_dynamic_crt: 0,
646
+ host_arch: 'arm64',
647
+ icu_data_in: '../../deps/icu-tmp/icudt76l.dat',
648
+ icu_endianness: 'l',
649
+ icu_gyp_path: 'tools/icu/icu-generic.gyp',
650
+ icu_path: 'deps/icu-small',
651
+ icu_small: false,
652
+ icu_ver_major: '76',
653
+ is_debug: 0,
654
+ llvm_version: '0.0',
655
+ napi_build_version: '9',
656
+ node_builtin_shareable_builtins: [] as string[],
657
+ node_byteorder: 'little',
658
+ node_debug_lib: false,
659
+ node_enable_d8: false,
660
+ node_enable_v8_vtunejit: false,
661
+ node_fipsinstall: false,
662
+ node_install_corepack: true,
663
+ node_install_npm: true,
664
+ node_library_files: [] as string[],
665
+ node_module_version: 131,
666
+ node_no_browser_globals: false,
667
+ node_prefix: '/',
668
+ node_release_urlbase: '',
669
+ node_section_ordering_info: '',
670
+ node_shared: false,
671
+ node_shared_brotli: false,
672
+ node_shared_cares: false,
673
+ node_shared_http_parser: false,
674
+ node_shared_libuv: false,
675
+ node_shared_nghttp2: false,
676
+ node_shared_openssl: false,
677
+ node_shared_zlib: false,
678
+ node_tag: '',
679
+ node_target_type: 'executable',
680
+ node_use_bundled_v8: true,
681
+ node_use_node_code_cache: true,
682
+ node_use_node_snapshot: true,
683
+ node_use_openssl: true,
684
+ node_use_v8_platform: true,
685
+ node_with_ltcg: false,
686
+ node_without_node_options: false,
687
+ openssl_is_fips: false,
688
+ openssl_quic: true,
689
+ ossfuzz: false,
690
+ shlib_suffix: 'so.131',
691
+ target_arch: 'arm64',
692
+ v8_enable_31bit_smis_on_64bit_arch: 0,
693
+ v8_enable_gdbjit: 0,
694
+ v8_enable_hugepage: 0,
695
+ v8_enable_i18n_support: 1,
696
+ v8_enable_inspector: 1,
697
+ v8_enable_javascript_promise_hooks: 1,
698
+ v8_enable_lite_mode: 0,
699
+ v8_enable_object_print: 1,
700
+ v8_enable_pointer_compression: 0,
701
+ v8_enable_shared_ro_heap: 1,
702
+ v8_enable_short_builtin_calls: 1,
703
+ v8_enable_webassembly: 1,
704
+ v8_no_strict_aliasing: 1,
705
+ v8_optimized_debug: 1,
706
+ v8_promise_internal_field_count: 1,
707
+ v8_random_seed: 0,
708
+ v8_trace_maps: 0,
709
+ v8_use_siphash: 1,
710
+ want_separate_host_toolset: 0,
711
+ },
712
+ });
713
+
714
+ const PROCESS_VERSIONS = createProcessVersions();
715
+ const PROCESS_RELEASE = createProcessRelease(
716
+ PROCESS_VERSIONS.node ?? RUNTIME_VERSIONS.find(([key]) => key === 'node')?.[1] ?? '0.0.0'
717
+ );
718
+
719
+ function createProcessVersions(): ProcessVersions {
720
+ const versions: ProcessVersions = {};
721
+ // Node-primary identity (LLP 0012#decision): only truthful keys ship ambient —
722
+ // the runtime, the engine, and the Node release the vendored compat corpus
723
+ // tracks. The old v8/uv/openssl/modules masquerade is gone from default
724
+ // execution; compat fixtures that hard-require those keys get them through
725
+ // the harness escape hatch below, never ambient.
726
+ const entries: Array<[string, string]> = [...RUNTIME_VERSIONS];
727
+
728
+ if (isCompatModeEnabled('bun')) {
729
+ // Opt-in Bun compat keeps detection coherent: when the Bun global
730
+ // exists, process.versions.bun exists too (LLP 0012#decision).
731
+ entries.push(['bun', BUN_COMPAT_VERSION]);
732
+ }
733
+
734
+ if (isCompatFixtureMode()) {
735
+ // Fixture-fidelity keys for the compat harness (EXACT_COMPAT_TEST):
736
+ // vendored Node/WPT tests read these. They describe what the fixtures
737
+ // expect, not what this runtime links (LLP 0012#decision escape hatch).
738
+ entries.push(
739
+ ['acorn', '8.15.0'],
740
+ ['ada', '2.9.2'],
741
+ ['ares', '1.34.4'],
742
+ ['brotli', '1.1.0'],
743
+ ['cjs_module_lexer', '2.1.0'],
744
+ ['cldr', '46.0'],
745
+ ['icu', '76.1'],
746
+ ['llhttp', '9.3.0'],
747
+ ['modules', '131'],
748
+ ['napi', '9'],
749
+ ['nbytes', '0.1.1'],
750
+ ['ncrypto', '0.0.1'],
751
+ ['nghttp2', '1.64.0'],
752
+ ['nghttp3', '1.6.0'],
753
+ ['ngtcp2', '1.9.1'],
754
+ ['openssl', '3.4.1'],
755
+ ['simdjson', '3.13.0'],
756
+ ['simdutf', '6.4.2'],
757
+ ['tz', '2025a'],
758
+ ['unicode', '16.0'],
759
+ ['uv', '1.50.0'],
760
+ ['uvwasi', '0.0.21'],
761
+ ['v8', '13.6.233.8-node.26'],
762
+ ['zlib', '1.3.1.1-motley-82a5fec'],
763
+ ['zstd', '1.5.7'],
764
+ );
765
+ }
766
+
767
+ for (const [key, value] of entries) {
768
+ Object.defineProperty(versions, key, {
769
+ value,
770
+ writable: false,
771
+ enumerable: true,
772
+ configurable: true,
773
+ });
774
+ }
775
+
776
+ return versions;
777
+ }
778
+
779
+ /// True when the named opt-in compat mode is active (set by the ibex CLI's
780
+ /// `--compat` flag via globalThis.__exactCompatModes, or the
781
+ /// EXACT_COMPAT_BUN env contract used by child spawns).
782
+ function isCompatModeEnabled(mode: string): boolean {
783
+ try {
784
+ const g = globalThis as any;
785
+ const modes = g.__exactCompatModes;
786
+ if (Array.isArray(modes) && modes.indexOf(mode) !== -1) return true;
787
+ if (mode === 'bun') {
788
+ const env = g.__exactHostEnv ?? g.process?.env;
789
+ if (env && env.EXACT_COMPAT_BUN === '1') return true;
790
+ }
791
+ } catch (_) {
792
+ // Identity must never throw during bootstrap.
793
+ }
794
+ return false;
795
+ }
796
+
797
+ function isCompatFixtureMode(): boolean {
798
+ try {
799
+ const g = globalThis as any;
800
+ const env = g.__exactHostEnv ?? g.process?.env;
801
+ return !!(env && env.EXACT_COMPAT_TEST);
802
+ } catch (_) {
803
+ return false;
804
+ }
805
+ }
806
+
807
+ function createProcessRelease(nodeVersion: string): ProcessRelease {
808
+ const release: ProcessRelease = { name: RELEASE_NAME };
809
+ const [majorText = '', minorText = ''] = String(nodeVersion).split('.');
810
+ const major = Number.parseInt(majorText, 10);
811
+ const minor = Number.parseInt(minorText, 10);
812
+ const ltsMap: Array<[number, number, string]> = [
813
+ [4, 2, 'Argon'],
814
+ [6, 9, 'Boron'],
815
+ [8, 9, 'Carbon'],
816
+ [10, 13, 'Dubnium'],
817
+ [12, 13, 'Erbium'],
818
+ [14, 15, 'Fermium'],
819
+ [16, 13, 'Gallium'],
820
+ [18, 12, 'Hydrogen'],
821
+ [20, 9, 'Iron'],
822
+ [22, 11, 'Jod'],
823
+ [24, 11, 'Krypton'],
824
+ ];
825
+ for (const [ltsMajor, ltsMinor, ltsName] of ltsMap) {
826
+ if (major === ltsMajor && minor >= ltsMinor) {
827
+ release.lts = ltsName;
828
+ break;
829
+ }
830
+ }
831
+ return release;
832
+ }
833
+
834
+ /**
835
+ * Create a process stream (stdout/stderr/stdin) with basic EventEmitter support.
836
+ * This ensures pipe() and other stream operations work even before stream-enhance runs.
837
+ */
838
+ function _makeProcessStream(fd: number, isTTY: boolean, writeFn?: (data: string) => boolean): any {
839
+ const listeners: Record<string, Array<{fn: Function, once: boolean}>> = {};
840
+ function coerceChunk(chunk: any): string {
841
+ if (chunk == null) return '';
842
+ if (typeof chunk === 'string') return chunk;
843
+ if (typeof Buffer !== 'undefined' && Buffer.isBuffer && Buffer.isBuffer(chunk)) return chunk.toString();
844
+ if (chunk instanceof Uint8Array) {
845
+ if (typeof TextDecoder !== 'undefined') return new TextDecoder().decode(chunk);
846
+ let out = '';
847
+ for (let i = 0; i < chunk.length; i++) out += String.fromCharCode(chunk[i]);
848
+ return out;
849
+ }
850
+ return String(chunk);
851
+ }
852
+ const stream: any = {
853
+ fd,
854
+ isTTY,
855
+ readable: fd === 0,
856
+ readableEnded: false,
857
+ readableFlowing: null,
858
+ readableLength: 0,
859
+ writable: fd > 0,
860
+ writableEnded: false,
861
+ writableFinished: false,
862
+ destroyed: false,
863
+ _encoding: null,
864
+ _paused: true,
865
+ _ended: false,
866
+ _pollTimer: 0,
867
+ on(event: string, fn: Function) { if (!listeners[event]) listeners[event] = []; listeners[event].push({fn, once: false}); return stream; },
868
+ addListener(event: string, fn: Function) { return stream.on(event, fn); },
869
+ once(event: string, fn: Function) { if (!listeners[event]) listeners[event] = []; listeners[event].push({fn, once: true}); return stream; },
870
+ emit(event: string, ...args: any[]) {
871
+ const list = listeners[event];
872
+ if (!list) return false;
873
+ const keep: typeof list = [];
874
+ for (let i = 0; i < list.length; i++) {
875
+ if (typeof list[i].fn === 'function') list[i].fn.apply(stream, args);
876
+ if (!list[i].once) keep.push(list[i]);
877
+ }
878
+ listeners[event] = keep;
879
+ return true;
880
+ },
881
+ removeListener(event: string, fn: Function) {
882
+ const list = listeners[event];
883
+ if (list) listeners[event] = list.filter(l => l.fn !== fn);
884
+ return stream;
885
+ },
886
+ off(event: string, fn: Function) { return stream.removeListener(event, fn); },
887
+ removeAllListeners(event?: string) { if (event) { listeners[event] = []; } else { for (const k in listeners) listeners[k] = []; } return stream; },
888
+ setMaxListeners() { return stream; },
889
+ getMaxListeners() { return 10; },
890
+ listenerCount(event: string) { return listeners[event] ? listeners[event].length : 0; },
891
+ listeners(event: string) { return (listeners[event] || []).map(l => l.fn); },
892
+ prependListener(event: string, fn: Function) { if (!listeners[event]) listeners[event] = []; listeners[event].unshift({fn, once: false}); return stream; },
893
+ prependOnceListener(event: string, fn: Function) { if (!listeners[event]) listeners[event] = []; listeners[event].unshift({fn, once: true}); return stream; },
894
+ rawListeners(event: string) { return stream.listeners(event); },
895
+ eventNames() { return Object.keys(listeners).filter(k => listeners[k] && listeners[k].length > 0); },
896
+ destroy(err?: any) {
897
+ stream.destroyed = true;
898
+ if (fd === 0) {
899
+ stream.readable = false;
900
+ stream.readableEnded = true;
901
+ stream.readableFlowing = false;
902
+ } else {
903
+ stream.writableEnded = true;
904
+ stream.writableFinished = true;
905
+ }
906
+ if (err) stream.emit('error', err);
907
+ stream.emit('close');
908
+ return stream;
909
+ },
910
+ };
911
+ if (fd === 0) {
912
+ stream.setEncoding = function(enc: string) {
913
+ stream._encoding = enc;
914
+ return stream;
915
+ };
916
+ stream.resume = function() {
917
+ stream.readable = true;
918
+ stream._paused = false;
919
+ stream.readableFlowing = true;
920
+ if (!stream._ended && !stream._pollTimer && typeof (globalThis as any).__exactStdinRead === 'function') {
921
+ (function pollStdin() {
922
+ if (stream._paused || stream._ended || stream.destroyed) {
923
+ return;
924
+ }
925
+ const stdinRead = (globalThis as any).__exactStdinRead;
926
+ const data = stdinRead(4096);
927
+ if (data === null) {
928
+ stream._pollTimer = setTimeout(pollStdin, 25);
929
+ return;
930
+ }
931
+ if (data === '') {
932
+ stream._ended = true;
933
+ stream._pollTimer = 0;
934
+ stream.readableEnded = true;
935
+ stream.emit('end');
936
+ stream.emit('close');
937
+ return;
938
+ }
939
+ stream._pollTimer = 0;
940
+ let chunk: any = data;
941
+ if (stream._encoding && typeof Buffer !== 'undefined' && Buffer.from) {
942
+ chunk = Buffer.from(data, 'binary').toString(stream._encoding);
943
+ }
944
+ stream.readableLength += chunk.length || 0;
945
+ stream.emit('data', chunk);
946
+ stream.readableLength = 0;
947
+ if (!stream._paused && !stream._ended) {
948
+ stream._pollTimer = setTimeout(pollStdin, 10);
949
+ }
950
+ })();
951
+ }
952
+ return stream;
953
+ };
954
+ stream.pause = function() {
955
+ stream._paused = true;
956
+ stream.readableFlowing = false;
957
+ if (stream._pollTimer) {
958
+ clearTimeout(stream._pollTimer);
959
+ stream._pollTimer = 0;
960
+ }
961
+ return stream;
962
+ };
963
+ stream.read = function(size?: number) {
964
+ const stdinRead = (globalThis as any).__exactStdinRead;
965
+ if (typeof stdinRead !== 'function') {
966
+ return null;
967
+ }
968
+ const data = stdinRead(size || 4096);
969
+ if (data === '') {
970
+ return null;
971
+ }
972
+ if (stream._encoding && data && typeof Buffer !== 'undefined' && Buffer.from) {
973
+ return Buffer.from(data, 'binary').toString(stream._encoding);
974
+ }
975
+ return data;
976
+ };
977
+ stream.pipe = function(destination: any) {
978
+ stream.on('data', (chunk: any) => {
979
+ destination.write(chunk);
980
+ });
981
+ stream.once('end', () => {
982
+ destination.end?.();
983
+ });
984
+ stream.once('error', (error: any) => {
985
+ if (typeof destination.emit === 'function') {
986
+ destination.emit('error', error);
987
+ } else {
988
+ destination.destroy?.(error);
989
+ }
990
+ });
991
+ stream.resume();
992
+ return destination;
993
+ };
994
+ const originalOn = stream.on;
995
+ stream.on = function(event: string, fn: Function) {
996
+ const result = originalOn.call(stream, event, fn);
997
+ if (event === 'data' && !stream._ended && stream._paused) {
998
+ stream.resume();
999
+ }
1000
+ return result;
1001
+ };
1002
+ stream.addListener = stream.on;
1003
+ const originalOnce = stream.once;
1004
+ stream.once = function(event: string, fn: Function) {
1005
+ const result = originalOnce.call(stream, event, fn);
1006
+ if (event === 'data' && !stream._ended && stream._paused) {
1007
+ stream.resume();
1008
+ }
1009
+ return result;
1010
+ };
1011
+ }
1012
+ if (writeFn) {
1013
+ const _exactWriteImpl = function(chunk: any, encoding?: any, callback?: Function) {
1014
+ if (typeof encoding === 'function') { callback = encoding; encoding = undefined; }
1015
+ const normalizedChunk = coerceChunk(chunk);
1016
+ const result = writeFn(normalizedChunk);
1017
+ if (typeof callback === 'function') callback();
1018
+ return result;
1019
+ };
1020
+ (_exactWriteImpl as any).__exactNativeWrite = true;
1021
+ stream.write = _exactWriteImpl;
1022
+ stream.end = function(chunk?: any, encoding?: any, callback?: Function) {
1023
+ if (typeof chunk === 'function') { callback = chunk; chunk = undefined; }
1024
+ if (typeof encoding === 'function') { callback = encoding; encoding = undefined; }
1025
+ if (chunk != null) stream.write(chunk, encoding);
1026
+ stream.writableEnded = true;
1027
+ stream.writableFinished = true;
1028
+ stream.emit('finish');
1029
+ stream.emit('close');
1030
+ if (typeof callback === 'function') callback();
1031
+ };
1032
+ }
1033
+ return stream;
1034
+ }
1035
+
1036
+ export interface ProcessRelease {
1037
+ name: string;
1038
+ lts?: string | false;
1039
+ sourceUrl?: string;
1040
+ headersUrl?: string;
1041
+ }
1042
+
1043
+ export interface HrtimeFunction {
1044
+ (time?: [number, number]): [number, number];
1045
+ bigint?: () => bigint;
1046
+ }
1047
+
1048
+ /**
1049
+ * Create a Proxy-based env object that reads from native
1050
+ */
1051
+ function createEnvProxy(): Record<string, string | undefined> {
1052
+ // Store for JS-set values (fallback and for values not in native)
1053
+ const jsEnv: Record<string, string | undefined> = {
1054
+ // Default values commonly expected by npm packages
1055
+ // Default to 'development' so capability checks allow operations during dev
1056
+ // Native layer can override this to 'production' for release builds
1057
+ NODE_ENV: 'development',
1058
+ };
1059
+ let nativeCache: Record<string, string> | null = null;
1060
+
1061
+ function refreshNativeCache(): Record<string, string> {
1062
+ if (typeof __exactGetAllEnv === 'function') {
1063
+ nativeCache = { ...__exactGetAllEnv() };
1064
+ } else if (nativeCache === null) {
1065
+ nativeCache = {};
1066
+ }
1067
+ return nativeCache ?? {};
1068
+ }
1069
+
1070
+ function getNativeValue(key: string): string | undefined {
1071
+ if (nativeCache && Object.prototype.hasOwnProperty.call(nativeCache, key)) {
1072
+ return nativeCache[key];
1073
+ }
1074
+ if (typeof __exactGetEnv === 'function') {
1075
+ const value = __exactGetEnv(key);
1076
+ if (value !== undefined) {
1077
+ refreshNativeCache()[key] = value;
1078
+ }
1079
+ return value;
1080
+ }
1081
+ return refreshNativeCache()[key];
1082
+ }
1083
+
1084
+ return new Proxy(jsEnv, {
1085
+ get(target, prop: string | symbol): string | undefined {
1086
+ if (typeof prop === 'symbol') {
1087
+ return undefined;
1088
+ }
1089
+
1090
+ // Special handling for toJSON
1091
+ if (prop === 'toJSON') {
1092
+ return () => {
1093
+ const all: Record<string, string> = { ...target } as Record<string, string>;
1094
+ Object.assign(all, refreshNativeCache());
1095
+ return all;
1096
+ };
1097
+ }
1098
+
1099
+ const nativeValue = getNativeValue(prop);
1100
+ if (nativeValue !== undefined) {
1101
+ return nativeValue;
1102
+ }
1103
+
1104
+ // Fall back to JS store
1105
+ return target[prop];
1106
+ },
1107
+
1108
+ set(target, prop: string | symbol, value: any): boolean {
1109
+ if (typeof prop === 'symbol') {
1110
+ throw new TypeError('Cannot convert a Symbol value to a string');
1111
+ }
1112
+ if (typeof value === 'symbol') {
1113
+ throw new TypeError('Cannot convert a Symbol value to a string');
1114
+ }
1115
+ const key = prop as string;
1116
+ if (key.length === 0) {
1117
+ return true;
1118
+ }
1119
+ const normalized = String(value);
1120
+ target[key] = normalized;
1121
+ if (nativeCache) {
1122
+ nativeCache[key] = normalized;
1123
+ }
1124
+ return true;
1125
+ },
1126
+
1127
+ has(target, prop: string | symbol): boolean {
1128
+ if (typeof prop === 'symbol') {
1129
+ return false;
1130
+ }
1131
+
1132
+ if (getNativeValue(prop) !== undefined) {
1133
+ return true;
1134
+ }
1135
+
1136
+ return prop in target;
1137
+ },
1138
+
1139
+ deleteProperty(target, prop: string | symbol): boolean {
1140
+ if (typeof prop === 'symbol') {
1141
+ return true;
1142
+ }
1143
+ const key = prop as string;
1144
+ delete target[key];
1145
+ if (nativeCache) {
1146
+ delete nativeCache[key];
1147
+ }
1148
+ return true;
1149
+ },
1150
+
1151
+ ownKeys(target): string[] {
1152
+ const keys = new Set(Object.keys(target));
1153
+ Object.keys(refreshNativeCache()).forEach(k => keys.add(k));
1154
+
1155
+ return Array.from(keys);
1156
+ },
1157
+
1158
+ defineProperty(target, prop: string | symbol, descriptor: PropertyDescriptor): boolean {
1159
+ if (typeof prop === 'symbol') {
1160
+ throw makeInvalidObjectDefinePropertyError(
1161
+ '\'process.env\' only accepts a configurable, writable, and enumerable data descriptor',
1162
+ );
1163
+ }
1164
+
1165
+ if (typeof descriptor.get === 'function' || typeof descriptor.set === 'function') {
1166
+ throw makeInvalidObjectDefinePropertyError(
1167
+ '\'process.env\' does not accept an accessor(getter/setter) descriptor',
1168
+ );
1169
+ }
1170
+
1171
+ if (descriptor.configurable !== true || descriptor.writable !== true || descriptor.enumerable !== true) {
1172
+ throw makeInvalidObjectDefinePropertyError(
1173
+ '\'process.env\' only accepts a configurable, writable, and enumerable data descriptor',
1174
+ );
1175
+ }
1176
+
1177
+ this.set!(target, prop, descriptor.value, target);
1178
+ return true;
1179
+ },
1180
+
1181
+ getOwnPropertyDescriptor(target, prop: string | symbol): PropertyDescriptor | undefined {
1182
+ if (typeof prop === 'symbol') {
1183
+ return undefined;
1184
+ }
1185
+
1186
+ const key = prop as string;
1187
+ if (Object.prototype.hasOwnProperty.call(target, key)) {
1188
+ return {
1189
+ value: target[key],
1190
+ writable: true,
1191
+ enumerable: true,
1192
+ configurable: true,
1193
+ };
1194
+ }
1195
+
1196
+ const nativeValue = getNativeValue(key);
1197
+ if (nativeValue !== undefined) {
1198
+ return {
1199
+ value: nativeValue,
1200
+ writable: true,
1201
+ enumerable: true,
1202
+ configurable: true,
1203
+ };
1204
+ }
1205
+
1206
+ return undefined;
1207
+ },
1208
+ });
1209
+ }
1210
+
1211
+ /**
1212
+ * Process object providing Node.js-like environment info.
1213
+ */
1214
+ class Process {
1215
+ private _maxListeners = 10;
1216
+ /**
1217
+ * Environment variables.
1218
+ * Reads from native layer with fallback to JS-set values.
1219
+ * NODE_ENV defaults to 'development' (native layer sets 'production' for release builds).
1220
+ */
1221
+ readonly env: Record<string, string | undefined> = createEnvProxy();
1222
+
1223
+ /**
1224
+ * Platform identifier.
1225
+ * Returns host platform when available (e.g. "linux", "darwin", "win32"),
1226
+ * otherwise falls back to runtime detection.
1227
+ */
1228
+ get platform(): string {
1229
+ const g = globalThis as any;
1230
+ if (typeof g.__exactPlatform === 'string' && g.__exactPlatform.length > 0) {
1231
+ return g.__exactPlatform;
1232
+ }
1233
+ return runtimeInfo.platform;
1234
+ }
1235
+
1236
+ /**
1237
+ * Process architecture.
1238
+ * Returns host arch when available (e.g. "x64", "arm64").
1239
+ */
1240
+ get arch(): string {
1241
+ const g = globalThis as any;
1242
+ if (typeof g.__exactArch === 'string' && g.__exactArch.length > 0) {
1243
+ return g.__exactArch;
1244
+ }
1245
+ // Avoid reading g.process.arch — it may be this instance, causing infinite recursion.
1246
+ // Use the cached native arch captured at init time instead.
1247
+ if (_nativeArch) {
1248
+ return _nativeArch;
1249
+ }
1250
+ return 'arm64';
1251
+ }
1252
+
1253
+ /**
1254
+ * Node.js-compatible version string.
1255
+ * Format: "v{major}.{minor}.{patch}"
1256
+ */
1257
+ get version(): string {
1258
+ return `v${PROCESS_VERSIONS.node ?? getRuntimeVersion()}`;
1259
+ }
1260
+
1261
+ /**
1262
+ * Version strings for various components.
1263
+ * Includes all fields that Node.js tests expect on `process.versions`.
1264
+ */
1265
+ get versions(): ProcessVersions {
1266
+ return PROCESS_VERSIONS;
1267
+ }
1268
+
1269
+ readonly config = PROCESS_DEFAULT_CONFIG;
1270
+
1271
+ /**
1272
+ * Release information.
1273
+ */
1274
+ get release(): ProcessRelease {
1275
+ return PROCESS_RELEASE;
1276
+ }
1277
+
1278
+ /**
1279
+ * Process title (runtime name).
1280
+ */
1281
+ get title(): string {
1282
+ return 'ibex';
1283
+ }
1284
+
1285
+ /**
1286
+ * Process ID (not meaningful in mobile context, always returns 1).
1287
+ */
1288
+ get pid(): number {
1289
+ return 1;
1290
+ }
1291
+
1292
+ /**
1293
+ * Parent process ID (always 0 in mobile context).
1294
+ */
1295
+ get ppid(): number {
1296
+ return 0;
1297
+ }
1298
+
1299
+ binding(name: string): unknown {
1300
+ if (name === 'util') {
1301
+ const types = (globalThis as any).require?.('util')?.types ?? {};
1302
+ const binding: Record<string, unknown> = {};
1303
+ for (const key of [
1304
+ 'isAnyArrayBuffer',
1305
+ 'isArrayBuffer',
1306
+ 'isArrayBufferView',
1307
+ 'isAsyncFunction',
1308
+ 'isDataView',
1309
+ 'isDate',
1310
+ 'isExternal',
1311
+ 'isMap',
1312
+ 'isMapIterator',
1313
+ 'isNativeError',
1314
+ 'isPromise',
1315
+ 'isRegExp',
1316
+ 'isSet',
1317
+ 'isSetIterator',
1318
+ 'isTypedArray',
1319
+ 'isUint8Array',
1320
+ ]) {
1321
+ binding[key] = types[key];
1322
+ }
1323
+ return binding;
1324
+ }
1325
+ // Return empty stubs for deprecated/internal bindings that vendored Node
1326
+ // modules may request at import time. Throwing here causes "unhandled
1327
+ // error between tests" noise and can break module-level initialization.
1328
+ if (name === 'constants') {
1329
+ return {
1330
+ os: {
1331
+ errno: {
1332
+ E2BIG: 7, EACCES: 13, EADDRINUSE: 48, EADDRNOTAVAIL: 49,
1333
+ EAFNOSUPPORT: 47, EAGAIN: 35, EALREADY: 37, EBADF: 9,
1334
+ EBUSY: 16, ECANCELED: 89, ECHILD: 10, ECONNABORTED: 53,
1335
+ ECONNREFUSED: 61, ECONNRESET: 54, EDEADLK: 11, EDESTADDRREQ: 39,
1336
+ EDOM: 33, EEXIST: 17, EFAULT: 14, EFBIG: 27, EHOSTUNREACH: 65,
1337
+ EINPROGRESS: 36, EINTR: 4, EINVAL: 22, EIO: 5, EISCONN: 56,
1338
+ EISDIR: 21, ELOOP: 62, EMFILE: 24, EMLINK: 31, EMSGSIZE: 40,
1339
+ ENAMETOOLONG: 63, ENETDOWN: 50, ENETRESET: 52, ENETUNREACH: 51,
1340
+ ENFILE: 23, ENOBUFS: 55, ENODEV: 19, ENOENT: 2, ENOEXEC: 8,
1341
+ ENOLCK: 77, ENOMEM: 12, ENOPROTOOPT: 42, ENOSPC: 28, ENOSYS: 78,
1342
+ ENOTCONN: 57, ENOTDIR: 20, ENOTEMPTY: 66, ENOTSOCK: 38,
1343
+ ENOTSUP: 45, ENOTTY: 25, ENXIO: 6, EOPNOTSUPP: 102,
1344
+ EOVERFLOW: 84, EPERM: 1, EPIPE: 32, EPROTONOSUPPORT: 43,
1345
+ EPROTOTYPE: 41, ERANGE: 34, EROFS: 30, ESPIPE: 29, ESRCH: 3,
1346
+ ETIMEDOUT: 60, ETXTBSY: 26, EWOULDBLOCK: 35, EXDEV: 18,
1347
+ },
1348
+ signals: {
1349
+ SIGHUP: 1, SIGINT: 2, SIGQUIT: 3, SIGILL: 4, SIGTRAP: 5,
1350
+ SIGABRT: 6, SIGFPE: 8, SIGKILL: 9, SIGBUS: 10, SIGSEGV: 11,
1351
+ SIGSYS: 12, SIGPIPE: 13, SIGALRM: 14, SIGTERM: 15, SIGURG: 16,
1352
+ SIGSTOP: 17, SIGTSTP: 18, SIGCONT: 19, SIGCHLD: 20, SIGTTIN: 21,
1353
+ SIGTTOU: 22, SIGIO: 23, SIGXCPU: 24, SIGXFSZ: 25, SIGVTALRM: 26,
1354
+ SIGPROF: 27, SIGINFO: 29, SIGUSR1: 30, SIGUSR2: 31,
1355
+ },
1356
+ },
1357
+ fs: {
1358
+ O_RDONLY: 0, O_WRONLY: 1, O_RDWR: 2, O_CREAT: 512, O_EXCL: 2048,
1359
+ O_TRUNC: 1024, O_APPEND: 8, O_DIRECTORY: 1048576, O_SYMLINK: 2097152,
1360
+ S_IFMT: 61440, S_IFREG: 32768, S_IFDIR: 16384, S_IFLNK: 40960,
1361
+ S_IFCHR: 8192, S_IFBLK: 24576, S_IFIFO: 4096, S_IFSOCK: 49152,
1362
+ },
1363
+ zlib: {
1364
+ Z_NO_FLUSH: 0, Z_PARTIAL_FLUSH: 1, Z_SYNC_FLUSH: 2,
1365
+ Z_FULL_FLUSH: 3, Z_FINISH: 4, Z_BLOCK: 5,
1366
+ Z_OK: 0, Z_STREAM_END: 1, Z_NEED_DICT: 2,
1367
+ Z_ERRNO: -1, Z_STREAM_ERROR: -2, Z_DATA_ERROR: -3,
1368
+ Z_MEM_ERROR: -4, Z_BUF_ERROR: -5, Z_VERSION_ERROR: -6,
1369
+ Z_NO_COMPRESSION: 0, Z_BEST_SPEED: 1, Z_BEST_COMPRESSION: 9,
1370
+ Z_DEFAULT_COMPRESSION: -1,
1371
+ Z_FILTERED: 1, Z_HUFFMAN_ONLY: 2, Z_RLE: 3, Z_FIXED: 4,
1372
+ Z_DEFAULT_STRATEGY: 0,
1373
+ Z_MIN_WINDOWBITS: 8, Z_MAX_WINDOWBITS: 15, Z_DEFAULT_WINDOWBITS: 15,
1374
+ Z_MIN_CHUNK: 64, Z_MAX_CHUNK: null, Z_DEFAULT_CHUNK: 16384,
1375
+ Z_MIN_MEMLEVEL: 1, Z_MAX_MEMLEVEL: 9, Z_DEFAULT_MEMLEVEL: 8,
1376
+ Z_MIN_LEVEL: -1, Z_MAX_LEVEL: 9, Z_DEFAULT_LEVEL: -1,
1377
+ DEFLATE: 1, INFLATE: 2, GZIP: 3, GUNZIP: 4,
1378
+ DEFLATERAW: 5, INFLATERAW: 6, UNZIP: 7,
1379
+ BROTLI_DECODE: 8, BROTLI_ENCODE: 9,
1380
+ BROTLI_OPERATION_PROCESS: 0, BROTLI_OPERATION_FLUSH: 1,
1381
+ BROTLI_OPERATION_FINISH: 2, BROTLI_OPERATION_EMIT_METADATA: 3,
1382
+ BROTLI_PARAM_MODE: 0, BROTLI_MODE_GENERIC: 0,
1383
+ BROTLI_MODE_TEXT: 1, BROTLI_MODE_FONT: 2, BROTLI_DEFAULT_MODE: 0,
1384
+ BROTLI_PARAM_QUALITY: 1, BROTLI_MIN_QUALITY: 0,
1385
+ BROTLI_MAX_QUALITY: 11, BROTLI_DEFAULT_QUALITY: 11,
1386
+ BROTLI_PARAM_LGWIN: 2, BROTLI_MIN_WINDOW_BITS: 10,
1387
+ BROTLI_MAX_WINDOW_BITS: 24, BROTLI_LARGE_MAX_WINDOW_BITS: 30,
1388
+ BROTLI_DEFAULT_WINDOW: 22, BROTLI_PARAM_LGBLOCK: 3,
1389
+ BROTLI_MIN_INPUT_BLOCK_BITS: 16, BROTLI_MAX_INPUT_BLOCK_BITS: 24,
1390
+ BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING: 4,
1391
+ BROTLI_PARAM_SIZE_HINT: 5, BROTLI_PARAM_LARGE_WINDOW: 6,
1392
+ BROTLI_PARAM_NPOSTFIX: 7, BROTLI_PARAM_NDIRECT: 8,
1393
+ BROTLI_DECODER_RESULT_ERROR: 0, BROTLI_DECODER_RESULT_SUCCESS: 1,
1394
+ BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT: 2,
1395
+ BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT: 3,
1396
+ BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION: 0,
1397
+ BROTLI_DECODER_PARAM_LARGE_WINDOW: 1,
1398
+ BROTLI_DECODER_NO_ERROR: 0, BROTLI_DECODER_SUCCESS: 1,
1399
+ BROTLI_DECODER_NEEDS_MORE_INPUT: 2,
1400
+ BROTLI_DECODER_NEEDS_MORE_OUTPUT: 3,
1401
+ },
1402
+ };
1403
+ }
1404
+ if (name === 'uv' || name === 'http_parser') {
1405
+ return {};
1406
+ }
1407
+ throw new Error(`No such module: ${name}`);
1408
+ }
1409
+
1410
+ /**
1411
+ * IPC channel (not available in Ibex runtime).
1412
+ */
1413
+ get channel(): undefined {
1414
+ return undefined;
1415
+ }
1416
+
1417
+ execve(execPath: string, args: string[], envObj?: Record<string, string>): void {
1418
+ validateExecveArguments(execPath, args, envObj, arguments.length >= 3);
1419
+
1420
+ if (isChildProcessPermissionDenied(this.execArgv)) {
1421
+ const err = new Error('Access to this API has been restricted') as Error & {
1422
+ code: string;
1423
+ permission: string;
1424
+ resource: string;
1425
+ };
1426
+ err.code = 'ERR_ACCESS_DENIED';
1427
+ err.permission = 'ChildProcess';
1428
+ err.resource = execPath;
1429
+ throw err;
1430
+ }
1431
+
1432
+ const requireFn = (globalThis as any).require;
1433
+ if (typeof requireFn !== 'function') {
1434
+ const err = new TypeError('process.execve is not supported in this runtime') as TypeError & { code: string };
1435
+ err.code = 'ERR_FEATURE_UNAVAILABLE_ON_PLATFORM';
1436
+ throw err;
1437
+ }
1438
+
1439
+ const childProcess = requireFn('child_process');
1440
+ if (!childProcess || typeof childProcess.spawnSync !== 'function') {
1441
+ const err = new TypeError('process.execve is not supported in this runtime') as TypeError & { code: string };
1442
+ err.code = 'ERR_FEATURE_UNAVAILABLE_ON_PLATFORM';
1443
+ throw err;
1444
+ }
1445
+
1446
+ const result = childProcess.spawnSync(execPath, args.slice(1), {
1447
+ env: envObj ?? { ...this.env },
1448
+ stdio: 'inherit',
1449
+ });
1450
+
1451
+ if (result?.error) {
1452
+ throw result.error;
1453
+ }
1454
+
1455
+ this.exit(typeof result?.status === 'number' ? result.status : 0);
1456
+ }
1457
+
1458
+ /**
1459
+ * Exit code for the process.
1460
+ * Node.js accepts number, string-convertible-to-number, null (resets to undefined), or undefined.
1461
+ */
1462
+ private _exitCode: number | undefined = undefined;
1463
+ private _uid = readNativeProcessId(_nativeGetuid, 0);
1464
+ private _gid = readNativeProcessId(_nativeGetgid, 0);
1465
+ private _euid = readNativeProcessId(_nativeGeteuid, this._uid);
1466
+ private _egid = readNativeProcessId(_nativeGetegid, this._gid);
1467
+
1468
+ get exitCode(): number | undefined {
1469
+ return this._exitCode;
1470
+ }
1471
+
1472
+ set exitCode(value: number | undefined) {
1473
+ if (value === null || value === undefined) {
1474
+ this._exitCode = undefined;
1475
+ return;
1476
+ }
1477
+ if (typeof value === 'string') {
1478
+ if (value.length === 0) {
1479
+ const e: any = new TypeError(`The "code" argument must be of type number. Received type string ('')`);
1480
+ e.code = 'ERR_INVALID_ARG_TYPE';
1481
+ throw e;
1482
+ }
1483
+ const num = Number(value);
1484
+ if (Number.isNaN(num) || !Number.isInteger(num) || !Number.isFinite(num)) {
1485
+ const e: any = new TypeError(`The "code" argument must be of type number. Received type string ('${value}')`);
1486
+ e.code = 'ERR_INVALID_ARG_TYPE';
1487
+ throw e;
1488
+ }
1489
+ this._exitCode = num;
1490
+ return;
1491
+ }
1492
+ if (typeof value === 'bigint') {
1493
+ const e: any = new TypeError(`The "code" argument must be of type number. Received type bigint (${value}n)`);
1494
+ e.code = 'ERR_INVALID_ARG_TYPE';
1495
+ throw e;
1496
+ }
1497
+ if (typeof value !== 'number') {
1498
+ const e: any = new TypeError(`The "code" argument must be of type number. Received type ${typeof value}`);
1499
+ e.code = 'ERR_INVALID_ARG_TYPE';
1500
+ throw e;
1501
+ }
1502
+ if (!Number.isInteger(value) || !Number.isFinite(value)) {
1503
+ const e: any = new RangeError(`The value of "code" is out of range. It must be an integer. Received ${value}`);
1504
+ e.code = 'ERR_OUT_OF_RANGE';
1505
+ throw e;
1506
+ }
1507
+ this._exitCode = value;
1508
+ }
1509
+
1510
+ /**
1511
+ * Whether deprecation warnings should be suppressed.
1512
+ */
1513
+ noDeprecation = false;
1514
+
1515
+ /**
1516
+ * Whether to throw on deprecation warnings instead of logging.
1517
+ */
1518
+ throwDeprecation = false;
1519
+
1520
+ /**
1521
+ * Whether to show stack traces for deprecation warnings.
1522
+ */
1523
+ traceDeprecation = false;
1524
+
1525
+ /**
1526
+ * Whether the process is currently exiting.
1527
+ */
1528
+ _exactExiting = false;
1529
+
1530
+ /**
1531
+ * Get the user ID of the process.
1532
+ */
1533
+ getuid(): number {
1534
+ return this._uid;
1535
+ }
1536
+
1537
+ /**
1538
+ * Get the group ID of the process.
1539
+ */
1540
+ getgid(): number {
1541
+ return this._gid;
1542
+ }
1543
+
1544
+ /**
1545
+ * Get the effective user ID of the process.
1546
+ */
1547
+ geteuid(): number {
1548
+ return this._euid;
1549
+ }
1550
+
1551
+ /**
1552
+ * Get the effective group ID of the process.
1553
+ */
1554
+ getegid(): number {
1555
+ return this._egid;
1556
+ }
1557
+
1558
+ /**
1559
+ * Set the user ID (throws - not supported).
1560
+ */
1561
+ setuid(id: number | string): void {
1562
+ const resolved = resolveCredentialId(id, 'user');
1563
+ if (this._uid !== 0 && this._euid !== 0) {
1564
+ throw makeCredentialPermissionError();
1565
+ }
1566
+ this._uid = resolved;
1567
+ this._euid = resolved;
1568
+ }
1569
+
1570
+ /**
1571
+ * Set the group ID (throws - not supported).
1572
+ */
1573
+ setgid(id: number | string): void {
1574
+ const resolved = resolveCredentialId(id, 'group');
1575
+ if (this._uid !== 0 && this._euid !== 0) {
1576
+ throw makeCredentialPermissionError();
1577
+ }
1578
+ this._gid = resolved;
1579
+ this._egid = resolved;
1580
+ }
1581
+
1582
+ /**
1583
+ * Set the effective user ID (throws - not supported).
1584
+ */
1585
+ seteuid(id: number | string): void {
1586
+ const resolved = resolveCredentialId(id, 'user');
1587
+ if (this._uid !== 0 && this._euid !== 0) {
1588
+ throw makeCredentialPermissionError();
1589
+ }
1590
+ this._euid = resolved;
1591
+ }
1592
+
1593
+ /**
1594
+ * Set the effective group ID (throws - not supported).
1595
+ */
1596
+ setegid(id: number | string): void {
1597
+ const resolved = resolveCredentialId(id, 'group');
1598
+ if (this._uid !== 0 && this._euid !== 0) {
1599
+ throw makeCredentialPermissionError();
1600
+ }
1601
+ this._egid = resolved;
1602
+ }
1603
+
1604
+ /**
1605
+ * Get supplementary group IDs.
1606
+ */
1607
+ getgroups(): number[] {
1608
+ return [this._gid];
1609
+ }
1610
+
1611
+ /**
1612
+ * Send a signal to a process.
1613
+ * Validates signal names/numbers per Node.js behavior.
1614
+ */
1615
+ kill(pid: number | string, signal?: string | number): true {
1616
+ const normalizedPid = normalizeProcessId(pid);
1617
+ const normalizedSignal = normalizeSignal(signal);
1618
+ (this._kill as (pid: number, signalNumber: number) => true).call(this, normalizedPid, normalizedSignal);
1619
+ return true;
1620
+ }
1621
+
1622
+ _kill(pid: number, signalNumber: number): true {
1623
+ if (_nativeProcessKill) {
1624
+ try {
1625
+ _nativeProcessKill(pid, signalNumber);
1626
+ return true;
1627
+ } catch {
1628
+ // Fall through to manual handling if native kill fails (e.g. sandbox)
1629
+ }
1630
+ }
1631
+ // Signal 0 is an existence check — always succeeds for our own pid
1632
+ if (pid === this.pid) {
1633
+ return true;
1634
+ }
1635
+ const e: any = new Error('kill ESRCH');
1636
+ e.code = 'ESRCH';
1637
+ e.errno = -3;
1638
+ e.syscall = 'kill';
1639
+ throw e;
1640
+ }
1641
+
1642
+ /**
1643
+ * Returns the current working directory.
1644
+ * In mobile context, this is the app's documents directory.
1645
+ */
1646
+ cwd(): string {
1647
+ if (_processCwd && _processCwd !== '/') {
1648
+ return _processCwd;
1649
+ }
1650
+ const nativeCwd = _readNativeCwd();
1651
+ if (nativeCwd) {
1652
+ _processCwd = nativeCwd;
1653
+ return _processCwd;
1654
+ }
1655
+ if (!_processCwd || _processCwd === '/') {
1656
+ _processCwd = '/';
1657
+ }
1658
+ return _processCwd;
1659
+ }
1660
+
1661
+ /**
1662
+ * Change working directory.
1663
+ */
1664
+ chdir(_directory: string): void {
1665
+ if (typeof _directory !== 'string') {
1666
+ const err = new TypeError(`The "directory" argument must be of type string. Received type ${typeof _directory}`);
1667
+ err.code = 'ERR_INVALID_ARG_TYPE';
1668
+ throw err;
1669
+ }
1670
+
1671
+ const resolvedPath = _resolveCwd(_directory);
1672
+ if (typeof __exactSetCwd !== 'function') {
1673
+ if (typeof (globalThis as any).__exactAccess === 'function') {
1674
+ try {
1675
+ (globalThis as any).__exactAccess(resolvedPath, 0);
1676
+ } catch (e) {
1677
+ throw _coerceChdirError(e, _directory);
1678
+ }
1679
+ }
1680
+ _processCwd = resolvedPath;
1681
+ return;
1682
+ }
1683
+
1684
+ try {
1685
+ __exactSetCwd(resolvedPath);
1686
+ _processCwd = resolvedPath;
1687
+ } catch (e) {
1688
+ throw _coerceChdirError(e, _directory);
1689
+ }
1690
+ }
1691
+
1692
+ /**
1693
+ * Exit the process.
1694
+ * Sets exitCode first, fires exit handlers, then terminates if native exit is available.
1695
+ */
1696
+ exit(code?: number): void {
1697
+ const requestedExitCode = code ?? this.exitCode ?? 0;
1698
+ this.exitCode = requestedExitCode;
1699
+
1700
+ if (this._exactExiting) {
1701
+ return;
1702
+ }
1703
+
1704
+ this._exactExiting = true;
1705
+ try {
1706
+ const listeners = [...(this._events.get('exit') || [])];
1707
+ for (const entry of listeners) {
1708
+ try {
1709
+ entry.fn(requestedExitCode);
1710
+ } catch (_e) {
1711
+ /* ignore */
1712
+ }
1713
+ }
1714
+ } catch (_e) {
1715
+ /* ignore */
1716
+ } finally {
1717
+ if (typeof this._events.clear === 'function') {
1718
+ this._events.clear();
1719
+ }
1720
+ }
1721
+ // Try native exit if available, but never throw from runtime-side.
1722
+ const finalExitCode = this.exitCode ?? 0;
1723
+ const g = globalThis as any;
1724
+ if (typeof g.__exactExit === 'function') {
1725
+ try {
1726
+ g.__exactExit(finalExitCode);
1727
+ } catch (_e) {
1728
+ /* ignore */
1729
+ }
1730
+ }
1731
+ }
1732
+
1733
+ /**
1734
+ * Abort the process.
1735
+ */
1736
+ abort(): never {
1737
+ throw new Error('process.abort() is not supported in Ibex runtime');
1738
+ }
1739
+
1740
+ /**
1741
+ * Schedule a callback to run on the next tick of the event loop.
1742
+ * This runs before any I/O events but after the current operation.
1743
+ */
1744
+ nextTick(callback: (...args: any[]) => void, ...args: any[]): void {
1745
+ if (_nativeProcessNextTick) {
1746
+ _nativeProcessNextTick(callback, ...args);
1747
+ return;
1748
+ }
1749
+ if (_nativeGlobalNextTick) {
1750
+ _nativeGlobalNextTick(callback, ...args);
1751
+ return;
1752
+ }
1753
+ _nextTickQueue.push({ callback, args });
1754
+ _scheduleNextTickDrain();
1755
+ }
1756
+
1757
+ /**
1758
+ * High-resolution time.
1759
+ * Returns [seconds, nanoseconds] tuple.
1760
+ * Also has hrtime.bigint() when the engine supports BigInt.
1761
+ */
1762
+ hrtime: HrtimeFunction = (() => {
1763
+ const hrtime = (time?: [number, number]): [number, number] => {
1764
+ if (time !== undefined) {
1765
+ if (!Array.isArray(time)) {
1766
+ const e: any = new TypeError(`The "time" argument must be an instance of Array. Received type ${typeof time} (${String(time)})`);
1767
+ e.code = 'ERR_INVALID_ARG_TYPE';
1768
+ throw e;
1769
+ }
1770
+ if (time.length !== 2) {
1771
+ const e: any = new RangeError(`The value of "time" is out of range. It must be 2. Received ${time.length}`);
1772
+ e.code = 'ERR_OUT_OF_RANGE';
1773
+ throw e;
1774
+ }
1775
+ }
1776
+ const [seconds, nanoseconds] = _monotonicHrtimeTuple();
1777
+
1778
+ if (time) {
1779
+ let diffSeconds = seconds - time[0];
1780
+ let diffNanos = nanoseconds - time[1];
1781
+ if (diffNanos < 0) {
1782
+ diffSeconds -= 1;
1783
+ diffNanos += 1e9;
1784
+ }
1785
+ return [diffSeconds, diffNanos];
1786
+ }
1787
+
1788
+ return [seconds, nanoseconds];
1789
+ };
1790
+
1791
+ if (_nativeBigInt) {
1792
+ hrtime.bigint = (): bigint =>
1793
+ _nativeProcessHrtimeBigint ? _nativeProcessHrtimeBigint() : _monotonicTimeNs();
1794
+ }
1795
+
1796
+ return hrtime;
1797
+ })();
1798
+
1799
+ /**
1800
+ * Memory usage (approximate, not accurate on mobile).
1801
+ */
1802
+ memoryUsage(): { rss: number; heapTotal: number; heapUsed: number; external: number; arrayBuffers: number } {
1803
+ const exactGlobal = globalThis as any;
1804
+ const nativeHeapInfo =
1805
+ typeof exactGlobal.__exactGetHeapInfo === 'function'
1806
+ ? exactGlobal.__exactGetHeapInfo(false)
1807
+ : null;
1808
+ if (nativeHeapInfo && typeof nativeHeapInfo === 'object') {
1809
+ const heapTotal =
1810
+ typeof nativeHeapInfo.hermes_heapSize === 'number'
1811
+ ? nativeHeapInfo.hermes_heapSize
1812
+ : typeof nativeHeapInfo.heapSize === 'number'
1813
+ ? nativeHeapInfo.heapSize
1814
+ : 0;
1815
+ const heapUsed =
1816
+ typeof nativeHeapInfo.hermes_allocatedBytes === 'number'
1817
+ ? nativeHeapInfo.hermes_allocatedBytes
1818
+ : typeof nativeHeapInfo.allocatedBytes === 'number'
1819
+ ? nativeHeapInfo.allocatedBytes
1820
+ : 0;
1821
+ const external =
1822
+ typeof nativeHeapInfo.hermes_externalBytes === 'number'
1823
+ ? nativeHeapInfo.hermes_externalBytes
1824
+ : typeof nativeHeapInfo.externalBytes === 'number'
1825
+ ? nativeHeapInfo.externalBytes
1826
+ : 0;
1827
+ const arrayBuffers =
1828
+ typeof nativeHeapInfo.hermes_arrayBufferBytes === 'number'
1829
+ ? nativeHeapInfo.hermes_arrayBufferBytes
1830
+ : typeof nativeHeapInfo.arrayBufferBytes === 'number'
1831
+ ? nativeHeapInfo.arrayBufferBytes
1832
+ : 0;
1833
+ const nativeRss =
1834
+ typeof exactGlobal.__exactGetProcessRSS === 'function'
1835
+ ? exactGlobal.__exactGetProcessRSS()
1836
+ : null;
1837
+ const rss =
1838
+ typeof nativeRss === 'number' && nativeRss > 0
1839
+ ? nativeRss
1840
+ : Math.max(heapTotal, heapUsed + external, 1024 * 1024);
1841
+
1842
+ return {
1843
+ rss,
1844
+ heapTotal,
1845
+ heapUsed,
1846
+ external,
1847
+ arrayBuffers,
1848
+ };
1849
+ }
1850
+
1851
+ const perfMemory = (globalThis as any).performance?.memory;
1852
+ const heapTotal = typeof perfMemory?.totalJSHeapSize === 'number' ? perfMemory.totalJSHeapSize : 0;
1853
+ const heapUsed = typeof perfMemory?.usedJSHeapSize === 'number' ? perfMemory.usedJSHeapSize : 0;
1854
+ const arrayBuffers = typeof perfMemory?.arrayBuffers === 'number' ? perfMemory.arrayBuffers : 0;
1855
+ const rss = typeof perfMemory?.jsHeapSizeLimit === 'number'
1856
+ ? Math.max(perfMemory.jsHeapSizeLimit, heapTotal, heapUsed)
1857
+ : Math.max(heapTotal, heapUsed, 1024 * 1024);
1858
+
1859
+ return {
1860
+ rss,
1861
+ heapTotal,
1862
+ heapUsed,
1863
+ external: 0,
1864
+ arrayBuffers,
1865
+ };
1866
+ }
1867
+
1868
+ /**
1869
+ * CPU usage (not available on mobile, returns zeros).
1870
+ */
1871
+ cpuUsage(prevValue?: { user: number; system: number }): { user: number; system: number } {
1872
+ if (prevValue !== undefined) {
1873
+ if (typeof prevValue !== 'object' || prevValue === null || Array.isArray(prevValue)) {
1874
+ const e: any = new TypeError(`The "prevValue" argument must be of type object. Received type ${typeof prevValue} (${String(prevValue)})`);
1875
+ e.code = 'ERR_INVALID_ARG_TYPE';
1876
+ throw e;
1877
+ }
1878
+ if (typeof prevValue.user !== 'number') {
1879
+ const v = prevValue.user;
1880
+ const received = v == null ? ` Received ${v}` : typeof v === 'function' ? ` Received function ${(v as any).name}` : typeof v === 'object' ? (v.constructor && v.constructor.name ? ` Received an instance of ${v.constructor.name}` : ` Received ${String(v)}`) : ` Received type ${typeof v} (${String(v)})`;
1881
+ const e: any = new TypeError(`The "prevValue.user" property must be of type number.${received}`);
1882
+ e.code = 'ERR_INVALID_ARG_TYPE';
1883
+ throw e;
1884
+ }
1885
+ if (typeof prevValue.system !== 'number') {
1886
+ const v = prevValue.system;
1887
+ const received = v == null ? ` Received ${v}` : typeof v === 'function' ? ` Received function ${(v as any).name}` : typeof v === 'object' ? (v.constructor && v.constructor.name ? ` Received an instance of ${v.constructor.name}` : ` Received ${String(v)}`) : ` Received type ${typeof v} (${String(v)})`;
1888
+ const e: any = new TypeError(`The "prevValue.system" property must be of type number.${received}`);
1889
+ e.code = 'ERR_INVALID_ARG_TYPE';
1890
+ throw e;
1891
+ }
1892
+ if (prevValue.user < 0 || !Number.isFinite(prevValue.user)) {
1893
+ const e: any = new RangeError(`The property 'prevValue.user' is invalid. Received ${prevValue.user}`);
1894
+ e.code = 'ERR_INVALID_ARG_VALUE';
1895
+ throw e;
1896
+ }
1897
+ if (prevValue.system < 0 || !Number.isFinite(prevValue.system)) {
1898
+ const e: any = new RangeError(`The property 'prevValue.system' is invalid. Received ${prevValue.system}`);
1899
+ e.code = 'ERR_INVALID_ARG_VALUE';
1900
+ throw e;
1901
+ }
1902
+ }
1903
+ return { user: 0, system: 0 };
1904
+ }
1905
+
1906
+ /**
1907
+ * Emit a warning (async like Node.js).
1908
+ */
1909
+ emitWarning(warning: string | Error, type?: string | { type?: string; code?: string; detail?: string; ctor?: Function }, code?: string | Function, ctor?: Function): void {
1910
+ let detail: string | undefined;
1911
+ if (typeof type === 'object' && type !== null && !Array.isArray(type)) {
1912
+ code = type.code;
1913
+ ctor = type.ctor;
1914
+ detail = type.detail;
1915
+ type = type.type || 'Warning';
1916
+ }
1917
+ if (typeof code === 'function') { ctor = code; code = undefined; }
1918
+ if (typeof type === 'function') { ctor = type as unknown as Function; type = 'Warning'; code = undefined; }
1919
+ // Validate
1920
+ if (warning === undefined || (typeof warning !== 'string' && !(warning instanceof Error))) {
1921
+ const e: any = new TypeError(`The "warning" argument must be of type string or an instance of Error. Received ${warning === undefined ? 'undefined' : 'type ' + typeof warning}`);
1922
+ e.code = 'ERR_INVALID_ARG_TYPE';
1923
+ throw e;
1924
+ }
1925
+ if (type !== undefined && typeof type !== 'string') {
1926
+ const e: any = new TypeError(`The "type" argument must be of type string. Received type ${typeof type}`);
1927
+ e.code = 'ERR_INVALID_ARG_TYPE';
1928
+ throw e;
1929
+ }
1930
+ if (code !== undefined && typeof code !== 'string') {
1931
+ const e: any = new TypeError(`The "code" argument must be of type string. Received type ${typeof code}`);
1932
+ e.code = 'ERR_INVALID_ARG_TYPE';
1933
+ throw e;
1934
+ }
1935
+ // Suppress deprecation warnings if noDeprecation is set
1936
+ if ((type === 'DeprecationWarning' || (typeof type === 'undefined' && typeof warning === 'string' && warning.startsWith('DEP'))) && this.noDeprecation) {
1937
+ return;
1938
+ }
1939
+ let warningObj: any;
1940
+ if (typeof warning === 'string') {
1941
+ warningObj = new Error(warning);
1942
+ warningObj.name = type || 'Warning';
1943
+ } else {
1944
+ warningObj = warning;
1945
+ }
1946
+ if (code) warningObj.code = code;
1947
+ if (type && warningObj.name !== type) warningObj.name = type;
1948
+ if (typeof detail === 'string') warningObj.detail = detail;
1949
+ // Node.js emits warnings asynchronously via nextTick
1950
+ this.nextTick(() => { this.emit('warning', warningObj); });
1951
+ }
1952
+
1953
+ /**
1954
+ * Process features flags.
1955
+ * Matches Node.js process.features structure.
1956
+ */
1957
+ features = {
1958
+ inspector: false,
1959
+ debug: false,
1960
+ uv: true,
1961
+ ipv6: true,
1962
+ tls_alpn: false,
1963
+ tls_sni: false,
1964
+ tls_ocsp: false,
1965
+ tls: false,
1966
+ cached_builtins: true,
1967
+ // Node.js 21+ moved to a nested structure
1968
+ typescript: false,
1969
+ require_module: false,
1970
+ };
1971
+
1972
+ debugPort = 9229;
1973
+
1974
+ getActiveResourcesInfo(): string[] { return []; }
1975
+ _getActiveRequests(): any[] { return []; }
1976
+ _getActiveHandles(): any[] { return []; }
1977
+
1978
+ resourceUsage(): Record<string, number> {
1979
+ return {
1980
+ userCPUTime: 0, systemCPUTime: 0, maxRSS: 0,
1981
+ sharedMemorySize: 0, unsharedDataSize: 0, unsharedStackSize: 0,
1982
+ minorPageFault: 0, majorPageFault: 0, swappedOut: 0,
1983
+ fsRead: 0, fsWrite: 0, ipcSent: 0, ipcReceived: 0,
1984
+ signalsCount: 0, voluntaryContextSwitches: 0, involuntaryContextSwitches: 0,
1985
+ };
1986
+ }
1987
+
1988
+ _umask = 0o022;
1989
+ umask = (mask?: number | string): number => {
1990
+ if (mask === undefined) {
1991
+ return this._umask;
1992
+ }
1993
+ const old = this._umask;
1994
+ if (typeof mask !== 'string' && typeof mask !== 'number') {
1995
+ const v = mask as any;
1996
+ const received = v == null ? ` Received ${v}` : typeof v === 'function' ? ` Received function ${v.name}` : typeof v === 'object' ? (v.constructor && v.constructor.name ? ` Received an instance of ${v.constructor.name}` : ` Received ${String(v)}`) : ` Received type ${typeof v} (${String(v)})`;
1997
+ const e: any = new TypeError(`The "mask" argument must be one of type string or number.${received}`);
1998
+ e.code = 'ERR_INVALID_ARG_TYPE';
1999
+ throw e;
2000
+ }
2001
+ if (typeof mask === 'string') {
2002
+ if (!/^(0o?)?[0-7]+$/.test(mask)) {
2003
+ const e: any = new RangeError(`The property 'mask' is invalid. Received '${mask}'`);
2004
+ e.code = 'ERR_INVALID_ARG_VALUE';
2005
+ throw e;
2006
+ }
2007
+ // Strip "0o" or "0" prefix before parsing as octal
2008
+ const stripped = mask.replace(/^0o/i, '').replace(/^0+(?=\d)/, '');
2009
+ mask = parseInt(stripped || '0', 8);
2010
+ }
2011
+ if (typeof mask === 'number' && mask === (mask | 0)) this._umask = mask & 0o777;
2012
+ return old;
2013
+ };
2014
+
2015
+ private _uncaughtCaptureCb: ((err: Error) => void) | null = null;
2016
+ setUncaughtExceptionCaptureCallback(fn: ((err: Error) => void) | null): void {
2017
+ if (fn !== null && typeof fn !== 'function') {
2018
+ const e: any = new TypeError('The "fn" argument must be of type function or null. Received type ' + typeof fn + ' (' + String(fn) + ')');
2019
+ e.code = 'ERR_INVALID_ARG_TYPE';
2020
+ throw e;
2021
+ }
2022
+ if (fn !== null && this._uncaughtCaptureCb !== null) {
2023
+ const e: any = new Error('process.setupUncaughtExceptionCapture() was called while a capture callback was already active');
2024
+ e.code = 'ERR_UNCAUGHT_EXCEPTION_CAPTURE_ALREADY_SET';
2025
+ throw e;
2026
+ }
2027
+ this._uncaughtCaptureCb = fn;
2028
+ }
2029
+
2030
+ hasUncaughtExceptionCaptureCallback(): boolean {
2031
+ return this._uncaughtCaptureCb !== null;
2032
+ }
2033
+
2034
+ report = {
2035
+ writeReport: () => '',
2036
+ getReport: () => ({}),
2037
+ directory: '',
2038
+ filename: '',
2039
+ compact: false,
2040
+ signal: 'SIGUSR2',
2041
+ reportOnFatalError: false,
2042
+ reportOnSignal: false,
2043
+ reportOnUncaughtException: false,
2044
+ };
2045
+
2046
+ allowedNodeEnvironmentFlags: Set<string> = createAllowedNodeEnvironmentFlags();
2047
+
2048
+ /**
2049
+ * Uptime in seconds.
2050
+ */
2051
+ uptime(): number {
2052
+ const timeOrigin = performance?.timeOrigin ?? Date.now();
2053
+ return (Date.now() - timeOrigin) / 1000;
2054
+ }
2055
+
2056
+ /**
2057
+ * Standard streams (minimal implementation with EventEmitter support).
2058
+ */
2059
+ private _stdin: any;
2060
+ private _stdout: any;
2061
+ private _stderr: any;
2062
+
2063
+ get stdin() {
2064
+ if (!this._stdin) {
2065
+ this._stdin = _makeProcessStream(0, false);
2066
+ }
2067
+ return this._stdin;
2068
+ }
2069
+
2070
+ get stdout() {
2071
+ if (!this._stdout) {
2072
+ this._stdout = _makeProcessStream(1, false, (data: string) => {
2073
+ // Use native write to avoid circular console.log -> stdout.write -> console.log loop
2074
+ const g = globalThis as any;
2075
+ // Ensure fs host functions are loaded (they're registered lazily)
2076
+ if (typeof g.__exactFsWrite !== 'function' && typeof g.__exactEnsureFs === 'function') {
2077
+ g.__exactEnsureFs();
2078
+ }
2079
+ if (typeof g.__exactFsWrite === 'function') {
2080
+ g.__exactFsWrite(1, data, -1);
2081
+ return true;
2082
+ }
2083
+ // Fallback to console.log only if native write is unavailable
2084
+ console.log(data);
2085
+ return true;
2086
+ });
2087
+ }
2088
+ return this._stdout;
2089
+ }
2090
+
2091
+ get stderr() {
2092
+ if (!this._stderr) {
2093
+ this._stderr = _makeProcessStream(2, false, (data: string) => {
2094
+ // Use native write to avoid circular console.error -> stderr.write -> console.error loop
2095
+ const g = globalThis as any;
2096
+ // Ensure fs host functions are loaded (they're registered lazily)
2097
+ if (typeof g.__exactFsWrite !== 'function' && typeof g.__exactEnsureFs === 'function') {
2098
+ g.__exactEnsureFs();
2099
+ }
2100
+ if (typeof g.__exactFsWrite === 'function') {
2101
+ g.__exactFsWrite(2, data, -1);
2102
+ return true;
2103
+ }
2104
+ // Fallback to console.error only if native write is unavailable
2105
+ console.error(data);
2106
+ return true;
2107
+ });
2108
+ }
2109
+ return this._stderr;
2110
+ }
2111
+
2112
+ /**
2113
+ * Execution arguments (empty in mobile context).
2114
+ */
2115
+ get argv(): string[] {
2116
+ return getRuntimeArgv();
2117
+ }
2118
+
2119
+ /**
2120
+ * Execution arguments including node path.
2121
+ */
2122
+ get argv0(): string {
2123
+ return getRuntimeArgv0();
2124
+ }
2125
+
2126
+ /**
2127
+ * Executable path.
2128
+ */
2129
+ get execPath(): string {
2130
+ return (typeof globalThis !== 'undefined' && (globalThis as any).__exactExecPath) || '/usr/bin/ibex';
2131
+ }
2132
+
2133
+ set execPath(path: string) {
2134
+ if (typeof path === 'string') {
2135
+ if (typeof globalThis !== 'undefined') {
2136
+ (globalThis as any).__exactExecPath = path;
2137
+ }
2138
+ }
2139
+ }
2140
+
2141
+ /**
2142
+ * Node-specific execution arguments (empty).
2143
+ */
2144
+ get execArgv(): string[] {
2145
+ if (typeof globalThis !== 'undefined' && Array.isArray((globalThis as any).__exactExecArgv)) {
2146
+ return (globalThis as any).__exactExecArgv;
2147
+ }
2148
+ return [];
2149
+ }
2150
+
2151
+ /**
2152
+ * Whether running in browser (always false).
2153
+ */
2154
+ get browser(): boolean {
2155
+ return false;
2156
+ }
2157
+
2158
+ // Real event emitter storage
2159
+ private _events: Map<string, Array<{ fn: (...args: any[]) => void; once: boolean }>> = new Map();
2160
+
2161
+ on(event: string, listener: (...args: any[]) => void): this {
2162
+ const listeners = this._events.get(event) || [];
2163
+ listeners.push({ fn: listener, once: false });
2164
+ this._events.set(event, listeners);
2165
+ if (event === 'uncaughtException') {
2166
+ this._hookUncaughtException();
2167
+ }
2168
+ if (event === 'unhandledRejection') {
2169
+ this._hookUnhandledRejection();
2170
+ }
2171
+ return this;
2172
+ }
2173
+
2174
+ off(event: string, listener: (...args: any[]) => void): this {
2175
+ return this.removeListener(event, listener);
2176
+ }
2177
+
2178
+ addListener(event: string, listener: (...args: any[]) => void): this {
2179
+ return this.on(event, listener);
2180
+ }
2181
+
2182
+ once(event: string, listener: (...args: any[]) => void): this {
2183
+ const listeners = this._events.get(event) || [];
2184
+ listeners.push({ fn: listener, once: true });
2185
+ this._events.set(event, listeners);
2186
+ if (event === 'uncaughtException') {
2187
+ this._hookUncaughtException();
2188
+ }
2189
+ if (event === 'unhandledRejection') {
2190
+ this._hookUnhandledRejection();
2191
+ }
2192
+ return this;
2193
+ }
2194
+
2195
+ prependListener(event: string, listener: (...args: any[]) => void): this {
2196
+ const listeners = this._events.get(event) || [];
2197
+ listeners.unshift({ fn: listener, once: false });
2198
+ this._events.set(event, listeners);
2199
+ return this;
2200
+ }
2201
+
2202
+ prependOnceListener(event: string, listener: (...args: any[]) => void): this {
2203
+ const listeners = this._events.get(event) || [];
2204
+ listeners.unshift({ fn: listener, once: true });
2205
+ this._events.set(event, listeners);
2206
+ return this;
2207
+ }
2208
+
2209
+ emit(event: string, ...args: any[]): boolean {
2210
+ const listeners = this._events.get(event);
2211
+ if (!listeners || listeners.length === 0) return false;
2212
+ const remaining: Array<{ fn: (...args: any[]) => void; once: boolean }> = [];
2213
+ for (const entry of listeners) {
2214
+ entry.fn(...args);
2215
+ if (!entry.once) remaining.push(entry);
2216
+ }
2217
+ this._events.set(event, remaining);
2218
+ return true;
2219
+ }
2220
+
2221
+ removeListener(event: string, listener: (...args: any[]) => void): this {
2222
+ const listeners = this._events.get(event);
2223
+ if (listeners) {
2224
+ this._events.set(event, listeners.filter(e => e.fn !== listener));
2225
+ }
2226
+ return this;
2227
+ }
2228
+
2229
+ removeAllListeners(event?: string): this {
2230
+ if (event) {
2231
+ this._events.delete(event);
2232
+ } else {
2233
+ this._events.clear();
2234
+ }
2235
+ return this;
2236
+ }
2237
+
2238
+ listeners(event: string): Array<(...args: any[]) => void> {
2239
+ return (this._events.get(event) || []).map(e => e.fn);
2240
+ }
2241
+
2242
+ rawListeners(event: string): Array<(...args: any[]) => void> {
2243
+ return this.listeners(event);
2244
+ }
2245
+
2246
+ listenerCount(event: string): number {
2247
+ return (this._events.get(event) || []).length;
2248
+ }
2249
+
2250
+ eventNames(): string[] {
2251
+ return Array.from(this._events.keys()).filter((event) => this.listenerCount(event) > 0);
2252
+ }
2253
+
2254
+ setMaxListeners(count: number): this {
2255
+ this._maxListeners = count;
2256
+ return this;
2257
+ }
2258
+
2259
+ getMaxListeners(): number {
2260
+ return this._maxListeners;
2261
+ }
2262
+
2263
+ private _uncaughtExceptionHooked = false;
2264
+ private _hookUncaughtException(): void {
2265
+ if (this._uncaughtExceptionHooked) return;
2266
+ this._uncaughtExceptionHooked = true;
2267
+ const g = globalThis as any;
2268
+ const self = this;
2269
+ const prev = g.onerror;
2270
+ g.onerror = function(msg: any, _src: any, _line: any, _col: any, err: any) {
2271
+ const error = err instanceof Error ? err : new Error(String(msg));
2272
+ if (self.listenerCount('uncaughtException') > 0) {
2273
+ self.emit('uncaughtException', error);
2274
+ return true; // suppress default
2275
+ }
2276
+ if (typeof prev === 'function') return prev(msg, _src, _line, _col, err);
2277
+ return false;
2278
+ };
2279
+ }
2280
+
2281
+ private _unhandledRejectionHooked = false;
2282
+ private _hookUnhandledRejection(): void {
2283
+ if (this._unhandledRejectionHooked) return;
2284
+ this._unhandledRejectionHooked = true;
2285
+ const g = globalThis as any;
2286
+ const self = this;
2287
+ const addFn = g.addEventListener;
2288
+ if (typeof addFn === 'function') {
2289
+ addFn.call(g, 'unhandledrejection', (event: any) => {
2290
+ if (self.listenerCount('unhandledRejection') > 0) {
2291
+ self.emit('unhandledRejection', event.reason, event.promise);
2292
+ event.preventDefault?.();
2293
+ }
2294
+ });
2295
+ }
2296
+ }
2297
+
2298
+ get [Symbol.toStringTag](): string {
2299
+ return 'process';
2300
+ }
2301
+ }
2302
+
2303
+ // Singleton process instance
2304
+ _installTimeZoneAwareDateToString();
2305
+ export const process = new Process();
2306
+ const exitCodeDescriptor = Object.getOwnPropertyDescriptor(Process.prototype, 'exitCode');
2307
+ if (exitCodeDescriptor?.get && exitCodeDescriptor?.set) {
2308
+ Object.defineProperty(process, 'exitCode', {
2309
+ get: exitCodeDescriptor.get.bind(process),
2310
+ set: exitCodeDescriptor.set.bind(process),
2311
+ enumerable: true,
2312
+ configurable: false,
2313
+ });
2314
+ }
2315
+
2316
+ export default process;
2317
+ function getRuntimeArgv(): string[] {
2318
+ if (typeof __exactArgv === 'object' && Array.isArray(__exactArgv) && __exactArgv.length > 0) {
2319
+ return __exactArgv;
2320
+ }
2321
+ return ['ibex'];
2322
+ }
2323
+
2324
+ function getRuntimeArgv0(): string {
2325
+ const argv = getRuntimeArgv();
2326
+ return argv[0] ?? 'ibex';
2327
+ }
2328
+
2329
+ function readNativeProcessId(reader: (() => number) | undefined, fallback: number): number {
2330
+ if (typeof reader !== 'function') {
2331
+ return fallback;
2332
+ }
2333
+ try {
2334
+ const value = reader();
2335
+ return typeof value === 'number' && Number.isInteger(value) ? value : fallback;
2336
+ } catch {
2337
+ return fallback;
2338
+ }
2339
+ }
2340
+
2341
+ function formatReceivedValue(value: unknown): string {
2342
+ if (value === null) return 'null';
2343
+ if (value === undefined) return 'undefined';
2344
+ if (typeof value === 'string') return `type string ('${value}')`;
2345
+ if (typeof value === 'bigint') return `type bigint (${value}n)`;
2346
+ if (typeof value === 'function') return `function ${(value as Function).name || '<anonymous>'}`;
2347
+ if (typeof value !== 'object') return `type ${typeof value} (${String(value)})`;
2348
+ const ctorName = (value as { constructor?: { name?: string } }).constructor?.name;
2349
+ return ctorName ? `an instance of ${ctorName}` : String(value);
2350
+ }
2351
+
2352
+ function makeCredentialTypeError(value: unknown): TypeError & { code: string } {
2353
+ const err = new TypeError(
2354
+ `The "id" argument must be one of type number or string. Received ${formatReceivedValue(value)}`,
2355
+ ) as TypeError & { code: string };
2356
+ err.code = 'ERR_INVALID_ARG_TYPE';
2357
+ return err;
2358
+ }
2359
+
2360
+ function makeUnknownCredentialError(kind: 'user' | 'group', value: string): Error & { code: string } {
2361
+ const err = new Error(
2362
+ `${kind === 'user' ? 'User' : 'Group'} identifier does not exist: ${value}`,
2363
+ ) as Error & { code: string };
2364
+ err.code = 'ERR_UNKNOWN_CREDENTIAL';
2365
+ return err;
2366
+ }
2367
+
2368
+ function makeCredentialPermissionError(): Error & { code: string } {
2369
+ const err = new Error('EPERM, Operation not permitted') as Error & { code: string };
2370
+ err.code = 'EPERM';
2371
+ return err;
2372
+ }
2373
+
2374
+ function resolveCredentialId(id: number | string, kind: 'user' | 'group'): number {
2375
+ if (typeof id === 'number') {
2376
+ if (!Number.isFinite(id) || !Number.isInteger(id)) {
2377
+ throw makeCredentialTypeError(id);
2378
+ }
2379
+ return Object.is(id, -0) ? 0 : id;
2380
+ }
2381
+ if (typeof id !== 'string') {
2382
+ throw makeCredentialTypeError(id);
2383
+ }
2384
+ const table = kind === 'user' ? USER_CREDENTIALS : GROUP_CREDENTIALS;
2385
+ if (Object.prototype.hasOwnProperty.call(table, id)) {
2386
+ return table[id];
2387
+ }
2388
+ const numeric = Number(id);
2389
+ if (id.length > 0 && Number.isFinite(numeric) && Number.isInteger(numeric)) {
2390
+ return Object.is(numeric, -0) ? 0 : numeric;
2391
+ }
2392
+ throw makeUnknownCredentialError(kind, id);
2393
+ }
2394
+
2395
+ function makeInvalidPidError(value: unknown): TypeError & { code: string } {
2396
+ const err = new TypeError(
2397
+ `The "pid" argument must be of type number. Received ${formatReceivedValue(value)}`,
2398
+ ) as TypeError & { code: string };
2399
+ err.code = 'ERR_INVALID_ARG_TYPE';
2400
+ return err;
2401
+ }
2402
+
2403
+ function normalizeProcessId(pid: number | string): number {
2404
+ if (typeof pid === 'string') {
2405
+ const numeric = Number(pid);
2406
+ if (!Number.isFinite(numeric) || !Number.isInteger(numeric)) {
2407
+ throw makeInvalidPidError(pid);
2408
+ }
2409
+ return Object.is(numeric, -0) ? 0 : numeric;
2410
+ }
2411
+ if (typeof pid !== 'number' || !Number.isFinite(pid) || !Number.isInteger(pid)) {
2412
+ throw makeInvalidPidError(pid);
2413
+ }
2414
+ return Object.is(pid, -0) ? 0 : pid;
2415
+ }
2416
+
2417
+ function normalizeSignal(signal?: string | number): number {
2418
+ if (signal === undefined) {
2419
+ return SIGNAL_NAME_TO_NUMBER.SIGTERM;
2420
+ }
2421
+ if (typeof signal === 'string') {
2422
+ if (signal === '0') {
2423
+ return 0;
2424
+ }
2425
+ const numeric = SIGNAL_NAME_TO_NUMBER[signal];
2426
+ if (numeric === undefined) {
2427
+ const err = new TypeError(`Unknown signal: ${signal}`) as TypeError & { code: string };
2428
+ err.code = 'ERR_UNKNOWN_SIGNAL';
2429
+ throw err;
2430
+ }
2431
+ return numeric;
2432
+ }
2433
+ if (typeof signal !== 'number' || !Number.isFinite(signal) || !Number.isInteger(signal)) {
2434
+ const err = new Error('kill EINVAL') as Error & { code: string };
2435
+ err.code = 'EINVAL';
2436
+ throw err;
2437
+ }
2438
+ if (signal < 0 || signal > 31) {
2439
+ const err = new Error('kill EINVAL') as Error & { code: string };
2440
+ err.code = 'EINVAL';
2441
+ throw err;
2442
+ }
2443
+ return signal;
2444
+ }
2445
+
2446
+ function inspectExecveValue(value: unknown): string {
2447
+ if (typeof value === 'string') {
2448
+ return `'${value.replace(/\0/g, '\\x00')}'`;
2449
+ }
2450
+ return String(value);
2451
+ }
2452
+
2453
+ function validateExecveArguments(
2454
+ execPath: unknown,
2455
+ args: unknown,
2456
+ envObj: unknown,
2457
+ hasEnvArgument: boolean,
2458
+ ): void {
2459
+ if (typeof execPath !== 'string') {
2460
+ const err = new TypeError(
2461
+ `The "execPath" argument must be of type string. Received type ${typeof execPath} (${String(execPath)})`,
2462
+ ) as TypeError & { code: string };
2463
+ err.code = 'ERR_INVALID_ARG_TYPE';
2464
+ throw err;
2465
+ }
2466
+
2467
+ if (!Array.isArray(args)) {
2468
+ const err = new TypeError(
2469
+ `The "args" argument must be an instance of Array. Received type ${typeof args} (${inspectExecveValue(args)})`,
2470
+ ) as TypeError & { code: string };
2471
+ err.code = 'ERR_INVALID_ARG_TYPE';
2472
+ throw err;
2473
+ }
2474
+
2475
+ for (let index = 0; index < args.length; index++) {
2476
+ const value = args[index];
2477
+ if (typeof value !== 'string' || value.includes('\0')) {
2478
+ const err = new TypeError(
2479
+ `The argument 'args[${index}]' must be a string without null bytes. Received ${inspectExecveValue(value)}`,
2480
+ ) as TypeError & { code: string };
2481
+ err.code = 'ERR_INVALID_ARG_VALUE';
2482
+ throw err;
2483
+ }
2484
+ }
2485
+
2486
+ if (!hasEnvArgument) {
2487
+ return;
2488
+ }
2489
+
2490
+ if (typeof envObj !== 'object' || envObj === null || Array.isArray(envObj)) {
2491
+ const err = new TypeError(
2492
+ `The "env" argument must be of type object. Received type ${typeof envObj} (${inspectExecveValue(envObj)})`,
2493
+ ) as TypeError & { code: string };
2494
+ err.code = 'ERR_INVALID_ARG_TYPE';
2495
+ throw err;
2496
+ }
2497
+
2498
+ const entries = Object.keys(envObj as Record<string, unknown>);
2499
+ for (const key of entries) {
2500
+ const value = (envObj as Record<string, unknown>)[key];
2501
+ if (typeof value !== 'string' || value.includes('\0')) {
2502
+ const pairs = entries.map((entryKey) => `${entryKey}: ${inspectExecveValue((envObj as Record<string, unknown>)[entryKey])}`);
2503
+ const err = new TypeError(
2504
+ `The argument 'env' must be an object with string keys and values without null bytes. Received { ${pairs.join(', ')} }`,
2505
+ ) as TypeError & { code: string };
2506
+ err.code = 'ERR_INVALID_ARG_VALUE';
2507
+ throw err;
2508
+ }
2509
+ }
2510
+ }
2511
+
2512
+ function isChildProcessPermissionDenied(execArgv: readonly string[]): boolean {
2513
+ let permissionMode = false;
2514
+ let allowChildProcess = false;
2515
+
2516
+ for (const rawArg of execArgv) {
2517
+ const arg = String(rawArg);
2518
+ if (arg === '--permission' || arg.startsWith('--permission=')) {
2519
+ permissionMode = true;
2520
+ continue;
2521
+ }
2522
+ if (arg === '--allow-child-process' || arg.startsWith('--allow-child-process=')) {
2523
+ allowChildProcess = true;
2524
+ }
2525
+ }
2526
+
2527
+ return permissionMode && !allowChildProcess;
2528
+ }