@secure-exec/core 0.1.1-rc.2 → 0.2.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. package/dist/esm-compiler.d.ts +5 -1
  2. package/dist/esm-compiler.js +5 -1
  3. package/dist/fs-helpers.d.ts +1 -1
  4. package/dist/generated/isolate-runtime.d.ts +15 -15
  5. package/dist/generated/isolate-runtime.js +15 -15
  6. package/dist/index.d.ts +25 -6
  7. package/dist/index.js +23 -3
  8. package/dist/isolate-runtime/apply-custom-global-policy.js +3 -3
  9. package/dist/isolate-runtime/apply-timing-mitigation-freeze.js +10 -8
  10. package/dist/isolate-runtime/apply-timing-mitigation-off.js +2 -2
  11. package/dist/isolate-runtime/bridge-attach.js +2 -2
  12. package/dist/isolate-runtime/bridge-initial-globals.js +3 -3
  13. package/dist/isolate-runtime/eval-script-result.js +1 -1
  14. package/dist/isolate-runtime/global-exposure-helpers.js +2 -2
  15. package/dist/isolate-runtime/init-commonjs-module-globals.js +2 -2
  16. package/dist/isolate-runtime/override-process-cwd.js +1 -1
  17. package/dist/isolate-runtime/override-process-env.js +1 -1
  18. package/dist/isolate-runtime/require-setup.js +2236 -19
  19. package/dist/isolate-runtime/set-commonjs-file-globals.js +2 -2
  20. package/dist/isolate-runtime/set-stdin-data.js +1 -1
  21. package/dist/isolate-runtime/setup-dynamic-import.js +47 -15
  22. package/dist/isolate-runtime/setup-fs-facade.js +2 -2
  23. package/dist/kernel/command-registry.d.ts +44 -0
  24. package/dist/kernel/command-registry.js +114 -0
  25. package/dist/kernel/device-layer.d.ts +12 -0
  26. package/dist/kernel/device-layer.js +262 -0
  27. package/dist/kernel/dns-cache.d.ts +29 -0
  28. package/dist/kernel/dns-cache.js +52 -0
  29. package/dist/kernel/fd-table.d.ts +84 -0
  30. package/dist/kernel/fd-table.js +278 -0
  31. package/dist/kernel/file-lock.d.ts +34 -0
  32. package/dist/kernel/file-lock.js +123 -0
  33. package/dist/kernel/host-adapter.d.ts +50 -0
  34. package/dist/kernel/host-adapter.js +8 -0
  35. package/dist/kernel/index.d.ts +36 -0
  36. package/dist/kernel/index.js +34 -0
  37. package/dist/kernel/inode-table.d.ts +43 -0
  38. package/dist/kernel/inode-table.js +85 -0
  39. package/dist/kernel/kernel.d.ts +9 -0
  40. package/dist/kernel/kernel.js +1396 -0
  41. package/dist/kernel/permissions.d.ts +27 -0
  42. package/dist/kernel/permissions.js +118 -0
  43. package/dist/kernel/pipe-manager.d.ts +64 -0
  44. package/dist/kernel/pipe-manager.js +267 -0
  45. package/dist/kernel/proc-layer.d.ts +11 -0
  46. package/dist/kernel/proc-layer.js +501 -0
  47. package/dist/kernel/process-table.d.ts +124 -0
  48. package/dist/kernel/process-table.js +631 -0
  49. package/dist/kernel/pty.d.ts +108 -0
  50. package/dist/kernel/pty.js +541 -0
  51. package/dist/kernel/socket-table.d.ts +305 -0
  52. package/dist/kernel/socket-table.js +1124 -0
  53. package/dist/kernel/timer-table.d.ts +54 -0
  54. package/dist/kernel/timer-table.js +108 -0
  55. package/dist/kernel/types.d.ts +500 -0
  56. package/dist/kernel/types.js +89 -0
  57. package/dist/kernel/user.d.ts +29 -0
  58. package/dist/kernel/user.js +35 -0
  59. package/dist/kernel/vfs.d.ts +54 -0
  60. package/dist/kernel/vfs.js +8 -0
  61. package/dist/kernel/wait.d.ts +45 -0
  62. package/dist/kernel/wait.js +112 -0
  63. package/dist/kernel/wstatus.d.ts +21 -0
  64. package/dist/kernel/wstatus.js +33 -0
  65. package/dist/module-resolver.d.ts +4 -0
  66. package/dist/module-resolver.js +4 -0
  67. package/dist/package-bundler.d.ts +6 -1
  68. package/dist/runtime-driver.d.ts +3 -1
  69. package/dist/shared/bridge-contract.d.ts +529 -94
  70. package/dist/shared/bridge-contract.js +86 -3
  71. package/dist/shared/console-formatter.js +4 -0
  72. package/dist/shared/global-exposure.js +345 -0
  73. package/dist/shared/in-memory-fs.d.ts +30 -11
  74. package/dist/shared/in-memory-fs.js +383 -109
  75. package/dist/shared/permissions.d.ts +4 -6
  76. package/dist/shared/permissions.js +24 -28
  77. package/dist/types.d.ts +20 -130
  78. package/dist/types.js +5 -0
  79. package/package.json +12 -22
  80. package/dist/bridge/active-handles.d.ts +0 -22
  81. package/dist/bridge/active-handles.js +0 -55
  82. package/dist/bridge/child-process.d.ts +0 -99
  83. package/dist/bridge/child-process.js +0 -656
  84. package/dist/bridge/fs.d.ts +0 -281
  85. package/dist/bridge/fs.js +0 -2231
  86. package/dist/bridge/index.d.ts +0 -10
  87. package/dist/bridge/index.js +0 -41
  88. package/dist/bridge/module.d.ts +0 -75
  89. package/dist/bridge/module.js +0 -299
  90. package/dist/bridge/network.d.ts +0 -250
  91. package/dist/bridge/network.js +0 -1433
  92. package/dist/bridge/os.d.ts +0 -13
  93. package/dist/bridge/os.js +0 -256
  94. package/dist/bridge/polyfills.d.ts +0 -2
  95. package/dist/bridge/polyfills.js +0 -11
  96. package/dist/bridge/process.d.ts +0 -89
  97. package/dist/bridge/process.js +0 -994
  98. package/dist/bridge.js +0 -11766
  99. package/dist/python-runtime.d.ts +0 -16
  100. package/dist/python-runtime.js +0 -45
  101. package/dist/runtime.d.ts +0 -31
  102. package/dist/runtime.js +0 -69
