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