opfs-worker 1.3.2 → 2.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 (149) hide show
  1. package/README.md +64 -458
  2. package/dist/BaseOPFS-BPw9AIQ-.cjs +4 -0
  3. package/dist/BaseOPFS-BPw9AIQ-.cjs.map +1 -0
  4. package/dist/BaseOPFS-Cylz6ijk.js +2036 -0
  5. package/dist/BaseOPFS-Cylz6ijk.js.map +1 -0
  6. package/dist/OPFSAsync-BKSAJJeh.js +124 -0
  7. package/dist/OPFSAsync-BKSAJJeh.js.map +1 -0
  8. package/dist/OPFSAsync-s2P7y3sw.cjs +2 -0
  9. package/dist/OPFSAsync-s2P7y3sw.cjs.map +1 -0
  10. package/dist/OPFSFacade-DePnNRgt.cjs +2 -0
  11. package/dist/OPFSFacade-DePnNRgt.cjs.map +1 -0
  12. package/dist/OPFSFacade-XohWlHuu.js +281 -0
  13. package/dist/OPFSFacade-XohWlHuu.js.map +1 -0
  14. package/dist/OPFSSync-C7KBepe_.cjs +2 -0
  15. package/dist/OPFSSync-C7KBepe_.cjs.map +1 -0
  16. package/dist/OPFSSync-CsSQkpk5.js +208 -0
  17. package/dist/OPFSSync-CsSQkpk5.js.map +1 -0
  18. package/dist/assets/dedicated.worker-nY3tK4zi.js.map +1 -0
  19. package/dist/{worker.d.ts → core/BaseOPFS.d.ts} +34 -300
  20. package/dist/core/BaseOPFS.d.ts.map +1 -0
  21. package/dist/core/OPFSAsync.d.ts +55 -0
  22. package/dist/core/OPFSAsync.d.ts.map +1 -0
  23. package/dist/core/OPFSSync.d.ts +54 -0
  24. package/dist/core/OPFSSync.d.ts.map +1 -0
  25. package/dist/createOPFSAsync-BwKDmHsy.cjs +2 -0
  26. package/dist/createOPFSAsync-BwKDmHsy.cjs.map +1 -0
  27. package/dist/createOPFSAsync-Y4Mg6qte.js +10 -0
  28. package/dist/createOPFSAsync-Y4Mg6qte.js.map +1 -0
  29. package/dist/createOPFSDedicated-CsnV6MLP.js +2333 -0
  30. package/dist/createOPFSDedicated-CsnV6MLP.js.map +1 -0
  31. package/dist/createOPFSDedicated-pKTRWLdz.cjs +2283 -0
  32. package/dist/createOPFSDedicated-pKTRWLdz.cjs.map +1 -0
  33. package/dist/createOPFSShared-CGdd__PH.js +23 -0
  34. package/dist/createOPFSShared-CGdd__PH.js.map +1 -0
  35. package/dist/createOPFSShared-CskROt7U.cjs +2 -0
  36. package/dist/createOPFSShared-CskROt7U.cjs.map +1 -0
  37. package/dist/dedicated.worker.js +2281 -0
  38. package/dist/dedicated.worker.js.map +1 -0
  39. package/dist/{facade.d.ts → facade/OPFSFacade.d.ts} +35 -10
  40. package/dist/facade/OPFSFacade.d.ts.map +1 -0
  41. package/dist/facade/createOPFSAsync.d.ts +16 -0
  42. package/dist/facade/createOPFSAsync.d.ts.map +1 -0
  43. package/dist/facade/createOPFSDedicated.d.ts +17 -0
  44. package/dist/facade/createOPFSDedicated.d.ts.map +1 -0
  45. package/dist/facade/createOPFSShared.d.ts +24 -0
  46. package/dist/facade/createOPFSShared.d.ts.map +1 -0
  47. package/dist/index.async.cjs +2 -0
  48. package/dist/index.async.cjs.map +1 -0
  49. package/dist/index.async.d.ts +10 -0
  50. package/dist/index.async.d.ts.map +1 -0
  51. package/dist/index.async.js +55 -0
  52. package/dist/index.async.js.map +1 -0
  53. package/dist/index.cjs +1 -2466
  54. package/dist/index.cjs.map +1 -1
  55. package/dist/index.d.ts +15 -7
  56. package/dist/index.d.ts.map +1 -1
  57. package/dist/index.js +61 -2799
  58. package/dist/index.js.map +1 -1
  59. package/dist/index.pure.cjs +2 -0
  60. package/dist/index.pure.cjs.map +1 -0
  61. package/dist/index.pure.d.ts +8 -0
  62. package/dist/index.pure.d.ts.map +1 -0
  63. package/dist/index.pure.js +53 -0
  64. package/dist/index.pure.js.map +1 -0
  65. package/dist/index.sharedworker.cjs +2 -0
  66. package/dist/index.sharedworker.cjs.map +1 -0
  67. package/dist/index.sharedworker.d.ts +11 -0
  68. package/dist/index.sharedworker.d.ts.map +1 -0
  69. package/dist/index.sharedworker.js +55 -0
  70. package/dist/index.sharedworker.js.map +1 -0
  71. package/dist/index.sync.cjs +2 -0
  72. package/dist/index.sync.cjs.map +1 -0
  73. package/dist/index.sync.d.ts +11 -0
  74. package/dist/index.sync.d.ts.map +1 -0
  75. package/dist/index.sync.js +55 -0
  76. package/dist/index.sync.js.map +1 -0
  77. package/dist/shared.worker.js +2166 -0
  78. package/dist/shared.worker.js.map +1 -0
  79. package/dist/types.d.ts +9 -4
  80. package/dist/types.d.ts.map +1 -1
  81. package/dist/utils/helpers.d.ts +11 -1
  82. package/dist/utils/helpers.d.ts.map +1 -1
  83. package/dist/worker/createDedicatedWorker.d.ts +30 -0
  84. package/dist/worker/createDedicatedWorker.d.ts.map +1 -0
  85. package/dist/worker/createSharedWorker.d.ts +37 -0
  86. package/dist/worker/createSharedWorker.d.ts.map +1 -0
  87. package/dist/worker/dedicated.worker.d.ts +2 -0
  88. package/dist/worker/dedicated.worker.d.ts.map +1 -0
  89. package/dist/worker/shared.worker.d.ts +2 -0
  90. package/dist/worker/shared.worker.d.ts.map +1 -0
  91. package/docs/README.md +30 -0
  92. package/docs/api/backend.md +36 -0
  93. package/docs/api/create.md +82 -0
  94. package/docs/api/facade.md +52 -0
  95. package/docs/choosing-a-mode.md +41 -0
  96. package/docs/file-descriptors.md +695 -0
  97. package/docs/guides/async.md +36 -0
  98. package/docs/guides/dedicated.md +76 -0
  99. package/docs/guides/hashing.md +34 -0
  100. package/docs/guides/pure.md +46 -0
  101. package/docs/guides/sharedworker.md +57 -0
  102. package/docs/guides/streaming.md +51 -0
  103. package/docs/guides/watching.md +35 -0
  104. package/docs/migration.md +41 -0
  105. package/docs/types.md +246 -0
  106. package/package.json +55 -10
  107. package/src/core/BaseOPFS.ts +951 -0
  108. package/src/core/OPFSAsync.ts +248 -0
  109. package/src/core/OPFSSync.ts +460 -0
  110. package/src/facade/OPFSFacade.ts +489 -0
  111. package/src/facade/createOPFSAsync.ts +22 -0
  112. package/src/facade/createOPFSDedicated.ts +23 -0
  113. package/src/facade/createOPFSShared.ts +30 -0
  114. package/src/index.async.ts +11 -0
  115. package/src/index.pure.ts +8 -0
  116. package/src/index.sharedworker.ts +12 -0
  117. package/src/index.sync.ts +12 -0
  118. package/src/index.ts +44 -0
  119. package/src/types.ts +103 -0
  120. package/src/utils/encoder.ts +205 -0
  121. package/src/utils/errors.ts +297 -0
  122. package/src/utils/helpers.ts +465 -0
  123. package/src/worker/createDedicatedWorker.ts +74 -0
  124. package/src/worker/createSharedWorker.ts +67 -0
  125. package/src/worker/dedicated.worker.ts +13 -0
  126. package/src/worker/shared.worker.ts +17 -0
  127. package/dist/assets/worker-1Wh1cr7P.js.map +0 -1
  128. package/dist/assets/worker-BeJaVyBV.js.map +0 -1
  129. package/dist/assets/worker-DYYLzR1Y.js.map +0 -1
  130. package/dist/facade.d.ts.map +0 -1
  131. package/dist/helpers-BuGfPAg0.js +0 -1439
  132. package/dist/helpers-BuGfPAg0.js.map +0 -1
  133. package/dist/helpers-CF7A2WQG.cjs +0 -4
  134. package/dist/helpers-CF7A2WQG.cjs.map +0 -1
  135. package/dist/helpers-CIiblZ8d.cjs +0 -4
  136. package/dist/helpers-CIiblZ8d.cjs.map +0 -1
  137. package/dist/helpers-CKOebsbw.js +0 -1423
  138. package/dist/helpers-CKOebsbw.js.map +0 -1
  139. package/dist/helpers-Ca2c767K.js +0 -1427
  140. package/dist/helpers-Ca2c767K.js.map +0 -1
  141. package/dist/helpers-Dwc92hv9.cjs +0 -4
  142. package/dist/helpers-Dwc92hv9.cjs.map +0 -1
  143. package/dist/raw.cjs +0 -2
  144. package/dist/raw.cjs.map +0 -1
  145. package/dist/raw.d.ts +0 -13
  146. package/dist/raw.d.ts.map +0 -1
  147. package/dist/raw.js +0 -1001
  148. package/dist/raw.js.map +0 -1
  149. package/dist/worker.d.ts.map +0 -1
