opfs-worker 0.2.4 → 0.2.5

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,256 +1,256 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const a=require("comlink"),n=require("./helpers-hEpet7x7.cjs"),o=`/**
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const a=require("comlink"),n=require("./helpers-DjY2OR7f.cjs"),o=`/**
2
2
  * @license
3
3
  * Copyright 2019 Google LLC
4
4
  * SPDX-License-Identifier: Apache-2.0
5
5
  */
6
- const H = Symbol("Comlink.proxy"), R = Symbol("Comlink.endpoint"), B = Symbol("Comlink.releaseProxy"), I = Symbol("Comlink.finalizer"), p = Symbol("Comlink.thrown"), $ = (t) => typeof t == "object" && t !== null || typeof t == "function", W = {
7
- canHandle: (t) => $(t) && t[H],
8
- serialize(t) {
9
- const { port1: e, port2: r } = new MessageChannel();
10
- return O(t, e), [r, [r]];
6
+ const H = Symbol("Comlink.proxy"), R = Symbol("Comlink.endpoint"), B = Symbol("Comlink.releaseProxy"), D = Symbol("Comlink.finalizer"), p = Symbol("Comlink.thrown"), $ = (e) => typeof e == "object" && e !== null || typeof e == "function", W = {
7
+ canHandle: (e) => $(e) && e[H],
8
+ serialize(e) {
9
+ const { port1: t, port2: r } = new MessageChannel();
10
+ return P(e, t), [r, [r]];
11
11
  },
12
- deserialize(t) {
13
- return t.start(), Y(t);
12
+ deserialize(e) {
13
+ return e.start(), Y(e);
14
14
  }
15
15
  }, j = {
16
- canHandle: (t) => $(t) && p in t,
17
- serialize({ value: t }) {
18
- let e;
19
- return t instanceof Error ? e = {
16
+ canHandle: (e) => $(e) && p in e,
17
+ serialize({ value: e }) {
18
+ let t;
19
+ return e instanceof Error ? t = {
20
20
  isError: !0,
21
21
  value: {
22
- message: t.message,
23
- name: t.name,
24
- stack: t.stack
22
+ message: e.message,
23
+ name: e.name,
24
+ stack: e.stack
25
25
  }
26
- } : e = { isError: !1, value: t }, [e, []];
26
+ } : t = { isError: !1, value: e }, [t, []];
27
27
  },
28
- deserialize(t) {
29
- throw t.isError ? Object.assign(new Error(t.value.message), t.value) : t.value;
28
+ deserialize(e) {
29
+ throw e.isError ? Object.assign(new Error(e.value.message), e.value) : e.value;
30
30
  }
31
31
  }, U = /* @__PURE__ */ new Map([
32
32
  ["proxy", W],
33
33
  ["throw", j]
34
34
  ]);
35
- function V(t, e) {
36
- for (const r of t)
37
- if (e === r || r === "*" || r instanceof RegExp && r.test(e))
35
+ function V(e, t) {
36
+ for (const r of e)
37
+ if (t === r || r === "*" || r instanceof RegExp && r.test(t))
38
38
  return !0;
39
39
  return !1;
40
40
  }
41
- function O(t, e = globalThis, r = ["*"]) {
42
- e.addEventListener("message", function a(n) {
43
- if (!n || !n.data)
41
+ function P(e, t = globalThis, r = ["*"]) {
42
+ t.addEventListener("message", function n(i) {
43
+ if (!i || !i.data)
44
44
  return;
45
- if (!V(r, n.origin)) {
46
- console.warn(\`Invalid origin '\${n.origin}' for comlink proxy\`);
45
+ if (!V(r, i.origin)) {
46
+ console.warn(\`Invalid origin '\${i.origin}' for comlink proxy\`);
47
47
  return;
48
48
  }
49
- const { id: i, type: o, path: s } = Object.assign({ path: [] }, n.data), l = (n.data.argumentList || []).map(y);
50
- let u;
49
+ const { id: a, type: s, path: o } = Object.assign({ path: [] }, i.data), l = (i.data.argumentList || []).map(y);
50
+ let h;
51
51
  try {
52
- const f = s.slice(0, -1).reduce((h, g) => h[g], t), w = s.reduce((h, g) => h[g], t);
53
- switch (o) {
52
+ const u = o.slice(0, -1).reduce((f, g) => f[g], e), w = o.reduce((f, g) => f[g], e);
53
+ switch (s) {
54
54
  case "GET":
55
- u = w;
55
+ h = w;
56
56
  break;
57
57
  case "SET":
58
- f[s.slice(-1)[0]] = y(n.data.value), u = !0;
58
+ u[o.slice(-1)[0]] = y(i.data.value), h = !0;
59
59
  break;
60
60
  case "APPLY":
61
- u = w.apply(f, l);
61
+ h = w.apply(u, l);
62
62
  break;
63
63
  case "CONSTRUCT":
64
64
  {
65
- const h = new w(...l);
66
- u = Q(h);
65
+ const f = new w(...l);
66
+ h = Q(f);
67
67
  }
68
68
  break;
69
69
  case "ENDPOINT":
70
70
  {
71
- const { port1: h, port2: g } = new MessageChannel();
72
- O(t, g), u = J(h, [h]);
71
+ const { port1: f, port2: g } = new MessageChannel();
72
+ P(e, g), h = J(f, [f]);
73
73
  }
74
74
  break;
75
75
  case "RELEASE":
76
- u = void 0;
76
+ h = void 0;
77
77
  break;
78
78
  default:
79
79
  return;
80
80
  }
81
- } catch (f) {
82
- u = { value: f, [p]: 0 };
81
+ } catch (u) {
82
+ h = { value: u, [p]: 0 };
83
83
  }
84
- Promise.resolve(u).catch((f) => ({ value: f, [p]: 0 })).then((f) => {
85
- const [w, h] = A(f);
86
- e.postMessage(Object.assign(Object.assign({}, w), { id: i }), h), o === "RELEASE" && (e.removeEventListener("message", a), L(e), I in t && typeof t[I] == "function" && t[I]());
87
- }).catch((f) => {
88
- const [w, h] = A({
84
+ Promise.resolve(h).catch((u) => ({ value: u, [p]: 0 })).then((u) => {
85
+ const [w, f] = A(u);
86
+ t.postMessage(Object.assign(Object.assign({}, w), { id: a }), f), s === "RELEASE" && (t.removeEventListener("message", n), L(t), D in e && typeof e[D] == "function" && e[D]());
87
+ }).catch((u) => {
88
+ const [w, f] = A({
89
89
  value: new TypeError("Unserializable return value"),
90
90
  [p]: 0
91
91
  });
92
- e.postMessage(Object.assign(Object.assign({}, w), { id: i }), h);
92
+ t.postMessage(Object.assign(Object.assign({}, w), { id: a }), f);
93
93
  });
94
- }), e.start && e.start();
94
+ }), t.start && t.start();
95
95
  }
96
- function G(t) {
97
- return t.constructor.name === "MessagePort";
96
+ function G(e) {
97
+ return e.constructor.name === "MessagePort";
98
98
  }
99
- function L(t) {
100
- G(t) && t.close();
99
+ function L(e) {
100
+ G(e) && e.close();
101
101
  }
102
- function Y(t, e) {
102
+ function Y(e, t) {
103
103
  const r = /* @__PURE__ */ new Map();
104
- return t.addEventListener("message", function(n) {
105
- const { data: i } = n;
106
- if (!i || !i.id)
104
+ return e.addEventListener("message", function(i) {
105
+ const { data: a } = i;
106
+ if (!a || !a.id)
107
107
  return;
108
- const o = r.get(i.id);
109
- if (o)
108
+ const s = r.get(a.id);
109
+ if (s)
110
110
  try {
111
- o(i);
111
+ s(a);
112
112
  } finally {
113
- r.delete(i.id);
113
+ r.delete(a.id);
114
114
  }
115
- }), P(t, r, [], e);
115
+ }), I(e, r, [], t);
116
116
  }
117
- function E(t) {
118
- if (t)
117
+ function E(e) {
118
+ if (e)
119
119
  throw new Error("Proxy has been released and is not useable");
120
120
  }
121
- function z(t) {
122
- return d(t, /* @__PURE__ */ new Map(), {
121
+ function z(e) {
122
+ return d(e, /* @__PURE__ */ new Map(), {
123
123
  type: "RELEASE"
124
124
  }).then(() => {
125
- L(t);
125
+ L(e);
126
126
  });
127
127
  }
128
- const F = /* @__PURE__ */ new WeakMap(), S = "FinalizationRegistry" in globalThis && new FinalizationRegistry((t) => {
129
- const e = (F.get(t) || 0) - 1;
130
- F.set(t, e), e === 0 && z(t);
128
+ const F = /* @__PURE__ */ new WeakMap(), S = "FinalizationRegistry" in globalThis && new FinalizationRegistry((e) => {
129
+ const t = (F.get(e) || 0) - 1;
130
+ F.set(e, t), t === 0 && z(e);
131
131
  });
132
- function X(t, e) {
133
- const r = (F.get(e) || 0) + 1;
134
- F.set(e, r), S && S.register(t, e, t);
132
+ function X(e, t) {
133
+ const r = (F.get(t) || 0) + 1;
134
+ F.set(t, r), S && S.register(e, t, e);
135
135
  }
136
- function q(t) {
137
- S && S.unregister(t);
136
+ function q(e) {
137
+ S && S.unregister(e);
138
138
  }
139
- function P(t, e, r = [], a = function() {
139
+ function I(e, t, r = [], n = function() {
140
140
  }) {
141
- let n = !1;
142
- const i = new Proxy(a, {
143
- get(o, s) {
144
- if (E(n), s === B)
141
+ let i = !1;
142
+ const a = new Proxy(n, {
143
+ get(s, o) {
144
+ if (E(i), o === B)
145
145
  return () => {
146
- q(i), z(t), e.clear(), n = !0;
146
+ q(a), z(e), t.clear(), i = !0;
147
147
  };
148
- if (s === "then") {
148
+ if (o === "then") {
149
149
  if (r.length === 0)
150
- return { then: () => i };
151
- const l = d(t, e, {
150
+ return { then: () => a };
151
+ const l = d(e, t, {
152
152
  type: "GET",
153
- path: r.map((u) => u.toString())
153
+ path: r.map((h) => h.toString())
154
154
  }).then(y);
155
155
  return l.then.bind(l);
156
156
  }
157
- return P(t, e, [...r, s]);
157
+ return I(e, t, [...r, o]);
158
158
  },
159
- set(o, s, l) {
160
- E(n);
161
- const [u, f] = A(l);
162
- return d(t, e, {
159
+ set(s, o, l) {
160
+ E(i);
161
+ const [h, u] = A(l);
162
+ return d(e, t, {
163
163
  type: "SET",
164
- path: [...r, s].map((w) => w.toString()),
165
- value: u
166
- }, f).then(y);
164
+ path: [...r, o].map((w) => w.toString()),
165
+ value: h
166
+ }, u).then(y);
167
167
  },
168
- apply(o, s, l) {
169
- E(n);
170
- const u = r[r.length - 1];
171
- if (u === R)
172
- return d(t, e, {
168
+ apply(s, o, l) {
169
+ E(i);
170
+ const h = r[r.length - 1];
171
+ if (h === R)
172
+ return d(e, t, {
173
173
  type: "ENDPOINT"
174
174
  }).then(y);
175
- if (u === "bind")
176
- return P(t, e, r.slice(0, -1));
177
- const [f, w] = k(l);
178
- return d(t, e, {
175
+ if (h === "bind")
176
+ return I(e, t, r.slice(0, -1));
177
+ const [u, w] = N(l);
178
+ return d(e, t, {
179
179
  type: "APPLY",
180
- path: r.map((h) => h.toString()),
181
- argumentList: f
180
+ path: r.map((f) => f.toString()),
181
+ argumentList: u
182
182
  }, w).then(y);
183
183
  },
184
- construct(o, s) {
185
- E(n);
186
- const [l, u] = k(s);
187
- return d(t, e, {
184
+ construct(s, o) {
185
+ E(i);
186
+ const [l, h] = N(o);
187
+ return d(e, t, {
188
188
  type: "CONSTRUCT",
189
- path: r.map((f) => f.toString()),
189
+ path: r.map((u) => u.toString()),
190
190
  argumentList: l
191
- }, u).then(y);
191
+ }, h).then(y);
192
192
  }
193
193
  });
194
- return X(i, t), i;
194
+ return X(a, e), a;
195
195
  }
196
- function K(t) {
197
- return Array.prototype.concat.apply([], t);
196
+ function K(e) {
197
+ return Array.prototype.concat.apply([], e);
198
198
  }
199
- function k(t) {
200
- const e = t.map(A);
201
- return [e.map((r) => r[0]), K(e.map((r) => r[1]))];
199
+ function N(e) {
200
+ const t = e.map(A);
201
+ return [t.map((r) => r[0]), K(t.map((r) => r[1]))];
202
202
  }
203
203
  const _ = /* @__PURE__ */ new WeakMap();
204
- function J(t, e) {
205
- return _.set(t, e), t;
204
+ function J(e, t) {
205
+ return _.set(e, t), e;
206
206
  }
207
- function Q(t) {
208
- return Object.assign(t, { [H]: !0 });
207
+ function Q(e) {
208
+ return Object.assign(e, { [H]: !0 });
209
209
  }
210
- function A(t) {
211
- for (const [e, r] of U)
212
- if (r.canHandle(t)) {
213
- const [a, n] = r.serialize(t);
210
+ function A(e) {
211
+ for (const [t, r] of U)
212
+ if (r.canHandle(e)) {
213
+ const [n, i] = r.serialize(e);
214
214
  return [
215
215
  {
216
216
  type: "HANDLER",
217
- name: e,
218
- value: a
217
+ name: t,
218
+ value: n
219
219
  },
220
- n
220
+ i
221
221
  ];
222
222
  }
223
223
  return [
224
224
  {
225
225
  type: "RAW",
226
- value: t
226
+ value: e
227
227
  },
228
- _.get(t) || []
228
+ _.get(e) || []
229
229
  ];
230
230
  }
231
- function y(t) {
232
- switch (t.type) {
231
+ function y(e) {
232
+ switch (e.type) {
233
233
  case "HANDLER":
234
- return U.get(t.name).deserialize(t.value);
234
+ return U.get(e.name).deserialize(e.value);
235
235
  case "RAW":
236
- return t.value;
236
+ return e.value;
237
237
  }
238
238
  }
239
- function d(t, e, r, a) {
240
- return new Promise((n) => {
241
- const i = Z();
242
- e.set(i, n), t.start && t.start(), t.postMessage(Object.assign({ id: i }, r), a);
239
+ function d(e, t, r, n) {
240
+ return new Promise((i) => {
241
+ const a = Z();
242
+ t.set(a, i), e.start && e.start(), e.postMessage(Object.assign({ id: a }, r), n);
243
243
  });
244
244
  }
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
248
  class c extends Error {
249
- constructor(e, r, a) {
250
- super(e), this.code = r, this.path = a, this.name = "OPFSError";
249
+ constructor(t, r, n) {
250
+ super(t), this.code = r, this.path = n, this.name = "OPFSError";
251
251
  }
252
252
  }
253
- class ee extends c {
253
+ class tt extends c {
254
254
  constructor() {
255
255
  super("OPFS is not supported in this browser", "OPFS_NOT_SUPPORTED");
256
256
  }
@@ -260,165 +260,166 @@ class T extends c {
260
260
  super("OPFS is not mounted", "OPFS_NOT_MOUNTED");
261
261
  }
262
262
  }
263
- class v extends c {
264
- constructor(e, r) {
265
- super(e, "INVALID_PATH", r);
263
+ class k extends c {
264
+ constructor(t, r) {
265
+ super(t, "INVALID_PATH", r);
266
266
  }
267
267
  }
268
- class D extends c {
269
- constructor(e) {
270
- super(\`File not found: \${e}\`, "FILE_NOT_FOUND", e);
268
+ class O extends c {
269
+ constructor(t) {
270
+ super(\`File not found: \${t}\`, "FILE_NOT_FOUND", t);
271
271
  }
272
272
  }
273
- function te(t, e = "utf-8") {
274
- switch (e) {
273
+ function et(e, t = "utf-8") {
274
+ switch (t) {
275
275
  case "utf8":
276
276
  case "utf-8":
277
- return new TextEncoder().encode(t);
277
+ return new TextEncoder().encode(e);
278
278
  case "utf16le":
279
279
  case "ucs2":
280
280
  case "ucs-2":
281
- return ne(t);
281
+ return nt(e);
282
282
  case "ascii":
283
- return se(t);
283
+ return st(e);
284
284
  case "latin1":
285
- return ie(t);
285
+ return at(e);
286
286
  case "binary":
287
- return Uint8Array.from(t, (r) => r.charCodeAt(0));
287
+ return Uint8Array.from(e, (r) => r.charCodeAt(0));
288
288
  case "base64":
289
- return Uint8Array.from(atob(t), (r) => r.charCodeAt(0));
289
+ return Uint8Array.from(atob(e), (r) => r.charCodeAt(0));
290
290
  case "hex":
291
- if (!/^[\\da-f]+$/i.test(t) || t.length % 2 !== 0)
291
+ if (!/^[\\da-f]+$/i.test(e) || e.length % 2 !== 0)
292
292
  throw new c("Invalid hex string", "INVALID_HEX_FORMAT");
293
- return Uint8Array.from(t.match(/.{1,2}/g).map((r) => parseInt(r, 16)));
293
+ return Uint8Array.from(e.match(/.{1,2}/g).map((r) => parseInt(r, 16)));
294
294
  default:
295
- return console.warn("Encoding not supported, falling back to UTF-8"), new TextEncoder().encode(t);
295
+ return console.warn("Encoding not supported, falling back to UTF-8"), new TextEncoder().encode(e);
296
296
  }
297
297
  }
298
- function re(t, e = "utf-8") {
299
- switch (e) {
298
+ function rt(e, t = "utf-8") {
299
+ switch (t) {
300
300
  case "utf8":
301
301
  case "utf-8":
302
- return new TextDecoder().decode(t);
302
+ return new TextDecoder().decode(e);
303
303
  case "utf16le":
304
304
  case "ucs2":
305
305
  case "ucs-2":
306
- return ae(t);
306
+ return it(e);
307
307
  case "latin1":
308
- return String.fromCharCode(...t);
308
+ return String.fromCharCode(...e);
309
309
  case "binary":
310
- return String.fromCharCode(...t);
310
+ return String.fromCharCode(...e);
311
311
  case "ascii":
312
- return String.fromCharCode(...t.map((r) => r & 127));
312
+ return String.fromCharCode(...e.map((r) => r & 127));
313
313
  case "base64":
314
- return btoa(String.fromCharCode(...t));
314
+ return btoa(String.fromCharCode(...e));
315
315
  case "hex":
316
- return Array.from(t).map((r) => r.toString(16).padStart(2, "0")).join("");
316
+ return Array.from(e).map((r) => r.toString(16).padStart(2, "0")).join("");
317
317
  default:
318
- return console.warn("Unsupported encoding, falling back to UTF-8"), new TextDecoder().decode(t);
318
+ return console.warn("Unsupported encoding, falling back to UTF-8"), new TextDecoder().decode(e);
319
319
  }
320
320
  }
321
- function ne(t) {
322
- const e = new Uint8Array(t.length * 2);
323
- for (let r = 0; r < t.length; r++) {
324
- const a = t.charCodeAt(r);
325
- e[r * 2] = a & 255, e[r * 2 + 1] = a >> 8;
321
+ function nt(e) {
322
+ const t = new Uint8Array(e.length * 2);
323
+ for (let r = 0; r < e.length; r++) {
324
+ const n = e.charCodeAt(r);
325
+ t[r * 2] = n & 255, t[r * 2 + 1] = n >> 8;
326
326
  }
327
- return e;
327
+ return t;
328
328
  }
329
- function ae(t) {
330
- t.length % 2 !== 0 && (console.warn("Invalid UTF-16LE buffer length, truncating last byte"), t = t.slice(0, t.length - 1));
331
- const e = new Uint16Array(t.buffer, t.byteOffset, t.byteLength / 2);
332
- return String.fromCharCode(...e);
329
+ function it(e) {
330
+ e.length % 2 !== 0 && (console.warn("Invalid UTF-16LE buffer length, truncating last byte"), e = e.slice(0, e.length - 1));
331
+ const t = new Uint16Array(e.buffer, e.byteOffset, e.byteLength / 2);
332
+ return String.fromCharCode(...t);
333
333
  }
334
- function ie(t) {
335
- const e = new Uint8Array(t.length);
336
- for (let r = 0; r < t.length; r++)
337
- e[r] = t.charCodeAt(r) & 255;
338
- return e;
334
+ function at(e) {
335
+ const t = new Uint8Array(e.length);
336
+ for (let r = 0; r < e.length; r++)
337
+ t[r] = e.charCodeAt(r) & 255;
338
+ return t;
339
339
  }
340
- function se(t) {
341
- const e = new Uint8Array(t.length);
342
- for (let r = 0; r < t.length; r++)
343
- e[r] = t.charCodeAt(r) & 127;
344
- return e;
340
+ function st(e) {
341
+ const t = new Uint8Array(e.length);
342
+ for (let r = 0; r < e.length; r++)
343
+ t[r] = e.charCodeAt(r) & 127;
344
+ return t;
345
345
  }
346
- function oe() {
346
+ function ot() {
347
347
  if (!("storage" in navigator) || !("getDirectory" in navigator.storage))
348
- throw new ee();
348
+ throw new tt();
349
349
  }
350
- function m(t) {
351
- return Array.isArray(t) ? t : t.split("/").filter(Boolean);
350
+ function m(e) {
351
+ return Array.isArray(e) ? e : e.split("/").filter(Boolean);
352
352
  }
353
- function x(t) {
354
- return typeof t == "string" ? t ?? "/" : \`/\${t.join("/")}\`;
353
+ function x(e) {
354
+ return typeof e == "string" ? e ?? "/" : \`/\${e.join("/")}\`;
355
355
  }
356
- function b(t) {
357
- const e = m(t);
358
- return e[e.length - 1] || "";
356
+ function C(e) {
357
+ const t = m(e);
358
+ return t[t.length - 1] || "";
359
359
  }
360
- function M(t) {
361
- const e = m(t);
362
- return e.pop(), x(e);
360
+ function M(e) {
361
+ const t = m(e);
362
+ return t.pop(), x(t);
363
363
  }
364
- function C(t) {
365
- return !t || t === "/" ? "/" : t.startsWith("/") ? t : \`/\${t}\`;
364
+ function b(e) {
365
+ return !e || e === "/" ? "/" : e.startsWith("/") ? e : \`/\${e}\`;
366
366
  }
367
- function ce(t) {
368
- const e = m(t), r = [];
369
- for (const a of e)
370
- if (!(a === "." || a === ""))
371
- if (a === "..") {
367
+ function ct(e) {
368
+ const t = m(e), r = [];
369
+ for (const n of t)
370
+ if (!(n === "." || n === ""))
371
+ if (n === "..") {
372
372
  if (r.length === 0)
373
373
  continue;
374
374
  r.pop();
375
375
  } else
376
- r.push(a);
376
+ r.push(n);
377
377
  return x(r);
378
378
  }
379
- function le(t, e = "utf-8") {
380
- return typeof t == "string" ? te(t, e) : t instanceof Uint8Array ? t : new Uint8Array(t);
379
+ function lt(e, t = "utf-8") {
380
+ return typeof e == "string" ? et(e, t) : e instanceof Uint8Array ? e : new Uint8Array(e);
381
381
  }
382
- async function ue(t) {
383
- const e = await t.createSyncAccessHandle();
382
+ async function ht(e) {
383
+ const t = await e.createSyncAccessHandle();
384
384
  try {
385
- const r = e.getSize(), a = new Uint8Array(r);
386
- return e.read(a, { at: 0 }), a;
385
+ const r = t.getSize(), n = new Uint8Array(r);
386
+ return t.read(n, { at: 0 }), n;
387
387
  } finally {
388
- e.close();
388
+ t.close();
389
389
  }
390
390
  }
391
- async function N(t, e, r, a = {}) {
392
- let n = null;
391
+ async function v(e, t, r, n = {}) {
392
+ let i = null;
393
393
  try {
394
- n = await t.createSyncAccessHandle();
395
- const i = le(e, r), o = a.append ? n.getSize() : 0;
396
- n.write(i, { at: o }), a.truncate && !a.append && n.truncate(i.byteLength), n.flush();
397
- } catch (i) {
398
- console.error(i);
399
- const o = a.append ? "append" : "write";
400
- throw new c(\`Failed to \${o} file\`, \`\${o.toUpperCase()}_FAILED\`);
394
+ i = await e.createSyncAccessHandle();
395
+ const a = lt(t, r), s = n.append ? i.getSize() : 0;
396
+ i.write(a, { at: s }), n.truncate && !n.append && i.truncate(a.byteLength), i.flush();
397
+ } catch (a) {
398
+ console.error(a);
399
+ const s = n.append ? "append" : "write";
400
+ throw new c(\`Failed to \${s} file\`, \`\${s.toUpperCase()}_FAILED\`);
401
401
  } finally {
402
- if (n)
402
+ if (i)
403
403
  try {
404
- n.close();
404
+ i.close();
405
405
  } catch {
406
406
  }
407
407
  }
408
408
  }
409
- async function fe(t, e = "SHA-1") {
409
+ async function ut(e, t = "SHA-1") {
410
+ e instanceof File && (e = await e.arrayBuffer());
410
411
  try {
411
- const r = new Uint8Array(t), a = await crypto.subtle.digest(e, r);
412
- return Array.from(new Uint8Array(a)).map((i) => i.toString(16).padStart(2, "0")).join("");
412
+ const r = new Uint8Array(e), n = await crypto.subtle.digest(t, r);
413
+ return Array.from(new Uint8Array(n)).map((a) => a.toString(16).padStart(2, "0")).join("");
413
414
  } catch (r) {
414
- throw console.warn(\`Failed to calculate \${e} hash:\`, r), r;
415
+ throw console.warn(\`Failed to calculate \${t} hash:\`, r), r;
415
416
  }
416
417
  }
417
- async function he(t) {
418
- const e = await t.arrayBuffer();
419
- return new Uint8Array(e);
418
+ async function ft(e) {
419
+ const t = await e.arrayBuffer();
420
+ return new Uint8Array(t);
420
421
  }
421
- class we {
422
+ class wt {
422
423
  /** Root directory handle for the file system */
423
424
  root = null;
424
425
  /** Watch event callback */
@@ -433,6 +434,8 @@ class we {
433
434
  scanning = !1;
434
435
  /** Promise to prevent concurrent mount operations */
435
436
  mountingPromise = null;
437
+ /** Hash algorithm for file hashing (null means no hashing) */
438
+ hashAlgorithm = null;
436
439
  /**
437
440
  * Notify about internal changes to the file system
438
441
  *
@@ -442,21 +445,34 @@ class we {
442
445
  * @param path - The path that was changed
443
446
  * @param type - The type of change (create, change, delete)
444
447
  */
445
- notifyInternalChange(e, r) {
446
- this.watchCallback && this.watchCallback({
447
- path: e,
448
- type: r
448
+ async notifyChange(t) {
449
+ if (!this.watchCallback)
450
+ return;
451
+ let r;
452
+ if (this.hashAlgorithm && !t.isDirectory && t.type !== "removed")
453
+ try {
454
+ const n = await this.stat(t.path);
455
+ n.isFile && n.hash && (r = n.hash);
456
+ } catch (n) {
457
+ console.warn(\`Failed to calculate hash for \${t.path}:\`, n);
458
+ }
459
+ this.watchCallback({
460
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
461
+ ...t,
462
+ ...r && { hash: r }
449
463
  });
450
464
  }
451
465
  /**
452
466
  * Creates a new OPFSFileSystem instance
453
467
  *
454
468
  * @param watchCallback - Optional callback for file change events
455
- * @param watchOptions - Optional configuration for watching
469
+ * @param options - Optional configuration options
470
+ * @param options.watchInterval - Polling interval in milliseconds for file watching
471
+ * @param options.hashAlgorithm - Hash algorithm for file hashing
456
472
  * @throws {OPFSError} If OPFS is not supported in the current browser
457
473
  */
458
- constructor(e, r) {
459
- oe(), e && (this.watchCallback = e, r?.watchInterval && (this.watchInterval = r.watchInterval)), this.mount("/");
474
+ constructor(t, r) {
475
+ ot(), t && (this.watchCallback = t), r && this.setOptions(r), this.mount("/");
460
476
  }
461
477
  /**
462
478
  * Initialize the file system within a given directory
@@ -479,14 +495,14 @@ class we {
479
495
  * await fs.mount('/my-app');
480
496
  * \`\`\`
481
497
  */
482
- async mount(e = "/") {
483
- return this.mountingPromise && await this.mountingPromise, this.mountingPromise = new Promise(async (r, a) => {
498
+ async mount(t = "/") {
499
+ return this.mountingPromise && await this.mountingPromise, this.mountingPromise = new Promise(async (r, n) => {
484
500
  this.root = null;
485
501
  try {
486
- const n = await navigator.storage.getDirectory();
487
- e === "/" ? this.root = n : this.root = await this.getDirectoryHandle(e, !0, n), r(!0);
488
- } catch (n) {
489
- console.error(n), a(new c("Failed to initialize OPFS", "INIT_FAILED"));
502
+ const i = await navigator.storage.getDirectory();
503
+ t === "/" ? this.root = i : this.root = await this.getDirectoryHandle(t, !0, i), r(!0);
504
+ } catch (i) {
505
+ console.error(i), n(new c("Failed to initialize OPFS", "INIT_FAILED"));
490
506
  } finally {
491
507
  this.mountingPromise = null;
492
508
  }
@@ -496,10 +512,19 @@ class we {
496
512
  * Set the watch callback for file change events
497
513
  *
498
514
  * @param callback - The callback function to invoke when files change
499
- * @param options - Optional configuration for watching
500
515
  */
501
- setWatchCallback(e, r) {
502
- this.watchCallback = e, r?.watchInterval && (this.watchInterval = r.watchInterval);
516
+ setWatchCallback(t) {
517
+ this.watchCallback = t;
518
+ }
519
+ /**
520
+ * Set configuration options for the file system
521
+ *
522
+ * @param options - Configuration options to update
523
+ * @param options.watchInterval - Polling interval in milliseconds for file watching
524
+ * @param options.hashAlgorithm - Hash algorithm for file hashing
525
+ */
526
+ setOptions(t) {
527
+ t.watchInterval !== void 0 && (this.watchInterval = t.watchInterval), t.hashAlgorithm !== void 0 && (this.hashAlgorithm = t.hashAlgorithm);
503
528
  }
504
529
  /**
505
530
  * Automatically mount the OPFS root if not already mounted
@@ -537,14 +562,14 @@ class we {
537
562
  * const docsDir2 = await fs.getDirectoryHandle(['users', 'john', 'documents'], true);
538
563
  * \`\`\`
539
564
  */
540
- async getDirectoryHandle(e, r = !1, a = this.root) {
541
- if (!a)
565
+ async getDirectoryHandle(t, r = !1, n = this.root) {
566
+ if (!n)
542
567
  throw new T();
543
- const n = Array.isArray(e) ? e : m(e);
544
- let i = a;
545
- for (const o of n)
546
- i = await i.getDirectoryHandle(o, { create: r });
547
- return i;
568
+ const i = Array.isArray(t) ? t : m(t);
569
+ let a = n;
570
+ for (const s of i)
571
+ a = await a.getDirectoryHandle(s, { create: r });
572
+ return a;
548
573
  }
549
574
  /**
550
575
  * Get a file handle from a path
@@ -565,45 +590,27 @@ class we {
565
590
  * const fileHandle2 = await fs.getFileHandle(['config', 'settings.json'], true);
566
591
  * \`\`\`
567
592
  */
568
- async getFileHandle(e, r = !1, a = this.root) {
569
- if (!a)
593
+ async getFileHandle(t, r = !1, n = this.root) {
594
+ if (!n)
570
595
  throw new T();
571
- const n = m(e);
572
- if (n.length === 0)
573
- throw new v("Path must not be empty", Array.isArray(e) ? e.join("/") : e);
574
- const i = n.pop();
575
- return (await this.getDirectoryHandle(n, r, a)).getFileHandle(i, { create: r });
596
+ const i = m(t);
597
+ if (i.length === 0)
598
+ throw new k("Path must not be empty", Array.isArray(t) ? t.join("/") : t);
599
+ const a = i.pop();
600
+ return (await this.getDirectoryHandle(i, r, n)).getFileHandle(a, { create: r });
576
601
  }
577
602
  /**
578
- * Recursively list all files and directories with their stats
603
+ * Get a complete index of all files and directories in the file system
579
604
  *
580
- * Traverses the entire file system starting from the root and returns
581
- * a Map containing all paths and their corresponding file statistics.
605
+ * This method recursively traverses the entire file system and returns
606
+ * a Map containing FileStat objects for every file and directory.
582
607
  *
583
- * @param options - Options for indexing
584
- * @param options.includeHash - Whether to calculate file hash (default: false)
585
- * @param options.hashAlgorithm - Hash algorithm to use (default: 'SHA-1', fastest)
586
- * @returns Promise that resolves to a Map of path => FileStat
587
- * @throws {OPFSError} If the indexing operation fails
608
+ * @returns Promise that resolves to a Map of paths to FileStat objects
609
+ * @throws {OPFSError} If the file system is not mounted
588
610
  *
589
611
  * @example
590
612
  * \`\`\`typescript
591
- * // Basic index without hash
592
613
  * const index = await fs.index();
593
- *
594
- * // Index with file hash
595
- * const indexWithHash = await fs.index({
596
- * includeHash: true,
597
- * hashAlgorithm: 'SHA-1'
598
- * });
599
- *
600
- * // Iterate through all files and directories
601
- * for (const [path, stat] of index) {
602
- * console.log(\`\${path}: \${stat.isFile ? 'file' : 'directory'} (\${stat.size} bytes)\`);
603
- * if (stat.hash) console.log(\` Hash: \${stat.hash}\`);
604
- * }
605
- *
606
- * // Get specific file stats
607
614
  * const fileStats = index.get('/data/config.json');
608
615
  * if (fileStats) {
609
616
  * console.log(\`File size: \${fileStats.size} bytes\`);
@@ -611,35 +618,35 @@ class we {
611
618
  * }
612
619
  * \`\`\`
613
620
  */
614
- async index(e) {
615
- const r = /* @__PURE__ */ new Map(), a = async (n) => {
621
+ async index() {
622
+ const t = /* @__PURE__ */ new Map(), r = async (n) => {
616
623
  const i = await this.readdir(n, { withFileTypes: !0 });
617
- for (const o of i) {
618
- const s = \`\${n === "/" ? "" : n}/\${o.name}\`;
624
+ for (const a of i) {
625
+ const s = \`\${n === "/" ? "" : n}/\${a.name}\`;
619
626
  try {
620
- const l = await this.stat(s, e);
621
- r.set(s, l), l.isDirectory && await a(s);
622
- } catch (l) {
623
- console.warn(\`Skipping broken entry: \${s}\`, l);
627
+ const o = await this.stat(s);
628
+ t.set(s, o), o.isDirectory && await r(s);
629
+ } catch (o) {
630
+ console.warn(\`Skipping broken entry: \${s}\`, o);
624
631
  }
625
632
  }
626
633
  };
627
- return r.set("/", {
634
+ return t.set("/", {
628
635
  kind: "directory",
629
636
  size: 0,
630
637
  mtime: (/* @__PURE__ */ new Date(0)).toISOString(),
631
638
  ctime: (/* @__PURE__ */ new Date(0)).toISOString(),
632
639
  isFile: !1,
633
640
  isDirectory: !0
634
- }), await a("/"), r;
641
+ }), await r("/"), t;
635
642
  }
636
- async readFile(e, r = "utf-8") {
643
+ async readFile(t, r = "utf-8") {
637
644
  await this.ensureMounted();
638
645
  try {
639
- const a = await this.getFileHandle(e, !1), n = await ue(a);
640
- return r === "binary" ? n : re(n, r);
641
- } catch (a) {
642
- throw console.error(a), new D(e);
646
+ const n = await this.getFileHandle(t, !1), i = await ht(n);
647
+ return r === "binary" ? i : rt(i, r);
648
+ } catch (n) {
649
+ throw console.error(n), new O(t);
643
650
  }
644
651
  }
645
652
  /**
@@ -667,10 +674,10 @@ class we {
667
674
  * await fs.writeFile('/data/utf16.txt', 'Hello World', 'utf-16le');
668
675
  * \`\`\`
669
676
  */
670
- async writeFile(e, r, a) {
677
+ async writeFile(t, r, n) {
671
678
  await this.ensureMounted();
672
- const n = await this.getFileHandle(e, !0);
673
- await N(n, r, a, { truncate: !0 }), this.notifyInternalChange(e, "change");
679
+ const i = await this.getFileHandle(t, !0);
680
+ await v(i, r, n, { truncate: !0 }), await this.notifyChange({ path: t, type: "changed", isDirectory: !1 });
674
681
  }
675
682
  /**
676
683
  * Append data to a file
@@ -694,10 +701,10 @@ class we {
694
701
  * await fs.appendFile('/data/binary.dat', additionalData);
695
702
  * \`\`\`
696
703
  */
697
- async appendFile(e, r, a) {
704
+ async appendFile(t, r, n) {
698
705
  await this.ensureMounted();
699
- const n = await this.getFileHandle(e, !0);
700
- await N(n, r, a, { append: !0 }), this.notifyInternalChange(e, "change");
706
+ const i = await this.getFileHandle(t, !0);
707
+ await v(i, r, n, { append: !0 }), await this.notifyChange({ path: t, type: "changed", isDirectory: !1 });
701
708
  }
702
709
  /**
703
710
  * Create a directory
@@ -720,55 +727,48 @@ class we {
720
727
  * await fs.mkdir('/users/john/documents/projects', { recursive: true });
721
728
  * \`\`\`
722
729
  */
723
- async mkdir(e, r) {
730
+ async mkdir(t, r) {
724
731
  if (await this.ensureMounted(), !this.root)
725
732
  throw new T();
726
- const a = r?.recursive ?? !1, n = m(e);
727
- let i = this.root;
728
- for (let o = 0; o < n.length; o++) {
729
- const s = n[o];
733
+ const n = r?.recursive ?? !1, i = m(t);
734
+ let a = this.root;
735
+ for (let s = 0; s < i.length; s++) {
736
+ const o = i[s];
730
737
  try {
731
- i = await i.getDirectoryHandle(s, { create: a || o === n.length - 1 });
738
+ a = await a.getDirectoryHandle(o, { create: n || s === i.length - 1 });
732
739
  } catch (l) {
733
740
  throw l.name === "NotFoundError" ? new c(
734
- \`Parent directory does not exist: \${x(n.slice(0, o + 1))}\`,
741
+ \`Parent directory does not exist: \${x(i.slice(0, s + 1))}\`,
735
742
  "ENOENT"
736
- ) : l.name === "TypeMismatchError" ? new c(\`Path segment is not a directory: \${s}\`, "ENOTDIR") : new c("Failed to create directory", "MKDIR_FAILED");
743
+ ) : l.name === "TypeMismatchError" ? new c(\`Path segment is not a directory: \${o}\`, "ENOTDIR") : new c("Failed to create directory", "MKDIR_FAILED");
737
744
  }
738
745
  }
739
- this.notifyInternalChange(e, "create");
746
+ await this.notifyChange({ path: t, type: "added", isDirectory: !0 });
740
747
  }
741
748
  /**
742
- * Get file or directory stats
749
+ * Get file or directory statistics
743
750
  *
744
- * Retrieves metadata about a file or directory, including size, modification time,
745
- * type information, and optionally file hashes.
751
+ * Returns detailed information about a file or directory, including
752
+ * size, modification time, and optionally a hash of the file content.
746
753
  *
747
754
  * @param path - The path to the file or directory
748
- * @param options - Options for stat operation
749
- * @param options.includeHash - Whether to calculate file hash (default: false, only for files)
750
- * @param options.hashAlgorithm - Hash algorithm to use (default: 'SHA-1', fastest)
751
- * @returns Promise that resolves to file/directory statistics
752
- * @throws {OPFSError} If the file or directory does not exist or cannot be accessed
755
+ * @returns Promise that resolves to FileStat object
756
+ * @throws {OPFSError} If the path does not exist or cannot be accessed
753
757
  *
754
758
  * @example
755
759
  * \`\`\`typescript
756
- * // Basic stats
757
- * const stats = await fs.stat('/config/settings.json');
760
+ * const stats = await fs.stat('/data/config.json');
758
761
  * console.log(\`File size: \${stats.size} bytes\`);
759
- * console.log(\`Is file: \${stats.isFile}\`);
760
- * console.log(\`Modified: \${stats.mtime}\`);
761
- *
762
- * // Stats with hash (SHA-1 is fastest)
763
- * const statsWithHash = await fs.stat('/config/settings.json', {
764
- * includeHash: true,
765
- * hashAlgorithm: 'SHA-1'
766
- * });
767
- * console.log(\`Hash: \${statsWithHash.hash}\`);
762
+ * console.log(\`Last modified: \${stats.mtime}\`);
763
+ *
764
+ * // If hashing is enabled, hash will be included
765
+ * if (stats.hash) {
766
+ * console.log(\`Hash: \${stats.hash}\`);
767
+ * }
768
768
  * \`\`\`
769
769
  */
770
- async stat(e, r) {
771
- if (await this.ensureMounted(), e === "/")
770
+ async stat(t) {
771
+ if (await this.ensureMounted(), t === "/")
772
772
  return {
773
773
  kind: "directory",
774
774
  size: 0,
@@ -777,30 +777,30 @@ class we {
777
777
  isFile: !1,
778
778
  isDirectory: !0
779
779
  };
780
- const a = b(e), n = await this.getDirectoryHandle(M(e), !1), i = r?.includeHash ?? !1, o = r?.hashAlgorithm ?? "SHA-1";
780
+ const r = C(t), n = await this.getDirectoryHandle(M(t), !1), i = this.hashAlgorithm !== null;
781
781
  try {
782
- const l = await (await n.getFileHandle(a, { create: !1 })).getFile(), u = {
782
+ const s = await (await n.getFileHandle(r, { create: !1 })).getFile(), o = {
783
783
  kind: "file",
784
- size: l.size,
785
- mtime: new Date(l.lastModified).toISOString(),
786
- ctime: new Date(l.lastModified).toISOString(),
784
+ size: s.size,
785
+ mtime: new Date(s.lastModified).toISOString(),
786
+ ctime: new Date(s.lastModified).toISOString(),
787
787
  isFile: !0,
788
788
  isDirectory: !1
789
789
  };
790
- if (i)
790
+ if (i && this.hashAlgorithm)
791
791
  try {
792
- const f = new Uint8Array(await l.arrayBuffer()), w = await fe(f, o);
793
- u.hash = w;
794
- } catch (f) {
795
- console.warn(\`Failed to calculate hash for \${e}:\`, f);
792
+ const l = await ut(s, this.hashAlgorithm);
793
+ o.hash = l;
794
+ } catch (l) {
795
+ console.warn(\`Failed to calculate hash for \${t}:\`, l);
796
796
  }
797
- return u;
798
- } catch (s) {
799
- if (s.name !== "TypeMismatchError" && s.name !== "NotFoundError")
797
+ return o;
798
+ } catch (a) {
799
+ if (a.name !== "TypeMismatchError" && a.name !== "NotFoundError")
800
800
  throw new c("Failed to stat (file)", "STAT_FAILED");
801
801
  }
802
802
  try {
803
- return await n.getDirectoryHandle(a, { create: !1 }), {
803
+ return await n.getDirectoryHandle(r, { create: !1 }), {
804
804
  kind: "directory",
805
805
  size: 0,
806
806
  mtime: (/* @__PURE__ */ new Date(0)).toISOString(),
@@ -808,30 +808,30 @@ class we {
808
808
  isFile: !1,
809
809
  isDirectory: !0
810
810
  };
811
- } catch (s) {
812
- throw s.name === "NotFoundError" ? new c(\`No such file or directory: \${e}\`, "ENOENT") : new c("Failed to stat (directory)", "STAT_FAILED");
811
+ } catch (a) {
812
+ throw a.name === "NotFoundError" ? new c(\`No such file or directory: \${t}\`, "ENOENT") : new c("Failed to stat (directory)", "STAT_FAILED");
813
813
  }
814
814
  }
815
- async readdir(e, r) {
815
+ async readdir(t, r) {
816
816
  await this.ensureMounted();
817
- const a = r?.withFileTypes ?? !1, n = await this.getDirectoryHandle(e, !1);
818
- if (a) {
819
- const i = [];
820
- for await (const [o, s] of n.entries()) {
821
- const l = s.kind === "file";
822
- i.push({
823
- name: o,
824
- kind: s.kind,
817
+ const n = r?.withFileTypes ?? !1, i = await this.getDirectoryHandle(t, !1);
818
+ if (n) {
819
+ const a = [];
820
+ for await (const [s, o] of i.entries()) {
821
+ const l = o.kind === "file";
822
+ a.push({
823
+ name: s,
824
+ kind: o.kind,
825
825
  isFile: l,
826
826
  isDirectory: !l
827
827
  });
828
828
  }
829
- return i;
829
+ return a;
830
830
  } else {
831
- const i = [];
832
- for await (const [o] of n.entries())
833
- i.push(o);
834
- return i;
831
+ const a = [];
832
+ for await (const [s] of i.entries())
833
+ a.push(s);
834
+ return a;
835
835
  }
836
836
  }
837
837
  /**
@@ -848,29 +848,29 @@ class we {
848
848
  * console.log(\`File exists: \${exists}\`);
849
849
  * \`\`\`
850
850
  */
851
- async exists(e) {
852
- if (await this.ensureMounted(), e === "/")
851
+ async exists(t) {
852
+ if (await this.ensureMounted(), t === "/")
853
853
  return !0;
854
- const r = b(e);
855
- let a = null;
854
+ const r = C(t);
855
+ let n = null;
856
856
  try {
857
- a = await this.getDirectoryHandle(M(e), !1);
858
- } catch (n) {
859
- throw (n.name === "NotFoundError" || n.name === "TypeMismatchError") && (a = null), n;
857
+ n = await this.getDirectoryHandle(M(t), !1);
858
+ } catch (i) {
859
+ throw (i.name === "NotFoundError" || i.name === "TypeMismatchError") && (n = null), i;
860
860
  }
861
- if (!a || !r)
861
+ if (!n || !r)
862
862
  return !1;
863
863
  try {
864
- return await a.getFileHandle(r, { create: !1 }), !0;
865
- } catch (n) {
866
- if (n.name !== "NotFoundError" && n.name !== "TypeMismatchError")
867
- throw n;
864
+ return await n.getFileHandle(r, { create: !1 }), !0;
865
+ } catch (i) {
866
+ if (i.name !== "NotFoundError" && i.name !== "TypeMismatchError")
867
+ throw i;
868
868
  }
869
869
  try {
870
- return await a.getDirectoryHandle(r, { create: !1 }), !0;
871
- } catch (n) {
872
- if (n.name !== "NotFoundError" && n.name !== "TypeMismatchError")
873
- throw n;
870
+ return await n.getDirectoryHandle(r, { create: !1 }), !0;
871
+ } catch (i) {
872
+ if (i.name !== "NotFoundError" && i.name !== "TypeMismatchError")
873
+ throw i;
874
874
  }
875
875
  return !1;
876
876
  }
@@ -893,17 +893,17 @@ class we {
893
893
  * await fs.clear('/data');
894
894
  * \`\`\`
895
895
  */
896
- async clear(e = "/") {
896
+ async clear(t = "/") {
897
897
  await this.ensureMounted();
898
898
  try {
899
- const r = await this.readdir(e, { withFileTypes: !0 });
900
- for (const a of r) {
901
- const n = \`\${e === "/" ? "" : e}/\${a.name}\`;
902
- await this.remove(n, { recursive: !0 });
899
+ const r = await this.readdir(t, { withFileTypes: !0 });
900
+ for (const n of r) {
901
+ const i = \`\${t === "/" ? "" : t}/\${n.name}\`;
902
+ await this.remove(i, { recursive: !0 });
903
903
  }
904
- this.notifyInternalChange(e, "change");
904
+ await this.notifyChange({ path: t, type: "changed", isDirectory: !0 });
905
905
  } catch (r) {
906
- throw r instanceof c ? r : new c(\`Failed to clear directory: \${e}\`, "CLEAR_FAILED");
906
+ throw r instanceof c ? r : new c(\`Failed to clear directory: \${t}\`, "CLEAR_FAILED");
907
907
  }
908
908
  }
909
909
  /**
@@ -930,24 +930,24 @@ class we {
930
930
  * await fs.rm('/maybe/exists', { force: true });
931
931
  * \`\`\`
932
932
  */
933
- async remove(e, r) {
933
+ async remove(t, r) {
934
934
  await this.ensureMounted();
935
- const a = r?.recursive ?? !1, n = r?.force ?? !1;
936
- if (e === "/")
935
+ const n = r?.recursive ?? !1, i = r?.force ?? !1;
936
+ if (t === "/")
937
937
  throw new c("Cannot remove root directory", "EROOT");
938
- const i = b(e);
939
- if (!i)
940
- throw new v("Invalid path", e);
941
- const o = await this.getDirectoryHandle(M(e), !1);
938
+ const a = C(t);
939
+ if (!a)
940
+ throw new k("Invalid path", t);
941
+ const s = await this.getDirectoryHandle(M(t), !1);
942
942
  try {
943
- await o.removeEntry(i, { recursive: a });
944
- } catch (s) {
945
- if (s.name === "NotFoundError") {
946
- if (!n)
947
- throw new c(\`No such file or directory: \${e}\`, "ENOENT");
948
- } 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");
943
+ await s.removeEntry(a, { recursive: n });
944
+ } catch (o) {
945
+ if (o.name === "NotFoundError") {
946
+ if (!i)
947
+ throw new c(\`No such file or directory: \${t}\`, "ENOENT");
948
+ } else throw o.name === "InvalidModificationError" ? new c(\`Directory not empty: \${t}. Use recursive option to force removal.\`, "ENOTEMPTY") : o.name === "TypeMismatchError" && !n ? new c(\`Cannot remove directory without recursive option: \${t}\`, "EISDIR") : new c(\`Failed to remove path: \${t}\`, "RM_FAILED");
949
949
  }
950
- this.notifyInternalChange(e, "delete");
950
+ await this.notifyChange({ path: t, type: "removed", isDirectory: !1 });
951
951
  }
952
952
  /**
953
953
  * Resolve a path to an absolute path
@@ -967,15 +967,15 @@ class we {
967
967
  * console.log(absolute); // '/data/file.txt'
968
968
  * \`\`\`
969
969
  */
970
- async realpath(e) {
970
+ async realpath(t) {
971
971
  await this.ensureMounted();
972
972
  try {
973
- const r = ce(e);
973
+ const r = ct(t);
974
974
  if (!await this.exists(r))
975
- throw new D(r);
975
+ throw new O(r);
976
976
  return r;
977
977
  } catch (r) {
978
- throw r instanceof c ? r : new c(\`Failed to resolve path: \${e}\`, "REALPATH_FAILED");
978
+ throw r instanceof c ? r : new c(\`Failed to resolve path: \${t}\`, "REALPATH_FAILED");
979
979
  }
980
980
  }
981
981
  /**
@@ -994,14 +994,14 @@ class we {
994
994
  * await fs.rename('/old/path/file.txt', '/new/path/renamed.txt');
995
995
  * \`\`\`
996
996
  */
997
- async rename(e, r) {
997
+ async rename(t, r) {
998
998
  await this.ensureMounted();
999
999
  try {
1000
- if (!await this.exists(e))
1001
- throw new D(e);
1002
- await this.copy(e, r, { recursive: !0 }), await this.remove(e, { recursive: !0 }), this.notifyInternalChange(e, "delete"), this.notifyInternalChange(r, "create");
1003
- } catch (a) {
1004
- throw a instanceof c ? a : new c(\`Failed to rename from \${e} to \${r}\`, "RENAME_FAILED");
1000
+ if (!await this.exists(t))
1001
+ throw new O(t);
1002
+ await this.copy(t, r, { recursive: !0 }), await this.remove(t, { recursive: !0 }), await this.notifyChange({ path: t, type: "removed", isDirectory: !1 }), await this.notifyChange({ path: r, type: "added", isDirectory: !1 });
1003
+ } catch (n) {
1004
+ throw n instanceof c ? n : new c(\`Failed to rename from \${t} to \${r}\`, "RENAME_FAILED");
1005
1005
  }
1006
1006
  }
1007
1007
  /**
@@ -1029,85 +1029,81 @@ class we {
1029
1029
  * await fs.copy('/source', '/dest', { recursive: true, force: false });
1030
1030
  * \`\`\`
1031
1031
  */
1032
- async copy(e, r, a) {
1032
+ async copy(t, r, n) {
1033
1033
  await this.ensureMounted();
1034
1034
  try {
1035
- const n = a?.recursive ?? !1, i = a?.force ?? !0;
1036
- if (!await this.exists(e))
1037
- throw new c(\`Source does not exist: \${e}\`, "ENOENT");
1038
- if (await this.exists(r) && !i)
1035
+ const i = n?.recursive ?? !1, a = n?.force ?? !0;
1036
+ if (!await this.exists(t))
1037
+ throw new c(\`Source does not exist: \${t}\`, "ENOENT");
1038
+ if (await this.exists(r) && !a)
1039
1039
  throw new c(\`Destination already exists: \${r}\`, "EEXIST");
1040
- if ((await this.stat(e)).isFile) {
1041
- const u = await this.readFile(e, "binary");
1042
- await this.writeFile(r, u);
1040
+ if ((await this.stat(t)).isFile) {
1041
+ const h = await this.readFile(t, "binary");
1042
+ await this.writeFile(r, h);
1043
1043
  } else {
1044
- if (!n)
1045
- throw new c(\`Cannot copy directory without recursive option: \${e}\`, "EISDIR");
1044
+ if (!i)
1045
+ throw new c(\`Cannot copy directory without recursive option: \${t}\`, "EISDIR");
1046
1046
  await this.mkdir(r, { recursive: !0 });
1047
- const u = await this.readdir(e, { withFileTypes: !0 });
1048
- for (const f of u) {
1049
- const w = \`\${e}/\${f.name}\`, h = \`\${r}/\${f.name}\`;
1050
- await this.copy(w, h, { recursive: !0, force: i });
1047
+ const h = await this.readdir(t, { withFileTypes: !0 });
1048
+ for (const u of h) {
1049
+ const w = \`\${t}/\${u.name}\`, f = \`\${r}/\${u.name}\`;
1050
+ await this.copy(w, f, { recursive: !0, force: a });
1051
1051
  }
1052
1052
  }
1053
- this.notifyInternalChange(r, "create");
1054
- } catch (n) {
1055
- throw n instanceof c ? n : new c(\`Failed to copy from \${e} to \${r}\`, "CP_FAILED");
1053
+ await this.notifyChange({ path: r, type: "added", isDirectory: !1 });
1054
+ } catch (i) {
1055
+ throw i instanceof c ? i : new c(\`Failed to copy from \${t} to \${r}\`, "CP_FAILED");
1056
1056
  }
1057
1057
  }
1058
1058
  /**
1059
1059
  * Start watching a file or directory for changes
1060
1060
  */
1061
- async watch(e) {
1061
+ async watch(t) {
1062
1062
  await this.ensureMounted();
1063
- const r = C(e), a = await this.buildSnapshot(r);
1064
- this.watchers.set(r, a), this.watchTimer || (this.watchTimer = setInterval(() => {
1063
+ const r = b(t), n = await this.buildSnapshot(r);
1064
+ this.watchers.set(r, n), this.watchTimer || (this.watchTimer = setInterval(() => {
1065
1065
  this.scanWatches();
1066
1066
  }, this.watchInterval));
1067
1067
  }
1068
1068
  /**
1069
1069
  * Stop watching a previously watched path
1070
1070
  */
1071
- unwatch(e) {
1072
- const r = C(e);
1071
+ unwatch(t) {
1072
+ const r = b(t);
1073
1073
  this.watchers.delete(r), this.watchers.size === 0 && this.watchTimer && (clearInterval(this.watchTimer), this.watchTimer = null);
1074
1074
  }
1075
- async buildSnapshot(e) {
1076
- const r = /* @__PURE__ */ new Map(), a = async (n) => {
1077
- const i = await this.stat(n);
1078
- if (r.set(n, i), i.isDirectory) {
1079
- const o = await this.readdir(n, { withFileTypes: !0 });
1080
- for (const s of o) {
1081
- const l = \`\${n === "/" ? "" : n}/\${s.name}\`;
1082
- await a(l);
1075
+ async buildSnapshot(t) {
1076
+ const r = /* @__PURE__ */ new Map(), n = async (i) => {
1077
+ const a = await this.stat(i);
1078
+ if (r.set(i, a), a.isDirectory) {
1079
+ const s = await this.readdir(i, { withFileTypes: !0 });
1080
+ for (const o of s) {
1081
+ const l = \`\${i === "/" ? "" : i}/\${o.name}\`;
1082
+ await n(l);
1083
1083
  }
1084
1084
  }
1085
1085
  };
1086
- return await a(e), r;
1086
+ return await n(t), r;
1087
1087
  }
1088
1088
  async scanWatches() {
1089
1089
  if (!this.scanning) {
1090
1090
  this.scanning = !0;
1091
1091
  try {
1092
1092
  await Promise.all(
1093
- [...this.watchers.entries()].map(async ([e, r]) => {
1094
- let a;
1093
+ [...this.watchers.entries()].map(async ([t, r]) => {
1094
+ let n;
1095
1095
  try {
1096
- a = await this.buildSnapshot(e);
1096
+ n = await this.buildSnapshot(t);
1097
1097
  } catch {
1098
- a = /* @__PURE__ */ new Map();
1098
+ n = /* @__PURE__ */ new Map();
1099
1099
  }
1100
- const n = [];
1101
- for (const [i, o] of a) {
1100
+ for (const [i, a] of n) {
1102
1101
  const s = r.get(i);
1103
- s ? (s.mtime !== o.mtime || s.size !== o.size) && n.push({ path: i, type: "change" }) : n.push({ path: i, type: "create" });
1102
+ s ? (s.mtime !== a.mtime || s.size !== a.size) && await this.notifyChange({ path: i, type: "changed", isDirectory: !1 }) : await this.notifyChange({ path: i, type: "added", isDirectory: !1 });
1104
1103
  }
1105
1104
  for (const i of r.keys())
1106
- a.has(i) || n.push({ path: i, type: "delete" });
1107
- if (n.length && this.watchCallback)
1108
- for (const i of n)
1109
- this.watchCallback(i);
1110
- this.watchers.set(e, a);
1105
+ n.has(i) || await this.notifyChange({ path: i, type: "removed", isDirectory: !1 });
1106
+ this.watchers.set(t, n);
1111
1107
  })
1112
1108
  );
1113
1109
  } finally {
@@ -1143,22 +1139,22 @@ class we {
1143
1139
  * await fs.sync(entries, { cleanBefore: true });
1144
1140
  * \`\`\`
1145
1141
  */
1146
- async sync(e, r) {
1142
+ async sync(t, r) {
1147
1143
  await this.ensureMounted();
1148
1144
  try {
1149
1145
  (r?.cleanBefore ?? !1) && await this.clear("/");
1150
- for (const [n, i] of e) {
1151
- const o = C(n);
1152
- let s;
1153
- i instanceof Blob ? s = await he(i) : s = i, await this.writeFile(o, s);
1146
+ for (const [i, a] of t) {
1147
+ const s = b(i);
1148
+ let o;
1149
+ a instanceof Blob ? o = await ft(a) : o = a, await this.writeFile(s, o);
1154
1150
  }
1155
- this.notifyInternalChange("/", "change");
1156
- } catch (a) {
1157
- throw a instanceof c ? a : new c("Failed to sync file system", "SYNC_FAILED");
1151
+ await this.notifyChange({ path: "/", type: "changed", isDirectory: !0 });
1152
+ } catch (n) {
1153
+ throw n instanceof c ? n : new c("Failed to sync file system", "SYNC_FAILED");
1158
1154
  }
1159
1155
  }
1160
1156
  }
1161
- typeof self < "u" && self.constructor.name === "DedicatedWorkerGlobalScope" && O(new we());
1162
- //# sourceMappingURL=worker-DCm4BiWM.js.map
1163
- `,i=typeof self<"u"&&self.Blob&&new Blob(["URL.revokeObjectURL(import.meta.url);",o],{type:"text/javascript;charset=utf-8"});function s(r){let e;try{if(e=i&&(self.URL||self.webkitURL).createObjectURL(i),!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(o),{type:"module",name:r?.name})}}function c(r,e){const t=a.wrap(new s);return r&&t.setWatchCallback(a.proxy(r),e),t}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;
1157
+ typeof self < "u" && self.constructor.name === "DedicatedWorkerGlobalScope" && P(new wt());
1158
+ //# sourceMappingURL=worker-BL3varjN.js.map
1159
+ `,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(r?a.proxy(r):()=>{}),t&&e.setOptions(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;
1164
1160
  //# sourceMappingURL=index.cjs.map