opfs-worker 0.2.1 → 0.2.3

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/index.js CHANGED
@@ -1,13 +1,1198 @@
1
- import { wrap } from 'comlink';
2
- import WorkerCtor from './worker?worker&inline';
3
- export * from './types';
4
- export * from './utils/errors';
5
- export * from './utils/helpers';
6
- export * from './utils/encoder';
7
- /**
8
- * Creates a new file system instance with inline worker
9
- * @returns Promise resolving to the file system interface
1
+ import { wrap as i, proxy as o } from "comlink";
2
+ import { D as u, F as d, O as p, b as w, a as y, P as m, c as g, S as v, T as E, e as S, k as F, d as b, l as P, h as x, o as A, f as T, m as O, g as I, j as _, n as D, i as k, r as R, s as U, w as C } from "./helpers-Co-qCBmA.js";
3
+ const a = `/**
4
+ * @license
5
+ * Copyright 2019 Google LLC
6
+ * SPDX-License-Identifier: Apache-2.0
10
7
  */
11
- export function createWorker() {
12
- return wrap(new WorkerCtor());
8
+ const H = Symbol("Comlink.proxy"), R = Symbol("Comlink.endpoint"), B = Symbol("Comlink.releaseProxy"), T = Symbol("Comlink.finalizer"), p = Symbol("Comlink.thrown"), $ = (t) => typeof t == "object" && t !== null || typeof t == "function", W = {
9
+ canHandle: (t) => $(t) && t[H],
10
+ serialize(t) {
11
+ const { port1: e, port2: r } = new MessageChannel();
12
+ return x(t, e), [r, [r]];
13
+ },
14
+ deserialize(t) {
15
+ return t.start(), Y(t);
16
+ }
17
+ }, j = {
18
+ canHandle: (t) => $(t) && p in t,
19
+ serialize({ value: t }) {
20
+ let e;
21
+ return t instanceof Error ? e = {
22
+ isError: !0,
23
+ value: {
24
+ message: t.message,
25
+ name: t.name,
26
+ stack: t.stack
27
+ }
28
+ } : e = { isError: !1, value: t }, [e, []];
29
+ },
30
+ deserialize(t) {
31
+ throw t.isError ? Object.assign(new Error(t.value.message), t.value) : t.value;
32
+ }
33
+ }, U = /* @__PURE__ */ new Map([
34
+ ["proxy", W],
35
+ ["throw", j]
36
+ ]);
37
+ function V(t, e) {
38
+ for (const r of t)
39
+ if (e === r || r === "*" || r instanceof RegExp && r.test(e))
40
+ return !0;
41
+ return !1;
13
42
  }
43
+ function x(t, e = globalThis, r = ["*"]) {
44
+ e.addEventListener("message", function a(n) {
45
+ if (!n || !n.data)
46
+ return;
47
+ if (!V(r, n.origin)) {
48
+ console.warn(\`Invalid origin '\${n.origin}' for comlink proxy\`);
49
+ return;
50
+ }
51
+ const { id: i, type: o, path: s } = Object.assign({ path: [] }, n.data), l = (n.data.argumentList || []).map(d);
52
+ let u;
53
+ try {
54
+ const f = s.slice(0, -1).reduce((h, g) => h[g], t), w = s.reduce((h, g) => h[g], t);
55
+ switch (o) {
56
+ case "GET":
57
+ u = w;
58
+ break;
59
+ case "SET":
60
+ f[s.slice(-1)[0]] = d(n.data.value), u = !0;
61
+ break;
62
+ case "APPLY":
63
+ u = w.apply(f, l);
64
+ break;
65
+ case "CONSTRUCT":
66
+ {
67
+ const h = new w(...l);
68
+ u = Q(h);
69
+ }
70
+ break;
71
+ case "ENDPOINT":
72
+ {
73
+ const { port1: h, port2: g } = new MessageChannel();
74
+ x(t, g), u = J(h, [h]);
75
+ }
76
+ break;
77
+ case "RELEASE":
78
+ u = void 0;
79
+ break;
80
+ default:
81
+ return;
82
+ }
83
+ } catch (f) {
84
+ u = { value: f, [p]: 0 };
85
+ }
86
+ Promise.resolve(u).catch((f) => ({ value: f, [p]: 0 })).then((f) => {
87
+ const [w, h] = A(f);
88
+ e.postMessage(Object.assign(Object.assign({}, w), { id: i }), h), o === "RELEASE" && (e.removeEventListener("message", a), L(e), T in t && typeof t[T] == "function" && t[T]());
89
+ }).catch((f) => {
90
+ const [w, h] = A({
91
+ value: new TypeError("Unserializable return value"),
92
+ [p]: 0
93
+ });
94
+ e.postMessage(Object.assign(Object.assign({}, w), { id: i }), h);
95
+ });
96
+ }), e.start && e.start();
97
+ }
98
+ function G(t) {
99
+ return t.constructor.name === "MessagePort";
100
+ }
101
+ function L(t) {
102
+ G(t) && t.close();
103
+ }
104
+ function Y(t, e) {
105
+ const r = /* @__PURE__ */ new Map();
106
+ return t.addEventListener("message", function(n) {
107
+ const { data: i } = n;
108
+ if (!i || !i.id)
109
+ return;
110
+ const o = r.get(i.id);
111
+ if (o)
112
+ try {
113
+ o(i);
114
+ } finally {
115
+ r.delete(i.id);
116
+ }
117
+ }), O(t, r, [], e);
118
+ }
119
+ function E(t) {
120
+ if (t)
121
+ throw new Error("Proxy has been released and is not useable");
122
+ }
123
+ function z(t) {
124
+ return y(t, /* @__PURE__ */ new Map(), {
125
+ type: "RELEASE"
126
+ }).then(() => {
127
+ L(t);
128
+ });
129
+ }
130
+ const F = /* @__PURE__ */ new WeakMap(), S = "FinalizationRegistry" in globalThis && new FinalizationRegistry((t) => {
131
+ const e = (F.get(t) || 0) - 1;
132
+ F.set(t, e), e === 0 && z(t);
133
+ });
134
+ function X(t, e) {
135
+ const r = (F.get(e) || 0) + 1;
136
+ F.set(e, r), S && S.register(t, e, t);
137
+ }
138
+ function q(t) {
139
+ S && S.unregister(t);
140
+ }
141
+ function O(t, e, r = [], a = function() {
142
+ }) {
143
+ let n = !1;
144
+ const i = new Proxy(a, {
145
+ get(o, s) {
146
+ if (E(n), s === B)
147
+ return () => {
148
+ q(i), z(t), e.clear(), n = !0;
149
+ };
150
+ if (s === "then") {
151
+ if (r.length === 0)
152
+ return { then: () => i };
153
+ const l = y(t, e, {
154
+ type: "GET",
155
+ path: r.map((u) => u.toString())
156
+ }).then(d);
157
+ return l.then.bind(l);
158
+ }
159
+ return O(t, e, [...r, s]);
160
+ },
161
+ set(o, s, l) {
162
+ E(n);
163
+ const [u, f] = A(l);
164
+ return y(t, e, {
165
+ type: "SET",
166
+ path: [...r, s].map((w) => w.toString()),
167
+ value: u
168
+ }, f).then(d);
169
+ },
170
+ apply(o, s, l) {
171
+ E(n);
172
+ const u = r[r.length - 1];
173
+ if (u === R)
174
+ return y(t, e, {
175
+ type: "ENDPOINT"
176
+ }).then(d);
177
+ if (u === "bind")
178
+ return O(t, e, r.slice(0, -1));
179
+ const [f, w] = N(l);
180
+ return y(t, e, {
181
+ type: "APPLY",
182
+ path: r.map((h) => h.toString()),
183
+ argumentList: f
184
+ }, w).then(d);
185
+ },
186
+ construct(o, s) {
187
+ E(n);
188
+ const [l, u] = N(s);
189
+ return y(t, e, {
190
+ type: "CONSTRUCT",
191
+ path: r.map((f) => f.toString()),
192
+ argumentList: l
193
+ }, u).then(d);
194
+ }
195
+ });
196
+ return X(i, t), i;
197
+ }
198
+ function K(t) {
199
+ return Array.prototype.concat.apply([], t);
200
+ }
201
+ function N(t) {
202
+ const e = t.map(A);
203
+ return [e.map((r) => r[0]), K(e.map((r) => r[1]))];
204
+ }
205
+ const _ = /* @__PURE__ */ new WeakMap();
206
+ function J(t, e) {
207
+ return _.set(t, e), t;
208
+ }
209
+ function Q(t) {
210
+ return Object.assign(t, { [H]: !0 });
211
+ }
212
+ function A(t) {
213
+ for (const [e, r] of U)
214
+ if (r.canHandle(t)) {
215
+ const [a, n] = r.serialize(t);
216
+ return [
217
+ {
218
+ type: "HANDLER",
219
+ name: e,
220
+ value: a
221
+ },
222
+ n
223
+ ];
224
+ }
225
+ return [
226
+ {
227
+ type: "RAW",
228
+ value: t
229
+ },
230
+ _.get(t) || []
231
+ ];
232
+ }
233
+ function d(t) {
234
+ switch (t.type) {
235
+ case "HANDLER":
236
+ return U.get(t.name).deserialize(t.value);
237
+ case "RAW":
238
+ return t.value;
239
+ }
240
+ }
241
+ function y(t, e, r, a) {
242
+ return new Promise((n) => {
243
+ const i = Z();
244
+ e.set(i, n), t.start && t.start(), t.postMessage(Object.assign({ id: i }, r), a);
245
+ });
246
+ }
247
+ function Z() {
248
+ return new Array(4).fill(0).map(() => Math.floor(Math.random() * Number.MAX_SAFE_INTEGER).toString(16)).join("-");
249
+ }
250
+ class c extends Error {
251
+ constructor(e, r, a) {
252
+ super(e), this.code = r, this.path = a, this.name = "OPFSError";
253
+ }
254
+ }
255
+ class ee extends c {
256
+ constructor() {
257
+ super("OPFS is not supported in this browser", "OPFS_NOT_SUPPORTED");
258
+ }
259
+ }
260
+ class D extends c {
261
+ constructor() {
262
+ super("OPFS is not mounted", "OPFS_NOT_MOUNTED");
263
+ }
264
+ }
265
+ class k extends c {
266
+ constructor(e, r) {
267
+ super(e, "INVALID_PATH", r);
268
+ }
269
+ }
270
+ class b extends c {
271
+ constructor(e) {
272
+ super(\`File not found: \${e}\`, "FILE_NOT_FOUND", e);
273
+ }
274
+ }
275
+ function te(t, e = "utf-8") {
276
+ switch (e) {
277
+ case "utf8":
278
+ case "utf-8":
279
+ return new TextEncoder().encode(t);
280
+ case "utf16le":
281
+ case "ucs2":
282
+ case "ucs-2":
283
+ return ne(t);
284
+ case "ascii":
285
+ return se(t);
286
+ case "latin1":
287
+ return ie(t);
288
+ case "binary":
289
+ return Uint8Array.from(t, (r) => r.charCodeAt(0));
290
+ case "base64":
291
+ return Uint8Array.from(atob(t), (r) => r.charCodeAt(0));
292
+ case "hex":
293
+ if (!/^[\\da-f]+$/i.test(t) || t.length % 2 !== 0)
294
+ throw new c("Invalid hex string", "INVALID_HEX_FORMAT");
295
+ return Uint8Array.from(t.match(/.{1,2}/g).map((r) => parseInt(r, 16)));
296
+ default:
297
+ return console.warn("Encoding not supported, falling back to UTF-8"), new TextEncoder().encode(t);
298
+ }
299
+ }
300
+ function re(t, e = "utf-8") {
301
+ switch (e) {
302
+ case "utf8":
303
+ case "utf-8":
304
+ return new TextDecoder().decode(t);
305
+ case "utf16le":
306
+ case "ucs2":
307
+ case "ucs-2":
308
+ return ae(t);
309
+ case "latin1":
310
+ return String.fromCharCode(...t);
311
+ case "binary":
312
+ return String.fromCharCode(...t);
313
+ case "ascii":
314
+ return String.fromCharCode(...t.map((r) => r & 127));
315
+ case "base64":
316
+ return btoa(String.fromCharCode(...t));
317
+ case "hex":
318
+ return Array.from(t).map((r) => r.toString(16).padStart(2, "0")).join("");
319
+ default:
320
+ return console.warn("Unsupported encoding, falling back to UTF-8"), new TextDecoder().decode(t);
321
+ }
322
+ }
323
+ function ne(t) {
324
+ const e = new Uint8Array(t.length * 2);
325
+ for (let r = 0; r < t.length; r++) {
326
+ const a = t.charCodeAt(r);
327
+ e[r * 2] = a & 255, e[r * 2 + 1] = a >> 8;
328
+ }
329
+ return e;
330
+ }
331
+ function ae(t) {
332
+ t.length % 2 !== 0 && (console.warn("Invalid UTF-16LE buffer length, truncating last byte"), t = t.slice(0, t.length - 1));
333
+ const e = new Uint16Array(t.buffer, t.byteOffset, t.byteLength / 2);
334
+ return String.fromCharCode(...e);
335
+ }
336
+ function ie(t) {
337
+ const e = new Uint8Array(t.length);
338
+ for (let r = 0; r < t.length; r++)
339
+ e[r] = t.charCodeAt(r) & 255;
340
+ return e;
341
+ }
342
+ function se(t) {
343
+ const e = new Uint8Array(t.length);
344
+ for (let r = 0; r < t.length; r++)
345
+ e[r] = t.charCodeAt(r) & 127;
346
+ return e;
347
+ }
348
+ function oe() {
349
+ if (!("storage" in navigator) || !("getDirectory" in navigator.storage))
350
+ throw new ee();
351
+ }
352
+ function m(t) {
353
+ return Array.isArray(t) ? t : t.split("/").filter(Boolean);
354
+ }
355
+ function v(t) {
356
+ return typeof t == "string" ? t ?? "/" : \`/\${t.join("/")}\`;
357
+ }
358
+ function I(t) {
359
+ const e = m(t);
360
+ return e[e.length - 1] || "";
361
+ }
362
+ function P(t) {
363
+ const e = m(t);
364
+ return e.pop(), v(e);
365
+ }
366
+ function M(t) {
367
+ return !t || t === "/" ? "/" : t.startsWith("/") ? t : \`/\${t}\`;
368
+ }
369
+ function ce(t) {
370
+ const e = m(t), r = [];
371
+ for (const a of e)
372
+ if (!(a === "." || a === ""))
373
+ if (a === "..") {
374
+ if (r.length === 0)
375
+ continue;
376
+ r.pop();
377
+ } else
378
+ r.push(a);
379
+ return v(r);
380
+ }
381
+ function le(t, e = "utf-8") {
382
+ return typeof t == "string" ? te(t, e) : t instanceof Uint8Array ? t : new Uint8Array(t);
383
+ }
384
+ async function ue(t) {
385
+ const e = await t.createSyncAccessHandle();
386
+ try {
387
+ const r = e.getSize(), a = new Uint8Array(r);
388
+ return e.read(a, { at: 0 }), a;
389
+ } finally {
390
+ e.close();
391
+ }
392
+ }
393
+ async function C(t, e, r, a = {}) {
394
+ let n = null;
395
+ try {
396
+ n = await t.createSyncAccessHandle();
397
+ const i = le(e, r), o = a.append ? n.getSize() : 0;
398
+ n.write(i, { at: o }), a.truncate && !a.append && n.truncate(i.byteLength), n.flush();
399
+ } catch (i) {
400
+ console.error(i);
401
+ const o = a.append ? "append" : "write";
402
+ throw new c(\`Failed to \${o} file\`, \`\${o.toUpperCase()}_FAILED\`);
403
+ } finally {
404
+ if (n)
405
+ try {
406
+ n.close();
407
+ } catch {
408
+ }
409
+ }
410
+ }
411
+ async function fe(t, e = "SHA-1") {
412
+ try {
413
+ const r = new Uint8Array(t), a = await crypto.subtle.digest(e, r);
414
+ return Array.from(new Uint8Array(a)).map((i) => i.toString(16).padStart(2, "0")).join("");
415
+ } catch (r) {
416
+ throw console.warn(\`Failed to calculate \${e} hash:\`, r), r;
417
+ }
418
+ }
419
+ async function he(t) {
420
+ const e = await t.arrayBuffer();
421
+ return new Uint8Array(e);
422
+ }
423
+ class we {
424
+ /** Root directory handle for the file system */
425
+ root = null;
426
+ /** Watch event callback */
427
+ watchCallback = null;
428
+ /** Map of watched paths to their last known state */
429
+ watchers = /* @__PURE__ */ new Map();
430
+ /** Interval handle for polling watched paths */
431
+ watchTimer = null;
432
+ /** Polling interval in milliseconds */
433
+ watchInterval = 1e3;
434
+ /** Flag to avoid concurrent scans */
435
+ scanning = !1;
436
+ /** Promise to prevent concurrent mount operations */
437
+ mountingPromise = null;
438
+ /**
439
+ * Creates a new OPFSFileSystem instance
440
+ *
441
+ * @param watchCallback - Optional callback for file change events
442
+ * @param watchOptions - Optional configuration for watching
443
+ * @throws {OPFSError} If OPFS is not supported in the current browser
444
+ */
445
+ constructor(e, r) {
446
+ oe(), e && (this.watchCallback = e, r?.watchInterval && (this.watchInterval = r.watchInterval)), this.mount("/");
447
+ }
448
+ /**
449
+ * Initialize the file system within a given directory
450
+ *
451
+ * This method sets up the root directory for all subsequent operations.
452
+ * If no root is specified, it will use the OPFS root directory.
453
+ *
454
+ * @param root - The root path for the file system (default: '/')
455
+ * @returns Promise that resolves to true if initialization was successful
456
+ * @throws {OPFSError} If initialization fails
457
+ *
458
+ * @example
459
+ * \`\`\`typescript
460
+ * const fs = new OPFSFileSystem();
461
+ *
462
+ * // Use OPFS root (default)
463
+ * await fs.mount();
464
+ *
465
+ * // Use custom directory
466
+ * await fs.mount('/my-app');
467
+ * \`\`\`
468
+ */
469
+ async mount(e = "/") {
470
+ return this.mountingPromise && await this.mountingPromise, this.mountingPromise = new Promise(async (r, a) => {
471
+ this.root = null;
472
+ try {
473
+ const n = await navigator.storage.getDirectory();
474
+ e === "/" ? this.root = n : this.root = await this.getDirectoryHandle(e, !0, n), r(!0);
475
+ } catch (n) {
476
+ console.error(n), a(new c("Failed to initialize OPFS", "INIT_FAILED"));
477
+ } finally {
478
+ this.mountingPromise = null;
479
+ }
480
+ }), this.mountingPromise;
481
+ }
482
+ /**
483
+ * Set the watch callback for file change events
484
+ *
485
+ * @param callback - The callback function to invoke when files change
486
+ * @param options - Optional configuration for watching
487
+ */
488
+ setWatchCallback(e, r) {
489
+ this.watchCallback = e, r?.watchInterval && (this.watchInterval = r.watchInterval);
490
+ }
491
+ /**
492
+ * Automatically mount the OPFS root if not already mounted
493
+ *
494
+ * This method is called internally when file operations are performed
495
+ * without explicitly mounting first.
496
+ *
497
+ * @returns Promise that resolves when auto-mount is complete
498
+ * @throws {OPFSError} If auto-mount fails
499
+ */
500
+ async ensureMounted() {
501
+ if (!this.root) {
502
+ if (this.mountingPromise) {
503
+ await this.mountingPromise;
504
+ return;
505
+ }
506
+ throw new c("OPFS not mounted", "NOT_MOUNTED");
507
+ }
508
+ }
509
+ /**
510
+ * Get a directory handle from a path
511
+ *
512
+ * Navigates through the directory structure to find or create a directory
513
+ * at the specified path.
514
+ *
515
+ * @param path - The path to the directory (string or array of segments)
516
+ * @param create - Whether to create the directory if it doesn't exist (default: false)
517
+ * @param from - The directory to start from (default: root directory)
518
+ * @returns Promise that resolves to the directory handle
519
+ * @throws {OPFSError} If the directory cannot be accessed or created
520
+ *
521
+ * @example
522
+ * \`\`\`typescript
523
+ * const docsDir = await fs.getDirectoryHandle('/users/john/documents', true);
524
+ * const docsDir2 = await fs.getDirectoryHandle(['users', 'john', 'documents'], true);
525
+ * \`\`\`
526
+ */
527
+ async getDirectoryHandle(e, r = !1, a = this.root) {
528
+ if (!a)
529
+ throw new D();
530
+ const n = Array.isArray(e) ? e : m(e);
531
+ let i = a;
532
+ for (const o of n)
533
+ i = await i.getDirectoryHandle(o, { create: r });
534
+ return i;
535
+ }
536
+ /**
537
+ * Get a file handle from a path
538
+ *
539
+ * Navigates to the parent directory and retrieves or creates a file handle
540
+ * for the specified file path.
541
+ *
542
+ * @param path - The path to the file (string or array of segments)
543
+ * @param create - Whether to create the file if it doesn't exist (default: false)
544
+ * @param from - The directory to start from (default: root directory)
545
+ * @returns Promise that resolves to the file handle
546
+ * @throws {PathError} If the path is empty
547
+ * @throws {OPFSError} If the file cannot be accessed or created
548
+ *
549
+ * @example
550
+ * \`\`\`typescript
551
+ * const fileHandle = await fs.getFileHandle('/config/settings.json', true);
552
+ * const fileHandle2 = await fs.getFileHandle(['config', 'settings.json'], true);
553
+ * \`\`\`
554
+ */
555
+ async getFileHandle(e, r = !1, a = this.root) {
556
+ if (!a)
557
+ throw new D();
558
+ const n = m(e);
559
+ if (n.length === 0)
560
+ throw new k("Path must not be empty", Array.isArray(e) ? e.join("/") : e);
561
+ const i = n.pop();
562
+ return (await this.getDirectoryHandle(n, r, a)).getFileHandle(i, { create: r });
563
+ }
564
+ /**
565
+ * Recursively list all files and directories with their stats
566
+ *
567
+ * Traverses the entire file system starting from the root and returns
568
+ * a Map containing all paths and their corresponding file statistics.
569
+ *
570
+ * @param options - Options for indexing
571
+ * @param options.includeHash - Whether to calculate file hash (default: false)
572
+ * @param options.hashAlgorithm - Hash algorithm to use (default: 'SHA-1', fastest)
573
+ * @returns Promise that resolves to a Map of path => FileStat
574
+ * @throws {OPFSError} If the indexing operation fails
575
+ *
576
+ * @example
577
+ * \`\`\`typescript
578
+ * // Basic index without hash
579
+ * const index = await fs.index();
580
+ *
581
+ * // Index with file hash
582
+ * const indexWithHash = await fs.index({
583
+ * includeHash: true,
584
+ * hashAlgorithm: 'SHA-1'
585
+ * });
586
+ *
587
+ * // Iterate through all files and directories
588
+ * for (const [path, stat] of index) {
589
+ * console.log(\`\${path}: \${stat.isFile ? 'file' : 'directory'} (\${stat.size} bytes)\`);
590
+ * if (stat.hash) console.log(\` Hash: \${stat.hash}\`);
591
+ * }
592
+ *
593
+ * // Get specific file stats
594
+ * const fileStats = index.get('/data/config.json');
595
+ * if (fileStats) {
596
+ * console.log(\`File size: \${fileStats.size} bytes\`);
597
+ * if (fileStats.hash) console.log(\`Hash: \${fileStats.hash}\`);
598
+ * }
599
+ * \`\`\`
600
+ */
601
+ async index(e) {
602
+ const r = /* @__PURE__ */ new Map(), a = async (n) => {
603
+ const i = await this.readdir(n, { withFileTypes: !0 });
604
+ for (const o of i) {
605
+ const s = \`\${n === "/" ? "" : n}/\${o.name}\`;
606
+ try {
607
+ const l = await this.stat(s, e);
608
+ r.set(s, l), l.isDirectory && await a(s);
609
+ } catch (l) {
610
+ console.warn(\`Skipping broken entry: \${s}\`, l);
611
+ }
612
+ }
613
+ };
614
+ return r.set("/", {
615
+ kind: "directory",
616
+ size: 0,
617
+ mtime: (/* @__PURE__ */ new Date(0)).toISOString(),
618
+ ctime: (/* @__PURE__ */ new Date(0)).toISOString(),
619
+ isFile: !1,
620
+ isDirectory: !0
621
+ }), await a("/"), r;
622
+ }
623
+ async readFile(e, r = "utf-8") {
624
+ await this.ensureMounted();
625
+ try {
626
+ const a = await this.getFileHandle(e, !1), n = await ue(a);
627
+ return r === "binary" ? n : re(n, r);
628
+ } catch (a) {
629
+ throw console.error(a), new b(e);
630
+ }
631
+ }
632
+ /**
633
+ * Write data to a file
634
+ *
635
+ * Creates or overwrites a file with the specified data. If the file already
636
+ * exists, it will be truncated before writing.
637
+ *
638
+ * @param path - The path to the file to write
639
+ * @param data - The data to write to the file (string, Uint8Array, or ArrayBuffer)
640
+ * @param encoding - The encoding to use when writing string data (default: 'utf-8')
641
+ * @returns Promise that resolves when the write operation is complete
642
+ * @throws {OPFSError} If writing the file fails
643
+ *
644
+ * @example
645
+ * \`\`\`typescript
646
+ * // Write text data
647
+ * await fs.writeFile('/config/settings.json', JSON.stringify({ theme: 'dark' }));
648
+ *
649
+ * // Write binary data
650
+ * const binaryData = new Uint8Array([1, 2, 3, 4, 5]);
651
+ * await fs.writeFile('/data/binary.dat', binaryData);
652
+ *
653
+ * // Write with specific encoding
654
+ * await fs.writeFile('/data/utf16.txt', 'Hello World', 'utf-16le');
655
+ * \`\`\`
656
+ */
657
+ async writeFile(e, r, a) {
658
+ await this.ensureMounted();
659
+ const n = await this.getFileHandle(e, !0);
660
+ await C(n, r, a, { truncate: !0 });
661
+ }
662
+ /**
663
+ * Append data to a file
664
+ *
665
+ * Adds data to the end of an existing file. If the file doesn't exist,
666
+ * it will be created.
667
+ *
668
+ * @param path - The path to the file to append to
669
+ * @param data - The data to append to the file (string, Uint8Array, or ArrayBuffer)
670
+ * @param encoding - The encoding to use when appending string data (default: 'utf-8')
671
+ * @returns Promise that resolves when the append operation is complete
672
+ * @throws {OPFSError} If appending to the file fails
673
+ *
674
+ * @example
675
+ * \`\`\`typescript
676
+ * // Append text to a log file
677
+ * await fs.appendFile('/logs/app.log', \`[\${new Date().toISOString()}] User logged in\\n\`);
678
+ *
679
+ * // Append binary data
680
+ * const additionalData = new Uint8Array([6, 7, 8]);
681
+ * await fs.appendFile('/data/binary.dat', additionalData);
682
+ * \`\`\`
683
+ */
684
+ async appendFile(e, r, a) {
685
+ await this.ensureMounted();
686
+ const n = await this.getFileHandle(e, !0);
687
+ await C(n, r, a, { append: !0 });
688
+ }
689
+ /**
690
+ * Create a directory
691
+ *
692
+ * Creates a new directory at the specified path. If the recursive option
693
+ * is enabled, parent directories will be created as needed.
694
+ *
695
+ * @param path - The path where the directory should be created
696
+ * @param options - Options for directory creation
697
+ * @param options.recursive - Whether to create parent directories if they don't exist (default: false)
698
+ * @returns Promise that resolves when the directory is created
699
+ * @throws {OPFSError} If the directory cannot be created
700
+ *
701
+ * @example
702
+ * \`\`\`typescript
703
+ * // Create a single directory
704
+ * await fs.mkdir('/users/john');
705
+ *
706
+ * // Create nested directories
707
+ * await fs.mkdir('/users/john/documents/projects', { recursive: true });
708
+ * \`\`\`
709
+ */
710
+ async mkdir(e, r) {
711
+ if (await this.ensureMounted(), !this.root)
712
+ throw new D();
713
+ const a = r?.recursive ?? !1, n = m(e);
714
+ let i = this.root;
715
+ for (let o = 0; o < n.length; o++) {
716
+ const s = n[o];
717
+ try {
718
+ i = await i.getDirectoryHandle(s, { create: a || o === n.length - 1 });
719
+ } catch (l) {
720
+ throw l.name === "NotFoundError" ? new c(
721
+ \`Parent directory does not exist: \${v(n.slice(0, o + 1))}\`,
722
+ "ENOENT"
723
+ ) : l.name === "TypeMismatchError" ? new c(\`Path segment is not a directory: \${s}\`, "ENOTDIR") : new c("Failed to create directory", "MKDIR_FAILED");
724
+ }
725
+ }
726
+ }
727
+ /**
728
+ * Get file or directory stats
729
+ *
730
+ * Retrieves metadata about a file or directory, including size, modification time,
731
+ * type information, and optionally file hashes.
732
+ *
733
+ * @param path - The path to the file or directory
734
+ * @param options - Options for stat operation
735
+ * @param options.includeHash - Whether to calculate file hash (default: false, only for files)
736
+ * @param options.hashAlgorithm - Hash algorithm to use (default: 'SHA-1', fastest)
737
+ * @returns Promise that resolves to file/directory statistics
738
+ * @throws {OPFSError} If the file or directory does not exist or cannot be accessed
739
+ *
740
+ * @example
741
+ * \`\`\`typescript
742
+ * // Basic stats
743
+ * const stats = await fs.stat('/config/settings.json');
744
+ * console.log(\`File size: \${stats.size} bytes\`);
745
+ * console.log(\`Is file: \${stats.isFile}\`);
746
+ * console.log(\`Modified: \${stats.mtime}\`);
747
+ *
748
+ * // Stats with hash (SHA-1 is fastest)
749
+ * const statsWithHash = await fs.stat('/config/settings.json', {
750
+ * includeHash: true,
751
+ * hashAlgorithm: 'SHA-1'
752
+ * });
753
+ * console.log(\`Hash: \${statsWithHash.hash}\`);
754
+ * \`\`\`
755
+ */
756
+ async stat(e, r) {
757
+ if (await this.ensureMounted(), e === "/")
758
+ return {
759
+ kind: "directory",
760
+ size: 0,
761
+ mtime: (/* @__PURE__ */ new Date(0)).toISOString(),
762
+ ctime: (/* @__PURE__ */ new Date(0)).toISOString(),
763
+ isFile: !1,
764
+ isDirectory: !0
765
+ };
766
+ const a = I(e), n = await this.getDirectoryHandle(P(e), !1), i = r?.includeHash ?? !1, o = r?.hashAlgorithm ?? "SHA-1";
767
+ try {
768
+ const l = await (await n.getFileHandle(a, { create: !1 })).getFile(), u = {
769
+ kind: "file",
770
+ size: l.size,
771
+ mtime: new Date(l.lastModified).toISOString(),
772
+ ctime: new Date(l.lastModified).toISOString(),
773
+ isFile: !0,
774
+ isDirectory: !1
775
+ };
776
+ if (i)
777
+ try {
778
+ const f = new Uint8Array(await l.arrayBuffer()), w = await fe(f, o);
779
+ u.hash = w;
780
+ } catch (f) {
781
+ console.warn(\`Failed to calculate hash for \${e}:\`, f);
782
+ }
783
+ return u;
784
+ } catch (s) {
785
+ if (s.name !== "TypeMismatchError" && s.name !== "NotFoundError")
786
+ throw new c("Failed to stat (file)", "STAT_FAILED");
787
+ }
788
+ try {
789
+ return await n.getDirectoryHandle(a, { create: !1 }), {
790
+ kind: "directory",
791
+ size: 0,
792
+ mtime: (/* @__PURE__ */ new Date(0)).toISOString(),
793
+ ctime: (/* @__PURE__ */ new Date(0)).toISOString(),
794
+ isFile: !1,
795
+ isDirectory: !0
796
+ };
797
+ } catch (s) {
798
+ throw s.name === "NotFoundError" ? new c(\`No such file or directory: \${e}\`, "ENOENT") : new c("Failed to stat (directory)", "STAT_FAILED");
799
+ }
800
+ }
801
+ async readdir(e, r) {
802
+ await this.ensureMounted();
803
+ const a = r?.withFileTypes ?? !1, n = await this.getDirectoryHandle(e, !1);
804
+ if (a) {
805
+ const i = [];
806
+ for await (const [o, s] of n.entries()) {
807
+ const l = s.kind === "file";
808
+ i.push({
809
+ name: o,
810
+ kind: s.kind,
811
+ isFile: l,
812
+ isDirectory: !l
813
+ });
814
+ }
815
+ return i;
816
+ } else {
817
+ const i = [];
818
+ for await (const [o] of n.entries())
819
+ i.push(o);
820
+ return i;
821
+ }
822
+ }
823
+ /**
824
+ * Check if a file or directory exists
825
+ *
826
+ * Verifies if a file or directory exists at the specified path.
827
+ *
828
+ * @param path - The path to check
829
+ * @returns Promise that resolves to true if the file or directory exists, false otherwise
830
+ *
831
+ * @example
832
+ * \`\`\`typescript
833
+ * const exists = await fs.exists('/config/settings.json');
834
+ * console.log(\`File exists: \${exists}\`);
835
+ * \`\`\`
836
+ */
837
+ async exists(e) {
838
+ if (await this.ensureMounted(), e === "/")
839
+ return !0;
840
+ const r = I(e);
841
+ let a = null;
842
+ try {
843
+ a = await this.getDirectoryHandle(P(e), !1);
844
+ } catch (n) {
845
+ throw (n.name === "NotFoundError" || n.name === "TypeMismatchError") && (a = null), n;
846
+ }
847
+ if (!a || !r)
848
+ return !1;
849
+ try {
850
+ return await a.getFileHandle(r, { create: !1 }), !0;
851
+ } catch (n) {
852
+ if (n.name !== "NotFoundError" && n.name !== "TypeMismatchError")
853
+ throw n;
854
+ }
855
+ try {
856
+ return await a.getDirectoryHandle(r, { create: !1 }), !0;
857
+ } catch (n) {
858
+ if (n.name !== "NotFoundError" && n.name !== "TypeMismatchError")
859
+ throw n;
860
+ }
861
+ return !1;
862
+ }
863
+ /**
864
+ * Clear all contents of a directory without removing the directory itself
865
+ *
866
+ * Removes all files and subdirectories within the specified directory,
867
+ * but keeps the directory itself.
868
+ *
869
+ * @param path - The path to the directory to clear (default: '/')
870
+ * @returns Promise that resolves when all contents are removed
871
+ * @throws {OPFSError} If the operation fails
872
+ *
873
+ * @example
874
+ * \`\`\`typescript
875
+ * // Clear root directory contents
876
+ * await fs.clear('/');
877
+ *
878
+ * // Clear specific directory contents
879
+ * await fs.clear('/data');
880
+ * \`\`\`
881
+ */
882
+ async clear(e = "/") {
883
+ await this.ensureMounted();
884
+ try {
885
+ const r = await this.readdir(e, { withFileTypes: !0 });
886
+ for (const a of r) {
887
+ const n = \`\${e === "/" ? "" : e}/\${a.name}\`;
888
+ await this.remove(n, { recursive: !0 });
889
+ }
890
+ } catch (r) {
891
+ throw r instanceof c ? r : new c(\`Failed to clear directory: \${e}\`, "CLEAR_FAILED");
892
+ }
893
+ }
894
+ /**
895
+ * Remove files and directories
896
+ *
897
+ * Removes files and directories. Similar to Node.js fs.rm().
898
+ *
899
+ * @param path - The path to remove
900
+ * @param options - Options for removal
901
+ * @param options.recursive - Whether to remove directories and their contents recursively (default: false)
902
+ * @param options.force - Whether to ignore errors if the path doesn't exist (default: false)
903
+ * @returns Promise that resolves when the removal is complete
904
+ * @throws {OPFSError} If the removal fails
905
+ *
906
+ * @example
907
+ * \`\`\`typescript
908
+ * // Remove a file
909
+ * await fs.rm('/path/to/file.txt');
910
+ *
911
+ * // Remove a directory and all its contents
912
+ * await fs.rm('/path/to/directory', { recursive: true });
913
+ *
914
+ * // Remove with force (ignore if doesn't exist)
915
+ * await fs.rm('/maybe/exists', { force: true });
916
+ * \`\`\`
917
+ */
918
+ async remove(e, r) {
919
+ await this.ensureMounted();
920
+ const a = r?.recursive ?? !1, n = r?.force ?? !1;
921
+ if (e === "/")
922
+ throw new c("Cannot remove root directory", "EROOT");
923
+ const i = I(e);
924
+ if (!i)
925
+ throw new k("Invalid path", e);
926
+ const o = await this.getDirectoryHandle(P(e), !1);
927
+ try {
928
+ await o.removeEntry(i, { recursive: a });
929
+ } catch (s) {
930
+ if (s.name === "NotFoundError") {
931
+ if (!n)
932
+ throw new c(\`No such file or directory: \${e}\`, "ENOENT");
933
+ } else throw s.name === "InvalidModificationError" ? new c(\`Directory not empty: \${e}. Use recursive option to force removal.\`, "ENOTEMPTY") : s.name === "TypeMismatchError" && !a ? new c(\`Cannot remove directory without recursive option: \${e}\`, "EISDIR") : new c(\`Failed to remove path: \${e}\`, "RM_FAILED");
934
+ }
935
+ }
936
+ /**
937
+ * Resolve a path to an absolute path
938
+ *
939
+ * Resolves relative paths and normalizes path segments (like '..' and '.').
940
+ * Similar to Node.js fs.realpath() but without symlink resolution since OPFS doesn't support symlinks.
941
+ *
942
+ * @param path - The path to resolve
943
+ * @returns Promise that resolves to the absolute normalized path
944
+ * @throws {FileNotFoundError} If the path does not exist
945
+ * @throws {OPFSError} If path resolution fails
946
+ *
947
+ * @example
948
+ * \`\`\`typescript
949
+ * // Resolve relative path
950
+ * const absolute = await fs.realpath('./config/../data/file.txt');
951
+ * console.log(absolute); // '/data/file.txt'
952
+ * \`\`\`
953
+ */
954
+ async realpath(e) {
955
+ await this.ensureMounted();
956
+ try {
957
+ const r = ce(e);
958
+ if (!await this.exists(r))
959
+ throw new b(r);
960
+ return r;
961
+ } catch (r) {
962
+ throw r instanceof c ? r : new c(\`Failed to resolve path: \${e}\`, "REALPATH_FAILED");
963
+ }
964
+ }
965
+ /**
966
+ * Rename a file or directory
967
+ *
968
+ * Changes the name of a file or directory. If the target path already exists,
969
+ * it will be replaced.
970
+ *
971
+ * @param oldPath - The current path of the file or directory
972
+ * @param newPath - The new path for the file or directory
973
+ * @returns Promise that resolves when the rename operation is complete
974
+ * @throws {OPFSError} If the rename operation fails
975
+ *
976
+ * @example
977
+ * \`\`\`typescript
978
+ * await fs.rename('/old/path/file.txt', '/new/path/renamed.txt');
979
+ * \`\`\`
980
+ */
981
+ async rename(e, r) {
982
+ await this.ensureMounted();
983
+ try {
984
+ if (!await this.exists(e))
985
+ throw new b(e);
986
+ await this.copy(e, r, { recursive: !0 }), await this.remove(e, { recursive: !0 });
987
+ } catch (a) {
988
+ throw a instanceof c ? a : new c(\`Failed to rename from \${e} to \${r}\`, "RENAME_FAILED");
989
+ }
990
+ }
991
+ /**
992
+ * Copy files and directories
993
+ *
994
+ * Copies files and directories. Similar to Node.js fs.cp().
995
+ *
996
+ * @param source - The source path to copy from
997
+ * @param destination - The destination path to copy to
998
+ * @param options - Options for copying
999
+ * @param options.recursive - Whether to copy directories recursively (default: false)
1000
+ * @param options.force - Whether to overwrite existing files (default: true)
1001
+ * @returns Promise that resolves when the copy operation is complete
1002
+ * @throws {OPFSError} If the copy operation fails
1003
+ *
1004
+ * @example
1005
+ * \`\`\`typescript
1006
+ * // Copy a file
1007
+ * await fs.copy('/source/file.txt', '/dest/file.txt');
1008
+ *
1009
+ * // Copy a directory and all its contents
1010
+ * await fs.copy('/source/dir', '/dest/dir', { recursive: true });
1011
+ *
1012
+ * // Copy without overwriting existing files
1013
+ * await fs.copy('/source', '/dest', { recursive: true, force: false });
1014
+ * \`\`\`
1015
+ */
1016
+ async copy(e, r, a) {
1017
+ await this.ensureMounted();
1018
+ try {
1019
+ const n = a?.recursive ?? !1, i = a?.force ?? !0;
1020
+ if (!await this.exists(e))
1021
+ throw new c(\`Source does not exist: \${e}\`, "ENOENT");
1022
+ if (await this.exists(r) && !i)
1023
+ throw new c(\`Destination already exists: \${r}\`, "EEXIST");
1024
+ if ((await this.stat(e)).isFile) {
1025
+ const u = await this.readFile(e, "binary");
1026
+ await this.writeFile(r, u);
1027
+ } else {
1028
+ if (!n)
1029
+ throw new c(\`Cannot copy directory without recursive option: \${e}\`, "EISDIR");
1030
+ await this.mkdir(r, { recursive: !0 });
1031
+ const u = await this.readdir(e, { withFileTypes: !0 });
1032
+ for (const f of u) {
1033
+ const w = \`\${e}/\${f.name}\`, h = \`\${r}/\${f.name}\`;
1034
+ await this.copy(w, h, { recursive: !0, force: i });
1035
+ }
1036
+ }
1037
+ } catch (n) {
1038
+ throw n instanceof c ? n : new c(\`Failed to copy from \${e} to \${r}\`, "CP_FAILED");
1039
+ }
1040
+ }
1041
+ /**
1042
+ * Start watching a file or directory for changes
1043
+ */
1044
+ async watch(e) {
1045
+ await this.ensureMounted();
1046
+ const r = M(e), a = await this.buildSnapshot(r);
1047
+ this.watchers.set(r, a), this.watchTimer || (this.watchTimer = setInterval(() => {
1048
+ this.scanWatches();
1049
+ }, this.watchInterval));
1050
+ }
1051
+ /**
1052
+ * Stop watching a previously watched path
1053
+ */
1054
+ unwatch(e) {
1055
+ const r = M(e);
1056
+ this.watchers.delete(r), this.watchers.size === 0 && this.watchTimer && (clearInterval(this.watchTimer), this.watchTimer = null);
1057
+ }
1058
+ async buildSnapshot(e) {
1059
+ const r = /* @__PURE__ */ new Map(), a = async (n) => {
1060
+ const i = await this.stat(n);
1061
+ if (r.set(n, i), i.isDirectory) {
1062
+ const o = await this.readdir(n, { withFileTypes: !0 });
1063
+ for (const s of o) {
1064
+ const l = \`\${n === "/" ? "" : n}/\${s.name}\`;
1065
+ await a(l);
1066
+ }
1067
+ }
1068
+ };
1069
+ return await a(e), r;
1070
+ }
1071
+ async scanWatches() {
1072
+ if (!this.scanning) {
1073
+ this.scanning = !0;
1074
+ try {
1075
+ await Promise.all(
1076
+ [...this.watchers.entries()].map(async ([e, r]) => {
1077
+ let a;
1078
+ try {
1079
+ a = await this.buildSnapshot(e);
1080
+ } catch {
1081
+ a = /* @__PURE__ */ new Map();
1082
+ }
1083
+ const n = [];
1084
+ for (const [i, o] of a) {
1085
+ const s = r.get(i);
1086
+ s ? (s.mtime !== o.mtime || s.size !== o.size) && n.push({ path: i, type: "change" }) : n.push({ path: i, type: "create" });
1087
+ }
1088
+ for (const i of r.keys())
1089
+ a.has(i) || n.push({ path: i, type: "delete" });
1090
+ if (n.length && this.watchCallback)
1091
+ for (const i of n)
1092
+ this.watchCallback(i);
1093
+ this.watchers.set(e, a);
1094
+ })
1095
+ );
1096
+ } finally {
1097
+ this.scanning = !1;
1098
+ }
1099
+ }
1100
+ }
1101
+ /**
1102
+ * Synchronize the file system with external data
1103
+ *
1104
+ * Syncs the file system with an array of entries containing paths and data.
1105
+ * This is useful for importing data from external sources or syncing with remote data.
1106
+ *
1107
+ * @param entries - Array of [path, data] tuples to sync
1108
+ * @param options - Options for synchronization
1109
+ * @param options.cleanBefore - Whether to clear the file system before syncing (default: false)
1110
+ * @returns Promise that resolves when synchronization is complete
1111
+ * @throws {OPFSError} If the synchronization fails
1112
+ *
1113
+ * @example
1114
+ * \`\`\`typescript
1115
+ * // Sync with external data
1116
+ * const entries: [string, string | Uint8Array | Blob][] = [
1117
+ * ['/config.json', JSON.stringify({ theme: 'dark' })],
1118
+ * ['/data/binary.dat', new Uint8Array([1, 2, 3, 4])],
1119
+ * ['/upload.txt', new Blob(['file content'], { type: 'text/plain' })]
1120
+ * ];
1121
+ *
1122
+ * // Sync without clearing existing files
1123
+ * await fs.sync(entries);
1124
+ *
1125
+ * // Clean file system and then sync
1126
+ * await fs.sync(entries, { cleanBefore: true });
1127
+ * \`\`\`
1128
+ */
1129
+ async sync(e, r) {
1130
+ await this.ensureMounted();
1131
+ try {
1132
+ (r?.cleanBefore ?? !1) && await this.clear("/");
1133
+ for (const [n, i] of e) {
1134
+ const o = M(n);
1135
+ let s;
1136
+ i instanceof Blob ? s = await he(i) : s = i, await this.writeFile(o, s);
1137
+ }
1138
+ } catch (a) {
1139
+ throw a instanceof c ? a : new c("Failed to sync file system", "SYNC_FAILED");
1140
+ }
1141
+ }
1142
+ }
1143
+ typeof self < "u" && self.constructor.name === "DedicatedWorkerGlobalScope" && x(new we());
1144
+ //# sourceMappingURL=worker-CRHhlrlS.js.map
1145
+ `, r = typeof self < "u" && self.Blob && new Blob(["URL.revokeObjectURL(import.meta.url);", a], { type: "text/javascript;charset=utf-8" });
1146
+ function s(e) {
1147
+ let n;
1148
+ try {
1149
+ if (n = r && (self.URL || self.webkitURL).createObjectURL(r), !n) throw "";
1150
+ const t = new Worker(n, {
1151
+ type: "module",
1152
+ name: e?.name
1153
+ });
1154
+ return t.addEventListener("error", () => {
1155
+ (self.URL || self.webkitURL).revokeObjectURL(n);
1156
+ }), t;
1157
+ } catch {
1158
+ return new Worker(
1159
+ "data:text/javascript;charset=utf-8," + encodeURIComponent(a),
1160
+ {
1161
+ type: "module",
1162
+ name: e?.name
1163
+ }
1164
+ );
1165
+ }
1166
+ }
1167
+ function l(e, n) {
1168
+ const t = i(new s());
1169
+ return e && t.setWatchCallback(o(e), n), t;
1170
+ }
1171
+ export {
1172
+ u as DirectoryNotFoundError,
1173
+ d as FileNotFoundError,
1174
+ p as OPFSError,
1175
+ w as OPFSNotMountedError,
1176
+ y as OPFSNotSupportedError,
1177
+ m as PathError,
1178
+ g as PermissionError,
1179
+ v as StorageError,
1180
+ E as TimeoutError,
1181
+ S as basename,
1182
+ F as calculateFileHash,
1183
+ b as checkOPFSSupport,
1184
+ P as convertBlobToUint8Array,
1185
+ x as createBuffer,
1186
+ l as createWorker,
1187
+ A as decodeBuffer,
1188
+ T as dirname,
1189
+ O as encodeString,
1190
+ I as extname,
1191
+ _ as joinPath,
1192
+ D as normalizePath,
1193
+ k as readFileData,
1194
+ R as resolvePath,
1195
+ U as splitPath,
1196
+ C as writeFileData
1197
+ };
1198
+ //# sourceMappingURL=index.js.map