@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,386 @@
1
+ /**
2
+ * Node.js-compatible fs/promises API.
3
+ *
4
+ * Built on the __exact* globals provided by the C++ Hermes bridge.
5
+ */
6
+
7
+ import { join } from '../node/path';
8
+ import { Dirent } from './Dirent';
9
+ import { Stats } from './Stats';
10
+ import {
11
+ accessNative,
12
+ appendFileBytes,
13
+ chmodNative,
14
+ closeFileDescriptor,
15
+ constants,
16
+ copyFileNative,
17
+ decodeBytes,
18
+ mkdtempNative,
19
+ mkdirNative,
20
+ openFileDescriptor,
21
+ parseReaddir,
22
+ readFileBytes,
23
+ readFileDescriptor,
24
+ realpathNative,
25
+ renameNative,
26
+ rmdirNative,
27
+ runAsync,
28
+ statJson,
29
+ toStats,
30
+ toUint8Array,
31
+ type FileData,
32
+ unlinkNative,
33
+ wrapBuffer,
34
+ writeFileBytes,
35
+ writeFileDescriptor,
36
+ lstatJson,
37
+ symlinkNative,
38
+ linkNative,
39
+ readlinkNative,
40
+ truncateNative,
41
+ utimesNative,
42
+ } from './shared';
43
+
44
+ export { Dirent, Stats, constants };
45
+
46
+ const VALID_SYMLINK_TYPES = new Set(['dir', 'file', 'junction']);
47
+
48
+ function describeArgValue(value: unknown): string {
49
+ if (value === null) {
50
+ return 'null';
51
+ }
52
+ if (value === undefined) {
53
+ return 'undefined';
54
+ }
55
+ if (Array.isArray(value)) {
56
+ return 'an instance of Array';
57
+ }
58
+ if (typeof value === 'function') {
59
+ return value.name ? `function ${value.name}` : 'function';
60
+ }
61
+ if (typeof value === 'object') {
62
+ const ctorName = (value as { constructor?: { name?: string } }).constructor?.name ?? 'Object';
63
+ return `an instance of ${ctorName}`;
64
+ }
65
+ if (typeof value === 'string') {
66
+ return `type string (${value})`;
67
+ }
68
+ if (typeof value === 'number') {
69
+ return `type number (${value})`;
70
+ }
71
+ if (typeof value === 'boolean') {
72
+ return `type boolean (${value})`;
73
+ }
74
+ if (typeof value === 'symbol') {
75
+ return `type symbol (${String(value)})`;
76
+ }
77
+ return `type ${typeof value}`;
78
+ }
79
+
80
+ function assignErrorCode<T extends Error>(error: T, code: string): T {
81
+ (error as T & { code: string }).code = code;
82
+ return error;
83
+ }
84
+
85
+ function makeInvalidArgTypeError(name: string, value: unknown): TypeError {
86
+ return assignErrorCode(
87
+ new TypeError(
88
+ `The "${name}" argument must be of type string or an instance of Buffer or URL. Received ${describeArgValue(value)}`,
89
+ ),
90
+ 'ERR_INVALID_ARG_TYPE',
91
+ );
92
+ }
93
+
94
+ function makeInvalidArgValueError(name: string, value: unknown, reason: string): TypeError {
95
+ let received: string;
96
+ if (typeof value === 'string') {
97
+ received = `'${value}'`;
98
+ } else if (value === undefined) {
99
+ received = 'undefined';
100
+ } else if (value === null) {
101
+ received = 'null';
102
+ } else {
103
+ received = String(value);
104
+ }
105
+ return assignErrorCode(
106
+ new TypeError(`The argument "${name}" must be ${reason}. Received ${received}`),
107
+ 'ERR_INVALID_ARG_VALUE',
108
+ );
109
+ }
110
+
111
+ function makeInvalidUrlSchemeError(): TypeError {
112
+ return assignErrorCode(new TypeError('The URL must be of scheme file'), 'ERR_INVALID_URL_SCHEME');
113
+ }
114
+
115
+ function arrayBufferViewToString(view: ArrayBufferView): string {
116
+ if (typeof Buffer !== 'undefined') {
117
+ return Buffer.from(view.buffer, view.byteOffset, view.byteLength).toString();
118
+ }
119
+ const bytes = new Uint8Array(view.buffer, view.byteOffset, view.byteLength);
120
+ if (typeof TextDecoder !== 'undefined') {
121
+ return new TextDecoder().decode(bytes);
122
+ }
123
+ let result = '';
124
+ for (let i = 0; i < bytes.length; i++) {
125
+ result += String.fromCharCode(bytes[i]);
126
+ }
127
+ return result;
128
+ }
129
+
130
+ function toPathString(value: unknown, name: string): string {
131
+ if (typeof value === 'string') {
132
+ return value;
133
+ }
134
+ if (typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) {
135
+ return value.toString();
136
+ }
137
+ if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && ArrayBuffer.isView(value)) {
138
+ return arrayBufferViewToString(value);
139
+ }
140
+ if (value && typeof value === 'object' && typeof (value as { href?: unknown }).href === 'string') {
141
+ const url = value as { protocol?: unknown; pathname?: unknown };
142
+ if (url.protocol !== 'file:') {
143
+ throw makeInvalidUrlSchemeError();
144
+ }
145
+ let pathname = typeof url.pathname === 'string' ? url.pathname : '';
146
+ if (
147
+ pathname.length >= 3 &&
148
+ pathname[0] === '/' &&
149
+ pathname[2] === ':' &&
150
+ /[A-Za-z]/.test(pathname[1])
151
+ ) {
152
+ pathname = pathname.slice(1);
153
+ }
154
+ return decodeURIComponent(pathname);
155
+ }
156
+ throw makeInvalidArgTypeError(name, value);
157
+ }
158
+
159
+ function validateSymlinkType(type: unknown): void {
160
+ if (type === undefined) {
161
+ return;
162
+ }
163
+ if (typeof type !== 'string' || !VALID_SYMLINK_TYPES.has(type)) {
164
+ throw makeInvalidArgValueError('type', type, "one of: 'dir', 'file', 'junction', or undefined");
165
+ }
166
+ }
167
+
168
+ function normalizeUtimesValue(value: number | Date | string): number {
169
+ if (value instanceof Date) {
170
+ return value.getTime() / 1000;
171
+ }
172
+ if (typeof value === 'string') {
173
+ return Number(value);
174
+ }
175
+ return value;
176
+ }
177
+
178
+ function normalizeRmError<T>(error: T, path?: string, recursive = false): T {
179
+ if (!error || typeof error !== 'object') {
180
+ return error;
181
+ }
182
+ const fsError = error as { syscall?: string; message?: string; code?: string; path?: string };
183
+ if (fsError.syscall === 'rmdir' || fsError.syscall === 'unlink') {
184
+ fsError.syscall = 'rm';
185
+ if (typeof fsError.message === 'string') {
186
+ fsError.message = fsError.message.replace(/, (?:rmdir|unlink) /, ', rm ');
187
+ }
188
+ }
189
+ if (
190
+ recursive &&
191
+ typeof process !== 'undefined' &&
192
+ process.platform === 'darwin' &&
193
+ fsError.code === 'EACCES'
194
+ ) {
195
+ fsError.code = 'ENOTEMPTY';
196
+ fsError.path = path ?? fsError.path;
197
+ if (path) {
198
+ fsError.message = `ENOTEMPTY: directory not empty, rm '${path}'`;
199
+ }
200
+ }
201
+ return error;
202
+ }
203
+
204
+ function rmSyncLike(path: string, options?: { recursive?: boolean; force?: boolean }): void {
205
+ const recursive = options?.recursive === true;
206
+ const force = options?.force === true;
207
+
208
+ try {
209
+ const info = toStats(lstatJson(path));
210
+ if (info.isDirectory()) {
211
+ if (recursive) {
212
+ const entries = parseReaddir(path, false) as string[];
213
+ for (const entry of entries) {
214
+ rmSyncLike(join(path, entry), options);
215
+ }
216
+ }
217
+ try {
218
+ rmdirNative(path);
219
+ } catch (error) {
220
+ throw normalizeRmError(error, path, recursive);
221
+ }
222
+ } else {
223
+ try {
224
+ unlinkNative(path);
225
+ } catch (error) {
226
+ throw normalizeRmError(error, path, recursive);
227
+ }
228
+ }
229
+ } catch (error) {
230
+ const normalizedError = normalizeRmError(error, path, recursive);
231
+ if (
232
+ force &&
233
+ normalizedError &&
234
+ typeof normalizedError === 'object' &&
235
+ (normalizedError as { code?: string }).code === 'ENOENT'
236
+ ) {
237
+ return;
238
+ }
239
+ throw normalizedError;
240
+ }
241
+ }
242
+
243
+ export async function readFile(path: string, options?: { encoding?: string } | string): Promise<Uint8Array | Buffer | string> {
244
+ return runAsync(() => {
245
+ const encoding = typeof options === 'string' ? options : options?.encoding;
246
+ const bytes = readFileBytes(path);
247
+ return encoding ? decodeBytes(bytes, encoding) : wrapBuffer(bytes);
248
+ });
249
+ }
250
+
251
+ export async function writeFile(path: string, data: FileData, _options?: { encoding?: string } | string): Promise<void> {
252
+ return runAsync(() => {
253
+ writeFileBytes(path, toUint8Array(data));
254
+ });
255
+ }
256
+
257
+ export async function appendFile(path: string, data: FileData, _options?: { encoding?: string } | string): Promise<void> {
258
+ return runAsync(() => {
259
+ appendFileBytes(path, toUint8Array(data));
260
+ });
261
+ }
262
+
263
+ export async function stat(path: string): Promise<Stats> {
264
+ return runAsync(() => toStats(statJson(path)));
265
+ }
266
+
267
+ export async function lstat(path: string): Promise<Stats> {
268
+ return runAsync(() => toStats(lstatJson(path)));
269
+ }
270
+
271
+ export async function readdir(path: string, options?: { withFileTypes?: boolean }): Promise<string[] | Dirent[]> {
272
+ return runAsync(() => parseReaddir(path, options?.withFileTypes) as string[] | Dirent[]);
273
+ }
274
+
275
+ export async function mkdir(path: string, options?: { recursive?: boolean } | number): Promise<void> {
276
+ return runAsync(() => {
277
+ const recursive = typeof options === 'object' && options !== null ? !!options.recursive : false;
278
+ mkdirNative(path, recursive);
279
+ });
280
+ }
281
+
282
+ export async function rmdir(path: string): Promise<void> {
283
+ return runAsync(() => rmdirNative(path));
284
+ }
285
+
286
+ export async function rm(path: string, options?: { recursive?: boolean; force?: boolean }): Promise<void> {
287
+ const targetPath = toPathString(path, 'path');
288
+ return runAsync(() => {
289
+ rmSyncLike(targetPath, options);
290
+ });
291
+ }
292
+
293
+ export async function unlink(path: string): Promise<void> {
294
+ return runAsync(() => unlinkNative(path));
295
+ }
296
+
297
+ export async function rename(oldPath: string, newPath: string): Promise<void> {
298
+ return runAsync(() => renameNative(oldPath, newPath));
299
+ }
300
+
301
+ export async function copyFile(src: string, dest: string): Promise<void> {
302
+ return runAsync(() => copyFileNative(src, dest));
303
+ }
304
+
305
+ export async function access(path: string, mode?: number): Promise<void> {
306
+ return runAsync(() => accessNative(path, mode ?? constants.F_OK));
307
+ }
308
+
309
+ export async function chmod(path: string, mode: number): Promise<void> {
310
+ return runAsync(() => chmodNative(path, mode));
311
+ }
312
+
313
+ export async function realpath(path: string): Promise<string> {
314
+ return runAsync(() => realpathNative(path));
315
+ }
316
+
317
+ export async function mkdtemp(prefix: string): Promise<string> {
318
+ return runAsync(() => mkdtempNative(prefix));
319
+ }
320
+
321
+ export async function open(path: string, flags?: string | number, mode?: number): Promise<number> {
322
+ return runAsync(() => openFileDescriptor(path, flags, mode));
323
+ }
324
+
325
+ export async function close(fd: number): Promise<void> {
326
+ return runAsync(() => closeFileDescriptor(fd));
327
+ }
328
+
329
+ export async function read(fd: number, buffer: Uint8Array, offset = 0, length = buffer.byteLength - offset, position?: number | null): Promise<{ bytesRead: number; buffer: Uint8Array }> {
330
+ return runAsync(() => {
331
+ const chunk = readFileDescriptor(fd, length, position);
332
+ buffer.set(chunk, offset);
333
+ return { bytesRead: chunk.byteLength, buffer };
334
+ });
335
+ }
336
+
337
+ export async function write(
338
+ fd: number,
339
+ buffer: string | Uint8Array,
340
+ offsetOrPosition = 0,
341
+ lengthOrEncoding?: number | string,
342
+ position?: number | null,
343
+ ): Promise<{ bytesWritten: number; buffer: string | Uint8Array }> {
344
+ return runAsync(() => {
345
+ if (typeof buffer === 'string') {
346
+ const writePosition = typeof offsetOrPosition === 'number' ? offsetOrPosition : position;
347
+ return {
348
+ bytesWritten: writeFileDescriptor(fd, toUint8Array(buffer), writePosition),
349
+ buffer,
350
+ };
351
+ }
352
+
353
+ const offset = offsetOrPosition;
354
+ const length = typeof lengthOrEncoding === 'number' ? lengthOrEncoding : buffer.byteLength - offset;
355
+ return {
356
+ bytesWritten: writeFileDescriptor(fd, buffer.subarray(offset, offset + length), position),
357
+ buffer,
358
+ };
359
+ });
360
+ }
361
+
362
+ export async function symlink(target: string, path: string, type?: string): Promise<void> {
363
+ const targetPath = toPathString(target, 'target');
364
+ const linkPath = toPathString(path, 'path');
365
+ validateSymlinkType(type);
366
+ return runAsync(() => symlinkNative(targetPath, linkPath));
367
+ }
368
+
369
+ export async function readlink(path: string): Promise<string> {
370
+ return runAsync(() => readlinkNative(path));
371
+ }
372
+
373
+ export async function link(existingPath: string, newPath: string): Promise<void> {
374
+ return runAsync(() => linkNative(existingPath, newPath));
375
+ }
376
+
377
+ export async function truncate(path: string, len = 0): Promise<void> {
378
+ return runAsync(() => truncateNative(path, len));
379
+ }
380
+
381
+ export async function utimes(path: string, atime: number | Date, mtime: number | Date): Promise<void> {
382
+ const targetPath = toPathString(path, 'path');
383
+ return runAsync(() => {
384
+ utimesNative(targetPath, normalizeUtimesValue(atime), normalizeUtimesValue(mtime));
385
+ });
386
+ }
@@ -0,0 +1,328 @@
1
+ // @ts-nocheck
2
+ import { join } from '../node/path';
3
+ import { Dirent } from './Dirent';
4
+ import { Stats } from './Stats';
5
+
6
+ declare global {
7
+ var __exactReadFile: ((path: string) => Uint8Array) | undefined;
8
+ var __exactWriteFile: ((path: string, data: Uint8Array) => void) | undefined;
9
+ var __exactAppendFile: ((path: string, data: Uint8Array) => void) | undefined;
10
+ var __exactStat: ((path: string) => string) | undefined;
11
+ var __exactLstat: ((path: string) => string) | undefined;
12
+ var __exactReaddir: ((path: string) => string) | undefined;
13
+ var __exactMkdir: ((path: string, recursive: boolean) => void) | undefined;
14
+ var __exactRmdir: ((path: string) => void) | undefined;
15
+ var __exactUnlink: ((path: string) => void) | undefined;
16
+ var __exactRename: ((from: string, to: string) => void) | undefined;
17
+ var __exactCopyFile: ((from: string, to: string) => void) | undefined;
18
+ var __exactAccess: ((path: string, mode: number) => void) | undefined;
19
+ var __exactChmod: ((path: string, mode: number) => void) | undefined;
20
+ var __exactRealpath: ((path: string) => string) | undefined;
21
+ var __exactMkdtemp: ((prefix: string) => string) | undefined;
22
+ var __exactFsOpen: ((path: string, flags: number, mode?: number) => number) | undefined;
23
+ var __exactFsClose: ((fd: number) => void) | undefined;
24
+ var __exactFsRead: ((fd: number, length: number, position: number) => Uint8Array) | undefined;
25
+ var __exactFsWrite: ((fd: number, data: Uint8Array, position: number) => number) | undefined;
26
+ var __exactEnsureFs: (() => void) | undefined;
27
+ var __exactSymlink: ((target: string, path: string) => void) | undefined;
28
+ var __exactLink: ((existingPath: string, newPath: string) => void) | undefined;
29
+ var __exactReadlink: ((path: string) => string) | undefined;
30
+ var __exactTruncate: ((path: string, len: number) => void) | undefined;
31
+ var __exactUtimes: ((path: string, atime: number, mtime: number) => void) | undefined;
32
+ }
33
+
34
+ export type BinaryData = Uint8Array | Buffer;
35
+ export type FileData = string | BinaryData;
36
+ export type Callback<T = void> = (err: Error | null, result?: T) => void;
37
+ export type ReadCallback = (err: Error | null, bytesRead: number, buffer: Uint8Array) => void;
38
+ export type WriteCallback = (err: Error | null, bytesWritten: number, buffer: string | Uint8Array) => void;
39
+
40
+ const UTF8_ENCODINGS = new Set(['utf8', 'utf-8']);
41
+
42
+ export const constants = Object.freeze({
43
+ F_OK: 0,
44
+ R_OK: 4,
45
+ W_OK: 2,
46
+ X_OK: 1,
47
+ O_RDONLY: 0,
48
+ O_WRONLY: 1,
49
+ O_RDWR: 2,
50
+ O_CREAT: 0x40,
51
+ O_EXCL: 0x80,
52
+ O_TRUNC: 0x200,
53
+ O_APPEND: 0x400,
54
+ O_DIRECTORY: 0x10000,
55
+ O_NOFOLLOW: 0x20000,
56
+ O_NONBLOCK: 0x800,
57
+ COPYFILE_EXCL: 1,
58
+ S_IFMT: 0o170000,
59
+ S_IFREG: 0o100000,
60
+ S_IFDIR: 0o040000,
61
+ S_IFCHR: 0o020000,
62
+ S_IFBLK: 0o060000,
63
+ S_IFIFO: 0o010000,
64
+ S_IFLNK: 0o120000,
65
+ S_IFSOCK: 0o140000,
66
+ });
67
+
68
+ export function coerceError(err: unknown): Error {
69
+ return err instanceof Error ? err : new Error(String(err));
70
+ }
71
+
72
+ export function queueTask(task: () => void): void {
73
+ if (typeof queueMicrotask === 'function') {
74
+ queueMicrotask(task);
75
+ return;
76
+ }
77
+ Promise.resolve().then(task);
78
+ }
79
+
80
+ export function wrapCallback<T>(fn: () => T, callback: Callback<T>): void {
81
+ queueTask(() => {
82
+ try {
83
+ callback(null, fn());
84
+ } catch (err) {
85
+ callback(coerceError(err));
86
+ }
87
+ });
88
+ }
89
+
90
+ export function runAsync<T>(fn: () => T): Promise<T> {
91
+ return new Promise<T>((resolve, reject) => {
92
+ queueTask(() => {
93
+ try {
94
+ resolve(fn());
95
+ } catch (err) {
96
+ reject(coerceError(err));
97
+ }
98
+ });
99
+ });
100
+ }
101
+
102
+ export function wrapBuffer(bytes: Uint8Array): BinaryData {
103
+ if (typeof Buffer !== 'undefined' && typeof Buffer.from === 'function') {
104
+ return Buffer.isBuffer(bytes)
105
+ ? bytes
106
+ : Buffer.from(bytes);
107
+ }
108
+ return bytes;
109
+ }
110
+
111
+ export function toUint8Array(data: FileData): Uint8Array {
112
+ if (typeof data === 'string') {
113
+ if (typeof TextEncoder !== 'undefined') {
114
+ return new TextEncoder().encode(data);
115
+ }
116
+ const buf = new Uint8Array(data.length * 3);
117
+ let offset = 0;
118
+ for (let i = 0; i < data.length; i++) {
119
+ const code = data.charCodeAt(i);
120
+ if (code < 0x80) {
121
+ buf[offset++] = code;
122
+ } else if (code < 0x800) {
123
+ buf[offset++] = 0xc0 | (code >> 6);
124
+ buf[offset++] = 0x80 | (code & 0x3f);
125
+ } else {
126
+ buf[offset++] = 0xe0 | (code >> 12);
127
+ buf[offset++] = 0x80 | ((code >> 6) & 0x3f);
128
+ buf[offset++] = 0x80 | (code & 0x3f);
129
+ }
130
+ }
131
+ return buf.slice(0, offset);
132
+ }
133
+ if (data instanceof Uint8Array) {
134
+ return data;
135
+ }
136
+ return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
137
+ }
138
+
139
+ export function decodeBytes(bytes: Uint8Array, encoding: string): string {
140
+ const normalized = UTF8_ENCODINGS.has(encoding.toLowerCase()) ? 'utf-8' : encoding;
141
+ if (typeof TextDecoder !== 'undefined') {
142
+ const decoded = new TextDecoder(normalized).decode(bytes);
143
+ if (
144
+ normalized === 'utf-8' &&
145
+ bytes.length >= 3 &&
146
+ bytes[0] === 0xef &&
147
+ bytes[1] === 0xbb &&
148
+ bytes[2] === 0xbf &&
149
+ decoded.charCodeAt(0) !== 0xfeff
150
+ ) {
151
+ return `\uFEFF${decoded}`;
152
+ }
153
+ return decoded;
154
+ }
155
+ let result = '';
156
+ for (let i = 0; i < bytes.length; i++) {
157
+ result += String.fromCharCode(bytes[i]);
158
+ }
159
+ return result;
160
+ }
161
+
162
+ function ensureFsPrimitive<T extends Function>(name: string): T {
163
+ const globalRef = globalThis as any;
164
+ let fn = globalRef[name];
165
+ if (typeof fn !== 'function' && typeof globalRef.__exactEnsureFs === 'function') {
166
+ globalRef.__exactEnsureFs();
167
+ fn = globalRef[name];
168
+ }
169
+ if (typeof fn !== 'function') {
170
+ throw new Error(`${name} is not available in this runtime`);
171
+ }
172
+ return fn as T;
173
+ }
174
+
175
+ export function readFileBytes(path: string): Uint8Array {
176
+ return ensureFsPrimitive<(path: string) => Uint8Array>('__exactReadFile')(path);
177
+ }
178
+
179
+ export function writeFileBytes(path: string, bytes: Uint8Array): void {
180
+ ensureFsPrimitive<(path: string, data: Uint8Array) => void>('__exactWriteFile')(path, bytes);
181
+ }
182
+
183
+ export function appendFileBytes(path: string, bytes: Uint8Array): void {
184
+ ensureFsPrimitive<(path: string, data: Uint8Array) => void>('__exactAppendFile')(path, bytes);
185
+ }
186
+
187
+ export function statJson(path: string): string {
188
+ return ensureFsPrimitive<(path: string) => string>('__exactStat')(path);
189
+ }
190
+
191
+ export function lstatJson(path: string): string {
192
+ return ensureFsPrimitive<(path: string) => string>('__exactLstat')(path);
193
+ }
194
+
195
+ export function readdirJson(path: string): string {
196
+ return ensureFsPrimitive<(path: string) => string>('__exactReaddir')(path);
197
+ }
198
+
199
+ export function mkdirNative(path: string, recursive: boolean): void {
200
+ ensureFsPrimitive<(path: string, recursive: boolean) => void>('__exactMkdir')(path, recursive);
201
+ }
202
+
203
+ export function rmdirNative(path: string): void {
204
+ ensureFsPrimitive<(path: string) => void>('__exactRmdir')(path);
205
+ }
206
+
207
+ export function unlinkNative(path: string): void {
208
+ ensureFsPrimitive<(path: string) => void>('__exactUnlink')(path);
209
+ }
210
+
211
+ export function renameNative(from: string, to: string): void {
212
+ ensureFsPrimitive<(from: string, to: string) => void>('__exactRename')(from, to);
213
+ }
214
+
215
+ export function copyFileNative(from: string, to: string): void {
216
+ ensureFsPrimitive<(from: string, to: string) => void>('__exactCopyFile')(from, to);
217
+ }
218
+
219
+ export function accessNative(path: string, mode: number): void {
220
+ ensureFsPrimitive<(path: string, mode: number) => void>('__exactAccess')(path, mode);
221
+ }
222
+
223
+ export function chmodNative(path: string, mode: number): void {
224
+ ensureFsPrimitive<(path: string, mode: number) => void>('__exactChmod')(path, mode);
225
+ }
226
+
227
+ export function realpathNative(path: string): string {
228
+ return ensureFsPrimitive<(path: string) => string>('__exactRealpath')(path);
229
+ }
230
+
231
+ export function mkdtempNative(prefix: string): string {
232
+ return ensureFsPrimitive<(prefix: string) => string>('__exactMkdtemp')(prefix);
233
+ }
234
+
235
+ export function toStats(json: string): Stats {
236
+ return new Stats(JSON.parse(json));
237
+ }
238
+
239
+ export function parseReaddir(path: string, withFileTypes = false): string[] | Dirent[] {
240
+ const entries = JSON.parse(readdirJson(path)) as string[];
241
+ if (!withFileTypes) {
242
+ return entries;
243
+ }
244
+ return entries.map((name) => new Dirent(name, toStats(lstatJson(join(path, name)))));
245
+ }
246
+
247
+ export function parseOpenFlags(flags?: string | number): number {
248
+ if (typeof flags === 'number') {
249
+ return flags;
250
+ }
251
+
252
+ switch (flags ?? 'r') {
253
+ case 'r':
254
+ return constants.O_RDONLY;
255
+ case 'r+':
256
+ return constants.O_RDWR;
257
+ case 'w':
258
+ return constants.O_TRUNC | constants.O_CREAT | constants.O_WRONLY;
259
+ case 'w+':
260
+ return constants.O_TRUNC | constants.O_CREAT | constants.O_RDWR;
261
+ case 'wx':
262
+ return constants.O_TRUNC | constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY;
263
+ case 'wx+':
264
+ return constants.O_TRUNC | constants.O_CREAT | constants.O_EXCL | constants.O_RDWR;
265
+ case 'a':
266
+ return constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY;
267
+ case 'a+':
268
+ return constants.O_APPEND | constants.O_CREAT | constants.O_RDWR;
269
+ case 'ax':
270
+ return constants.O_APPEND | constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY;
271
+ case 'ax+':
272
+ return constants.O_APPEND | constants.O_CREAT | constants.O_EXCL | constants.O_RDWR;
273
+ default:
274
+ throw new Error(`Unsupported fs open flag: ${flags}`);
275
+ }
276
+ }
277
+
278
+ function normalizePosition(position?: number | null): number {
279
+ return position == null ? -1 : position;
280
+ }
281
+
282
+ export function openFileDescriptor(path: string, flags?: string | number, mode = 0o666): number {
283
+ return ensureFsPrimitive<(path: string, flags: number, mode?: number) => number>('__exactFsOpen')(
284
+ path,
285
+ parseOpenFlags(flags),
286
+ mode,
287
+ );
288
+ }
289
+
290
+ export function closeFileDescriptor(fd: number): void {
291
+ ensureFsPrimitive<(fd: number) => void>('__exactFsClose')(fd);
292
+ }
293
+
294
+ export function readFileDescriptor(fd: number, length: number, position?: number | null): Uint8Array {
295
+ return ensureFsPrimitive<(fd: number, length: number, position: number) => Uint8Array>('__exactFsRead')(
296
+ fd,
297
+ length,
298
+ normalizePosition(position),
299
+ );
300
+ }
301
+
302
+ export function writeFileDescriptor(fd: number, data: Uint8Array, position?: number | null): number {
303
+ return ensureFsPrimitive<(fd: number, data: Uint8Array, position: number) => number>('__exactFsWrite')(
304
+ fd,
305
+ data,
306
+ normalizePosition(position),
307
+ );
308
+ }
309
+
310
+ export function symlinkNative(target: string, path: string): void {
311
+ ensureFsPrimitive<(target: string, path: string) => void>('__exactSymlink')(target, path);
312
+ }
313
+
314
+ export function linkNative(existingPath: string, newPath: string): void {
315
+ ensureFsPrimitive<(existingPath: string, newPath: string) => void>('__exactLink')(existingPath, newPath);
316
+ }
317
+
318
+ export function readlinkNative(path: string): string {
319
+ return ensureFsPrimitive<(path: string) => string>('__exactReadlink')(path);
320
+ }
321
+
322
+ export function truncateNative(path: string, len: number): void {
323
+ ensureFsPrimitive<(path: string, len: number) => void>('__exactTruncate')(path, len);
324
+ }
325
+
326
+ export function utimesNative(path: string, atime: number, mtime: number): void {
327
+ ensureFsPrimitive<(path: string, atime: number, mtime: number) => void>('__exactUtimes')(path, atime, mtime);
328
+ }