opfs-worker 0.2.1 → 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/index.cjs CHANGED
@@ -1,13 +1,13 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("comlink"),n=require("./helpers-hEpet7x7.cjs"),i=`/**
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const a=require("comlink"),n=require("./helpers-hEpet7x7.cjs"),o=`/**
2
2
  * @license
3
3
  * Copyright 2019 Google LLC
4
4
  * SPDX-License-Identifier: Apache-2.0
5
5
  */
6
- const M = Symbol("Comlink.proxy"), R = Symbol("Comlink.endpoint"), B = Symbol("Comlink.releaseProxy"), T = Symbol("Comlink.finalizer"), p = Symbol("Comlink.thrown"), $ = (e) => typeof e == "object" && e !== null || typeof e == "function", W = {
7
- canHandle: (e) => $(e) && e[M],
6
+ const H = Symbol("Comlink.proxy"), R = Symbol("Comlink.endpoint"), B = Symbol("Comlink.releaseProxy"), T = Symbol("Comlink.finalizer"), p = Symbol("Comlink.thrown"), $ = (e) => typeof e == "object" && e !== null || typeof e == "function", W = {
7
+ canHandle: (e) => $(e) && e[H],
8
8
  serialize(e) {
9
9
  const { port1: t, port2: r } = new MessageChannel();
10
- return N(e, t), [r, [r]];
10
+ return O(e, t), [r, [r]];
11
11
  },
12
12
  deserialize(e) {
13
13
  return e.start(), Y(e);
@@ -38,7 +38,7 @@ function V(e, t) {
38
38
  return !0;
39
39
  return !1;
40
40
  }
41
- function N(e, t = globalThis, r = ["*"]) {
41
+ function O(e, t = globalThis, r = ["*"]) {
42
42
  t.addEventListener("message", function a(n) {
43
43
  if (!n || !n.data)
44
44
  return;
@@ -46,45 +46,45 @@ function N(e, t = globalThis, r = ["*"]) {
46
46
  console.warn(\`Invalid origin '\${n.origin}' for comlink proxy\`);
47
47
  return;
48
48
  }
49
- const { id: s, type: o, path: i } = Object.assign({ path: [] }, n.data), c = (n.data.argumentList || []).map(y);
50
- let f;
49
+ const { id: s, type: o, path: i } = Object.assign({ path: [] }, n.data), l = (n.data.argumentList || []).map(d);
50
+ let u;
51
51
  try {
52
- const u = i.slice(0, -1).reduce((h, g) => h[g], e), w = i.reduce((h, g) => h[g], e);
52
+ const f = i.slice(0, -1).reduce((h, g) => h[g], e), w = i.reduce((h, g) => h[g], e);
53
53
  switch (o) {
54
54
  case "GET":
55
- f = w;
55
+ u = w;
56
56
  break;
57
57
  case "SET":
58
- u[i.slice(-1)[0]] = y(n.data.value), f = !0;
58
+ f[i.slice(-1)[0]] = d(n.data.value), u = !0;
59
59
  break;
60
60
  case "APPLY":
61
- f = w.apply(u, c);
61
+ u = w.apply(f, l);
62
62
  break;
63
63
  case "CONSTRUCT":
64
64
  {
65
- const h = new w(...c);
66
- f = Q(h);
65
+ const h = new w(...l);
66
+ u = Q(h);
67
67
  }
68
68
  break;
69
69
  case "ENDPOINT":
70
70
  {
71
71
  const { port1: h, port2: g } = new MessageChannel();
72
- N(e, g), f = J(h, [h]);
72
+ O(e, g), u = J(h, [h]);
73
73
  }
74
74
  break;
75
75
  case "RELEASE":
76
- f = void 0;
76
+ u = void 0;
77
77
  break;
78
78
  default:
79
79
  return;
80
80
  }
81
- } catch (u) {
82
- f = { value: u, [p]: 0 };
81
+ } catch (f) {
82
+ u = { value: f, [p]: 0 };
83
83
  }
84
- Promise.resolve(f).catch((u) => ({ value: u, [p]: 0 })).then((u) => {
85
- const [w, h] = A(u);
84
+ Promise.resolve(u).catch((f) => ({ value: f, [p]: 0 })).then((f) => {
85
+ const [w, h] = A(f);
86
86
  t.postMessage(Object.assign(Object.assign({}, w), { id: s }), h), o === "RELEASE" && (t.removeEventListener("message", a), L(t), T in e && typeof e[T] == "function" && e[T]());
87
- }).catch((u) => {
87
+ }).catch((f) => {
88
88
  const [w, h] = A({
89
89
  value: new TypeError("Unserializable return value"),
90
90
  [p]: 0
@@ -112,14 +112,14 @@ function Y(e, t) {
112
112
  } finally {
113
113
  r.delete(s.id);
114
114
  }
115
- }), P(e, r, [], t);
115
+ }), x(e, r, [], t);
116
116
  }
117
117
  function E(e) {
118
118
  if (e)
119
119
  throw new Error("Proxy has been released and is not useable");
120
120
  }
121
121
  function z(e) {
122
- return d(e, /* @__PURE__ */ new Map(), {
122
+ return y(e, /* @__PURE__ */ new Map(), {
123
123
  type: "RELEASE"
124
124
  }).then(() => {
125
125
  L(e);
@@ -136,7 +136,7 @@ function X(e, t) {
136
136
  function q(e) {
137
137
  S && S.unregister(e);
138
138
  }
139
- function P(e, t, r = [], a = function() {
139
+ function x(e, t, r = [], a = function() {
140
140
  }) {
141
141
  let n = !1;
142
142
  const s = new Proxy(a, {
@@ -148,47 +148,47 @@ function P(e, t, r = [], a = function() {
148
148
  if (i === "then") {
149
149
  if (r.length === 0)
150
150
  return { then: () => s };
151
- const c = d(e, t, {
151
+ const l = y(e, t, {
152
152
  type: "GET",
153
- path: r.map((f) => f.toString())
154
- }).then(y);
155
- return c.then.bind(c);
153
+ path: r.map((u) => u.toString())
154
+ }).then(d);
155
+ return l.then.bind(l);
156
156
  }
157
- return P(e, t, [...r, i]);
157
+ return x(e, t, [...r, i]);
158
158
  },
159
- set(o, i, c) {
159
+ set(o, i, l) {
160
160
  E(n);
161
- const [f, u] = A(c);
162
- return d(e, t, {
161
+ const [u, f] = A(l);
162
+ return y(e, t, {
163
163
  type: "SET",
164
164
  path: [...r, i].map((w) => w.toString()),
165
- value: f
166
- }, u).then(y);
165
+ value: u
166
+ }, f).then(d);
167
167
  },
168
- apply(o, i, c) {
168
+ apply(o, i, l) {
169
169
  E(n);
170
- const f = r[r.length - 1];
171
- if (f === R)
172
- return d(e, t, {
170
+ const u = r[r.length - 1];
171
+ if (u === R)
172
+ return y(e, t, {
173
173
  type: "ENDPOINT"
174
- }).then(y);
175
- if (f === "bind")
176
- return P(e, t, r.slice(0, -1));
177
- const [u, w] = k(c);
178
- return d(e, t, {
174
+ }).then(d);
175
+ if (u === "bind")
176
+ return x(e, t, r.slice(0, -1));
177
+ const [f, w] = v(l);
178
+ return y(e, t, {
179
179
  type: "APPLY",
180
180
  path: r.map((h) => h.toString()),
181
- argumentList: u
182
- }, w).then(y);
181
+ argumentList: f
182
+ }, w).then(d);
183
183
  },
184
184
  construct(o, i) {
185
185
  E(n);
186
- const [c, f] = k(i);
187
- return d(e, t, {
186
+ const [l, u] = v(i);
187
+ return y(e, t, {
188
188
  type: "CONSTRUCT",
189
- path: r.map((u) => u.toString()),
190
- argumentList: c
191
- }, f).then(y);
189
+ path: r.map((f) => f.toString()),
190
+ argumentList: l
191
+ }, u).then(d);
192
192
  }
193
193
  });
194
194
  return X(s, e), s;
@@ -196,7 +196,7 @@ function P(e, t, r = [], a = function() {
196
196
  function K(e) {
197
197
  return Array.prototype.concat.apply([], e);
198
198
  }
199
- function k(e) {
199
+ function v(e) {
200
200
  const t = e.map(A);
201
201
  return [t.map((r) => r[0]), K(t.map((r) => r[1]))];
202
202
  }
@@ -205,7 +205,7 @@ function J(e, t) {
205
205
  return _.set(e, t), e;
206
206
  }
207
207
  function Q(e) {
208
- return Object.assign(e, { [M]: !0 });
208
+ return Object.assign(e, { [H]: !0 });
209
209
  }
210
210
  function A(e) {
211
211
  for (const [t, r] of U)
@@ -228,7 +228,7 @@ function A(e) {
228
228
  _.get(e) || []
229
229
  ];
230
230
  }
231
- function y(e) {
231
+ function d(e) {
232
232
  switch (e.type) {
233
233
  case "HANDLER":
234
234
  return U.get(e.name).deserialize(e.value);
@@ -236,7 +236,7 @@ function y(e) {
236
236
  return e.value;
237
237
  }
238
238
  }
239
- function d(e, t, r, a) {
239
+ function y(e, t, r, a) {
240
240
  return new Promise((n) => {
241
241
  const s = Z();
242
242
  t.set(s, n), e.start && e.start(), e.postMessage(Object.assign({ id: s }, r), a);
@@ -245,27 +245,27 @@ function d(e, t, r, a) {
245
245
  function Z() {
246
246
  return new Array(4).fill(0).map(() => Math.floor(Math.random() * Number.MAX_SAFE_INTEGER).toString(16)).join("-");
247
247
  }
248
- class l extends Error {
248
+ class c extends Error {
249
249
  constructor(t, r, a) {
250
250
  super(t), this.code = r, this.path = a, this.name = "OPFSError";
251
251
  }
252
252
  }
253
- class ee extends l {
253
+ class ee extends c {
254
254
  constructor() {
255
255
  super("OPFS is not supported in this browser", "OPFS_NOT_SUPPORTED");
256
256
  }
257
257
  }
258
- class D extends l {
258
+ class D extends c {
259
259
  constructor() {
260
260
  super("OPFS is not mounted", "OPFS_NOT_MOUNTED");
261
261
  }
262
262
  }
263
- class v extends l {
263
+ class k extends c {
264
264
  constructor(t, r) {
265
265
  super(t, "INVALID_PATH", r);
266
266
  }
267
267
  }
268
- class b extends l {
268
+ class b extends c {
269
269
  constructor(t) {
270
270
  super(\`File not found: \${t}\`, "FILE_NOT_FOUND", t);
271
271
  }
@@ -289,7 +289,7 @@ function te(e, t = "utf-8") {
289
289
  return Uint8Array.from(atob(e), (r) => r.charCodeAt(0));
290
290
  case "hex":
291
291
  if (!/^[\\da-f]+$/i.test(e) || e.length % 2 !== 0)
292
- throw new l("Invalid hex string", "INVALID_HEX_FORMAT");
292
+ throw new c("Invalid hex string", "INVALID_HEX_FORMAT");
293
293
  return Uint8Array.from(e.match(/.{1,2}/g).map((r) => parseInt(r, 16)));
294
294
  default:
295
295
  return console.warn("Encoding not supported, falling back to UTF-8"), new TextEncoder().encode(e);
@@ -350,18 +350,18 @@ function oe() {
350
350
  function m(e) {
351
351
  return Array.isArray(e) ? e : e.split("/").filter(Boolean);
352
352
  }
353
- function H(e) {
353
+ function N(e) {
354
354
  return typeof e == "string" ? e ?? "/" : \`/\${e.join("/")}\`;
355
355
  }
356
- function I(e) {
356
+ function P(e) {
357
357
  const t = m(e);
358
358
  return t[t.length - 1] || "";
359
359
  }
360
- function x(e) {
360
+ function M(e) {
361
361
  const t = m(e);
362
- return t.pop(), H(t);
362
+ return t.pop(), N(t);
363
363
  }
364
- function O(e) {
364
+ function I(e) {
365
365
  return !e || e === "/" ? "/" : e.startsWith("/") ? e : \`/\${e}\`;
366
366
  }
367
367
  function ce(e) {
@@ -374,12 +374,12 @@ function ce(e) {
374
374
  r.pop();
375
375
  } else
376
376
  r.push(a);
377
- return H(r);
377
+ return N(r);
378
378
  }
379
379
  function le(e, t = "utf-8") {
380
380
  return typeof e == "string" ? te(e, t) : e instanceof Uint8Array ? e : new Uint8Array(e);
381
381
  }
382
- async function fe(e) {
382
+ async function ue(e) {
383
383
  const t = await e.createSyncAccessHandle();
384
384
  try {
385
385
  const r = t.getSize(), a = new Uint8Array(r);
@@ -397,7 +397,7 @@ async function C(e, t, r, a = {}) {
397
397
  } catch (s) {
398
398
  console.error(s);
399
399
  const o = a.append ? "append" : "write";
400
- throw new l(\`Failed to \${o} file\`, \`\${o.toUpperCase()}_FAILED\`);
400
+ throw new c(\`Failed to \${o} file\`, \`\${o.toUpperCase()}_FAILED\`);
401
401
  } finally {
402
402
  if (n)
403
403
  try {
@@ -406,7 +406,7 @@ async function C(e, t, r, a = {}) {
406
406
  }
407
407
  }
408
408
  }
409
- async function ue(e, t = "SHA-1") {
409
+ async function fe(e, t = "SHA-1") {
410
410
  try {
411
411
  const r = new Uint8Array(e), a = await crypto.subtle.digest(t, r);
412
412
  return Array.from(new Uint8Array(a)).map((s) => s.toString(16).padStart(2, "0")).join("");
@@ -431,19 +431,23 @@ class we {
431
431
  watchInterval = 1e3;
432
432
  /** Flag to avoid concurrent scans */
433
433
  scanning = !1;
434
+ /** Promise to prevent concurrent mount operations */
435
+ mountingPromise = null;
434
436
  /**
435
437
  * Creates a new OPFSFileSystem instance
436
438
  *
439
+ * @param watchCallback - Optional callback for file change events
440
+ * @param watchOptions - Optional configuration for watching
437
441
  * @throws {OPFSError} If OPFS is not supported in the current browser
438
442
  */
439
- constructor() {
440
- oe();
443
+ constructor(t, r) {
444
+ oe(), t && (this.watchCallback = t, r?.watchInterval && (this.watchInterval = r.watchInterval)), this.mount("/");
441
445
  }
442
446
  /**
443
447
  * Initialize the file system within a given directory
444
448
  *
445
449
  * This method sets up the root directory for all subsequent operations.
446
- * It must be called before any other file system operations.
450
+ * If no root is specified, it will use the OPFS root directory.
447
451
  *
448
452
  * @param root - The root path for the file system (default: '/')
449
453
  * @returns Promise that resolves to true if initialization was successful
@@ -452,15 +456,52 @@ class we {
452
456
  * @example
453
457
  * \`\`\`typescript
454
458
  * const fs = new OPFSFileSystem();
455
- * const success = await fs.init('/my-app');
459
+ *
460
+ * // Use OPFS root (default)
461
+ * await fs.mount();
462
+ *
463
+ * // Use custom directory
464
+ * await fs.mount('/my-app');
456
465
  * \`\`\`
457
466
  */
458
- async mount(t = "/", r, a) {
459
- try {
460
- const n = await navigator.storage.getDirectory();
461
- return this.root = await this.getDirectoryHandle(t, !0, n), r && (this.watchCallback = r, a?.watchInterval && (this.watchInterval = a.watchInterval)), !0;
462
- } catch (n) {
463
- throw console.error(n), new l("Failed to initialize OPFS", "INIT_FAILED");
467
+ async mount(t = "/") {
468
+ return this.mountingPromise && await this.mountingPromise, this.mountingPromise = new Promise(async (r, a) => {
469
+ this.root = null;
470
+ try {
471
+ const n = await navigator.storage.getDirectory();
472
+ t === "/" ? this.root = n : this.root = await this.getDirectoryHandle(t, !0, n), r(!0);
473
+ } catch (n) {
474
+ console.error(n), a(new c("Failed to initialize OPFS", "INIT_FAILED"));
475
+ } finally {
476
+ this.mountingPromise = null;
477
+ }
478
+ }), this.mountingPromise;
479
+ }
480
+ /**
481
+ * Set the watch callback for file change events
482
+ *
483
+ * @param callback - The callback function to invoke when files change
484
+ * @param options - Optional configuration for watching
485
+ */
486
+ setWatchCallback(t, r) {
487
+ this.watchCallback = t, r?.watchInterval && (this.watchInterval = r.watchInterval);
488
+ }
489
+ /**
490
+ * Automatically mount the OPFS root if not already mounted
491
+ *
492
+ * This method is called internally when file operations are performed
493
+ * without explicitly mounting first.
494
+ *
495
+ * @returns Promise that resolves when auto-mount is complete
496
+ * @throws {OPFSError} If auto-mount fails
497
+ */
498
+ async ensureMounted() {
499
+ if (!this.root) {
500
+ if (this.mountingPromise) {
501
+ await this.mountingPromise;
502
+ return;
503
+ }
504
+ throw new c("OPFS not mounted", "NOT_MOUNTED");
464
505
  }
465
506
  }
466
507
  /**
@@ -514,7 +555,7 @@ class we {
514
555
  throw new D();
515
556
  const n = m(t);
516
557
  if (n.length === 0)
517
- throw new v("Path must not be empty", Array.isArray(t) ? t.join("/") : t);
558
+ throw new k("Path must not be empty", Array.isArray(t) ? t.join("/") : t);
518
559
  const s = n.pop();
519
560
  return (await this.getDirectoryHandle(n, r, a)).getFileHandle(s, { create: r });
520
561
  }
@@ -561,10 +602,10 @@ class we {
561
602
  for (const o of s) {
562
603
  const i = \`\${n === "/" ? "" : n}/\${o.name}\`;
563
604
  try {
564
- const c = await this.stat(i, t);
565
- r.set(i, c), c.isDirectory && await a(i);
566
- } catch (c) {
567
- console.warn(\`Skipping broken entry: \${i}\`, c);
605
+ const l = await this.stat(i, t);
606
+ r.set(i, l), l.isDirectory && await a(i);
607
+ } catch (l) {
608
+ console.warn(\`Skipping broken entry: \${i}\`, l);
568
609
  }
569
610
  }
570
611
  };
@@ -578,8 +619,9 @@ class we {
578
619
  }), await a("/"), r;
579
620
  }
580
621
  async readFile(t, r = "utf-8") {
622
+ await this.ensureMounted();
581
623
  try {
582
- const a = await this.getFileHandle(t, !1), n = await fe(a);
624
+ const a = await this.getFileHandle(t, !1), n = await ue(a);
583
625
  return r === "binary" ? n : re(n, r);
584
626
  } catch (a) {
585
627
  throw console.error(a), new b(t);
@@ -611,6 +653,7 @@ class we {
611
653
  * \`\`\`
612
654
  */
613
655
  async writeFile(t, r, a) {
656
+ await this.ensureMounted();
614
657
  const n = await this.getFileHandle(t, !0);
615
658
  await C(n, r, a, { truncate: !0 });
616
659
  }
@@ -637,6 +680,7 @@ class we {
637
680
  * \`\`\`
638
681
  */
639
682
  async appendFile(t, r, a) {
683
+ await this.ensureMounted();
640
684
  const n = await this.getFileHandle(t, !0);
641
685
  await C(n, r, a, { append: !0 });
642
686
  }
@@ -662,7 +706,7 @@ class we {
662
706
  * \`\`\`
663
707
  */
664
708
  async mkdir(t, r) {
665
- if (!this.root)
709
+ if (await this.ensureMounted(), !this.root)
666
710
  throw new D();
667
711
  const a = r?.recursive ?? !1, n = m(t);
668
712
  let s = this.root;
@@ -670,11 +714,11 @@ class we {
670
714
  const i = n[o];
671
715
  try {
672
716
  s = await s.getDirectoryHandle(i, { create: a || o === n.length - 1 });
673
- } catch (c) {
674
- throw c.name === "NotFoundError" ? new l(
675
- \`Parent directory does not exist: \${H(n.slice(0, o + 1))}\`,
717
+ } catch (l) {
718
+ throw l.name === "NotFoundError" ? new c(
719
+ \`Parent directory does not exist: \${N(n.slice(0, o + 1))}\`,
676
720
  "ENOENT"
677
- ) : c.name === "TypeMismatchError" ? new l(\`Path segment is not a directory: \${i}\`, "ENOTDIR") : new l("Failed to create directory", "MKDIR_FAILED");
721
+ ) : l.name === "TypeMismatchError" ? new c(\`Path segment is not a directory: \${i}\`, "ENOTDIR") : new c("Failed to create directory", "MKDIR_FAILED");
678
722
  }
679
723
  }
680
724
  }
@@ -708,27 +752,28 @@ class we {
708
752
  * \`\`\`
709
753
  */
710
754
  async stat(t, r) {
711
- const a = I(t), n = await this.getDirectoryHandle(x(t), !1), s = r?.includeHash ?? !1, o = r?.hashAlgorithm ?? "SHA-1";
755
+ await this.ensureMounted();
756
+ const a = P(t), n = await this.getDirectoryHandle(M(t), !1), s = r?.includeHash ?? !1, o = r?.hashAlgorithm ?? "SHA-1";
712
757
  try {
713
- const c = await (await n.getFileHandle(a, { create: !1 })).getFile(), f = {
758
+ const l = await (await n.getFileHandle(a, { create: !1 })).getFile(), u = {
714
759
  kind: "file",
715
- size: c.size,
716
- mtime: new Date(c.lastModified).toISOString(),
717
- ctime: new Date(c.lastModified).toISOString(),
760
+ size: l.size,
761
+ mtime: new Date(l.lastModified).toISOString(),
762
+ ctime: new Date(l.lastModified).toISOString(),
718
763
  isFile: !0,
719
764
  isDirectory: !1
720
765
  };
721
766
  if (s)
722
767
  try {
723
- const u = new Uint8Array(await c.arrayBuffer()), w = await ue(u, o);
724
- f.hash = w;
725
- } catch (u) {
726
- console.warn(\`Failed to calculate hash for \${t}:\`, u);
768
+ const f = new Uint8Array(await l.arrayBuffer()), w = await fe(f, o);
769
+ u.hash = w;
770
+ } catch (f) {
771
+ console.warn(\`Failed to calculate hash for \${t}:\`, f);
727
772
  }
728
- return f;
773
+ return u;
729
774
  } catch (i) {
730
775
  if (i.name !== "TypeMismatchError" && i.name !== "NotFoundError")
731
- throw new l("Failed to stat (file)", "STAT_FAILED");
776
+ throw new c("Failed to stat (file)", "STAT_FAILED");
732
777
  }
733
778
  try {
734
779
  return await n.getDirectoryHandle(a, { create: !1 }), {
@@ -740,20 +785,21 @@ class we {
740
785
  isDirectory: !0
741
786
  };
742
787
  } catch (i) {
743
- throw i.name === "NotFoundError" ? new l(\`No such file or directory: \${t}\`, "ENOENT") : new l("Failed to stat (directory)", "STAT_FAILED");
788
+ throw i.name === "NotFoundError" ? new c(\`No such file or directory: \${t}\`, "ENOENT") : new c("Failed to stat (directory)", "STAT_FAILED");
744
789
  }
745
790
  }
746
791
  async readdir(t, r) {
792
+ await this.ensureMounted();
747
793
  const a = r?.withFileTypes ?? !1, n = await this.getDirectoryHandle(t, !1);
748
794
  if (a) {
749
795
  const s = [];
750
796
  for await (const [o, i] of n.entries()) {
751
- const c = i.kind === "file";
797
+ const l = i.kind === "file";
752
798
  s.push({
753
799
  name: o,
754
800
  kind: i.kind,
755
- isFile: c,
756
- isDirectory: !c
801
+ isFile: l,
802
+ isDirectory: !l
757
803
  });
758
804
  }
759
805
  return s;
@@ -779,10 +825,11 @@ class we {
779
825
  * \`\`\`
780
826
  */
781
827
  async exists(t) {
782
- const r = I(t);
828
+ await this.ensureMounted();
829
+ const r = P(t);
783
830
  let a = null;
784
831
  try {
785
- a = await this.getDirectoryHandle(x(t), !1);
832
+ a = await this.getDirectoryHandle(M(t), !1);
786
833
  } catch (n) {
787
834
  throw (n.name === "NotFoundError" || n.name === "TypeMismatchError") && (a = null), n;
788
835
  }
@@ -822,6 +869,7 @@ class we {
822
869
  * \`\`\`
823
870
  */
824
871
  async clear(t = "/") {
872
+ await this.ensureMounted();
825
873
  try {
826
874
  const r = await this.readdir(t, { withFileTypes: !0 });
827
875
  for (const a of r) {
@@ -829,7 +877,7 @@ class we {
829
877
  await this.remove(n, { recursive: !0 });
830
878
  }
831
879
  } catch (r) {
832
- throw r instanceof l ? r : new l(\`Failed to clear directory: \${t}\`, "CLEAR_FAILED");
880
+ throw r instanceof c ? r : new c(\`Failed to clear directory: \${t}\`, "CLEAR_FAILED");
833
881
  }
834
882
  }
835
883
  /**
@@ -857,17 +905,18 @@ class we {
857
905
  * \`\`\`
858
906
  */
859
907
  async remove(t, r) {
860
- const a = r?.recursive ?? !1, n = r?.force ?? !1, s = I(t);
908
+ await this.ensureMounted();
909
+ const a = r?.recursive ?? !1, n = r?.force ?? !1, s = P(t);
861
910
  if (!s)
862
- throw new v("Invalid path", t);
863
- const o = await this.getDirectoryHandle(x(t), !1);
911
+ throw new k("Invalid path", t);
912
+ const o = await this.getDirectoryHandle(M(t), !1);
864
913
  try {
865
914
  await o.removeEntry(s, { recursive: a });
866
915
  } catch (i) {
867
916
  if (i.name === "NotFoundError") {
868
917
  if (!n)
869
- throw new l(\`No such file or directory: \${t}\`, "ENOENT");
870
- } else throw i.name === "InvalidModificationError" ? new l(\`Directory not empty: \${t}. Use recursive option to force removal.\`, "ENOTEMPTY") : i.name === "TypeMismatchError" && !a ? new l(\`Cannot remove directory without recursive option: \${t}\`, "EISDIR") : new l(\`Failed to remove path: \${t}\`, "RM_FAILED");
918
+ throw new c(\`No such file or directory: \${t}\`, "ENOENT");
919
+ } else throw i.name === "InvalidModificationError" ? new c(\`Directory not empty: \${t}. Use recursive option to force removal.\`, "ENOTEMPTY") : i.name === "TypeMismatchError" && !a ? new c(\`Cannot remove directory without recursive option: \${t}\`, "EISDIR") : new c(\`Failed to remove path: \${t}\`, "RM_FAILED");
871
920
  }
872
921
  }
873
922
  /**
@@ -889,13 +938,14 @@ class we {
889
938
  * \`\`\`
890
939
  */
891
940
  async realpath(t) {
941
+ await this.ensureMounted();
892
942
  try {
893
943
  const r = ce(t);
894
944
  if (!await this.exists(r))
895
945
  throw new b(r);
896
946
  return r;
897
947
  } catch (r) {
898
- throw r instanceof l ? r : new l(\`Failed to resolve path: \${t}\`, "REALPATH_FAILED");
948
+ throw r instanceof c ? r : new c(\`Failed to resolve path: \${t}\`, "REALPATH_FAILED");
899
949
  }
900
950
  }
901
951
  /**
@@ -915,12 +965,13 @@ class we {
915
965
  * \`\`\`
916
966
  */
917
967
  async rename(t, r) {
968
+ await this.ensureMounted();
918
969
  try {
919
970
  if (!await this.exists(t))
920
971
  throw new b(t);
921
972
  await this.copy(t, r, { recursive: !0 }), await this.remove(t, { recursive: !0 });
922
973
  } catch (a) {
923
- throw a instanceof l ? a : new l(\`Failed to rename from \${t} to \${r}\`, "RENAME_FAILED");
974
+ throw a instanceof c ? a : new c(\`Failed to rename from \${t} to \${r}\`, "RENAME_FAILED");
924
975
  }
925
976
  }
926
977
  /**
@@ -939,44 +990,46 @@ class we {
939
990
  * @example
940
991
  * \`\`\`typescript
941
992
  * // Copy a file
942
- * await fs.cp('/source/file.txt', '/dest/file.txt');
993
+ * await fs.copy('/source/file.txt', '/dest/file.txt');
943
994
  *
944
995
  * // Copy a directory and all its contents
945
- * await fs.cp('/source/dir', '/dest/dir', { recursive: true });
996
+ * await fs.copy('/source/dir', '/dest/dir', { recursive: true });
946
997
  *
947
998
  * // Copy without overwriting existing files
948
- * await fs.cp('/source', '/dest', { recursive: true, force: false });
999
+ * await fs.copy('/source', '/dest', { recursive: true, force: false });
949
1000
  * \`\`\`
950
1001
  */
951
1002
  async copy(t, r, a) {
1003
+ await this.ensureMounted();
952
1004
  try {
953
1005
  const n = a?.recursive ?? !1, s = a?.force ?? !0;
954
1006
  if (!await this.exists(t))
955
- throw new l(\`Source does not exist: \${t}\`, "ENOENT");
1007
+ throw new c(\`Source does not exist: \${t}\`, "ENOENT");
956
1008
  if (await this.exists(r) && !s)
957
- throw new l(\`Destination already exists: \${r}\`, "EEXIST");
1009
+ throw new c(\`Destination already exists: \${r}\`, "EEXIST");
958
1010
  if ((await this.stat(t)).isFile) {
959
- const f = await this.readFile(t, "binary");
960
- await this.writeFile(r, f);
1011
+ const u = await this.readFile(t, "binary");
1012
+ await this.writeFile(r, u);
961
1013
  } else {
962
1014
  if (!n)
963
- throw new l(\`Cannot copy directory without recursive option: \${t}\`, "EISDIR");
1015
+ throw new c(\`Cannot copy directory without recursive option: \${t}\`, "EISDIR");
964
1016
  await this.mkdir(r, { recursive: !0 });
965
- const f = await this.readdir(t, { withFileTypes: !0 });
966
- for (const u of f) {
967
- const w = \`\${t}/\${u.name}\`, h = \`\${r}/\${u.name}\`;
1017
+ const u = await this.readdir(t, { withFileTypes: !0 });
1018
+ for (const f of u) {
1019
+ const w = \`\${t}/\${f.name}\`, h = \`\${r}/\${f.name}\`;
968
1020
  await this.copy(w, h, { recursive: !0, force: s });
969
1021
  }
970
1022
  }
971
1023
  } catch (n) {
972
- throw n instanceof l ? n : new l(\`Failed to copy from \${t} to \${r}\`, "CP_FAILED");
1024
+ throw n instanceof c ? n : new c(\`Failed to copy from \${t} to \${r}\`, "CP_FAILED");
973
1025
  }
974
1026
  }
975
1027
  /**
976
1028
  * Start watching a file or directory for changes
977
1029
  */
978
1030
  async watch(t) {
979
- const r = O(t), a = await this.buildSnapshot(r);
1031
+ await this.ensureMounted();
1032
+ const r = I(t), a = await this.buildSnapshot(r);
980
1033
  this.watchers.set(r, a), this.watchTimer || (this.watchTimer = setInterval(() => {
981
1034
  this.scanWatches();
982
1035
  }, this.watchInterval));
@@ -985,7 +1038,7 @@ class we {
985
1038
  * Stop watching a previously watched path
986
1039
  */
987
1040
  unwatch(t) {
988
- const r = O(t);
1041
+ const r = I(t);
989
1042
  this.watchers.delete(r), this.watchers.size === 0 && this.watchTimer && (clearInterval(this.watchTimer), this.watchTimer = null);
990
1043
  }
991
1044
  async buildSnapshot(t) {
@@ -994,8 +1047,8 @@ class we {
994
1047
  if (r.set(n, s), s.isDirectory) {
995
1048
  const o = await this.readdir(n, { withFileTypes: !0 });
996
1049
  for (const i of o) {
997
- const c = \`\${n === "/" ? "" : n}/\${i.name}\`;
998
- await a(c);
1050
+ const l = \`\${n === "/" ? "" : n}/\${i.name}\`;
1051
+ await a(l);
999
1052
  }
1000
1053
  }
1001
1054
  };
@@ -1060,19 +1113,20 @@ class we {
1060
1113
  * \`\`\`
1061
1114
  */
1062
1115
  async sync(t, r) {
1116
+ await this.ensureMounted();
1063
1117
  try {
1064
1118
  (r?.cleanBefore ?? !1) && await this.clear("/");
1065
1119
  for (const [n, s] of t) {
1066
- const o = O(n);
1120
+ const o = I(n);
1067
1121
  let i;
1068
1122
  s instanceof Blob ? i = await he(s) : i = s, await this.writeFile(o, i);
1069
1123
  }
1070
1124
  } catch (a) {
1071
- throw a instanceof l ? a : new l("Failed to sync file system", "SYNC_FAILED");
1125
+ throw a instanceof c ? a : new c("Failed to sync file system", "SYNC_FAILED");
1072
1126
  }
1073
1127
  }
1074
1128
  }
1075
- typeof self < "u" && self.constructor.name === "DedicatedWorkerGlobalScope" && N(new we());
1076
- //# sourceMappingURL=worker-ChfzBM-o.js.map
1077
- `,a=typeof self<"u"&&self.Blob&&new Blob(["URL.revokeObjectURL(import.meta.url);",i],{type:"text/javascript;charset=utf-8"});function s(r){let e;try{if(e=a&&(self.URL||self.webkitURL).createObjectURL(a),!e)throw"";const t=new Worker(e,{type:"module",name:r?.name});return t.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(e)}),t}catch{return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(i),{type:"module",name:r?.name})}}function c(){return o.wrap(new s)}exports.DirectoryNotFoundError=n.DirectoryNotFoundError;exports.FileNotFoundError=n.FileNotFoundError;exports.OPFSError=n.OPFSError;exports.OPFSNotMountedError=n.OPFSNotMountedError;exports.OPFSNotSupportedError=n.OPFSNotSupportedError;exports.PathError=n.PathError;exports.PermissionError=n.PermissionError;exports.StorageError=n.StorageError;exports.TimeoutError=n.TimeoutError;exports.basename=n.basename;exports.calculateFileHash=n.calculateFileHash;exports.checkOPFSSupport=n.checkOPFSSupport;exports.convertBlobToUint8Array=n.convertBlobToUint8Array;exports.createBuffer=n.createBuffer;exports.decodeBuffer=n.decodeBuffer;exports.dirname=n.dirname;exports.encodeString=n.encodeString;exports.extname=n.extname;exports.joinPath=n.joinPath;exports.normalizePath=n.normalizePath;exports.readFileData=n.readFileData;exports.resolvePath=n.resolvePath;exports.splitPath=n.splitPath;exports.writeFileData=n.writeFileData;exports.createWorker=c;
1129
+ typeof self < "u" && self.constructor.name === "DedicatedWorkerGlobalScope" && O(new we());
1130
+ //# sourceMappingURL=worker-CMvl9yOu.js.map
1131
+ `,i=typeof self<"u"&&self.Blob&&new Blob(["URL.revokeObjectURL(import.meta.url);",o],{type:"text/javascript;charset=utf-8"});function s(r){let t;try{if(t=i&&(self.URL||self.webkitURL).createObjectURL(i),!t)throw"";const e=new Worker(t,{type:"module",name:r?.name});return e.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),e}catch{return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(o),{type:"module",name:r?.name})}}function c(r,t){const e=a.wrap(new s);return r&&e.setWatchCallback(a.proxy(r),t),e}exports.DirectoryNotFoundError=n.DirectoryNotFoundError;exports.FileNotFoundError=n.FileNotFoundError;exports.OPFSError=n.OPFSError;exports.OPFSNotMountedError=n.OPFSNotMountedError;exports.OPFSNotSupportedError=n.OPFSNotSupportedError;exports.PathError=n.PathError;exports.PermissionError=n.PermissionError;exports.StorageError=n.StorageError;exports.TimeoutError=n.TimeoutError;exports.basename=n.basename;exports.calculateFileHash=n.calculateFileHash;exports.checkOPFSSupport=n.checkOPFSSupport;exports.convertBlobToUint8Array=n.convertBlobToUint8Array;exports.createBuffer=n.createBuffer;exports.decodeBuffer=n.decodeBuffer;exports.dirname=n.dirname;exports.encodeString=n.encodeString;exports.extname=n.extname;exports.joinPath=n.joinPath;exports.normalizePath=n.normalizePath;exports.readFileData=n.readFileData;exports.resolvePath=n.resolvePath;exports.splitPath=n.splitPath;exports.writeFileData=n.writeFileData;exports.createWorker=c;
1078
1132
  //# sourceMappingURL=index.cjs.map