package/dist/bridge/fs.js DELETED
@@ -1,2231 +0,0 @@
1
- // fs polyfill module for isolated-vm
2
- // This module runs inside the isolate and provides Node.js fs API compatibility
3
- // It communicates with the host via the _fs Reference object
4
- import { Buffer } from "buffer";
5
- // File descriptor table — capped to prevent resource exhaustion
6
- const MAX_BRIDGE_FDS = 1024;
7
- const fdTable = new Map();
8
- let nextFd = 3;
9
- const O_RDONLY = 0;
10
- const O_WRONLY = 1;
11
- const O_RDWR = 2;
12
- const O_ACCMODE = 3;
13
- const O_CREAT = 64;
14
- const O_EXCL = 128;
15
- const O_TRUNC = 512;
16
- const O_APPEND = 1024;
17
- // Stats class
18
- class Stats {
19
- dev;
20
- ino;
21
- mode;
22
- nlink;
23
- uid;
24
- gid;
25
- rdev;
26
- size;
27
- blksize;
28
- blocks;
29
- atimeMs;
30
- mtimeMs;
31
- ctimeMs;
32
- birthtimeMs;
33
- atime;
34
- mtime;
35
- ctime;
36
- birthtime;
37
- constructor(init) {
38
- this.dev = init.dev ?? 0;
39
- this.ino = init.ino ?? 0;
40
- this.mode = init.mode;
41
- this.nlink = init.nlink ?? 1;
42
- this.uid = init.uid ?? 0;
43
- this.gid = init.gid ?? 0;
44
- this.rdev = init.rdev ?? 0;
45
- this.size = init.size;
46
- this.blksize = init.blksize ?? 4096;
47
- this.blocks = init.blocks ?? Math.ceil(init.size / 512);
48
- this.atimeMs = init.atimeMs ?? Date.now();
49
- this.mtimeMs = init.mtimeMs ?? Date.now();
50
- this.ctimeMs = init.ctimeMs ?? Date.now();
51
- this.birthtimeMs = init.birthtimeMs ?? Date.now();
52
- this.atime = new Date(this.atimeMs);
53
- this.mtime = new Date(this.mtimeMs);
54
- this.ctime = new Date(this.ctimeMs);
55
- this.birthtime = new Date(this.birthtimeMs);
56
- }
57
- isFile() {
58
- return (this.mode & 61440) === 32768;
59
- }
60
- isDirectory() {
61
- return (this.mode & 61440) === 16384;
62
- }
63
- isSymbolicLink() {
64
- return (this.mode & 61440) === 40960;
65
- }
66
- isBlockDevice() {
67
- return false;
68
- }
69
- isCharacterDevice() {
70
- return false;
71
- }
72
- isFIFO() {
73
- return false;
74
- }
75
- isSocket() {
76
- return false;
77
- }
78
- }
79
- // Dirent class for readdir with withFileTypes
80
- class Dirent {
81
- name;
82
- parentPath;
83
- path; // Deprecated alias for parentPath
84
- _isDir;
85
- constructor(name, isDir, parentPath = "") {
86
- this.name = name;
87
- this._isDir = isDir;
88
- this.parentPath = parentPath;
89
- this.path = parentPath;
90
- }
91
- isFile() {
92
- return !this._isDir;
93
- }
94
- isDirectory() {
95
- return this._isDir;
96
- }
97
- isSymbolicLink() {
98
- return false;
99
- }
100
- isBlockDevice() {
101
- return false;
102
- }
103
- isCharacterDevice() {
104
- return false;
105
- }
106
- isFIFO() {
107
- return false;
108
- }
109
- isSocket() {
110
- return false;
111
- }
112
- }
113
- // Dir class for opendir — async-iterable directory handle
114
- class Dir {
115
- path;
116
- _entries = null;
117
- _index = 0;
118
- _closed = false;
119
- constructor(dirPath) {
120
- this.path = dirPath;
121
- }
122
- _load() {
123
- if (this._entries === null) {
124
- this._entries = fs.readdirSync(this.path, { withFileTypes: true });
125
- }
126
- return this._entries;
127
- }
128
- readSync() {
129
- if (this._closed)
130
- throw new Error("Directory handle was closed");
131
- const entries = this._load();
132
- if (this._index >= entries.length)
133
- return null;
134
- return entries[this._index++];
135
- }
136
- async read() {
137
- return this.readSync();
138
- }
139
- closeSync() {
140
- this._closed = true;
141
- }
142
- async close() {
143
- this.closeSync();
144
- }
145
- async *[Symbol.asyncIterator]() {
146
- const entries = this._load();
147
- for (const entry of entries) {
148
- if (this._closed)
149
- return;
150
- yield entry;
151
- }
152
- this._closed = true;
153
- }
154
- }
155
- // ReadStream class for createReadStream
156
- // Provides a proper readable stream implementation that works with stream.pipeline
157
- class ReadStream {
158
- _options;
159
- // ReadStream-specific properties
160
- bytesRead = 0;
161
- path;
162
- pending = true;
163
- // Readable stream properties
164
- readable = true;
165
- readableAborted = false;
166
- readableDidRead = false;
167
- readableEncoding = null;
168
- readableEnded = false;
169
- readableFlowing = null;
170
- readableHighWaterMark = 65536;
171
- readableLength = 0;
172
- readableObjectMode = false;
173
- destroyed = false;
174
- closed = false;
175
- errored = null;
176
- // Internal state
177
- _content = null;
178
- _listeners = new Map();
179
- _started = false;
180
- constructor(filePath, _options) {
181
- this._options = _options;
182
- this.path = filePath;
183
- if (_options?.encoding) {
184
- this.readableEncoding = _options.encoding;
185
- }
186
- if (_options?.highWaterMark) {
187
- this.readableHighWaterMark = _options.highWaterMark;
188
- }
189
- }
190
- _loadContent() {
191
- if (this._content === null) {
192
- const pathStr = typeof this.path === 'string' ? this.path : this.path.toString();
193
- // readFileSync already normalizes the path
194
- this._content = fs.readFileSync(pathStr);
195
- this.pending = false;
196
- }
197
- return this._content;
198
- }
199
- // Start reading - called when 'data' listener is added or resume() is called
200
- _startReading() {
201
- if (this._started || this.destroyed)
202
- return;
203
- this._started = true;
204
- this.readableFlowing = true;
205
- Promise.resolve().then(() => {
206
- try {
207
- const content = this._loadContent();
208
- this.readableDidRead = true;
209
- // Determine start/end positions
210
- const start = this._options?.start ?? 0;
211
- const end = this._options?.end ?? content.length;
212
- const chunk = content.slice(start, end);
213
- this.bytesRead = chunk.length;
214
- // Emit data event
215
- this.emit('data', chunk);
216
- // Emit end and close
217
- Promise.resolve().then(() => {
218
- this.readable = false;
219
- this.readableEnded = true;
220
- this.emit('end');
221
- Promise.resolve().then(() => {
222
- this.closed = true;
223
- this.emit('close');
224
- });
225
- });
226
- }
227
- catch (err) {
228
- this.errored = err;
229
- this.emit('error', err);
230
- this.destroy(err);
231
- }
232
- });
233
- }
234
- // Event handling
235
- on(event, listener) {
236
- if (!this._listeners.has(event)) {
237
- this._listeners.set(event, []);
238
- }
239
- this._listeners.get(event).push(listener);
240
- // Start reading when 'data' listener is added (flowing mode)
241
- if (event === 'data' && !this._started) {
242
- this._startReading();
243
- }
244
- return this;
245
- }
246
- once(event, listener) {
247
- const wrapper = (...args) => {
248
- this.off(event, wrapper);
249
- listener(...args);
250
- };
251
- wrapper._originalListener = listener;
252
- return this.on(event, wrapper);
253
- }
254
- off(event, listener) {
255
- const listeners = this._listeners.get(event);
256
- if (listeners) {
257
- const idx = listeners.findIndex(fn => fn === listener || fn._originalListener === listener);
258
- if (idx !== -1)
259
- listeners.splice(idx, 1);
260
- }
261
- return this;
262
- }
263
- removeListener(event, listener) {
264
- return this.off(event, listener);
265
- }
266
- removeAllListeners(event) {
267
- if (event) {
268
- this._listeners.delete(event);
269
- }
270
- else {
271
- this._listeners.clear();
272
- }
273
- return this;
274
- }
275
- emit(event, ...args) {
276
- const listeners = this._listeners.get(event);
277
- if (listeners && listeners.length > 0) {
278
- listeners.slice().forEach(fn => fn(...args));
279
- return true;
280
- }
281
- return false;
282
- }
283
- // Readable methods
284
- read(_size) {
285
- if (this.readableEnded || this.destroyed)
286
- return null;
287
- try {
288
- const content = this._loadContent();
289
- const start = this._options?.start ?? 0;
290
- const end = this._options?.end ?? content.length;
291
- const chunk = content.slice(start, end);
292
- this.bytesRead = chunk.length;
293
- this.readableDidRead = true;
294
- this.readable = false;
295
- this.readableEnded = true;
296
- // Schedule end event
297
- Promise.resolve().then(() => {
298
- this.emit('end');
299
- Promise.resolve().then(() => {
300
- this.closed = true;
301
- this.emit('close');
302
- });
303
- });
304
- return this.readableEncoding ? chunk.toString(this.readableEncoding) : chunk;
305
- }
306
- catch (err) {
307
- this.errored = err;
308
- this.emit('error', err);
309
- return null;
310
- }
311
- }
312
- pipe(destination, _options) {
313
- const content = this._loadContent();
314
- const start = this._options?.start ?? 0;
315
- const end = this._options?.end ?? content.length;
316
- const chunk = content.slice(start, end);
317
- this.bytesRead = chunk.length;
318
- this.readableDidRead = true;
319
- if (typeof destination.write === 'function') {
320
- destination.write(chunk);
321
- }
322
- if (typeof destination.end === 'function') {
323
- Promise.resolve().then(() => destination.end());
324
- }
325
- this.readable = false;
326
- this.readableEnded = true;
327
- this.closed = true;
328
- Promise.resolve().then(() => {
329
- this.emit('end');
330
- this.emit('close');
331
- });
332
- return destination;
333
- }
334
- unpipe(_destination) {
335
- return this;
336
- }
337
- pause() {
338
- this.readableFlowing = false;
339
- return this;
340
- }
341
- resume() {
342
- this.readableFlowing = true;
343
- if (!this._started) {
344
- this._startReading();
345
- }
346
- return this;
347
- }
348
- setEncoding(encoding) {
349
- this.readableEncoding = encoding;
350
- return this;
351
- }
352
- destroy(error) {
353
- if (this.destroyed)
354
- return this;
355
- this.destroyed = true;
356
- this.readable = false;
357
- if (error) {
358
- this.errored = error;
359
- this.emit('error', error);
360
- }
361
- this.emit('close');
362
- this.closed = true;
363
- return this;
364
- }
365
- close(callback) {
366
- if (this.closed) {
367
- if (callback)
368
- Promise.resolve().then(() => callback(null));
369
- return;
370
- }
371
- this.closed = true;
372
- this.readable = false;
373
- this.destroyed = true;
374
- Promise.resolve().then(() => {
375
- this.emit('close');
376
- if (callback)
377
- callback(null);
378
- });
379
- }
380
- // Symbol.asyncIterator for async iteration
381
- async *[Symbol.asyncIterator]() {
382
- const content = this._loadContent();
383
- const start = this._options?.start ?? 0;
384
- const end = this._options?.end ?? content.length;
385
- const chunk = content.slice(start, end);
386
- yield this.readableEncoding ? chunk.toString(this.readableEncoding) : chunk;
387
- }
388
- }
389
- // WriteStream class for createWriteStream
390
- // This provides a type-safe implementation that satisfies nodeFs.WriteStream
391
- const MAX_WRITE_STREAM_BYTES = 16 * 1024 * 1024; // 16MB cap to prevent memory exhaustion
392
- // We use 'as' assertion at the return site since the full interface is complex
393
- class WriteStream {
394
- // WriteStream-specific properties
395
- bytesWritten = 0;
396
- path;
397
- pending = false;
398
- // Writable stream properties
399
- writable = true;
400
- writableAborted = false;
401
- writableEnded = false;
402
- writableFinished = false;
403
- writableHighWaterMark = 16384;
404
- writableLength = 0;
405
- writableObjectMode = false;
406
- writableCorked = 0;
407
- destroyed = false;
408
- closed = false;
409
- errored = null;
410
- writableNeedDrain = false;
411
- // Internal state
412
- _chunks = [];
413
- _listeners = new Map();
414
- constructor(filePath, _options) {
415
- this.path = filePath;
416
- }
417
- // WriteStream-specific methods
418
- close(callback) {
419
- if (this.closed) {
420
- if (callback)
421
- Promise.resolve().then(() => callback(null));
422
- return;
423
- }
424
- this.closed = true;
425
- this.writable = false;
426
- Promise.resolve().then(() => {
427
- this.emit("close");
428
- if (callback)
429
- callback(null);
430
- });
431
- }
432
- // Writable methods
433
- write(chunk, encodingOrCallback, callback) {
434
- if (this.writableEnded || this.destroyed) {
435
- const err = new Error("write after end");
436
- if (typeof encodingOrCallback === "function") {
437
- Promise.resolve().then(() => encodingOrCallback(err));
438
- }
439
- else if (callback) {
440
- Promise.resolve().then(() => callback(err));
441
- }
442
- return false;
443
- }
444
- let data;
445
- if (typeof chunk === "string") {
446
- data = Buffer.from(chunk, typeof encodingOrCallback === "string" ? encodingOrCallback : "utf8");
447
- }
448
- else if (Buffer.isBuffer(chunk)) {
449
- data = new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength);
450
- }
451
- else if (chunk instanceof Uint8Array) {
452
- data = chunk;
453
- }
454
- else {
455
- data = Buffer.from(String(chunk));
456
- }
457
- // Cap buffered data to prevent memory exhaustion
458
- if (this.writableLength + data.length > MAX_WRITE_STREAM_BYTES) {
459
- const err = new Error(`WriteStream buffer exceeded ${MAX_WRITE_STREAM_BYTES} bytes`);
460
- this.errored = err;
461
- this.destroyed = true;
462
- this.writable = false;
463
- const cb = typeof encodingOrCallback === "function" ? encodingOrCallback : callback;
464
- if (cb)
465
- Promise.resolve().then(() => cb(err));
466
- Promise.resolve().then(() => this.emit("error", err));
467
- return false;
468
- }
469
- this._chunks.push(data);
470
- this.bytesWritten += data.length;
471
- this.writableLength += data.length;
472
- const cb = typeof encodingOrCallback === "function" ? encodingOrCallback : callback;
473
- if (cb)
474
- Promise.resolve().then(() => cb(null));
475
- return true;
476
- }
477
- end(chunkOrCb, encodingOrCallback, callback) {
478
- if (this.writableEnded)
479
- return this;
480
- let cb;
481
- if (typeof chunkOrCb === "function") {
482
- cb = chunkOrCb;
483
- }
484
- else if (typeof encodingOrCallback === "function") {
485
- cb = encodingOrCallback;
486
- if (chunkOrCb !== undefined && chunkOrCb !== null) {
487
- this.write(chunkOrCb);
488
- }
489
- }
490
- else {
491
- cb = callback;
492
- if (chunkOrCb !== undefined && chunkOrCb !== null) {
493
- this.write(chunkOrCb, encodingOrCallback);
494
- }
495
- }
496
- this.writableEnded = true;
497
- // Concatenate and write all chunks
498
- const totalLength = this._chunks.reduce((sum, c) => sum + c.length, 0);
499
- const result = new Uint8Array(totalLength);
500
- let offset = 0;
501
- for (const c of this._chunks) {
502
- result.set(c, offset);
503
- offset += c.length;
504
- }
505
- // Write to filesystem
506
- const pathStr = typeof this.path === "string" ? this.path : this.path.toString();
507
- fs.writeFileSync(pathStr, result);
508
- this.writable = false;
509
- this.writableFinished = true;
510
- this.writableLength = 0;
511
- Promise.resolve().then(() => {
512
- this.emit("finish");
513
- this.emit("close");
514
- this.closed = true;
515
- if (cb)
516
- cb();
517
- });
518
- return this;
519
- }
520
- setDefaultEncoding(_encoding) {
521
- return this;
522
- }
523
- cork() {
524
- this.writableCorked++;
525
- }
526
- uncork() {
527
- if (this.writableCorked > 0)
528
- this.writableCorked--;
529
- }
530
- destroy(error) {
531
- if (this.destroyed)
532
- return this;
533
- this.destroyed = true;
534
- this.writable = false;
535
- if (error) {
536
- this.errored = error;
537
- Promise.resolve().then(() => {
538
- this.emit("error", error);
539
- this.emit("close");
540
- this.closed = true;
541
- });
542
- }
543
- else {
544
- Promise.resolve().then(() => {
545
- this.emit("close");
546
- this.closed = true;
547
- });
548
- }
549
- return this;
550
- }
551
- // Internal methods (required by Writable interface but not typically called directly)
552
- _write(_chunk, _encoding, callback) {
553
- callback();
554
- }
555
- _destroy(_error, callback) {
556
- callback();
557
- }
558
- _final(callback) {
559
- callback();
560
- }
561
- // EventEmitter methods
562
- addListener(event, listener) {
563
- return this.on(event, listener);
564
- }
565
- on(event, listener) {
566
- const listeners = this._listeners.get(event) || [];
567
- listeners.push(listener);
568
- this._listeners.set(event, listeners);
569
- return this;
570
- }
571
- once(event, listener) {
572
- const wrapper = (...args) => {
573
- this.removeListener(event, wrapper);
574
- listener(...args);
575
- };
576
- return this.on(event, wrapper);
577
- }
578
- prependListener(event, listener) {
579
- const listeners = this._listeners.get(event) || [];
580
- listeners.unshift(listener);
581
- this._listeners.set(event, listeners);
582
- return this;
583
- }
584
- prependOnceListener(event, listener) {
585
- const wrapper = (...args) => {
586
- this.removeListener(event, wrapper);
587
- listener(...args);
588
- };
589
- return this.prependListener(event, wrapper);
590
- }
591
- removeListener(event, listener) {
592
- const listeners = this._listeners.get(event);
593
- if (listeners) {
594
- const idx = listeners.indexOf(listener);
595
- if (idx !== -1)
596
- listeners.splice(idx, 1);
597
- }
598
- return this;
599
- }
600
- off(event, listener) {
601
- return this.removeListener(event, listener);
602
- }
603
- removeAllListeners(event) {
604
- if (event !== undefined) {
605
- this._listeners.delete(event);
606
- }
607
- else {
608
- this._listeners.clear();
609
- }
610
- return this;
611
- }
612
- emit(event, ...args) {
613
- const listeners = this._listeners.get(event);
614
- if (listeners && listeners.length > 0) {
615
- listeners.slice().forEach(l => l(...args));
616
- return true;
617
- }
618
- return false;
619
- }
620
- listeners(event) {
621
- return [...(this._listeners.get(event) || [])];
622
- }
623
- rawListeners(event) {
624
- return this.listeners(event);
625
- }
626
- listenerCount(event) {
627
- return (this._listeners.get(event) || []).length;
628
- }
629
- eventNames() {
630
- return [...this._listeners.keys()];
631
- }
632
- getMaxListeners() {
633
- return 10;
634
- }
635
- setMaxListeners(_n) {
636
- return this;
637
- }
638
- // Pipe methods (minimal implementation)
639
- pipe(destination, _options) {
640
- return destination;
641
- }
642
- unpipe(_destination) {
643
- return this;
644
- }
645
- // Additional required methods
646
- compose(_stream, _options) {
647
- throw new Error("compose not implemented in sandbox");
648
- }
649
- [Symbol.asyncDispose]() {
650
- return Promise.resolve();
651
- }
652
- }
653
- // Parse flags string to number
654
- function parseFlags(flags) {
655
- if (typeof flags === "number")
656
- return flags;
657
- const flagMap = {
658
- r: O_RDONLY,
659
- "r+": O_RDWR,
660
- w: O_WRONLY | O_CREAT | O_TRUNC,
661
- "w+": O_RDWR | O_CREAT | O_TRUNC,
662
- a: O_WRONLY | O_APPEND | O_CREAT,
663
- "a+": O_RDWR | O_APPEND | O_CREAT,
664
- wx: O_WRONLY | O_CREAT | O_TRUNC | O_EXCL,
665
- xw: O_WRONLY | O_CREAT | O_TRUNC | O_EXCL,
666
- "wx+": O_RDWR | O_CREAT | O_TRUNC | O_EXCL,
667
- "xw+": O_RDWR | O_CREAT | O_TRUNC | O_EXCL,
668
- ax: O_WRONLY | O_APPEND | O_CREAT | O_EXCL,
669
- xa: O_WRONLY | O_APPEND | O_CREAT | O_EXCL,
670
- "ax+": O_RDWR | O_APPEND | O_CREAT | O_EXCL,
671
- "xa+": O_RDWR | O_APPEND | O_CREAT | O_EXCL,
672
- };
673
- if (flags in flagMap)
674
- return flagMap[flags];
675
- throw new Error("Unknown file flag: " + flags);
676
- }
677
- // Check if flags allow reading
678
- function canRead(flags) {
679
- const mode = flags & O_ACCMODE;
680
- return mode === 0 || mode === 2;
681
- }
682
- // Check if flags allow writing
683
- function canWrite(flags) {
684
- const mode = flags & O_ACCMODE;
685
- return mode === 1 || mode === 2;
686
- }
687
- // Helper to create fs errors
688
- function createFsError(code, message, syscall, path) {
689
- const err = new Error(message);
690
- err.code = code;
691
- err.errno = code === "ENOENT" ? -2 : code === "EACCES" ? -13 : code === "EBADF" ? -9 : code === "EMFILE" ? -24 : -1;
692
- err.syscall = syscall;
693
- if (path)
694
- err.path = path;
695
- return err;
696
- }
697
- /** Wrap a bridge call with ENOENT/EACCES error re-creation. */
698
- function bridgeCall(fn, syscall, path) {
699
- try {
700
- return fn();
701
- }
702
- catch (err) {
703
- const msg = err.message || String(err);
704
- if (msg.includes("ENOENT") || msg.includes("no such file or directory") || msg.includes("not found")) {
705
- throw createFsError("ENOENT", `ENOENT: no such file or directory, ${syscall} '${path}'`, syscall, path);
706
- }
707
- if (msg.includes("EACCES") || msg.includes("permission denied")) {
708
- throw createFsError("EACCES", `EACCES: permission denied, ${syscall} '${path}'`, syscall, path);
709
- }
710
- if (msg.includes("EEXIST") || msg.includes("file already exists")) {
711
- throw createFsError("EEXIST", `EEXIST: file already exists, ${syscall} '${path}'`, syscall, path);
712
- }
713
- if (msg.includes("EINVAL") || msg.includes("invalid argument")) {
714
- throw createFsError("EINVAL", `EINVAL: invalid argument, ${syscall} '${path}'`, syscall, path);
715
- }
716
- throw err;
717
- }
718
- }
719
- // Glob pattern matching helper — converts glob to regex and walks VFS recursively
720
- function _globToRegex(pattern) {
721
- // Determine base directory vs glob portion
722
- let regexStr = "";
723
- let i = 0;
724
- while (i < pattern.length) {
725
- const ch = pattern[i];
726
- if (ch === "*" && pattern[i + 1] === "*") {
727
- // ** matches any depth of directories
728
- if (pattern[i + 2] === "/") {
729
- regexStr += "(?:.+/)?";
730
- i += 3;
731
- }
732
- else {
733
- regexStr += ".*";
734
- i += 2;
735
- }
736
- }
737
- else if (ch === "*") {
738
- regexStr += "[^/]*";
739
- i++;
740
- }
741
- else if (ch === "?") {
742
- regexStr += "[^/]";
743
- i++;
744
- }
745
- else if (ch === "{") {
746
- const close = pattern.indexOf("}", i);
747
- if (close !== -1) {
748
- const alternatives = pattern.slice(i + 1, close).split(",");
749
- regexStr += "(?:" + alternatives.map(a => a.replace(/[.*+?^${}()|[\]\\]/g, "\\$&").replace(/\\\*/g, "[^/]*")).join("|") + ")";
750
- i = close + 1;
751
- }
752
- else {
753
- regexStr += "\\{";
754
- i++;
755
- }
756
- }
757
- else if (ch === "[") {
758
- const close = pattern.indexOf("]", i);
759
- if (close !== -1) {
760
- regexStr += pattern.slice(i, close + 1);
761
- i = close + 1;
762
- }
763
- else {
764
- regexStr += "\\[";
765
- i++;
766
- }
767
- }
768
- else if (".+^${}()|[]\\".includes(ch)) {
769
- regexStr += "\\" + ch;
770
- i++;
771
- }
772
- else {
773
- regexStr += ch;
774
- i++;
775
- }
776
- }
777
- return new RegExp("^" + regexStr + "$");
778
- }
779
- function _globGetBase(pattern) {
780
- // Find the longest directory prefix that has no glob characters
781
- const parts = pattern.split("/");
782
- const baseParts = [];
783
- for (const part of parts) {
784
- if (/[*?{}\[\]]/.test(part))
785
- break;
786
- baseParts.push(part);
787
- }
788
- return baseParts.join("/") || "/";
789
- }
790
- // Recursively walk VFS directory and collect matching paths
791
- // We use a reference to `fs` via late-binding in the fs object method
792
- const MAX_GLOB_DEPTH = 100; // Prevent stack overflow on deeply nested trees
793
- function _globCollect(pattern, results) {
794
- const regex = _globToRegex(pattern);
795
- const base = _globGetBase(pattern);
796
- const walk = (dir, depth) => {
797
- if (depth > MAX_GLOB_DEPTH)
798
- return;
799
- let entries;
800
- try {
801
- entries = _globReadDir(dir);
802
- }
803
- catch {
804
- return; // Directory doesn't exist or not readable
805
- }
806
- for (const entry of entries) {
807
- const fullPath = dir === "/" ? "/" + entry : dir + "/" + entry;
808
- // Check if this path matches the pattern
809
- if (regex.test(fullPath)) {
810
- results.push(fullPath);
811
- }
812
- // Recurse into directories if pattern has ** or more segments
813
- try {
814
- const stat = _globStat(fullPath);
815
- if (stat.isDirectory()) {
816
- walk(fullPath, depth + 1);
817
- }
818
- }
819
- catch {
820
- // Not a directory or stat failed — skip
821
- }
822
- }
823
- };
824
- // Start walking from the base directory
825
- try {
826
- // Check if base itself matches (edge case)
827
- if (regex.test(base)) {
828
- const stat = _globStat(base);
829
- if (!stat.isDirectory()) {
830
- results.push(base);
831
- return;
832
- }
833
- }
834
- walk(base, 0);
835
- }
836
- catch {
837
- // Base doesn't exist — no matches
838
- }
839
- }
840
- // Late-bound references — these get assigned after fs is defined
841
- let _globReadDir;
842
- let _globStat;
843
- // Helper to convert PathLike to string
844
- function toPathString(path) {
845
- if (typeof path === "string")
846
- return path;
847
- if (Buffer.isBuffer(path))
848
- return path.toString("utf8");
849
- if (path instanceof URL)
850
- return path.pathname;
851
- return String(path);
852
- }
853
- // Note: Path normalization is handled by VirtualFileSystem, not here.
854
- // The VFS expects /data/* paths for Directory access, so we pass paths through unchanged.
855
- // The fs module implementation
856
- const fs = {
857
- // Constants
858
- constants: {
859
- // File Access Constants
860
- F_OK: 0,
861
- R_OK: 4,
862
- W_OK: 2,
863
- X_OK: 1,
864
- // File Copy Constants
865
- COPYFILE_EXCL: 1,
866
- COPYFILE_FICLONE: 2,
867
- COPYFILE_FICLONE_FORCE: 4,
868
- // File Open Constants
869
- O_RDONLY,
870
- O_WRONLY,
871
- O_RDWR,
872
- O_CREAT,
873
- O_EXCL,
874
- O_NOCTTY: 256,
875
- O_TRUNC,
876
- O_APPEND,
877
- O_DIRECTORY: 65536,
878
- O_NOATIME: 262144,
879
- O_NOFOLLOW: 131072,
880
- O_SYNC: 1052672,
881
- O_DSYNC: 4096,
882
- O_SYMLINK: 2097152,
883
- O_DIRECT: 16384,
884
- O_NONBLOCK: 2048,
885
- // File Type Constants
886
- S_IFMT: 61440,
887
- S_IFREG: 32768,
888
- S_IFDIR: 16384,
889
- S_IFCHR: 8192,
890
- S_IFBLK: 24576,
891
- S_IFIFO: 4096,
892
- S_IFLNK: 40960,
893
- S_IFSOCK: 49152,
894
- // File Mode Constants
895
- S_IRWXU: 448,
896
- S_IRUSR: 256,
897
- S_IWUSR: 128,
898
- S_IXUSR: 64,
899
- S_IRWXG: 56,
900
- S_IRGRP: 32,
901
- S_IWGRP: 16,
902
- S_IXGRP: 8,
903
- S_IRWXO: 7,
904
- S_IROTH: 4,
905
- S_IWOTH: 2,
906
- S_IXOTH: 1,
907
- UV_FS_O_FILEMAP: 536870912,
908
- },
909
- Stats,
910
- Dirent,
911
- Dir,
912
- // Sync methods
913
- readFileSync(path, options) {
914
- const rawPath = typeof path === "number" ? fdTable.get(path)?.path : toPathString(path);
915
- if (!rawPath)
916
- throw createFsError("EBADF", "EBADF: bad file descriptor", "read");
917
- const pathStr = rawPath;
918
- const encoding = typeof options === "string" ? options : options?.encoding;
919
- try {
920
- if (encoding) {
921
- // Text mode - use text read
922
- const content = _fs.readFile(pathStr);
923
- return content;
924
- }
925
- else {
926
- // Binary mode - host returns raw Uint8Array via MessagePack bin
927
- const binaryData = _fs.readFileBinary(pathStr);
928
- return Buffer.from(binaryData);
929
- }
930
- }
931
- catch (err) {
932
- const errMsg = err.message || String(err);
933
- // Convert various "not found" errors to proper ENOENT
934
- if (errMsg.includes("entry not found") ||
935
- errMsg.includes("not found") ||
936
- errMsg.includes("ENOENT") ||
937
- errMsg.includes("no such file or directory")) {
938
- throw createFsError("ENOENT", `ENOENT: no such file or directory, open '${rawPath}'`, "open", rawPath);
939
- }
940
- // Convert permission errors to proper EACCES
941
- if (errMsg.includes("EACCES") || errMsg.includes("permission denied")) {
942
- throw createFsError("EACCES", `EACCES: permission denied, open '${rawPath}'`, "open", rawPath);
943
- }
944
- throw err;
945
- }
946
- },
947
- writeFileSync(file, data, _options) {
948
- const rawPath = typeof file === "number" ? fdTable.get(file)?.path : toPathString(file);
949
- if (!rawPath)
950
- throw createFsError("EBADF", "EBADF: bad file descriptor", "write");
951
- const pathStr = rawPath;
952
- if (typeof data === "string") {
953
- // Text mode - use text write
954
- // Return the result so async callers (fs.promises) can await it.
955
- return _fs.writeFile(pathStr, data);
956
- }
957
- else if (ArrayBuffer.isView(data)) {
958
- // Binary mode - send raw Uint8Array via MessagePack bin
959
- const uint8 = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
960
- return _fs.writeFileBinary(pathStr, uint8);
961
- }
962
- else {
963
- // Fallback to text mode
964
- return _fs.writeFile(pathStr, String(data));
965
- }
966
- },
967
- appendFileSync(path, data, options) {
968
- const existing = fs.existsSync(path)
969
- ? fs.readFileSync(path, "utf8")
970
- : "";
971
- const content = typeof data === "string" ? data : String(data);
972
- fs.writeFileSync(path, existing + content, options);
973
- },
974
- readdirSync(path, options) {
975
- const rawPath = toPathString(path);
976
- const pathStr = rawPath;
977
- let entries;
978
- try {
979
- entries = _fs.readDir(pathStr);
980
- }
981
- catch (err) {
982
- // Convert "entry not found" and similar errors to proper ENOENT
983
- const errMsg = err.message || String(err);
984
- if (errMsg.includes("entry not found") || errMsg.includes("not found")) {
985
- throw createFsError("ENOENT", `ENOENT: no such file or directory, scandir '${rawPath}'`, "scandir", rawPath);
986
- }
987
- throw err;
988
- }
989
- if (options?.withFileTypes) {
990
- return entries.map((e) => new Dirent(e.name, e.isDirectory, rawPath));
991
- }
992
- return entries.map((e) => e.name);
993
- },
994
- mkdirSync(path, options) {
995
- const rawPath = toPathString(path);
996
- const pathStr = rawPath;
997
- const recursive = typeof options === "object" ? options?.recursive ?? false : false;
998
- _fs.mkdir(pathStr, recursive);
999
- return recursive ? rawPath : undefined;
1000
- },
1001
- rmdirSync(path, _options) {
1002
- const pathStr = toPathString(path);
1003
- _fs.rmdir(pathStr);
1004
- },
1005
- rmSync(path, options) {
1006
- const pathStr = toPathString(path);
1007
- const opts = options || {};
1008
- try {
1009
- const stats = fs.statSync(pathStr);
1010
- if (stats.isDirectory()) {
1011
- if (opts.recursive) {
1012
- // Recursively remove directory contents
1013
- const entries = fs.readdirSync(pathStr);
1014
- for (const entry of entries) {
1015
- const entryPath = pathStr.endsWith("/") ? pathStr + entry : pathStr + "/" + entry;
1016
- const entryStats = fs.statSync(entryPath);
1017
- if (entryStats.isDirectory()) {
1018
- fs.rmSync(entryPath, { recursive: true });
1019
- }
1020
- else {
1021
- fs.unlinkSync(entryPath);
1022
- }
1023
- }
1024
- fs.rmdirSync(pathStr);
1025
- }
1026
- else {
1027
- fs.rmdirSync(pathStr);
1028
- }
1029
- }
1030
- else {
1031
- fs.unlinkSync(pathStr);
1032
- }
1033
- }
1034
- catch (e) {
1035
- if (opts.force && e.code === "ENOENT") {
1036
- return; // Ignore ENOENT when force is true
1037
- }
1038
- throw e;
1039
- }
1040
- },
1041
- existsSync(path) {
1042
- const pathStr = toPathString(path);
1043
- return _fs.exists(pathStr);
1044
- },
1045
- statSync(path, _options) {
1046
- const rawPath = toPathString(path);
1047
- const pathStr = rawPath;
1048
- let stat;
1049
- try {
1050
- stat = _fs.stat(pathStr);
1051
- }
1052
- catch (err) {
1053
- // Convert various "not found" errors to proper ENOENT
1054
- const errMsg = err.message || String(err);
1055
- if (errMsg.includes("entry not found") ||
1056
- errMsg.includes("not found") ||
1057
- errMsg.includes("ENOENT") ||
1058
- errMsg.includes("no such file or directory")) {
1059
- throw createFsError("ENOENT", `ENOENT: no such file or directory, stat '${rawPath}'`, "stat", rawPath);
1060
- }
1061
- throw err;
1062
- }
1063
- return new Stats(stat);
1064
- },
1065
- lstatSync(path, _options) {
1066
- const pathStr = toPathString(path);
1067
- const stat = bridgeCall(() => _fs.lstat(pathStr), "lstat", pathStr);
1068
- return new Stats(stat);
1069
- },
1070
- unlinkSync(path) {
1071
- const pathStr = toPathString(path);
1072
- _fs.unlink(pathStr);
1073
- },
1074
- renameSync(oldPath, newPath) {
1075
- const oldPathStr = toPathString(oldPath);
1076
- const newPathStr = toPathString(newPath);
1077
- _fs.rename(oldPathStr, newPathStr);
1078
- },
1079
- copyFileSync(src, dest, _mode) {
1080
- // readFileSync and writeFileSync already normalize paths
1081
- const content = fs.readFileSync(src);
1082
- fs.writeFileSync(dest, content);
1083
- },
1084
- // Recursive copy
1085
- cpSync(src, dest, options) {
1086
- const srcPath = toPathString(src);
1087
- const destPath = toPathString(dest);
1088
- const opts = options || {};
1089
- const srcStat = fs.statSync(srcPath);
1090
- if (srcStat.isDirectory()) {
1091
- if (!opts.recursive) {
1092
- throw createFsError("ERR_FS_EISDIR", `Path is a directory: cp '${srcPath}'`, "cp", srcPath);
1093
- }
1094
- // Create destination directory
1095
- try {
1096
- fs.mkdirSync(destPath, { recursive: true });
1097
- }
1098
- catch {
1099
- // May already exist
1100
- }
1101
- // Copy contents recursively
1102
- const entries = fs.readdirSync(srcPath);
1103
- for (const entry of entries) {
1104
- const srcEntry = srcPath.endsWith("/") ? srcPath + entry : srcPath + "/" + entry;
1105
- const destEntry = destPath.endsWith("/") ? destPath + entry : destPath + "/" + entry;
1106
- fs.cpSync(srcEntry, destEntry, opts);
1107
- }
1108
- }
1109
- else {
1110
- // File copy
1111
- if (opts.errorOnExist && fs.existsSync(destPath)) {
1112
- throw createFsError("EEXIST", `EEXIST: file already exists, cp '${srcPath}' -> '${destPath}'`, "cp", destPath);
1113
- }
1114
- if (!opts.force && opts.force !== undefined && fs.existsSync(destPath)) {
1115
- return; // Skip without error when force is false
1116
- }
1117
- fs.copyFileSync(srcPath, destPath);
1118
- }
1119
- },
1120
- // Temp directory creation
1121
- mkdtempSync(prefix, _options) {
1122
- const suffix = Math.random().toString(36).slice(2, 8);
1123
- const dirPath = prefix + suffix;
1124
- fs.mkdirSync(dirPath, { recursive: true });
1125
- return dirPath;
1126
- },
1127
- // Directory handle (sync)
1128
- opendirSync(path, _options) {
1129
- const pathStr = toPathString(path);
1130
- // Verify directory exists
1131
- const stat = fs.statSync(pathStr);
1132
- if (!stat.isDirectory()) {
1133
- throw createFsError("ENOTDIR", `ENOTDIR: not a directory, opendir '${pathStr}'`, "opendir", pathStr);
1134
- }
1135
- return new Dir(pathStr);
1136
- },
1137
- // File descriptor methods
1138
- openSync(path, flags, _mode) {
1139
- // Enforce bridge-side FD limit
1140
- if (fdTable.size >= MAX_BRIDGE_FDS) {
1141
- throw createFsError("EMFILE", "EMFILE: too many open files, open '" + toPathString(path) + "'", "open", toPathString(path));
1142
- }
1143
- const rawPath = toPathString(path);
1144
- const pathStr = rawPath;
1145
- const numFlags = parseFlags(flags);
1146
- const fd = nextFd++;
1147
- // Check if file exists (existsSync already normalizes)
1148
- const exists = fs.existsSync(path);
1149
- // Handle O_CREAT - create file if it doesn't exist
1150
- if (numFlags & 64 && !exists) {
1151
- fs.writeFileSync(path, "");
1152
- }
1153
- else if (!exists && !(numFlags & 64)) {
1154
- throw createFsError("ENOENT", `ENOENT: no such file or directory, open '${rawPath}'`, "open", rawPath);
1155
- }
1156
- // Handle O_TRUNC - truncate file
1157
- if (numFlags & 512 && exists) {
1158
- fs.writeFileSync(path, "");
1159
- }
1160
- // Store normalized path in fd table for subsequent operations
1161
- fdTable.set(fd, { path: pathStr, flags: numFlags, position: 0 });
1162
- return fd;
1163
- },
1164
- closeSync(fd) {
1165
- if (!fdTable.has(fd)) {
1166
- throw createFsError("EBADF", "EBADF: bad file descriptor, close", "close");
1167
- }
1168
- fdTable.delete(fd);
1169
- },
1170
- readSync(fd, buffer, offset, length, position) {
1171
- const entry = fdTable.get(fd);
1172
- if (!entry) {
1173
- throw createFsError("EBADF", "EBADF: bad file descriptor, read", "read");
1174
- }
1175
- if (!canRead(entry.flags)) {
1176
- throw createFsError("EBADF", "EBADF: bad file descriptor, read", "read");
1177
- }
1178
- const content = fs.readFileSync(entry.path, "utf8");
1179
- const readOffset = offset ?? 0;
1180
- const readLength = length ?? (buffer.byteLength - readOffset);
1181
- const pos = position !== null && position !== undefined ? Number(position) : entry.position;
1182
- const toRead = content.slice(pos, pos + readLength);
1183
- const bytes = Buffer.from(toRead);
1184
- const targetBuffer = new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
1185
- for (let i = 0; i < bytes.length && i < readLength; i++) {
1186
- targetBuffer[readOffset + i] = bytes[i];
1187
- }
1188
- if (position === null || position === undefined) {
1189
- entry.position += bytes.length;
1190
- }
1191
- return bytes.length;
1192
- },
1193
- writeSync(fd, buffer, offsetOrPosition, lengthOrEncoding, position) {
1194
- const entry = fdTable.get(fd);
1195
- if (!entry) {
1196
- throw createFsError("EBADF", "EBADF: bad file descriptor, write", "write");
1197
- }
1198
- // fs.writeSync
1199
- if (!canWrite(entry.flags)) {
1200
- throw createFsError("EBADF", "EBADF: bad file descriptor, write", "write");
1201
- }
1202
- // Handle string or buffer
1203
- let data;
1204
- let writePosition;
1205
- if (typeof buffer === "string") {
1206
- data = buffer;
1207
- writePosition = offsetOrPosition;
1208
- }
1209
- else {
1210
- const offset = offsetOrPosition ?? 0;
1211
- const length = (typeof lengthOrEncoding === "number" ? lengthOrEncoding : null) ?? (buffer.byteLength - offset);
1212
- const view = new Uint8Array(buffer.buffer, buffer.byteOffset + offset, length);
1213
- data = new TextDecoder().decode(view);
1214
- writePosition = position;
1215
- }
1216
- // Read existing content
1217
- let content = "";
1218
- if (fs.existsSync(entry.path)) {
1219
- content = fs.readFileSync(entry.path, "utf8");
1220
- }
1221
- // Determine write position
1222
- let writePos;
1223
- if (entry.flags & 1024) {
1224
- // O_APPEND
1225
- writePos = content.length;
1226
- }
1227
- else if (writePosition !== null && writePosition !== undefined) {
1228
- writePos = writePosition;
1229
- }
1230
- else {
1231
- writePos = entry.position;
1232
- }
1233
- // Pad with nulls if writing past end
1234
- while (content.length < writePos) {
1235
- content += "\0";
1236
- }
1237
- // Write data
1238
- const newContent = content.slice(0, writePos) + data + content.slice(writePos + data.length);
1239
- fs.writeFileSync(entry.path, newContent);
1240
- // Update position if not using explicit position
1241
- if (writePosition === null || writePosition === undefined) {
1242
- entry.position = writePos + data.length;
1243
- }
1244
- return data.length;
1245
- },
1246
- fstatSync(fd) {
1247
- const entry = fdTable.get(fd);
1248
- if (!entry) {
1249
- throw createFsError("EBADF", "EBADF: bad file descriptor, fstat", "fstat");
1250
- }
1251
- return fs.statSync(entry.path);
1252
- },
1253
- ftruncateSync(fd, len) {
1254
- const entry = fdTable.get(fd);
1255
- if (!entry) {
1256
- throw createFsError("EBADF", "EBADF: bad file descriptor, ftruncate", "ftruncate");
1257
- }
1258
- const content = fs.existsSync(entry.path)
1259
- ? fs.readFileSync(entry.path, "utf8")
1260
- : "";
1261
- const newLen = len ?? 0;
1262
- if (content.length > newLen) {
1263
- fs.writeFileSync(entry.path, content.slice(0, newLen));
1264
- }
1265
- else {
1266
- let padded = content;
1267
- while (padded.length < newLen)
1268
- padded += "\0";
1269
- fs.writeFileSync(entry.path, padded);
1270
- }
1271
- },
1272
- // fsync / fdatasync — no-op for in-memory VFS (nothing to flush to disk)
1273
- fsyncSync(fd) {
1274
- if (!fdTable.has(fd)) {
1275
- throw createFsError("EBADF", "EBADF: bad file descriptor, fsync", "fsync");
1276
- }
1277
- },
1278
- fdatasyncSync(fd) {
1279
- if (!fdTable.has(fd)) {
1280
- throw createFsError("EBADF", "EBADF: bad file descriptor, fdatasync", "fdatasync");
1281
- }
1282
- },
1283
- // readv — scatter-read into multiple buffers
1284
- readvSync(fd, buffers, position) {
1285
- const entry = fdTable.get(fd);
1286
- if (!entry) {
1287
- throw createFsError("EBADF", "EBADF: bad file descriptor, readv", "readv");
1288
- }
1289
- if (!canRead(entry.flags)) {
1290
- throw createFsError("EBADF", "EBADF: bad file descriptor, readv", "readv");
1291
- }
1292
- let totalBytesRead = 0;
1293
- for (const buffer of buffers) {
1294
- const target = buffer instanceof Uint8Array
1295
- ? buffer
1296
- : new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
1297
- const bytesRead = fs.readSync(fd, target, 0, target.byteLength, position);
1298
- totalBytesRead += bytesRead;
1299
- if (position !== null && position !== undefined) {
1300
- position += bytesRead;
1301
- }
1302
- // EOF — stop filling further buffers
1303
- if (bytesRead < target.byteLength)
1304
- break;
1305
- }
1306
- return totalBytesRead;
1307
- },
1308
- // statfs — return synthetic filesystem stats for the in-memory VFS
1309
- statfsSync(path, _options) {
1310
- const pathStr = toPathString(path);
1311
- // Verify path exists
1312
- if (!fs.existsSync(pathStr)) {
1313
- throw createFsError("ENOENT", `ENOENT: no such file or directory, statfs '${pathStr}'`, "statfs", pathStr);
1314
- }
1315
- // Return synthetic stats — in-memory VFS has no real block device
1316
- return {
1317
- type: 0x01021997, // TMPFS_MAGIC
1318
- bsize: 4096,
1319
- blocks: 262144, // 1GB virtual capacity
1320
- bfree: 262144,
1321
- bavail: 262144,
1322
- files: 1000000,
1323
- ffree: 999999,
1324
- };
1325
- },
1326
- // glob — pattern matching over VFS files
1327
- globSync(pattern, _options) {
1328
- const patterns = Array.isArray(pattern) ? pattern : [pattern];
1329
- const results = [];
1330
- for (const pat of patterns) {
1331
- _globCollect(pat, results);
1332
- }
1333
- return [...new Set(results)].sort();
1334
- },
1335
- // Metadata and link sync methods — delegate to VFS via host refs
1336
- chmodSync(path, mode) {
1337
- const pathStr = toPathString(path);
1338
- const modeNum = typeof mode === "string" ? parseInt(mode, 8) : mode;
1339
- bridgeCall(() => _fs.chmod(pathStr, modeNum), "chmod", pathStr);
1340
- },
1341
- chownSync(path, uid, gid) {
1342
- const pathStr = toPathString(path);
1343
- bridgeCall(() => _fs.chown(pathStr, uid, gid), "chown", pathStr);
1344
- },
1345
- linkSync(existingPath, newPath) {
1346
- const existingStr = toPathString(existingPath);
1347
- const newStr = toPathString(newPath);
1348
- bridgeCall(() => _fs.link(existingStr, newStr), "link", newStr);
1349
- },
1350
- symlinkSync(target, path, _type) {
1351
- const targetStr = toPathString(target);
1352
- const pathStr = toPathString(path);
1353
- bridgeCall(() => _fs.symlink(targetStr, pathStr), "symlink", pathStr);
1354
- },
1355
- readlinkSync(path, _options) {
1356
- const pathStr = toPathString(path);
1357
- return bridgeCall(() => _fs.readlink(pathStr), "readlink", pathStr);
1358
- },
1359
- truncateSync(path, len) {
1360
- const pathStr = toPathString(path);
1361
- bridgeCall(() => _fs.truncate(pathStr, len ?? 0), "truncate", pathStr);
1362
- },
1363
- utimesSync(path, atime, mtime) {
1364
- const pathStr = toPathString(path);
1365
- const atimeNum = typeof atime === "number" ? atime : new Date(atime).getTime() / 1000;
1366
- const mtimeNum = typeof mtime === "number" ? mtime : new Date(mtime).getTime() / 1000;
1367
- bridgeCall(() => _fs.utimes(pathStr, atimeNum, mtimeNum), "utimes", pathStr);
1368
- },
1369
- // Async methods - wrap sync methods in callbacks/promises
1370
- //
1371
- // IMPORTANT: Low-level fd operations (open, close, read, write) and operations commonly
1372
- // used by streaming libraries (stat, lstat, rename, unlink) must defer their callbacks
1373
- // using queueMicrotask(). This is critical for proper stream operation.
1374
- //
1375
- // Why: Node.js streams (like tar, minipass, fs-minipass) use callback chains where each
1376
- // callback triggers the next read/write operation. These streams also rely on events like
1377
- // 'drain' to know when to resume writing. If callbacks fire synchronously, the event loop
1378
- // never gets a chance to process these events, causing streams to stall after the first chunk.
1379
- //
1380
- // Example problem without queueMicrotask:
1381
- // 1. tar calls fs.read() with callback
1382
- // 2. Our sync implementation calls callback immediately
1383
- // 3. Callback writes to stream, stream buffer fills, returns false (needs drain)
1384
- // 4. Code sets up 'drain' listener and returns
1385
- // 5. But we never returned to event loop, so 'drain' never fires
1386
- // 6. Stream hangs forever
1387
- //
1388
- // With queueMicrotask, step 2 defers the callback, allowing the event loop to process
1389
- // pending events (including 'drain') before the next operation starts.
1390
- readFile(path, options, callback) {
1391
- if (typeof options === "function") {
1392
- callback = options;
1393
- options = undefined;
1394
- }
1395
- if (callback) {
1396
- try {
1397
- callback(null, fs.readFileSync(path, options));
1398
- }
1399
- catch (e) {
1400
- callback(e);
1401
- }
1402
- }
1403
- else {
1404
- return Promise.resolve(fs.readFileSync(path, options));
1405
- }
1406
- },
1407
- writeFile(path, data, options, callback) {
1408
- if (typeof options === "function") {
1409
- callback = options;
1410
- options = undefined;
1411
- }
1412
- if (callback) {
1413
- try {
1414
- fs.writeFileSync(path, data, options);
1415
- callback(null);
1416
- }
1417
- catch (e) {
1418
- callback(e);
1419
- }
1420
- }
1421
- else {
1422
- return Promise.resolve(fs.writeFileSync(path, data, options));
1423
- }
1424
- },
1425
- appendFile(path, data, options, callback) {
1426
- if (typeof options === "function") {
1427
- callback = options;
1428
- options = undefined;
1429
- }
1430
- if (callback) {
1431
- try {
1432
- fs.appendFileSync(path, data, options);
1433
- callback(null);
1434
- }
1435
- catch (e) {
1436
- callback(e);
1437
- }
1438
- }
1439
- else {
1440
- return Promise.resolve(fs.appendFileSync(path, data, options));
1441
- }
1442
- },
1443
- readdir(path, options, callback) {
1444
- if (typeof options === "function") {
1445
- callback = options;
1446
- options = undefined;
1447
- }
1448
- if (callback) {
1449
- try {
1450
- callback(null, fs.readdirSync(path, options));
1451
- }
1452
- catch (e) {
1453
- callback(e);
1454
- }
1455
- }
1456
- else {
1457
- return Promise.resolve(fs.readdirSync(path, options));
1458
- }
1459
- },
1460
- mkdir(path, options, callback) {
1461
- if (typeof options === "function") {
1462
- callback = options;
1463
- options = undefined;
1464
- }
1465
- if (callback) {
1466
- try {
1467
- fs.mkdirSync(path, options);
1468
- callback(null);
1469
- }
1470
- catch (e) {
1471
- callback(e);
1472
- }
1473
- }
1474
- else {
1475
- fs.mkdirSync(path, options);
1476
- return Promise.resolve();
1477
- }
1478
- },
1479
- rmdir(path, callback) {
1480
- if (callback) {
1481
- // Defer callback to next tick to allow event loop to process stream events
1482
- const cb = callback;
1483
- try {
1484
- fs.rmdirSync(path);
1485
- queueMicrotask(() => cb(null));
1486
- }
1487
- catch (e) {
1488
- queueMicrotask(() => cb(e));
1489
- }
1490
- }
1491
- else {
1492
- return Promise.resolve(fs.rmdirSync(path));
1493
- }
1494
- },
1495
- // rm - remove files or directories (with recursive support)
1496
- rm(path, options, callback) {
1497
- let opts = {};
1498
- let cb;
1499
- if (typeof options === "function") {
1500
- cb = options;
1501
- }
1502
- else if (options) {
1503
- opts = options;
1504
- cb = callback;
1505
- }
1506
- else {
1507
- cb = callback;
1508
- }
1509
- const doRm = () => {
1510
- try {
1511
- const stats = fs.statSync(path);
1512
- if (stats.isDirectory()) {
1513
- if (opts.recursive) {
1514
- // Recursively remove directory contents
1515
- const entries = fs.readdirSync(path);
1516
- for (const entry of entries) {
1517
- const entryPath = path.endsWith("/") ? path + entry : path + "/" + entry;
1518
- const entryStats = fs.statSync(entryPath);
1519
- if (entryStats.isDirectory()) {
1520
- fs.rmSync(entryPath, { recursive: true });
1521
- }
1522
- else {
1523
- fs.unlinkSync(entryPath);
1524
- }
1525
- }
1526
- fs.rmdirSync(path);
1527
- }
1528
- else {
1529
- fs.rmdirSync(path);
1530
- }
1531
- }
1532
- else {
1533
- fs.unlinkSync(path);
1534
- }
1535
- }
1536
- catch (e) {
1537
- if (opts.force && e.code === "ENOENT") {
1538
- return; // Ignore ENOENT when force is true
1539
- }
1540
- throw e;
1541
- }
1542
- };
1543
- if (cb) {
1544
- // Defer callback to next tick to allow event loop to process stream events
1545
- try {
1546
- doRm();
1547
- queueMicrotask(() => cb(null));
1548
- }
1549
- catch (e) {
1550
- queueMicrotask(() => cb(e));
1551
- }
1552
- }
1553
- else {
1554
- doRm();
1555
- return Promise.resolve();
1556
- }
1557
- },
1558
- exists(path, callback) {
1559
- if (callback) {
1560
- callback(fs.existsSync(path));
1561
- }
1562
- else {
1563
- return Promise.resolve(fs.existsSync(path));
1564
- }
1565
- },
1566
- stat(path, callback) {
1567
- if (callback) {
1568
- // Defer callback to next tick to allow event loop to process stream events
1569
- const cb = callback;
1570
- try {
1571
- const stats = fs.statSync(path);
1572
- queueMicrotask(() => cb(null, stats));
1573
- }
1574
- catch (e) {
1575
- queueMicrotask(() => cb(e));
1576
- }
1577
- }
1578
- else {
1579
- return Promise.resolve(fs.statSync(path));
1580
- }
1581
- },
1582
- lstat(path, callback) {
1583
- if (callback) {
1584
- // Defer callback to next tick to allow event loop to process stream events
1585
- const cb = callback;
1586
- try {
1587
- const stats = fs.lstatSync(path);
1588
- queueMicrotask(() => cb(null, stats));
1589
- }
1590
- catch (e) {
1591
- queueMicrotask(() => cb(e));
1592
- }
1593
- }
1594
- else {
1595
- return Promise.resolve(fs.lstatSync(path));
1596
- }
1597
- },
1598
- unlink(path, callback) {
1599
- if (callback) {
1600
- // Defer callback to next tick to allow event loop to process stream events
1601
- const cb = callback;
1602
- try {
1603
- fs.unlinkSync(path);
1604
- queueMicrotask(() => cb(null));
1605
- }
1606
- catch (e) {
1607
- queueMicrotask(() => cb(e));
1608
- }
1609
- }
1610
- else {
1611
- return Promise.resolve(fs.unlinkSync(path));
1612
- }
1613
- },
1614
- rename(oldPath, newPath, callback) {
1615
- if (callback) {
1616
- // Defer callback to next tick to allow event loop to process stream events
1617
- const cb = callback;
1618
- try {
1619
- fs.renameSync(oldPath, newPath);
1620
- queueMicrotask(() => cb(null));
1621
- }
1622
- catch (e) {
1623
- queueMicrotask(() => cb(e));
1624
- }
1625
- }
1626
- else {
1627
- return Promise.resolve(fs.renameSync(oldPath, newPath));
1628
- }
1629
- },
1630
- copyFile(src, dest, callback) {
1631
- if (callback) {
1632
- try {
1633
- fs.copyFileSync(src, dest);
1634
- callback(null);
1635
- }
1636
- catch (e) {
1637
- callback(e);
1638
- }
1639
- }
1640
- else {
1641
- return Promise.resolve(fs.copyFileSync(src, dest));
1642
- }
1643
- },
1644
- cp(src, dest, options, callback) {
1645
- if (typeof options === "function") {
1646
- callback = options;
1647
- options = undefined;
1648
- }
1649
- if (callback) {
1650
- try {
1651
- fs.cpSync(src, dest, options);
1652
- callback(null);
1653
- }
1654
- catch (e) {
1655
- callback(e);
1656
- }
1657
- }
1658
- else {
1659
- return Promise.resolve(fs.cpSync(src, dest, options));
1660
- }
1661
- },
1662
- mkdtemp(prefix, options, callback) {
1663
- if (typeof options === "function") {
1664
- callback = options;
1665
- options = undefined;
1666
- }
1667
- if (callback) {
1668
- try {
1669
- callback(null, fs.mkdtempSync(prefix, options));
1670
- }
1671
- catch (e) {
1672
- callback(e);
1673
- }
1674
- }
1675
- else {
1676
- return Promise.resolve(fs.mkdtempSync(prefix, options));
1677
- }
1678
- },
1679
- opendir(path, options, callback) {
1680
- if (typeof options === "function") {
1681
- callback = options;
1682
- options = undefined;
1683
- }
1684
- if (callback) {
1685
- try {
1686
- callback(null, fs.opendirSync(path, options));
1687
- }
1688
- catch (e) {
1689
- callback(e);
1690
- }
1691
- }
1692
- else {
1693
- return Promise.resolve(fs.opendirSync(path, options));
1694
- }
1695
- },
1696
- open(path, flags, mode, callback) {
1697
- if (typeof mode === "function") {
1698
- callback = mode;
1699
- mode = undefined;
1700
- }
1701
- if (callback) {
1702
- // Defer callback to next tick to allow event loop to process stream events
1703
- const cb = callback;
1704
- try {
1705
- const fd = fs.openSync(path, flags, mode);
1706
- queueMicrotask(() => cb(null, fd));
1707
- }
1708
- catch (e) {
1709
- queueMicrotask(() => cb(e));
1710
- }
1711
- }
1712
- else {
1713
- return Promise.resolve(fs.openSync(path, flags, mode));
1714
- }
1715
- },
1716
- close(fd, callback) {
1717
- if (callback) {
1718
- // Defer callback to next tick to allow event loop to process stream events
1719
- const cb = callback;
1720
- try {
1721
- fs.closeSync(fd);
1722
- queueMicrotask(() => cb(null));
1723
- }
1724
- catch (e) {
1725
- queueMicrotask(() => cb(e));
1726
- }
1727
- }
1728
- else {
1729
- return Promise.resolve(fs.closeSync(fd));
1730
- }
1731
- },
1732
- read(fd, buffer, offset, length, position, callback) {
1733
- if (callback) {
1734
- // Defer callback to next tick to allow event loop to process stream events
1735
- const cb = callback;
1736
- try {
1737
- const bytesRead = fs.readSync(fd, buffer, offset, length, position);
1738
- queueMicrotask(() => cb(null, bytesRead, buffer));
1739
- }
1740
- catch (e) {
1741
- queueMicrotask(() => cb(e));
1742
- }
1743
- }
1744
- else {
1745
- return Promise.resolve(fs.readSync(fd, buffer, offset, length, position));
1746
- }
1747
- },
1748
- write(fd, buffer, offset, length, position, callback) {
1749
- if (typeof offset === "function") {
1750
- callback = offset;
1751
- offset = undefined;
1752
- length = undefined;
1753
- position = undefined;
1754
- }
1755
- else if (typeof length === "function") {
1756
- callback = length;
1757
- length = undefined;
1758
- position = undefined;
1759
- }
1760
- else if (typeof position === "function") {
1761
- callback = position;
1762
- position = undefined;
1763
- }
1764
- if (callback) {
1765
- // Defer callback to next tick to allow event loop to process stream events
1766
- const cb = callback;
1767
- try {
1768
- const bytesWritten = fs.writeSync(fd, buffer, offset, length, position);
1769
- queueMicrotask(() => cb(null, bytesWritten));
1770
- }
1771
- catch (e) {
1772
- queueMicrotask(() => cb(e));
1773
- }
1774
- }
1775
- else {
1776
- return Promise.resolve(fs.writeSync(fd, buffer, offset, length, position));
1777
- }
1778
- },
1779
- // writev - write multiple buffers to a file descriptor
1780
- writev(fd, buffers, position, callback) {
1781
- if (typeof position === "function") {
1782
- callback = position;
1783
- position = null;
1784
- }
1785
- if (callback) {
1786
- try {
1787
- const bytesWritten = fs.writevSync(fd, buffers, position);
1788
- callback(null, bytesWritten, buffers);
1789
- }
1790
- catch (e) {
1791
- callback(e);
1792
- }
1793
- }
1794
- },
1795
- writevSync(fd, buffers, position) {
1796
- let totalBytesWritten = 0;
1797
- for (const buffer of buffers) {
1798
- const bytes = buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
1799
- totalBytesWritten += fs.writeSync(fd, bytes, 0, bytes.length, position);
1800
- if (position !== null && position !== undefined) {
1801
- position += bytes.length;
1802
- }
1803
- }
1804
- return totalBytesWritten;
1805
- },
1806
- fstat(fd, callback) {
1807
- if (callback) {
1808
- try {
1809
- callback(null, fs.fstatSync(fd));
1810
- }
1811
- catch (e) {
1812
- callback(e);
1813
- }
1814
- }
1815
- else {
1816
- return Promise.resolve(fs.fstatSync(fd));
1817
- }
1818
- },
1819
- // fsync / fdatasync async callback forms
1820
- fsync(fd, callback) {
1821
- if (callback) {
1822
- try {
1823
- fs.fsyncSync(fd);
1824
- callback(null);
1825
- }
1826
- catch (e) {
1827
- callback(e);
1828
- }
1829
- }
1830
- else {
1831
- return Promise.resolve(fs.fsyncSync(fd));
1832
- }
1833
- },
1834
- fdatasync(fd, callback) {
1835
- if (callback) {
1836
- try {
1837
- fs.fdatasyncSync(fd);
1838
- callback(null);
1839
- }
1840
- catch (e) {
1841
- callback(e);
1842
- }
1843
- }
1844
- else {
1845
- return Promise.resolve(fs.fdatasyncSync(fd));
1846
- }
1847
- },
1848
- // readv async callback form
1849
- readv(fd, buffers, position, callback) {
1850
- if (typeof position === "function") {
1851
- callback = position;
1852
- position = null;
1853
- }
1854
- if (callback) {
1855
- try {
1856
- const bytesRead = fs.readvSync(fd, buffers, position);
1857
- callback(null, bytesRead, buffers);
1858
- }
1859
- catch (e) {
1860
- callback(e);
1861
- }
1862
- }
1863
- },
1864
- // statfs async callback form
1865
- statfs(path, options, callback) {
1866
- if (typeof options === "function") {
1867
- callback = options;
1868
- options = undefined;
1869
- }
1870
- if (callback) {
1871
- try {
1872
- callback(null, fs.statfsSync(path, options));
1873
- }
1874
- catch (e) {
1875
- callback(e);
1876
- }
1877
- }
1878
- else {
1879
- return Promise.resolve(fs.statfsSync(path, options));
1880
- }
1881
- },
1882
- // glob async callback form
1883
- glob(pattern, options, callback) {
1884
- if (typeof options === "function") {
1885
- callback = options;
1886
- options = undefined;
1887
- }
1888
- if (callback) {
1889
- try {
1890
- callback(null, fs.globSync(pattern, options));
1891
- }
1892
- catch (e) {
1893
- callback(e);
1894
- }
1895
- }
1896
- },
1897
- // fs.promises API
1898
- // Note: Using async functions to properly catch sync errors and return rejected promises
1899
- promises: {
1900
- async readFile(path, options) {
1901
- return fs.readFileSync(path, options);
1902
- },
1903
- async writeFile(path, data, options) {
1904
- return fs.writeFileSync(path, data, options);
1905
- },
1906
- async appendFile(path, data, options) {
1907
- return fs.appendFileSync(path, data, options);
1908
- },
1909
- async readdir(path, options) {
1910
- return fs.readdirSync(path, options);
1911
- },
1912
- async mkdir(path, options) {
1913
- return fs.mkdirSync(path, options);
1914
- },
1915
- async rmdir(path) {
1916
- return fs.rmdirSync(path);
1917
- },
1918
- async stat(path) {
1919
- return fs.statSync(path);
1920
- },
1921
- async lstat(path) {
1922
- return fs.lstatSync(path);
1923
- },
1924
- async unlink(path) {
1925
- return fs.unlinkSync(path);
1926
- },
1927
- async rename(oldPath, newPath) {
1928
- return fs.renameSync(oldPath, newPath);
1929
- },
1930
- async copyFile(src, dest) {
1931
- return fs.copyFileSync(src, dest);
1932
- },
1933
- async cp(src, dest, options) {
1934
- return fs.cpSync(src, dest, options);
1935
- },
1936
- async mkdtemp(prefix, options) {
1937
- return fs.mkdtempSync(prefix, options);
1938
- },
1939
- async opendir(path, options) {
1940
- return fs.opendirSync(path, options);
1941
- },
1942
- async statfs(path, options) {
1943
- return fs.statfsSync(path, options);
1944
- },
1945
- async glob(pattern, _options) {
1946
- return fs.globSync(pattern, _options);
1947
- },
1948
- async access(path) {
1949
- if (!fs.existsSync(path)) {
1950
- throw createFsError("ENOENT", `ENOENT: no such file or directory, access '${path}'`, "access", path);
1951
- }
1952
- },
1953
- async rm(path, options) {
1954
- return fs.rmSync(path, options);
1955
- },
1956
- async chmod(path, mode) {
1957
- return fs.chmodSync(path, mode);
1958
- },
1959
- async chown(path, uid, gid) {
1960
- return fs.chownSync(path, uid, gid);
1961
- },
1962
- async link(existingPath, newPath) {
1963
- return fs.linkSync(existingPath, newPath);
1964
- },
1965
- async symlink(target, path) {
1966
- return fs.symlinkSync(target, path);
1967
- },
1968
- async readlink(path) {
1969
- return fs.readlinkSync(path);
1970
- },
1971
- async truncate(path, len) {
1972
- return fs.truncateSync(path, len);
1973
- },
1974
- async utimes(path, atime, mtime) {
1975
- return fs.utimesSync(path, atime, mtime);
1976
- },
1977
- },
1978
- // Compatibility methods
1979
- accessSync(path) {
1980
- // existsSync already normalizes the path
1981
- if (!fs.existsSync(path)) {
1982
- throw createFsError("ENOENT", `ENOENT: no such file or directory, access '${path}'`, "access", path);
1983
- }
1984
- },
1985
- access(path, mode, callback) {
1986
- if (typeof mode === "function") {
1987
- callback = mode;
1988
- mode = undefined;
1989
- }
1990
- if (callback) {
1991
- try {
1992
- fs.accessSync(path);
1993
- callback(null);
1994
- }
1995
- catch (e) {
1996
- callback(e);
1997
- }
1998
- }
1999
- else {
2000
- return fs.promises.access(path);
2001
- }
2002
- },
2003
- realpathSync: Object.assign(function realpathSync(path) {
2004
- // Resolve symlinks by walking each path component via lstat + readlink
2005
- const MAX_SYMLINK_DEPTH = 40;
2006
- let symlinksFollowed = 0;
2007
- const raw = toPathString(path);
2008
- // Build initial queue: normalize . and .. segments
2009
- const pending = [];
2010
- for (const seg of raw.split("/")) {
2011
- if (!seg || seg === ".")
2012
- continue;
2013
- if (seg === "..") {
2014
- if (pending.length > 0)
2015
- pending.pop();
2016
- }
2017
- else
2018
- pending.push(seg);
2019
- }
2020
- // Walk each component, resolving symlinks via a queue
2021
- const resolved = [];
2022
- while (pending.length > 0) {
2023
- const seg = pending.shift();
2024
- if (seg === ".")
2025
- continue;
2026
- if (seg === "..") {
2027
- if (resolved.length > 0)
2028
- resolved.pop();
2029
- continue;
2030
- }
2031
- resolved.push(seg);
2032
- const currentPath = "/" + resolved.join("/");
2033
- try {
2034
- const stat = fs.lstatSync(currentPath);
2035
- if (stat.isSymbolicLink()) {
2036
- if (++symlinksFollowed > MAX_SYMLINK_DEPTH) {
2037
- const err = new Error(`ELOOP: too many levels of symbolic links, realpath '${raw}'`);
2038
- err.code = "ELOOP";
2039
- err.syscall = "realpath";
2040
- err.path = raw;
2041
- throw err;
2042
- }
2043
- const target = fs.readlinkSync(currentPath);
2044
- // Prepend target segments to pending for re-resolution
2045
- const targetSegs = target.split("/").filter(Boolean);
2046
- if (target.startsWith("/")) {
2047
- // Absolute symlink — restart from root
2048
- resolved.length = 0;
2049
- }
2050
- else {
2051
- // Relative symlink — drop current component
2052
- resolved.pop();
2053
- }
2054
- // Prepend target segments so they're processed next
2055
- pending.unshift(...targetSegs);
2056
- }
2057
- }
2058
- catch (e) {
2059
- const err = e;
2060
- if (err.code === "ELOOP")
2061
- throw e;
2062
- if (err.code === "ENOENT" || err.code === "ENOTDIR") {
2063
- const enoent = new Error(`ENOENT: no such file or directory, realpath '${raw}'`);
2064
- enoent.code = "ENOENT";
2065
- enoent.syscall = "realpath";
2066
- enoent.path = raw;
2067
- throw enoent;
2068
- }
2069
- break;
2070
- }
2071
- }
2072
- return "/" + resolved.join("/") || "/";
2073
- }, {
2074
- native(path) {
2075
- return fs.realpathSync(path);
2076
- }
2077
- }),
2078
- realpath: Object.assign(function realpath(path, callback) {
2079
- if (callback) {
2080
- callback(null, fs.realpathSync(path));
2081
- }
2082
- else {
2083
- return Promise.resolve(fs.realpathSync(path));
2084
- }
2085
- }, {
2086
- native(path, callback) {
2087
- if (callback) {
2088
- callback(null, fs.realpathSync.native(path));
2089
- }
2090
- else {
2091
- return Promise.resolve(fs.realpathSync.native(path));
2092
- }
2093
- }
2094
- }),
2095
- createReadStream(path, options) {
2096
- const pathStr = typeof path === "string" ? path : path instanceof Buffer ? path.toString() : String(path);
2097
- const opts = typeof options === "string" ? { encoding: options } : options;
2098
- // Use type assertion since our ReadStream has all the methods npm needs
2099
- // but not all the complex overloaded signatures of the full Node.js interface
2100
- return new ReadStream(pathStr, opts);
2101
- },
2102
- createWriteStream(path, options) {
2103
- const pathStr = typeof path === "string" ? path : path instanceof Buffer ? path.toString() : String(path);
2104
- const opts = typeof options === "string" ? { encoding: options } : options;
2105
- // Use type assertion since our WriteStream has all the methods npm needs
2106
- // but not all the complex overloaded signatures of the full Node.js interface
2107
- return new WriteStream(pathStr, opts);
2108
- },
2109
- // Unsupported fs APIs — watch requires kernel-level inotify, use polling instead
2110
- watch(..._args) {
2111
- throw new Error("fs.watch is not supported in sandbox — use polling");
2112
- },
2113
- watchFile(..._args) {
2114
- throw new Error("fs.watchFile is not supported in sandbox — use polling");
2115
- },
2116
- unwatchFile(..._args) {
2117
- throw new Error("fs.unwatchFile is not supported in sandbox — use polling");
2118
- },
2119
- chmod(path, mode, callback) {
2120
- if (callback) {
2121
- try {
2122
- fs.chmodSync(path, mode);
2123
- callback(null);
2124
- }
2125
- catch (e) {
2126
- callback(e);
2127
- }
2128
- }
2129
- else {
2130
- return Promise.resolve(fs.chmodSync(path, mode));
2131
- }
2132
- },
2133
- chown(path, uid, gid, callback) {
2134
- if (callback) {
2135
- try {
2136
- fs.chownSync(path, uid, gid);
2137
- callback(null);
2138
- }
2139
- catch (e) {
2140
- callback(e);
2141
- }
2142
- }
2143
- else {
2144
- return Promise.resolve(fs.chownSync(path, uid, gid));
2145
- }
2146
- },
2147
- link(existingPath, newPath, callback) {
2148
- if (callback) {
2149
- try {
2150
- fs.linkSync(existingPath, newPath);
2151
- callback(null);
2152
- }
2153
- catch (e) {
2154
- callback(e);
2155
- }
2156
- }
2157
- else {
2158
- return Promise.resolve(fs.linkSync(existingPath, newPath));
2159
- }
2160
- },
2161
- symlink(target, path, typeOrCb, callback) {
2162
- if (typeof typeOrCb === "function") {
2163
- callback = typeOrCb;
2164
- }
2165
- if (callback) {
2166
- try {
2167
- fs.symlinkSync(target, path);
2168
- callback(null);
2169
- }
2170
- catch (e) {
2171
- callback(e);
2172
- }
2173
- }
2174
- else {
2175
- return Promise.resolve(fs.symlinkSync(target, path));
2176
- }
2177
- },
2178
- readlink(path, optionsOrCb, callback) {
2179
- if (typeof optionsOrCb === "function") {
2180
- callback = optionsOrCb;
2181
- }
2182
- if (callback) {
2183
- try {
2184
- callback(null, fs.readlinkSync(path));
2185
- }
2186
- catch (e) {
2187
- callback(e);
2188
- }
2189
- }
2190
- else {
2191
- return Promise.resolve(fs.readlinkSync(path));
2192
- }
2193
- },
2194
- truncate(path, lenOrCb, callback) {
2195
- if (typeof lenOrCb === "function") {
2196
- callback = lenOrCb;
2197
- lenOrCb = 0;
2198
- }
2199
- if (callback) {
2200
- try {
2201
- fs.truncateSync(path, lenOrCb);
2202
- callback(null);
2203
- }
2204
- catch (e) {
2205
- callback(e);
2206
- }
2207
- }
2208
- else {
2209
- return Promise.resolve(fs.truncateSync(path, lenOrCb));
2210
- }
2211
- },
2212
- utimes(path, atime, mtime, callback) {
2213
- if (callback) {
2214
- try {
2215
- fs.utimesSync(path, atime, mtime);
2216
- callback(null);
2217
- }
2218
- catch (e) {
2219
- callback(e);
2220
- }
2221
- }
2222
- else {
2223
- return Promise.resolve(fs.utimesSync(path, atime, mtime));
2224
- }
2225
- },
2226
- };
2227
- // Wire late-bound glob helpers to the fs object
2228
- _globReadDir = (dir) => fs.readdirSync(dir);
2229
- _globStat = (path) => fs.statSync(path);
2230
- // Export the fs module
2231
- export default fs;