opfs-worker 0.1.1 → 0.2.0

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