@@ -0,0 +1,951 @@
1
+ import { WatchEventType } from '../types';
2
+ import {
3
+ AlreadyExistsError,
4
+ DirectoryOperationError,
5
+ ExistenceError,
6
+ FileSystemOperationError,
7
+ FileTypeError,
8
+ InitializationFailedError,
9
+ OPFSError,
10
+ OperationNotSupportedError,
11
+ PathError,
12
+ mapDomError
13
+ } from '../utils/errors';
14
+
15
+ import {
16
+ basename,
17
+ calculateFileHash,
18
+ checkOPFSSupport,
19
+ convertBlobToUint8Array,
20
+ dirname,
21
+ joinPath,
22
+ matchMinimatch,
23
+ normalizeMinimatch,
24
+ normalizePath,
25
+ removeEntry,
26
+ resolvePath,
27
+ splitPath
28
+ } from '../utils/helpers';
29
+
30
+ import type { DirentData, FileStat, OPFSOptions, RenameOptions, WatchEvent, WatchOptions, WatchSnapshot } from '../types';
31
+
32
+
33
+ /**
34
+ * Shared OPFS logic (directories, meta, watch, high-level helpers).
35
+ * File I/O backends implement {@link readFile}, {@link writeFile}, {@link appendFile},
36
+ * and {@link writeStream}.
37
+ */
38
+ export abstract class BaseOPFS {
39
+ /** Root directory handle for the file system */
40
+ protected root!: FileSystemDirectoryHandle;
41
+
42
+ /** Map of watched paths and options */
43
+ protected watchers = new Map<string, WatchSnapshot>();
44
+
45
+ /** Promise to prevent concurrent mount operations */
46
+ protected mountingPromise: Promise<boolean> | null = null;
47
+
48
+ /** BroadcastChannel instance for sending events */
49
+ protected broadcastChannel: BroadcastChannel | null = null;
50
+
51
+ /** Configuration options */
52
+ protected options: Required<OPFSOptions> = {
53
+ root: '/',
54
+ namespace: '',
55
+ maxFileSize: 50 * 1024 * 1024,
56
+ hashAlgorithm: 'etag',
57
+ broadcastChannel: 'opfs-worker',
58
+ };
59
+
60
+ /**
61
+ * Notify about internal changes to the file system
62
+ *
63
+ * This method is called by internal operations to notify clients about
64
+ * changes, even when no specific paths are being watched.
65
+ *
66
+ * @param event - The event describing the change
67
+ */
68
+ protected async notifyChange(event: Omit<WatchEvent, 'timestamp' | 'hash' | 'namespace'>): Promise<void> {
69
+ // This instance not configured to send events
70
+ if (!this.options.broadcastChannel) {
71
+ return;
72
+ }
73
+
74
+ const path = event.path;
75
+
76
+ const match = [...this.watchers.values()].some((snapshot) => {
77
+ return (
78
+ matchMinimatch(path, snapshot.pattern)
79
+ && snapshot.include.some(include => include && matchMinimatch(path, include))
80
+ && !snapshot.exclude.some(exclude => exclude && matchMinimatch(path, exclude))
81
+ );
82
+ });
83
+
84
+ if (!match) {
85
+ return;
86
+ }
87
+
88
+ let hash: string | undefined;
89
+
90
+ if (this.options.hashAlgorithm) {
91
+ try {
92
+ const stat = await this.stat(path);
93
+
94
+ hash = stat.hash;
95
+ }
96
+ catch {}
97
+ }
98
+
99
+ // Send event via BroadcastChannel
100
+ try {
101
+ if (!this.broadcastChannel) {
102
+ this.broadcastChannel = new BroadcastChannel(this.options.broadcastChannel as string);
103
+ }
104
+
105
+ const watchEvent: WatchEvent = {
106
+ namespace: this.options.namespace,
107
+ timestamp: new Date().toISOString(),
108
+ ...event,
109
+ ...(hash && { hash }),
110
+ };
111
+
112
+ this.broadcastChannel.postMessage(watchEvent);
113
+ }
114
+ catch (error) {
115
+ console.warn('Failed to send event via BroadcastChannel:', error);
116
+ }
117
+ }
118
+
119
+ constructor(options?: OPFSOptions) {
120
+ checkOPFSSupport();
121
+
122
+ if (options) {
123
+ void this.setOptions(options);
124
+ }
125
+ }
126
+
127
+ /** Read file contents as bytes */
128
+ abstract readFile(path: string): Promise<Uint8Array>;
129
+
130
+ /** Create or overwrite a file with binary data */
131
+ abstract writeFile(path: string, data: Uint8Array | ArrayBuffer): Promise<void>;
132
+
133
+ /** Append binary data to a file */
134
+ abstract appendFile(path: string, data: Uint8Array | ArrayBuffer): Promise<void>;
135
+
136
+ /** Create or overwrite a file from a byte stream */
137
+ abstract writeStream(
138
+ path: string,
139
+ stream: ReadableStream<Uint8Array>,
140
+ onProgress?: (bytesWritten: number) => unknown
141
+ ): Promise<number>;
142
+
143
+ /**
144
+ * Initialize the file system within a given directory.
145
+ * If no root is specified, uses the OPFS root directory.
146
+ */
147
+ protected async mount(): Promise<boolean> {
148
+ const root = this.options.root;
149
+
150
+ // If already mounting, wait for previous operation to complete first
151
+ if (this.mountingPromise) {
152
+ await this.mountingPromise;
153
+ }
154
+
155
+ // eslint-disable-next-line no-async-promise-executor
156
+ this.mountingPromise = new Promise<boolean>(async(resolve, reject) => {
157
+ try {
158
+ const rootDir = await navigator.storage.getDirectory();
159
+
160
+ this.root = (root === '/') ? rootDir : await this.getDirectoryHandle(root, true, rootDir);
161
+
162
+ resolve(true);
163
+ }
164
+ catch (error) {
165
+ reject(new InitializationFailedError(root, error));
166
+ }
167
+ finally {
168
+ this.mountingPromise = null;
169
+ }
170
+ });
171
+
172
+ return this.mountingPromise;
173
+ }
174
+
175
+
176
+ /**
177
+ * Update configuration options
178
+ *
179
+ * @param options - Configuration options to update
180
+ * @param options.root - Root path for the file system
181
+ * @param options.watchInterval - Polling interval in milliseconds for file watching
182
+ * @param options.hashAlgorithm - Hash algorithm for file hashing
183
+ * @param options.maxFileSize - Maximum file size for hashing in bytes
184
+ * @param options.broadcastChannel - Custom name for the broadcast channel
185
+ */
186
+ async setOptions(options: OPFSOptions): Promise<void> {
187
+ if (options.hashAlgorithm !== undefined) {
188
+ this.options.hashAlgorithm = options.hashAlgorithm;
189
+ }
190
+
191
+ if (options.maxFileSize !== undefined) {
192
+ this.options.maxFileSize = options.maxFileSize;
193
+ }
194
+
195
+ if (options.broadcastChannel !== undefined) {
196
+ // Close existing channel if name changed
197
+ if (this.broadcastChannel && this.options.broadcastChannel !== options.broadcastChannel) {
198
+ this.broadcastChannel.close();
199
+ this.broadcastChannel = null;
200
+ }
201
+
202
+ this.options.broadcastChannel = options.broadcastChannel;
203
+ }
204
+
205
+ if (options.namespace) {
206
+ this.options.namespace = options.namespace;
207
+ }
208
+
209
+ if (options.root !== undefined) {
210
+ this.options.root = normalizePath(options.root);
211
+
212
+ if (!this.options.namespace) {
213
+ this.options.namespace = `opfs-worker:${ this.options.root }`;
214
+ }
215
+
216
+ await this.mount();
217
+ }
218
+ }
219
+
220
+ /**
221
+ * Get a directory handle from a path
222
+ *
223
+ * Navigates through the directory structure to find or create a directory
224
+ * at the specified path.
225
+ *
226
+ * @param path - The path to the directory (string or array of segments)
227
+ * @param create - Whether to create the directory if it doesn't exist (default: false)
228
+ * @param from - The directory to start from (default: root directory)
229
+ * @returns Promise that resolves to the directory handle
230
+ * @throws {OPFSError} If the directory cannot be accessed or created
231
+ *
232
+ * @example
233
+ * ```typescript
234
+ * const docsDir = await fs.getDirectoryHandle('/users/john/documents', true);
235
+ * const docsDir2 = await fs.getDirectoryHandle(['users', 'john', 'documents'], true);
236
+ * ```
237
+ */
238
+ protected async getDirectoryHandle(path: string | string[], create: boolean = false, from: FileSystemDirectoryHandle | null = this.root): Promise<FileSystemDirectoryHandle> {
239
+ const segments = Array.isArray(path) ? path : splitPath(path);
240
+ let current = from;
241
+
242
+ for (const segment of segments) {
243
+ current = await current!.getDirectoryHandle(segment, { create });
244
+ }
245
+
246
+ return current!;
247
+ }
248
+
249
+ /**
250
+ * Get a file handle from a path
251
+ *
252
+ * Navigates to the parent directory and retrieves or creates a file handle
253
+ * for the specified file path.
254
+ *
255
+ * @param path - The path to the file (string or array of segments)
256
+ * @param create - Whether to create the file if it doesn't exist (default: false)
257
+ * @param _from - The directory to start from (default: root directory)
258
+ * @returns Promise that resolves to the file handle
259
+ * @throws {PathError} If the path is empty
260
+ * @throws {OPFSError} If the file cannot be accessed or created
261
+ *
262
+ * @example
263
+ * ```typescript
264
+ * const fileHandle = await fs.getFileHandle('/config/settings.json', true);
265
+ * const fileHandle2 = await fs.getFileHandle(['config', 'settings.json'], true);
266
+ * ```
267
+ */
268
+ protected async getFileHandle(path: string | string[], create = false, _from: FileSystemDirectoryHandle | null = this.root): Promise<FileSystemFileHandle> {
269
+ const segments = splitPath(path);
270
+
271
+ if (segments.length === 0) {
272
+ throw new PathError('Path must not be empty', Array.isArray(path) ? path.join('/') : path);
273
+ }
274
+
275
+ const fileName = segments.pop()!;
276
+ const dir = await this.getDirectoryHandle(segments, create, _from);
277
+
278
+ return dir.getFileHandle(fileName, { create });
279
+ }
280
+
281
+ /**
282
+ * Get a complete index of all files and directories in the file system
283
+ *
284
+ * This method recursively traverses the entire file system and returns
285
+ * a Map containing FileStat objects for every file and directory.
286
+ *
287
+ * @returns Promise that resolves to a Map of paths to FileStat objects
288
+ * @throws {OPFSError} If the file system is not mounted
289
+ *
290
+ * @example
291
+ * ```typescript
292
+ * const index = await fs.index();
293
+ * const fileStats = index.get('/data/config.json');
294
+ * if (fileStats) {
295
+ * console.log(`File size: ${fileStats.size} bytes`);
296
+ * if (fileStats.hash) console.log(`Hash: ${fileStats.hash}`);
297
+ * }
298
+ * ```
299
+ */
300
+ async index(): Promise<Map<string, FileStat>> {
301
+ const result = new Map<string, FileStat>();
302
+
303
+ const walk = async(dirPath: string) => {
304
+ const items = await this.readDir(dirPath);
305
+
306
+ for (const item of items) {
307
+ const fullPath = `${ dirPath === '/' ? '' : dirPath }/${ item.name }`;
308
+
309
+ try {
310
+ const stat = await this.stat(fullPath);
311
+
312
+ result.set(fullPath, stat);
313
+
314
+ if (stat.isDirectory) {
315
+ await walk(fullPath);
316
+ }
317
+ }
318
+ catch (err) {
319
+ console.warn(`Skipping broken entry: ${ fullPath }`, err);
320
+ }
321
+ }
322
+ };
323
+
324
+ result.set('/', {
325
+ kind: 'directory',
326
+ size: 0,
327
+ mtime: new Date(0).toISOString(),
328
+ ctime: new Date(0).toISOString(),
329
+ isFile: false,
330
+ isDirectory: true,
331
+ });
332
+
333
+ await walk('/');
334
+
335
+ return result;
336
+ }
337
+
338
+ /**
339
+ * Create a directory
340
+ *
341
+ * Creates a new directory at the specified path. If the recursive option
342
+ * is enabled, parent directories will be created as needed.
343
+ *
344
+ * @param path - The path where the directory should be created
345
+ * @param options - Options for directory creation
346
+ * @param options.recursive - Whether to create parent directories if they don't exist (default: false)
347
+ * @returns Promise that resolves when the directory is created
348
+ * @throws {OPFSError} If the directory cannot be created
349
+ *
350
+ * @example
351
+ * ```typescript
352
+ * // Create a single directory
353
+ * await fs.mkdir('/users/john');
354
+ *
355
+ * // Create nested directories
356
+ * await fs.mkdir('/users/john/documents/projects', { recursive: true });
357
+ * ```
358
+ */
359
+ async mkdir(path: string, options?: { recursive?: boolean }): Promise<void> {
360
+ await this.mount();
361
+
362
+ const recursive = options?.recursive ?? false;
363
+ const segments = splitPath(path);
364
+
365
+ let current: FileSystemDirectoryHandle | null = this.root;
366
+
367
+ for (let i = 0; i < segments.length; i++) {
368
+ const segment = segments[i];
369
+
370
+ try {
371
+ current = await current.getDirectoryHandle(segment!, { create: recursive || i === segments.length - 1 });
372
+ }
373
+ catch (err: any) {
374
+ if (err.name === 'NotFoundError') {
375
+ throw mapDomError(err, {
376
+ path: joinPath(segments.slice(0, i + 1)),
377
+ existenceType: 'directory',
378
+ });
379
+ }
380
+
381
+ if (err.name === 'TypeMismatchError') {
382
+ throw mapDomError(err, { path: segment!, isDirectory: false });
383
+ }
384
+
385
+ throw new FileSystemOperationError('create directory', segment!, err);
386
+ }
387
+ }
388
+
389
+ await this.notifyChange({ path, type: WatchEventType.Added, isDirectory: true });
390
+ }
391
+
392
+ /**
393
+ * Get file or directory statistics
394
+ *
395
+ * Returns detailed information about a file or directory, including
396
+ * size, modification time, and optionally a hash of the file content.
397
+ *
398
+ * @param path - The path to the file or directory
399
+ * @returns Promise that resolves to FileStat object
400
+ * @throws {OPFSError} If the path does not exist or cannot be accessed
401
+ *
402
+ * @example
403
+ * ```typescript
404
+ * const stats = await fs.stat('/data/config.json');
405
+ * console.log(`File size: ${stats.size} bytes`);
406
+ * console.log(`Last modified: ${stats.mtime}`);
407
+ *
408
+ * // If hashing is enabled, hash will be included
409
+ * if (stats.hash) {
410
+ * console.log(`Hash: ${stats.hash}`);
411
+ * }
412
+ * ```
413
+ */
414
+ async stat(path: string): Promise<FileStat> {
415
+ await this.mount();
416
+
417
+ // Special handling for root directory
418
+ if (path === '/') {
419
+ return {
420
+ kind: 'directory',
421
+ size: 0,
422
+ mtime: new Date(0).toISOString(),
423
+ ctime: new Date(0).toISOString(),
424
+ isFile: false,
425
+ isDirectory: true,
426
+ };
427
+ }
428
+
429
+ const name = basename(path);
430
+ let parentDir: FileSystemDirectoryHandle;
431
+
432
+ try {
433
+ parentDir = await this.getDirectoryHandle(dirname(path), false);
434
+ const hashAlgorithm = this.options.hashAlgorithm;
435
+
436
+ const fileHandle = await parentDir.getFileHandle(name, { create: false });
437
+ const file = await fileHandle.getFile();
438
+
439
+ const baseStat: FileStat = {
440
+ kind: 'file',
441
+ size: file.size,
442
+ mtime: new Date(file.lastModified).toISOString(),
443
+ ctime: new Date(file.lastModified).toISOString(),
444
+ isFile: true,
445
+ isDirectory: false,
446
+ };
447
+
448
+ if (hashAlgorithm === 'etag') {
449
+ baseStat.hash = `${ file.lastModified.toString(36) }-${ file.size.toString(36) }`;
450
+ }
451
+ // Crypto hash
452
+ else if (typeof hashAlgorithm === 'string') {
453
+ try {
454
+ const hash = await calculateFileHash(file, hashAlgorithm, this.options.maxFileSize);
455
+
456
+ baseStat.hash = hash;
457
+ }
458
+ catch (error) {
459
+ console.warn(`Failed to calculate hash for ${ path }:`, error);
460
+ }
461
+ }
462
+
463
+ return baseStat;
464
+ }
465
+ catch (e: any) {
466
+ if (e.name === 'NotFoundError') {
467
+ throw new ExistenceError('file', path, e);
468
+ }
469
+
470
+ if (e.name !== 'TypeMismatchError') {
471
+ throw new FileSystemOperationError('stat', path, e);
472
+ }
473
+ }
474
+
475
+ try {
476
+ await parentDir!.getDirectoryHandle(name, { create: false });
477
+
478
+ return {
479
+ kind: 'directory',
480
+ size: 0,
481
+ mtime: new Date(0).toISOString(),
482
+ ctime: new Date(0).toISOString(),
483
+ isFile: false,
484
+ isDirectory: true,
485
+ };
486
+ }
487
+ catch (e: any) {
488
+ throw new FileSystemOperationError('stat', path, e);
489
+ }
490
+ }
491
+
492
+ /**
493
+ * Read a directory's contents
494
+ *
495
+ * Lists all files and subdirectories within the specified directory.
496
+ *
497
+ * @param path - The path to the directory to read
498
+ * @returns Promise that resolves to an array of detailed file/directory information
499
+ * @throws {OPFSError} If the directory does not exist or cannot be accessed
500
+ *
501
+ * @example
502
+ * ```typescript
503
+ * // Get detailed information about files and directories
504
+ * const detailed = await fs.readDir('/users/john/documents');
505
+ * detailed.forEach(item => {
506
+ * console.log(`${item.name} - ${item.isFile ? 'file' : 'directory'}`);
507
+ * });
508
+ * ```
509
+ */
510
+ async readDir(path: string): Promise<DirentData[]> {
511
+ await this.mount();
512
+
513
+ const dir = await this.getDirectoryHandle(path, false);
514
+
515
+ const results: DirentData[] = [];
516
+
517
+ for await (const [name, handle] of (dir as any).entries()) {
518
+ const isFile = handle.kind === 'file';
519
+
520
+ results.push({
521
+ name,
522
+ kind: handle.kind,
523
+ isFile,
524
+ isDirectory: !isFile,
525
+ });
526
+ }
527
+
528
+ return results;
529
+ }
530
+
531
+ /**
532
+ * Check if a file or directory exists
533
+ *
534
+ * Verifies if a file or directory exists at the specified path.
535
+ *
536
+ * @param path - The path to check
537
+ * @returns Promise that resolves to true if the file or directory exists, false otherwise
538
+ *
539
+ * @example
540
+ * ```typescript
541
+ * const exists = await fs.exists('/config/settings.json');
542
+ * console.log(`File exists: ${exists}`);
543
+ * ```
544
+ */
545
+ async exists(path: string): Promise<boolean> {
546
+ await this.mount();
547
+
548
+ if (path === '/') {
549
+ return true;
550
+ }
551
+
552
+ const name = basename(path);
553
+ let dir: FileSystemDirectoryHandle | null = null;
554
+
555
+ try {
556
+ dir = await this.getDirectoryHandle(dirname(path), false);
557
+ }
558
+ catch (e: any) {
559
+ dir = null;
560
+
561
+ if (e.name !== 'NotFoundError' && e.name !== 'TypeMismatchError') {
562
+ throw e;
563
+ }
564
+ }
565
+
566
+ if (!dir || !name) {
567
+ return false;
568
+ }
569
+
570
+ try {
571
+ await dir.getFileHandle(name, { create: false });
572
+
573
+ return true;
574
+ }
575
+ catch (err: any) {
576
+ if (err.name !== 'NotFoundError' && err.name !== 'TypeMismatchError') {
577
+ throw err;
578
+ }
579
+
580
+ try {
581
+ await dir.getDirectoryHandle(name, { create: false });
582
+
583
+ return true;
584
+ }
585
+ catch (err: any) {
586
+ if (err.name !== 'NotFoundError' && err.name !== 'TypeMismatchError') {
587
+ throw err;
588
+ }
589
+
590
+ return false;
591
+ }
592
+ }
593
+ }
594
+
595
+ /**
596
+ * Clear all contents of a directory without removing the directory itself
597
+ *
598
+ * Removes all files and subdirectories within the specified directory,
599
+ * but keeps the directory itself.
600
+ *
601
+ * @param path - The path to the directory to clear (default: '/')
602
+ * @returns Promise that resolves when all contents are removed
603
+ * @throws {OPFSError} If the operation fails
604
+ *
605
+ * @example
606
+ * ```typescript
607
+ * // Clear root directory contents
608
+ * await fs.clear('/');
609
+ *
610
+ * // Clear specific directory contents
611
+ * await fs.clear('/data');
612
+ * ```
613
+ */
614
+ async clear(path: string = '/'): Promise<void> {
615
+ await this.mount();
616
+
617
+ try {
618
+ const items = await this.readDir(path);
619
+
620
+ for (const item of items) {
621
+ const itemPath = `${ path === '/' ? '' : path }/${ item.name }`;
622
+
623
+ await this.remove(itemPath, { recursive: true });
624
+ }
625
+
626
+ await this.notifyChange({ path, type: WatchEventType.Changed, isDirectory: true });
627
+ }
628
+ catch (error: any) {
629
+ if (error instanceof OPFSError) {
630
+ throw error;
631
+ }
632
+
633
+ throw mapDomError(error, { path, isDirectory: true });
634
+ }
635
+ }
636
+
637
+ /**
638
+ * Remove files and directories
639
+ *
640
+ * Removes files and directories. Similar to Node.js fs.rm().
641
+ *
642
+ * @param path - The path to remove
643
+ * @param options - Options for removal
644
+ * @param options.recursive - Whether to remove directories and their contents recursively (default: false)
645
+ * @param options.force - Whether to ignore errors if the path doesn't exist (default: false)
646
+ * @returns Promise that resolves when the removal is complete
647
+ * @throws {OPFSError} If the removal fails
648
+ *
649
+ * @example
650
+ * ```typescript
651
+ * // Remove a file
652
+ * await fs.rm('/path/to/file.txt');
653
+ *
654
+ * // Remove a directory and all its contents
655
+ * await fs.rm('/path/to/directory', { recursive: true });
656
+ *
657
+ * // Remove with force (ignore if doesn't exist)
658
+ * await fs.rm('/maybe/exists', { force: true });
659
+ * ```
660
+ */
661
+ async remove(path: string, options?: { recursive?: boolean; force?: boolean }): Promise<void> {
662
+ await this.mount();
663
+
664
+ // Special handling for root directory
665
+ if (path === '/') {
666
+ throw new DirectoryOperationError('EROOT', path);
667
+ }
668
+
669
+ const { recursive = false, force = false } = options || {};
670
+
671
+ const parent = await this.getDirectoryHandle(dirname(path), false);
672
+ const stat = await this.stat(path);
673
+
674
+ await removeEntry(parent, path, { recursive, force });
675
+
676
+ await this.notifyChange({ path, type: WatchEventType.Removed, isDirectory: stat.isDirectory });
677
+ }
678
+
679
+ /**
680
+ * Resolve a path to an absolute path
681
+ *
682
+ * Resolves relative paths and normalizes path segments (like '..' and '.').
683
+ * Similar to Node.js fs.realpath() but without symlink resolution since OPFS doesn't support symlinks.
684
+ *
685
+ * @param path - The path to resolve
686
+ * @returns Promise that resolves to the absolute normalized path
687
+ * @throws {FileNotFoundError} If the path does not exist
688
+ * @throws {OPFSError} If path resolution fails
689
+ *
690
+ * @example
691
+ * ```typescript
692
+ * // Resolve relative path
693
+ * const absolute = await fs.realpath('./config/../data/file.txt');
694
+ * console.log(absolute); // '/data/file.txt'
695
+ * ```
696
+ */
697
+ async realpath(path: string): Promise<string> {
698
+ await this.mount();
699
+
700
+ try {
701
+ const normalizedPath = resolvePath(path);
702
+ const exists = await this.exists(normalizedPath);
703
+
704
+ if (!exists) {
705
+ throw new ExistenceError('file', normalizedPath);
706
+ }
707
+
708
+ return normalizedPath;
709
+ }
710
+ catch (error) {
711
+ if (error instanceof OPFSError) {
712
+ throw error;
713
+ }
714
+
715
+ throw mapDomError(error, { path });
716
+ }
717
+ }
718
+
719
+ /**
720
+ * Rename a file or directory
721
+ *
722
+ * Changes the name of a file or directory. If the target path already exists,
723
+ * it will be replaced only if overwrite option is enabled.
724
+ *
725
+ * @param oldPath - The current path of the file or directory
726
+ * @param newPath - The new path for the file or directory
727
+ * @param options - Options for renaming
728
+ * @param options.overwrite - Whether to overwrite existing files (default: false)
729
+ * @returns Promise that resolves when the rename operation is complete
730
+ * @throws {OPFSError} If the rename operation fails
731
+ *
732
+ * @example
733
+ * ```typescript
734
+ * // Basic rename (fails if target exists)
735
+ * await fs.rename('/old/path/file.txt', '/new/path/renamed.txt');
736
+ *
737
+ * // Rename with overwrite
738
+ * await fs.rename('/old/path/file.txt', '/new/path/renamed.txt', { overwrite: true });
739
+ * ```
740
+ */
741
+ async rename(oldPath: string, newPath: string, options?: RenameOptions): Promise<void> {
742
+ await this.mount();
743
+
744
+ try {
745
+ const overwrite = options?.overwrite ?? false;
746
+
747
+ const sourceStat = await this.stat(oldPath);
748
+ const destExists = await this.exists(newPath);
749
+
750
+ if (destExists && !overwrite) {
751
+ throw new AlreadyExistsError(newPath);
752
+ }
753
+
754
+ await this.copy(oldPath, newPath, { recursive: true, overwrite });
755
+ await this.remove(oldPath, { recursive: true });
756
+
757
+ // Notify about the rename operation
758
+ await this.notifyChange({ path: oldPath, type: WatchEventType.Removed, isDirectory: sourceStat.isDirectory });
759
+ await this.notifyChange({ path: newPath, type: WatchEventType.Added, isDirectory: sourceStat.isDirectory });
760
+ }
761
+ catch (error) {
762
+ if (error instanceof OPFSError) {
763
+ throw error;
764
+ }
765
+
766
+ throw mapDomError(error, { path: oldPath });
767
+ }
768
+ }
769
+
770
+ /**
771
+ * Copy files and directories
772
+ *
773
+ * Copies files and directories. Similar to Node.js fs.cp().
774
+ *
775
+ * @param source - The source path to copy from
776
+ * @param destination - The destination path to copy to
777
+ * @param options - Options for copying
778
+ * @param options.recursive - Whether to copy directories recursively (default: false)
779
+ * @param options.overwrite - Whether to overwrite existing files (default: true)
780
+ * @returns Promise that resolves when the copy operation is complete
781
+ * @throws {OPFSError} If the copy operation fails
782
+ *
783
+ * @example
784
+ * ```typescript
785
+ * // Copy a file
786
+ * await fs.copy('/source/file.txt', '/dest/file.txt');
787
+ *
788
+ * // Copy a directory and all its contents
789
+ * await fs.copy('/source/dir', '/dest/dir', { recursive: true });
790
+ *
791
+ * // Copy without overwriting existing files
792
+ * await fs.copy('/source', '/dest', { recursive: true, overwrite: false });
793
+ * ```
794
+ */
795
+ async copy(source: string, destination: string, options?: { recursive?: boolean; overwrite?: boolean }): Promise<void> {
796
+ await this.mount();
797
+
798
+ try {
799
+ const recursive = options?.recursive ?? false;
800
+ const overwrite = options?.overwrite ?? true;
801
+
802
+ const sourceExists = await this.exists(source);
803
+
804
+ if (!sourceExists) {
805
+ throw new ExistenceError('source', source);
806
+ }
807
+
808
+ const destExists = await this.exists(destination);
809
+
810
+ if (destExists && !overwrite) {
811
+ throw new AlreadyExistsError(destination);
812
+ }
813
+
814
+ const sourceStats = await this.stat(source);
815
+
816
+ if (sourceStats.isFile) {
817
+ const content = await this.readFile(source);
818
+
819
+ await this.writeFile(destination, content);
820
+ }
821
+ else {
822
+ if (!recursive) {
823
+ throw new FileTypeError('directory', source);
824
+ }
825
+
826
+ await this.mkdir(destination, { recursive: true });
827
+
828
+ const items = await this.readDir(source);
829
+
830
+ for (const item of items) {
831
+ const sourceItemPath = `${ source }/${ item.name }`;
832
+ const destItemPath = `${ destination }/${ item.name }`;
833
+
834
+ await this.copy(sourceItemPath, destItemPath, { recursive: true, overwrite });
835
+ }
836
+ }
837
+ }
838
+ catch (error) {
839
+ if (error instanceof OPFSError) {
840
+ throw error;
841
+ }
842
+
843
+ throw mapDomError(error, { path: source });
844
+ }
845
+ }
846
+
847
+ /**
848
+ * Start watching a file or directory for changes
849
+ *
850
+ * @param path - The path to watch (minimatch syntax allowed)
851
+ * @param options - Watch options
852
+ * @param options.recursive - Whether to watch recursively (default: true)
853
+ * @param options.exclude - Glob pattern(s) to exclude (minimatch).
854
+ * @returns Promise that resolves when watching starts
855
+ *
856
+ * @example
857
+ * ```typescript
858
+ * // Watch entire directory tree recursively (default)
859
+ * await fs.watch('/data');
860
+ *
861
+ * // Watch only immediate children (shallow)
862
+ * await fs.watch('/data', { recursive: false });
863
+ *
864
+ * // Watch a single file
865
+ * await fs.watch('/config.json', { recursive: false });
866
+ *
867
+ * // Watch all json files but not in dist directory
868
+ * await fs.watch('/**\/*.json', { recursive: false, exclude: ['dist/**'] });
869
+ *
870
+ * ```
871
+ */
872
+ async watch(path: string, options?: WatchOptions): Promise<void> {
873
+ if (!this.options.broadcastChannel) {
874
+ throw new OperationNotSupportedError('This instance is not configured to send events. Please specify options.broadcastChannel to enable watching.');
875
+ }
876
+
877
+ const snapshot: WatchSnapshot = {
878
+ pattern: normalizeMinimatch(path, options?.recursive ?? true),
879
+ include: Array.isArray(options?.include) ? options.include : [options?.include ?? '**'],
880
+ exclude: Array.isArray(options?.exclude) ? options.exclude : [options?.exclude ?? ''],
881
+ };
882
+
883
+ this.watchers.set(path, snapshot);
884
+ }
885
+
886
+ /**
887
+ * Stop watching a previously watched path
888
+ */
889
+ unwatch(path: string): void {
890
+ this.watchers.delete(path);
891
+ }
892
+
893
+ /**
894
+ * Bulk-create files from `[path, data]` entries (strings, bytes, or Blobs).
895
+ *
896
+ * @param entries - Array of `[path, data]` tuples
897
+ * @throws {OPFSError} If a write fails
898
+ *
899
+ * @example
900
+ * ```typescript
901
+ * await fs.createIndex([
902
+ * ['/config.json', JSON.stringify({ theme: 'dark' })],
903
+ * ['/data/binary.dat', new Uint8Array([1, 2, 3, 4])],
904
+ * ['/upload.txt', new Blob(['file content'], { type: 'text/plain' })],
905
+ * ]);
906
+ * ```
907
+ */
908
+ async createIndex(entries: [string, string | Uint8Array | Blob][]): Promise<void> {
909
+ await this.mount();
910
+
911
+ try {
912
+ for (const [path, data] of entries) {
913
+ const normalizedPath = normalizePath(path);
914
+
915
+ let fileData: Uint8Array;
916
+
917
+ if (data instanceof Blob) {
918
+ fileData = await convertBlobToUint8Array(data);
919
+ }
920
+ else if (typeof data === 'string') {
921
+ // Convert string to Uint8Array using UTF-8 encoding
922
+ fileData = new TextEncoder().encode(data);
923
+ }
924
+ else {
925
+ fileData = data;
926
+ }
927
+
928
+ await this.writeFile(normalizedPath, fileData);
929
+ }
930
+ }
931
+ catch (error) {
932
+ if (error instanceof OPFSError) {
933
+ throw error;
934
+ }
935
+
936
+ throw mapDomError(error);
937
+ }
938
+ }
939
+
940
+ /**
941
+ * Dispose of resources and clean up the file system instance
942
+ */
943
+ dispose(): void {
944
+ if (this.broadcastChannel) {
945
+ this.broadcastChannel.close();
946
+ this.broadcastChannel = null;
947
+ }
948
+
949
+ this.watchers.clear();
950
+ }
951
+ }