opfs-worker 0.2.0 → 0.2.2

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.
package/dist/worker.js DELETED
@@ -1,865 +0,0 @@
1
- import { expose } from 'comlink';
2
- import { decodeBuffer } from './utils/encoder';
3
- import { FileNotFoundError, OPFSError, OPFSNotMountedError, PathError } from './utils/errors';
4
- import { calculateFileHash, checkOPFSSupport, joinPath, readFileData, splitPath, writeFileData } from './utils/helpers';
5
- /**
6
- * OPFS (Origin Private File System) File System implementation
7
- *
8
- * This class provides a high-level interface for working with the browser's
9
- * Origin Private File System API, offering file and directory operations
10
- * similar to Node.js fs module.
11
- *
12
- * @example
13
- * ```typescript
14
- * const fs = new OPFSFileSystem();
15
- * await fs.init('/my-app');
16
- * await fs.writeFile('/data/config.json', JSON.stringify({ theme: 'dark' }));
17
- * const config = await fs.readFile('/data/config.json');
18
- * ```
19
- */
20
- export class OPFSWorker {
21
- /** Root directory handle for the file system */
22
- root = null;
23
- /** Watch event callback */
24
- watchCallback = null;
25
- /** Map of watched paths to their last known state */
26
- watchers = new Map();
27
- /** Interval handle for polling watched paths */
28
- watchTimer = null;
29
- /** Polling interval in milliseconds */
30
- watchInterval = 1000;
31
- /** Flag to avoid concurrent scans */
32
- scanning = false;
33
- /**
34
- * Creates a new OPFSFileSystem instance
35
- *
36
- * @throws {OPFSError} If OPFS is not supported in the current browser
37
- */
38
- constructor() {
39
- checkOPFSSupport();
40
- }
41
- /**
42
- * Initialize the file system within a given directory
43
- *
44
- * This method sets up the root directory for all subsequent operations.
45
- * It must be called before any other file system operations.
46
- *
47
- * @param root - The root path for the file system (default: '/')
48
- * @returns Promise that resolves to true if initialization was successful
49
- * @throws {OPFSError} If initialization fails
50
- *
51
- * @example
52
- * ```typescript
53
- * const fs = new OPFSFileSystem();
54
- * const success = await fs.init('/my-app');
55
- * ```
56
- */
57
- async mount(root = '/', watchCallback, options) {
58
- try {
59
- const rootDir = await navigator.storage.getDirectory();
60
- this.root = await this.getDirectoryHandle(root, true, rootDir);
61
- if (watchCallback) {
62
- this.watchCallback = watchCallback;
63
- if (options?.watchInterval) {
64
- this.watchInterval = options.watchInterval;
65
- }
66
- }
67
- return true;
68
- }
69
- catch (error) {
70
- console.error(error);
71
- throw new OPFSError('Failed to initialize OPFS', 'INIT_FAILED');
72
- }
73
- }
74
- /**
75
- * Get a directory handle from a path
76
- *
77
- * Navigates through the directory structure to find or create a directory
78
- * at the specified path.
79
- *
80
- * @param path - The path to the directory (string or array of segments)
81
- * @param create - Whether to create the directory if it doesn't exist (default: false)
82
- * @param from - The directory to start from (default: root directory)
83
- * @returns Promise that resolves to the directory handle
84
- * @throws {OPFSError} If the directory cannot be accessed or created
85
- *
86
- * @example
87
- * ```typescript
88
- * const docsDir = await fs.getDirectoryHandle('/users/john/documents', true);
89
- * const docsDir2 = await fs.getDirectoryHandle(['users', 'john', 'documents'], true);
90
- * ```
91
- */
92
- async getDirectoryHandle(path, create = false, from = this.root) {
93
- if (!from) {
94
- throw new OPFSNotMountedError();
95
- }
96
- const segments = Array.isArray(path) ? path : splitPath(path);
97
- let current = from;
98
- for (const segment of segments) {
99
- current = await current.getDirectoryHandle(segment, { create });
100
- }
101
- return current;
102
- }
103
- /**
104
- * Get a file handle from a path
105
- *
106
- * Navigates to the parent directory and retrieves or creates a file handle
107
- * for the specified file path.
108
- *
109
- * @param path - The path to the file (string or array of segments)
110
- * @param create - Whether to create the file if it doesn't exist (default: false)
111
- * @param from - The directory to start from (default: root directory)
112
- * @returns Promise that resolves to the file handle
113
- * @throws {PathError} If the path is empty
114
- * @throws {OPFSError} If the file cannot be accessed or created
115
- *
116
- * @example
117
- * ```typescript
118
- * const fileHandle = await fs.getFileHandle('/config/settings.json', true);
119
- * const fileHandle2 = await fs.getFileHandle(['config', 'settings.json'], true);
120
- * ```
121
- */
122
- async getFileHandle(path, create = false, from = this.root) {
123
- if (!from) {
124
- throw new OPFSNotMountedError();
125
- }
126
- const segments = splitPath(path);
127
- if (segments.length === 0) {
128
- throw new PathError('Path must not be empty', Array.isArray(path) ? path.join('/') : path);
129
- }
130
- const fileName = segments.pop();
131
- const dir = await this.getDirectoryHandle(segments, create, from);
132
- return dir.getFileHandle(fileName, { create });
133
- }
134
- /**
135
- * Recursively list all files and directories with their stats
136
- *
137
- * Traverses the entire file system starting from the root and returns
138
- * a Map containing all paths and their corresponding file statistics.
139
- *
140
- * @param options - Options for indexing
141
- * @param options.includeHash - Whether to calculate file hash (default: false)
142
- * @param options.hashAlgorithm - Hash algorithm to use (default: 'SHA-1', fastest)
143
- * @returns Promise that resolves to a Map of path => FileStat
144
- * @throws {OPFSError} If the indexing operation fails
145
- *
146
- * @example
147
- * ```typescript
148
- * // Basic index without hash
149
- * const index = await fs.index();
150
- *
151
- * // Index with file hash
152
- * const indexWithHash = await fs.index({
153
- * includeHash: true,
154
- * hashAlgorithm: 'SHA-1'
155
- * });
156
- *
157
- * // Iterate through all files and directories
158
- * for (const [path, stat] of index) {
159
- * console.log(`${path}: ${stat.isFile ? 'file' : 'directory'} (${stat.size} bytes)`);
160
- * if (stat.hash) console.log(` Hash: ${stat.hash}`);
161
- * }
162
- *
163
- * // Get specific file stats
164
- * const fileStats = index.get('/data/config.json');
165
- * if (fileStats) {
166
- * console.log(`File size: ${fileStats.size} bytes`);
167
- * if (fileStats.hash) console.log(`Hash: ${fileStats.hash}`);
168
- * }
169
- * ```
170
- */
171
- async index(options) {
172
- const result = new Map();
173
- const walk = async (dirPath) => {
174
- const items = await this.readdir(dirPath, { withFileTypes: true });
175
- for (const item of items) {
176
- const fullPath = `${dirPath === '/' ? '' : dirPath}/${item.name}`;
177
- try {
178
- const stat = await this.stat(fullPath, options);
179
- result.set(fullPath, stat);
180
- if (stat.isDirectory) {
181
- await walk(fullPath);
182
- }
183
- }
184
- catch (err) {
185
- console.warn(`Skipping broken entry: ${fullPath}`, err);
186
- }
187
- }
188
- };
189
- // Add root directory
190
- result.set('/', {
191
- kind: 'directory',
192
- size: 0,
193
- mtime: new Date(0).toISOString(),
194
- ctime: new Date(0).toISOString(),
195
- isFile: false,
196
- isDirectory: true,
197
- });
198
- await walk('/');
199
- return result;
200
- }
201
- async readFile(path, encoding = 'utf-8') {
202
- try {
203
- const fileHandle = await this.getFileHandle(path, false);
204
- const buffer = await readFileData(fileHandle);
205
- if (encoding === 'binary') {
206
- return buffer;
207
- }
208
- return decodeBuffer(buffer, encoding);
209
- }
210
- catch (err) {
211
- console.error(err);
212
- throw new FileNotFoundError(path);
213
- }
214
- }
215
- /**
216
- * Write data to a file
217
- *
218
- * Creates or overwrites a file with the specified data. If the file already
219
- * exists, it will be truncated before writing.
220
- *
221
- * @param path - The path to the file to write
222
- * @param data - The data to write to the file (string, Uint8Array, or ArrayBuffer)
223
- * @param encoding - The encoding to use when writing string data (default: 'utf-8')
224
- * @returns Promise that resolves when the write operation is complete
225
- * @throws {OPFSError} If writing the file fails
226
- *
227
- * @example
228
- * ```typescript
229
- * // Write text data
230
- * await fs.writeFile('/config/settings.json', JSON.stringify({ theme: 'dark' }));
231
- *
232
- * // Write binary data
233
- * const binaryData = new Uint8Array([1, 2, 3, 4, 5]);
234
- * await fs.writeFile('/data/binary.dat', binaryData);
235
- *
236
- * // Write with specific encoding
237
- * await fs.writeFile('/data/utf16.txt', 'Hello World', 'utf-16le');
238
- * ```
239
- */
240
- async writeFile(path, data, encoding) {
241
- const fileHandle = await this.getFileHandle(path, true);
242
- await writeFileData(fileHandle, data, encoding, { truncate: true });
243
- }
244
- /**
245
- * Append data to a file
246
- *
247
- * Adds data to the end of an existing file. If the file doesn't exist,
248
- * it will be created.
249
- *
250
- * @param path - The path to the file to append to
251
- * @param data - The data to append to the file (string, Uint8Array, or ArrayBuffer)
252
- * @param encoding - The encoding to use when appending string data (default: 'utf-8')
253
- * @returns Promise that resolves when the append operation is complete
254
- * @throws {OPFSError} If appending to the file fails
255
- *
256
- * @example
257
- * ```typescript
258
- * // Append text to a log file
259
- * await fs.appendFile('/logs/app.log', `[${new Date().toISOString()}] User logged in\n`);
260
- *
261
- * // Append binary data
262
- * const additionalData = new Uint8Array([6, 7, 8]);
263
- * await fs.appendFile('/data/binary.dat', additionalData);
264
- * ```
265
- */
266
- async appendFile(path, data, encoding) {
267
- const fileHandle = await this.getFileHandle(path, true);
268
- await writeFileData(fileHandle, data, encoding, { append: true });
269
- }
270
- /**
271
- * Create a directory
272
- *
273
- * Creates a new directory at the specified path. If the recursive option
274
- * is enabled, parent directories will be created as needed.
275
- *
276
- * @param path - The path where the directory should be created
277
- * @param options - Options for directory creation
278
- * @param options.recursive - Whether to create parent directories if they don't exist (default: false)
279
- * @returns Promise that resolves when the directory is created
280
- * @throws {OPFSError} If the directory cannot be created
281
- *
282
- * @example
283
- * ```typescript
284
- * // Create a single directory
285
- * await fs.mkdir('/users/john');
286
- *
287
- * // Create nested directories
288
- * await fs.mkdir('/users/john/documents/projects', { recursive: true });
289
- * ```
290
- */
291
- async mkdir(path, options) {
292
- if (!this.root) {
293
- throw new OPFSNotMountedError();
294
- }
295
- const recursive = options?.recursive ?? false;
296
- const segments = splitPath(path);
297
- let current = this.root;
298
- for (let i = 0; i < segments.length; i++) {
299
- const segment = segments[i];
300
- try {
301
- current = await current.getDirectoryHandle(segment, { create: recursive || i === segments.length - 1 });
302
- }
303
- catch (e) {
304
- if (e.name === 'NotFoundError') {
305
- throw new OPFSError(`Parent directory does not exist: ${joinPath(segments.slice(0, i + 1))}`, 'ENOENT');
306
- }
307
- if (e.name === 'TypeMismatchError') {
308
- throw new OPFSError(`Path segment is not a directory: ${segment}`, 'ENOTDIR');
309
- }
310
- throw new OPFSError('Failed to create directory', 'MKDIR_FAILED');
311
- }
312
- }
313
- }
314
- /**
315
- * Get file or directory stats
316
- *
317
- * Retrieves metadata about a file or directory, including size, modification time,
318
- * type information, and optionally file hashes.
319
- *
320
- * @param path - The path to the file or directory
321
- * @param options - Options for stat operation
322
- * @param options.includeHash - Whether to calculate file hash (default: false, only for files)
323
- * @param options.hashAlgorithm - Hash algorithm to use (default: 'SHA-1', fastest)
324
- * @returns Promise that resolves to file/directory statistics
325
- * @throws {OPFSError} If the file or directory does not exist or cannot be accessed
326
- *
327
- * @example
328
- * ```typescript
329
- * // Basic stats
330
- * const stats = await fs.stat('/config/settings.json');
331
- * console.log(`File size: ${stats.size} bytes`);
332
- * console.log(`Is file: ${stats.isFile}`);
333
- * console.log(`Modified: ${stats.mtime}`);
334
- *
335
- * // Stats with hash (SHA-1 is fastest)
336
- * const statsWithHash = await fs.stat('/config/settings.json', {
337
- * includeHash: true,
338
- * hashAlgorithm: 'SHA-1'
339
- * });
340
- * console.log(`Hash: ${statsWithHash.hash}`);
341
- * ```
342
- */
343
- async stat(path, options) {
344
- const segments = splitPath(path);
345
- const name = segments.pop();
346
- const parentDir = await this.getDirectoryHandle(segments, false);
347
- const includeHash = options?.includeHash ?? false;
348
- const hashAlgorithm = options?.hashAlgorithm ?? 'SHA-1';
349
- // Get as file first
350
- try {
351
- const fileHandle = await parentDir.getFileHandle(name, { create: false });
352
- const file = await fileHandle.getFile();
353
- const baseStat = {
354
- kind: 'file',
355
- size: file.size,
356
- mtime: new Date(file.lastModified).toISOString(),
357
- ctime: new Date(file.lastModified).toISOString(),
358
- isFile: true,
359
- isDirectory: false,
360
- };
361
- // Calculate hash if requested
362
- if (includeHash) {
363
- try {
364
- const buffer = new Uint8Array(await file.arrayBuffer());
365
- const hash = await calculateFileHash(buffer, hashAlgorithm);
366
- baseStat.hash = hash;
367
- }
368
- catch (error) {
369
- console.warn(`Failed to calculate hash for ${path}:`, error);
370
- }
371
- }
372
- return baseStat;
373
- }
374
- catch (e) {
375
- if (e.name !== 'TypeMismatchError' && e.name !== 'NotFoundError') {
376
- throw new OPFSError('Failed to stat (file)', 'STAT_FAILED');
377
- }
378
- }
379
- // Get as directory
380
- try {
381
- await parentDir.getDirectoryHandle(name, { create: false });
382
- return {
383
- kind: 'directory',
384
- size: 0,
385
- mtime: new Date(0).toISOString(),
386
- ctime: new Date(0).toISOString(),
387
- isFile: false,
388
- isDirectory: true,
389
- // Directories don't have hashes
390
- };
391
- }
392
- catch (e) {
393
- if (e.name === 'NotFoundError') {
394
- throw new OPFSError(`No such file or directory: ${path}`, 'ENOENT');
395
- }
396
- throw new OPFSError('Failed to stat (directory)', 'STAT_FAILED');
397
- }
398
- }
399
- async readdir(path, options) {
400
- const withTypes = options?.withFileTypes ?? false;
401
- const dir = await this.getDirectoryHandle(path, false);
402
- // Use type assertion to access the entries() method
403
- if (withTypes) {
404
- const results = [];
405
- for await (const [name, handle] of dir.entries()) {
406
- const isFile = handle.kind === 'file';
407
- results.push({
408
- name,
409
- kind: handle.kind,
410
- isFile,
411
- isDirectory: !isFile,
412
- });
413
- }
414
- return results;
415
- }
416
- else {
417
- const results = [];
418
- for await (const [name] of dir.entries()) {
419
- results.push(name);
420
- }
421
- return results;
422
- }
423
- }
424
- /**
425
- * Check if a file or directory exists
426
- *
427
- * Verifies if a file or directory exists at the specified path.
428
- *
429
- * @param path - The path to check
430
- * @returns Promise that resolves to true if the file or directory exists, false otherwise
431
- *
432
- * @example
433
- * ```typescript
434
- * const exists = await fs.exists('/config/settings.json');
435
- * console.log(`File exists: ${exists}`);
436
- * ```
437
- */
438
- async exists(path) {
439
- const segments = splitPath(path);
440
- const name = segments.pop();
441
- let dir = null;
442
- try {
443
- dir = await this.getDirectoryHandle(segments, false);
444
- }
445
- catch (e) {
446
- if (e.name === 'NotFoundError' || e.name === 'TypeMismatchError') {
447
- dir = null;
448
- }
449
- throw e;
450
- }
451
- if (!dir || !name) {
452
- return false;
453
- }
454
- // Get as file
455
- try {
456
- await dir.getFileHandle(name, { create: false });
457
- return true;
458
- }
459
- catch (e) {
460
- if (e.name !== 'NotFoundError' && e.name !== 'TypeMismatchError') {
461
- throw e;
462
- }
463
- }
464
- // Get as directory
465
- try {
466
- await dir.getDirectoryHandle(name, { create: false });
467
- return true;
468
- }
469
- catch (e) {
470
- if (e.name !== 'NotFoundError' && e.name !== 'TypeMismatchError') {
471
- throw e;
472
- }
473
- }
474
- return false;
475
- }
476
- /**
477
- * Clear all contents of a directory without removing the directory itself
478
- *
479
- * Removes all files and subdirectories within the specified directory,
480
- * but keeps the directory itself.
481
- *
482
- * @param path - The path to the directory to clear (default: '/')
483
- * @returns Promise that resolves when all contents are removed
484
- * @throws {OPFSError} If the operation fails
485
- *
486
- * @example
487
- * ```typescript
488
- * // Clear root directory contents
489
- * await fs.clear('/');
490
- *
491
- * // Clear specific directory contents
492
- * await fs.clear('/data');
493
- * ```
494
- */
495
- async clear(path = '/') {
496
- try {
497
- const items = await this.readdir(path, { withFileTypes: true });
498
- for (const item of items) {
499
- const itemPath = `${path === '/' ? '' : path}/${item.name}`;
500
- await this.remove(itemPath, { recursive: true });
501
- }
502
- }
503
- catch (error) {
504
- if (error instanceof OPFSError) {
505
- throw error;
506
- }
507
- throw new OPFSError(`Failed to clear directory: ${path}`, 'CLEAR_FAILED');
508
- }
509
- }
510
- /**
511
- * Remove files and directories
512
- *
513
- * Removes files and directories. Similar to Node.js fs.rm().
514
- *
515
- * @param path - The path to remove
516
- * @param options - Options for removal
517
- * @param options.recursive - Whether to remove directories and their contents recursively (default: false)
518
- * @param options.force - Whether to ignore errors if the path doesn't exist (default: false)
519
- * @returns Promise that resolves when the removal is complete
520
- * @throws {OPFSError} If the removal fails
521
- *
522
- * @example
523
- * ```typescript
524
- * // Remove a file
525
- * await fs.rm('/path/to/file.txt');
526
- *
527
- * // Remove a directory and all its contents
528
- * await fs.rm('/path/to/directory', { recursive: true });
529
- *
530
- * // Remove with force (ignore if doesn't exist)
531
- * await fs.rm('/maybe/exists', { force: true });
532
- * ```
533
- */
534
- async remove(path, options) {
535
- const recursive = options?.recursive ?? false;
536
- const force = options?.force ?? false;
537
- const segments = splitPath(path);
538
- const name = segments.pop();
539
- if (!name) {
540
- throw new PathError('Invalid path', path);
541
- }
542
- const parent = await this.getDirectoryHandle(segments, false);
543
- try {
544
- await parent.removeEntry(name, { recursive });
545
- }
546
- catch (e) {
547
- if (e.name === 'NotFoundError') {
548
- if (!force) {
549
- throw new OPFSError(`No such file or directory: ${path}`, 'ENOENT');
550
- }
551
- }
552
- else if (e.name === 'InvalidModificationError') {
553
- throw new OPFSError(`Directory not empty: ${path}. Use recursive option to force removal.`, 'ENOTEMPTY');
554
- }
555
- else if (e.name === 'TypeMismatchError' && !recursive) {
556
- throw new OPFSError(`Cannot remove directory without recursive option: ${path}`, 'EISDIR');
557
- }
558
- else {
559
- throw new OPFSError(`Failed to remove path: ${path}`, 'RM_FAILED');
560
- }
561
- }
562
- }
563
- /**
564
- * Resolve a path to an absolute path
565
- *
566
- * Resolves relative paths and normalizes path segments (like '..' and '.').
567
- * Similar to Node.js fs.realpath() but without symlink resolution since OPFS doesn't support symlinks.
568
- *
569
- * @param path - The path to resolve
570
- * @returns Promise that resolves to the absolute normalized path
571
- * @throws {FileNotFoundError} If the path does not exist
572
- * @throws {OPFSError} If path resolution fails
573
- *
574
- * @example
575
- * ```typescript
576
- * // Resolve relative path
577
- * const absolute = await fs.realpath('./config/../data/file.txt');
578
- * console.log(absolute); // '/data/file.txt'
579
- * ```
580
- */
581
- async realpath(path) {
582
- try {
583
- const segments = splitPath(path);
584
- const normalizedSegments = [];
585
- for (const segment of segments) {
586
- if (segment === '.' || segment === '') {
587
- // Skip current directory references and empty segments
588
- continue;
589
- }
590
- else if (segment === '..') {
591
- if (normalizedSegments.length === 0) {
592
- throw new OPFSError('Path escapes root', 'EINVAL');
593
- }
594
- // Go up one directory
595
- if (normalizedSegments.length > 0) {
596
- normalizedSegments.pop();
597
- }
598
- }
599
- else {
600
- // Regular segment
601
- normalizedSegments.push(segment);
602
- }
603
- }
604
- const normalizedPath = joinPath(normalizedSegments);
605
- const exists = await this.exists(normalizedPath);
606
- if (!exists) {
607
- throw new FileNotFoundError(normalizedPath);
608
- }
609
- return normalizedPath;
610
- }
611
- catch (error) {
612
- if (error instanceof OPFSError) {
613
- throw error;
614
- }
615
- throw new OPFSError(`Failed to resolve path: ${path}`, 'REALPATH_FAILED');
616
- }
617
- }
618
- /**
619
- * Rename a file or directory
620
- *
621
- * Changes the name of a file or directory. If the target path already exists,
622
- * it will be replaced.
623
- *
624
- * @param oldPath - The current path of the file or directory
625
- * @param newPath - The new path for the file or directory
626
- * @returns Promise that resolves when the rename operation is complete
627
- * @throws {OPFSError} If the rename operation fails
628
- *
629
- * @example
630
- * ```typescript
631
- * await fs.rename('/old/path/file.txt', '/new/path/renamed.txt');
632
- * ```
633
- */
634
- async rename(oldPath, newPath) {
635
- try {
636
- // Check if source exists
637
- const sourceExists = await this.exists(oldPath);
638
- if (!sourceExists) {
639
- throw new FileNotFoundError(oldPath);
640
- }
641
- await this.copy(oldPath, newPath, { recursive: true });
642
- await this.remove(oldPath, { recursive: true });
643
- }
644
- catch (error) {
645
- if (error instanceof OPFSError) {
646
- throw error;
647
- }
648
- throw new OPFSError(`Failed to rename from ${oldPath} to ${newPath}`, 'RENAME_FAILED');
649
- }
650
- }
651
- /**
652
- * Copy files and directories
653
- *
654
- * Copies files and directories. Similar to Node.js fs.cp().
655
- *
656
- * @param source - The source path to copy from
657
- * @param destination - The destination path to copy to
658
- * @param options - Options for copying
659
- * @param options.recursive - Whether to copy directories recursively (default: false)
660
- * @param options.force - Whether to overwrite existing files (default: true)
661
- * @returns Promise that resolves when the copy operation is complete
662
- * @throws {OPFSError} If the copy operation fails
663
- *
664
- * @example
665
- * ```typescript
666
- * // Copy a file
667
- * await fs.cp('/source/file.txt', '/dest/file.txt');
668
- *
669
- * // Copy a directory and all its contents
670
- * await fs.cp('/source/dir', '/dest/dir', { recursive: true });
671
- *
672
- * // Copy without overwriting existing files
673
- * await fs.cp('/source', '/dest', { recursive: true, force: false });
674
- * ```
675
- */
676
- async copy(source, destination, options) {
677
- try {
678
- const recursive = options?.recursive ?? false;
679
- const force = options?.force ?? true;
680
- const sourceExists = await this.exists(source);
681
- if (!sourceExists) {
682
- throw new OPFSError(`Source does not exist: ${source}`, 'ENOENT');
683
- }
684
- // Check if destination exists and handle accordingly
685
- const destExists = await this.exists(destination);
686
- if (destExists && !force) {
687
- throw new OPFSError(`Destination already exists: ${destination}`, 'EEXIST');
688
- }
689
- // Get source stats to determine if it's a file or directory
690
- const sourceStats = await this.stat(source);
691
- if (sourceStats.isFile) {
692
- // Copy file
693
- const content = await this.readFile(source, 'binary');
694
- await this.writeFile(destination, content);
695
- }
696
- else {
697
- // Copy directory
698
- if (!recursive) {
699
- throw new OPFSError(`Cannot copy directory without recursive option: ${source}`, 'EISDIR');
700
- }
701
- // Create destination directory
702
- await this.mkdir(destination, { recursive: true });
703
- // Copy all contents
704
- const items = await this.readdir(source, { withFileTypes: true });
705
- for (const item of items) {
706
- const sourceItemPath = `${source}/${item.name}`;
707
- const destItemPath = `${destination}/${item.name}`;
708
- // Recursively copy each item
709
- await this.copy(sourceItemPath, destItemPath, { recursive: true, force });
710
- }
711
- }
712
- }
713
- catch (error) {
714
- if (error instanceof OPFSError) {
715
- throw error;
716
- }
717
- throw new OPFSError(`Failed to copy from ${source} to ${destination}`, 'CP_FAILED');
718
- }
719
- }
720
- /**
721
- * Start watching a file or directory for changes
722
- */
723
- async watch(path) {
724
- const normalizedPath = path.startsWith('/') ? path : `/${path}`;
725
- const snapshot = await this.buildSnapshot(normalizedPath);
726
- this.watchers.set(normalizedPath, snapshot);
727
- if (!this.watchTimer) {
728
- this.watchTimer = setInterval(() => {
729
- void this.scanWatches();
730
- }, this.watchInterval);
731
- }
732
- }
733
- /**
734
- * Stop watching a previously watched path
735
- */
736
- unwatch(path) {
737
- const normalizedPath = path.startsWith('/') ? path : `/${path}`;
738
- this.watchers.delete(normalizedPath);
739
- if (this.watchers.size === 0 && this.watchTimer) {
740
- clearInterval(this.watchTimer);
741
- this.watchTimer = null;
742
- }
743
- }
744
- async buildSnapshot(rootPath) {
745
- const result = new Map();
746
- const walk = async (current) => {
747
- const stat = await this.stat(current);
748
- result.set(current, stat);
749
- if (stat.isDirectory) {
750
- const entries = await this.readdir(current, { withFileTypes: true });
751
- for (const entry of entries) {
752
- const child = `${current === '/' ? '' : current}/${entry.name}`;
753
- await walk(child);
754
- }
755
- }
756
- };
757
- await walk(rootPath);
758
- return result;
759
- }
760
- async scanWatches() {
761
- if (this.scanning) {
762
- return;
763
- }
764
- this.scanning = true;
765
- try {
766
- await Promise.all([...this.watchers.entries()].map(async ([rootPath, prev]) => {
767
- let next;
768
- try {
769
- next = await this.buildSnapshot(rootPath);
770
- }
771
- catch {
772
- next = new Map();
773
- }
774
- const events = [];
775
- for (const [p, stat] of next) {
776
- const old = prev.get(p);
777
- if (!old) {
778
- events.push({ path: p, type: 'create' });
779
- }
780
- else if (old.mtime !== stat.mtime || old.size !== stat.size) {
781
- events.push({ path: p, type: 'change' });
782
- }
783
- }
784
- for (const p of prev.keys()) {
785
- if (!next.has(p)) {
786
- events.push({ path: p, type: 'delete' });
787
- }
788
- }
789
- if (events.length && this.watchCallback) {
790
- for (const event of events) {
791
- this.watchCallback(event);
792
- }
793
- }
794
- this.watchers.set(rootPath, next);
795
- }));
796
- }
797
- finally {
798
- this.scanning = false;
799
- }
800
- }
801
- /**
802
- * Synchronize the file system with external data
803
- *
804
- * Syncs the file system with an array of entries containing paths and data.
805
- * This is useful for importing data from external sources or syncing with remote data.
806
- *
807
- * @param entries - Array of [path, data] tuples to sync
808
- * @param options - Options for synchronization
809
- * @param options.cleanBefore - Whether to clear the file system before syncing (default: false)
810
- * @returns Promise that resolves when synchronization is complete
811
- * @throws {OPFSError} If the synchronization fails
812
- *
813
- * @example
814
- * ```typescript
815
- * // Sync with external data
816
- * const entries: [string, string | Uint8Array | Blob][] = [
817
- * ['/config.json', JSON.stringify({ theme: 'dark' })],
818
- * ['/data/binary.dat', new Uint8Array([1, 2, 3, 4])],
819
- * ['/upload.txt', new Blob(['file content'], { type: 'text/plain' })]
820
- * ];
821
- *
822
- * // Sync without clearing existing files
823
- * await fs.sync(entries);
824
- *
825
- * // Clean file system and then sync
826
- * await fs.sync(entries, { cleanBefore: true });
827
- * ```
828
- */
829
- async sync(entries, options) {
830
- try {
831
- const cleanBefore = options?.cleanBefore ?? false;
832
- // Clear file system if requested
833
- if (cleanBefore) {
834
- await this.clear('/');
835
- }
836
- // Process each entry
837
- for (const [path, data] of entries) {
838
- // Normalize path to ensure it starts with /
839
- const normalizedPath = path.startsWith('/') ? path : `/${path}`;
840
- // Convert data to appropriate format
841
- let fileData;
842
- if (data instanceof Blob) {
843
- // Convert Blob to Uint8Array
844
- const arrayBuffer = await data.arrayBuffer();
845
- fileData = new Uint8Array(arrayBuffer);
846
- }
847
- else {
848
- fileData = data;
849
- }
850
- // Write the file (this will create directories as needed)
851
- await this.writeFile(normalizedPath, fileData);
852
- }
853
- }
854
- catch (error) {
855
- if (error instanceof OPFSError) {
856
- throw error;
857
- }
858
- throw new OPFSError('Failed to sync file system', 'SYNC_FAILED');
859
- }
860
- }
861
- }
862
- // Only expose the worker when running in a Web Worker environment
863
- if (typeof self !== 'undefined' && self.constructor.name === 'DedicatedWorkerGlobalScope') {
864
- expose(new OPFSWorker());
865
- }