opfs-worker 1.3.0 → 1.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,12 +1,12 @@
1
1
  import { wrap as u } from "comlink";
2
- import { i as h, d as l, e as c } from "./helpers-BuGfPAg0.js";
3
- import { A as E, N as S, D as P, E as O, F, j as A, c as T, I as R, h as I, O as C, a as $, f as D, g as _, P as N, k as z, b as k, S as M, T as j, V as W, W as L, p as U, C as H, B, L as G, n as q, G as Y, z as V, l as X, M as Z, q as J, y as K, v as Q, o as nn, m as tn, u as en, t as rn, r as sn, H as an, x as on, K as cn, s as hn, J as ln, w as pn } from "./helpers-BuGfPAg0.js";
2
+ import { i as h, d as l, e as c } from "./helpers-CKOebsbw.js";
3
+ import { A as E, M as S, D as P, E as O, F, j as A, c as T, I as R, h as C, O as I, a as $, f as D, g as _, P as N, b as z, S as k, V as M, W as j, o as L, B as W, z as U, K as H, l as B, C as G, y as q, k as V, L as Y, p as J, x as X, u as Z, n as K, m as Q, t as nn, r as tn, q as en, G as rn, v as sn, J as an, s as on, H as cn, w as hn } from "./helpers-CKOebsbw.js";
4
4
  const f = `/**
5
5
  * @license
6
6
  * Copyright 2019 Google LLC
7
7
  * SPDX-License-Identifier: Apache-2.0
8
8
  */
9
- const bt = Symbol("Comlink.proxy"), Ht = Symbol("Comlink.endpoint"), Wt = Symbol("Comlink.releaseProxy"), J = Symbol("Comlink.finalizer"), U = Symbol("Comlink.thrown"), Ot = (s) => typeof s == "object" && s !== null || typeof s == "function", _t = {
9
+ const bt = Symbol("Comlink.proxy"), Ht = Symbol("Comlink.endpoint"), Wt = Symbol("Comlink.releaseProxy"), J = Symbol("Comlink.finalizer"), U = Symbol("Comlink.thrown"), Ot = (s) => typeof s == "object" && s !== null || typeof s == "function", jt = {
10
10
  canHandle: (s) => Ot(s) && s[bt],
11
11
  serialize(s) {
12
12
  const { port1: t, port2: e } = new MessageChannel();
@@ -15,7 +15,7 @@ const bt = Symbol("Comlink.proxy"), Ht = Symbol("Comlink.endpoint"), Wt = Symbol
15
15
  deserialize(s) {
16
16
  return s.start(), Gt(s);
17
17
  }
18
- }, jt = {
18
+ }, _t = {
19
19
  canHandle: (s) => Ot(s) && U in s,
20
20
  serialize({ value: s }) {
21
21
  let t;
@@ -32,8 +32,8 @@ const bt = Symbol("Comlink.proxy"), Ht = Symbol("Comlink.endpoint"), Wt = Symbol
32
32
  throw s.isError ? Object.assign(new Error(s.value.message), s.value) : s.value;
33
33
  }
34
34
  }, Dt = /* @__PURE__ */ new Map([
35
- ["proxy", _t],
36
- ["throw", jt]
35
+ ["proxy", jt],
36
+ ["throw", _t]
37
37
  ]);
38
38
  function Ut(s, t) {
39
39
  for (const e of s)
@@ -291,7 +291,7 @@ class w extends Error {
291
291
  }
292
292
  class Qt extends w {
293
293
  constructor(t) {
294
- super("OPFS is not supported in this browser", "OPFS_NOT_SUPPORTED", void 0, void 0, t);
294
+ super("OPFS is not supported in this browser", "ENOTSUP", void 0, void 0, t);
295
295
  }
296
296
  }
297
297
  class Kt extends w {
@@ -311,7 +311,7 @@ class F extends w {
311
311
  }
312
312
  class te extends w {
313
313
  constructor(t, e, n) {
314
- super(\`Permission denied for \${e} on: \${t}\`, "PERMISSION_DENIED", t, e, n);
314
+ super(\`Permission denied for \${e} on: \${t}\`, "EACCES", t, e, n);
315
315
  }
316
316
  }
317
317
  class ee extends w {
@@ -324,10 +324,10 @@ class se extends w {
324
324
  super(\`File is busy: \${t}\`, "EBUSY", t, "open", e);
325
325
  }
326
326
  }
327
- class L extends w {
328
- constructor(t, e, n, r) {
329
- const i = e === "directory" ? \`Is a directory: \${n}\` : \`Not a directory: \${n}\`, o = e === "directory" ? "EISDIR" : "ENOTDIR";
330
- super(i, o, n, "access", r);
327
+ class z extends w {
328
+ constructor(t, e, n) {
329
+ const r = t === "directory" ? \`Is a directory: \${e}\` : \`Not a directory: \${e}\`, i = t === "directory" ? "EISDIR" : "ENOTDIR";
330
+ super(r, i, e, "access", n);
331
331
  }
332
332
  }
333
333
  class N extends w {
@@ -359,15 +359,11 @@ class Ct extends w {
359
359
  class rt extends w {
360
360
  constructor(t, e, n) {
361
361
  const r = {
362
- remove: \`Failed to remove entry: \${e}\`,
363
- clear: \`Directory not empty: \${e}. Use recursive option to force removal.\`,
364
- root: "Cannot remove root directory"
365
- }, i = {
366
- remove: "RM_FAILED",
367
- clear: "ENOTEMPTY",
368
- root: "EROOT"
362
+ RM_FAILED: \`Failed to remove entry: \${e}\`,
363
+ ENOTEMPTY: \`Directory not empty: \${e}. Use recursive option to force removal.\`,
364
+ EROOT: "Cannot remove root directory"
369
365
  };
370
- super(r[t], i[t], e, "unlink", n);
366
+ super(r[t] || \`Directory operation failed: \${e}\`, t, e, "unlink", n);
371
367
  }
372
368
  }
373
369
  class re extends w {
@@ -385,7 +381,7 @@ class K extends w {
385
381
  super(\`Destination already exists: \${t}\`, "EEXIST", t, "open", e);
386
382
  }
387
383
  }
388
- function _(s, t, e, n) {
384
+ function j(s, t, e, n) {
389
385
  const r = \`\${s.toUpperCase()}_FAILED\`;
390
386
  return new w(\`Failed to \${s} file descriptor: \${t}\`, r, e, s, n);
391
387
  }
@@ -399,7 +395,7 @@ function A(s, t) {
399
395
  case "NotFoundError":
400
396
  return new F("file", e, s);
401
397
  case "TypeMismatchError":
402
- return n !== void 0 ? n ? new L("file", "directory", e || "unknown", s) : new L("directory", "file", e || "unknown", s) : new N("argument", \`Type mismatch: \${e || "unknown"}\`, e, s);
398
+ return n !== void 0 ? n ? new z("directory", e || "unknown", s) : new z("file", e || "unknown", s) : new N("argument", \`Type mismatch: \${e || "unknown"}\`, e, s);
403
399
  case "NotAllowedError":
404
400
  case "SecurityError":
405
401
  return new te(e, "unknown", s);
@@ -606,7 +602,7 @@ const Oe = 1024 * 64, Z = (s) => {
606
602
  }
607
603
  const u = "[" + (h ? "^" : "") + dt(n) + "]", d = "[" + (h ? "" : "^") + dt(r) + "]";
608
604
  return [n.length && r.length ? "(" + u + "|" + d + ")" : n.length ? u : d, a, c - e, !0];
609
- }, k = (s, { windowsPathsNoEscape: t = !1 } = {}) => t ? s.replace(/\\[([^\\/\\\\])\\]/g, "$1") : s.replace(/((?!\\\\).|^)\\[([^\\/\\\\])\\]/g, "$1$2").replace(/\\\\([^\\/])/g, "$1"), Ne = /* @__PURE__ */ new Set(["!", "?", "+", "*", "@"]), pt = (s) => Ne.has(s), Ce = "(?!(?:^|/)\\\\.\\\\.?(?:$|/))", j = "(?!\\\\.)", Fe = /* @__PURE__ */ new Set(["[", "."]), $e = /* @__PURE__ */ new Set(["..", "."]), Me = new Set("().*{}+?[]^$\\\\!"), Pe = (s) => s.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, "\\\\$&"), ct = "[^/]", gt = ct + "*?", wt = ct + "+?";
605
+ }, k = (s, { windowsPathsNoEscape: t = !1 } = {}) => t ? s.replace(/\\[([^\\/\\\\])\\]/g, "$1") : s.replace(/((?!\\\\).|^)\\[([^\\/\\\\])\\]/g, "$1$2").replace(/\\\\([^\\/])/g, "$1"), Ne = /* @__PURE__ */ new Set(["!", "?", "+", "*", "@"]), pt = (s) => Ne.has(s), Ce = "(?!(?:^|/)\\\\.\\\\.?(?:$|/))", _ = "(?!\\\\.)", Fe = /* @__PURE__ */ new Set(["[", "."]), $e = /* @__PURE__ */ new Set(["..", "."]), Me = new Set("().*{}+?[]^$\\\\!"), Pe = (s) => s.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, "\\\\$&"), ct = "[^/]", gt = ct + "*?", wt = ct + "+?";
610
606
  class E {
611
607
  type;
612
608
  #s;
@@ -870,7 +866,7 @@ class E {
870
866
  h.startsWith("\\\\.") && g.has(h.charAt(2)) || // the pattern starts with \\.\\., and then [ or .
871
867
  h.startsWith("\\\\.\\\\.") && g.has(h.charAt(4))
872
868
  ), S = !e && !t && g.has(h.charAt(0));
873
- c = p ? Ce : S ? j : "";
869
+ c = p ? Ce : S ? _ : "";
874
870
  }
875
871
  let f = "";
876
872
  return this.isEnd() && this.#s.#a && this.#e?.type === "!" && (f = "(?:$|\\\\/)"), [
@@ -886,15 +882,15 @@ class E {
886
882
  const l = this.toString();
887
883
  return this.#t = [l], this.type = null, this.#n = void 0, [l, k(this.toString()), !1, !1];
888
884
  }
889
- let o = !n || t || e || !j ? "" : this.#f(!0);
885
+ let o = !n || t || e || !_ ? "" : this.#f(!0);
890
886
  o === i && (o = ""), o && (i = \`(?:\${i})(?:\${o})*?\`);
891
887
  let a = "";
892
888
  if (this.type === "!" && this.#u)
893
- a = (this.isStart() && !e ? j : "") + wt;
889
+ a = (this.isStart() && !e ? _ : "") + wt;
894
890
  else {
895
891
  const l = this.type === "!" ? (
896
892
  // !() must match something,but !(x) can match ''
897
- "))" + (this.isStart() && !e && !t ? j : "") + gt + ")"
893
+ "))" + (this.isStart() && !e && !t ? _ : "") + gt + ")"
898
894
  ) : this.type === "@" ? ")" : this.type === "?" ? ")?" : this.type === "+" && o ? ")" : this.type === "*" && o ? ")?" : \`)\${this.type}\`;
899
895
  a = r + i + l;
900
896
  }
@@ -945,7 +941,7 @@ class E {
945
941
  return [i, k(t), !!e, o];
946
942
  }
947
943
  }
948
- const Te = (s, { windowsPathsNoEscape: t = !1 } = {}) => t ? s.replace(/[?*()[\\]]/g, "[$&]") : s.replace(/[?*()[\\]\\\\]/g, "\\\\$&"), y = (s, t, e = {}) => (Z(t), !e.nocomment && t.charAt(0) === "#" ? !1 : new X(t, e).match(s)), Re = /^\\*+([^+@!?\\*\\[\\(]*)$/, Ie = (s) => (t) => !t.startsWith(".") && t.endsWith(s), ke = (s) => (t) => t.endsWith(s), ze = (s) => (s = s.toLowerCase(), (t) => !t.startsWith(".") && t.toLowerCase().endsWith(s)), Le = (s) => (s = s.toLowerCase(), (t) => t.toLowerCase().endsWith(s)), He = /^\\*+\\.\\*+$/, We = (s) => !s.startsWith(".") && s.includes("."), _e = (s) => s !== "." && s !== ".." && s.includes("."), je = /^\\.\\*+$/, Ue = (s) => s !== "." && s !== ".." && s.startsWith("."), Be = /^\\*+$/, Ge = (s) => s.length !== 0 && !s.startsWith("."), qe = (s) => s.length !== 0 && s !== "." && s !== "..", Ve = /^\\?+([^+@!?\\*\\[\\(]*)?$/, Ye = ([s, t = ""]) => {
944
+ const Te = (s, { windowsPathsNoEscape: t = !1 } = {}) => t ? s.replace(/[?*()[\\]]/g, "[$&]") : s.replace(/[?*()[\\]\\\\]/g, "\\\\$&"), y = (s, t, e = {}) => (Z(t), !e.nocomment && t.charAt(0) === "#" ? !1 : new X(t, e).match(s)), Re = /^\\*+([^+@!?\\*\\[\\(]*)$/, Ie = (s) => (t) => !t.startsWith(".") && t.endsWith(s), ke = (s) => (t) => t.endsWith(s), Le = (s) => (s = s.toLowerCase(), (t) => !t.startsWith(".") && t.toLowerCase().endsWith(s)), ze = (s) => (s = s.toLowerCase(), (t) => t.toLowerCase().endsWith(s)), He = /^\\*+\\.\\*+$/, We = (s) => !s.startsWith(".") && s.includes("."), je = (s) => s !== "." && s !== ".." && s.includes("."), _e = /^\\.\\*+$/, Ue = (s) => s !== "." && s !== ".." && s.startsWith("."), Be = /^\\*+$/, Ge = (s) => s.length !== 0 && !s.startsWith("."), qe = (s) => s.length !== 0 && s !== "." && s !== "..", Ve = /^\\?+([^+@!?\\*\\[\\(]*)?$/, Ye = ([s, t = ""]) => {
949
945
  const e = It([s]);
950
946
  return t ? (t = t.toLowerCase(), (n) => e(n) && n.toLowerCase().endsWith(t)) : e;
951
947
  }, Ze = ([s, t = ""]) => {
@@ -963,10 +959,10 @@ const Te = (s, { windowsPathsNoEscape: t = !1 } = {}) => t ? s.replace(/[?*()[\\
963
959
  }, kt = ([s]) => {
964
960
  const t = s.length;
965
961
  return (e) => e.length === t && e !== "." && e !== "..";
966
- }, zt = typeof process == "object" && process ? typeof process.env == "object" && process.env && process.env.__MINIMATCH_TESTING_PLATFORM__ || process.platform : "posix", mt = {
962
+ }, Lt = typeof process == "object" && process ? typeof process.env == "object" && process.env && process.env.__MINIMATCH_TESTING_PLATFORM__ || process.platform : "posix", mt = {
967
963
  win32: { sep: "\\\\" },
968
964
  posix: { sep: "/" }
969
- }, Qe = zt === "win32" ? mt.win32.sep : mt.posix.sep;
965
+ }, Qe = Lt === "win32" ? mt.win32.sep : mt.posix.sep;
970
966
  y.sep = Qe;
971
967
  const O = Symbol("globstar **");
972
968
  y.GLOBSTAR = O;
@@ -1007,8 +1003,8 @@ const b = (s, t = {}) => Object.assign({}, s, t), rs = (s) => {
1007
1003
  });
1008
1004
  };
1009
1005
  y.defaults = rs;
1010
- const Lt = (s, t = {}) => (Z(s), t.nobrace || !/\\{(?:(?!\\{).)*\\}/.test(s) ? [s] : ye(s));
1011
- y.braceExpand = Lt;
1006
+ const zt = (s, t = {}) => (Z(s), t.nobrace || !/\\{(?:(?!\\{).)*\\}/.test(s) ? [s] : ye(s));
1007
+ y.braceExpand = zt;
1012
1008
  const is = (s, t = {}) => new X(s, t).makeRe();
1013
1009
  y.makeRe = is;
1014
1010
  const os = (s, t, e = {}) => {
@@ -1036,7 +1032,7 @@ class X {
1036
1032
  windowsNoMagicRoot;
1037
1033
  regexp;
1038
1034
  constructor(t, e = {}) {
1039
- Z(t), e = e || {}, this.options = e, this.pattern = t, this.platform = e.platform || zt, this.isWindows = this.platform === "win32", this.windowsPathsNoEscape = !!e.windowsPathsNoEscape || e.allowWindowsEscape === !1, this.windowsPathsNoEscape && (this.pattern = this.pattern.replace(/\\\\/g, "/")), this.preserveMultipleSlashes = !!e.preserveMultipleSlashes, this.regexp = null, this.negate = !1, this.nonegate = !!e.nonegate, this.comment = !1, this.empty = !1, this.partial = !!e.partial, this.nocase = !!this.options.nocase, this.windowsNoMagicRoot = e.windowsNoMagicRoot !== void 0 ? e.windowsNoMagicRoot : !!(this.isWindows && this.nocase), this.globSet = [], this.globParts = [], this.set = [], this.make();
1035
+ Z(t), e = e || {}, this.options = e, this.pattern = t, this.platform = e.platform || Lt, this.isWindows = this.platform === "win32", this.windowsPathsNoEscape = !!e.windowsPathsNoEscape || e.allowWindowsEscape === !1, this.windowsPathsNoEscape && (this.pattern = this.pattern.replace(/\\\\/g, "/")), this.preserveMultipleSlashes = !!e.preserveMultipleSlashes, this.regexp = null, this.negate = !1, this.nonegate = !!e.nonegate, this.comment = !1, this.empty = !1, this.partial = !!e.partial, this.nocase = !!this.options.nocase, this.windowsNoMagicRoot = e.windowsNoMagicRoot !== void 0 ? e.windowsNoMagicRoot : !!(this.isWindows && this.nocase), this.globSet = [], this.globParts = [], this.set = [], this.make();
1040
1036
  }
1041
1037
  hasMagic() {
1042
1038
  if (this.options.magicalBraces && this.set.length > 1)
@@ -1293,7 +1289,7 @@ globstar while\`, t, u, e, d, g), this.matchOne(t.slice(u), e.slice(d), n))
1293
1289
  throw new Error("wtf?");
1294
1290
  }
1295
1291
  braceExpand() {
1296
- return Lt(this.pattern, this.options);
1292
+ return zt(this.pattern, this.options);
1297
1293
  }
1298
1294
  parse(t) {
1299
1295
  Z(t);
@@ -1303,7 +1299,7 @@ globstar while\`, t, u, e, d, g), this.matchOne(t.slice(u), e.slice(d), n))
1303
1299
  if (t === "")
1304
1300
  return "";
1305
1301
  let n, r = null;
1306
- (n = t.match(Be)) ? r = e.dot ? qe : Ge : (n = t.match(Re)) ? r = (e.nocase ? e.dot ? Le : ze : e.dot ? ke : Ie)(n[1]) : (n = t.match(Ve)) ? r = (e.nocase ? e.dot ? Ze : Ye : e.dot ? Xe : Je)(n) : (n = t.match(He)) ? r = e.dot ? _e : We : (n = t.match(je)) && (r = Ue);
1302
+ (n = t.match(Be)) ? r = e.dot ? qe : Ge : (n = t.match(Re)) ? r = (e.nocase ? e.dot ? ze : Le : e.dot ? ke : Ie)(n[1]) : (n = t.match(Ve)) ? r = (e.nocase ? e.dot ? Ze : Ye : e.dot ? Xe : Je)(n) : (n = t.match(He)) ? r = e.dot ? je : We : (n = t.match(_e)) && (r = Ue);
1307
1303
  const i = E.fromGlob(t, this.options).toMMPattern();
1308
1304
  return r && typeof i == "object" && Reflect.defineProperty(i, "test", { value: r }), i;
1309
1305
  }
@@ -1375,7 +1371,7 @@ function cs() {
1375
1371
  if (!("storage" in navigator) || !("getDirectory" in navigator.storage))
1376
1372
  throw new Qt();
1377
1373
  }
1378
- async function z(s, t, e) {
1374
+ async function L(s, t, e) {
1379
1375
  return typeof navigator < "u" && navigator.locks?.request ? navigator.locks.request(\`opfs:\${s.replace(/\\/+/g, "/")}\`, { mode: t }, e) : e();
1380
1376
  }
1381
1377
  function M(s) {
@@ -1428,7 +1424,7 @@ async function us(s) {
1428
1424
  }
1429
1425
  async function fs(s, t, e = {}) {
1430
1426
  const n = it(t);
1431
- return z(t, "exclusive", async () => {
1427
+ return L(t, "exclusive", async () => {
1432
1428
  const r = e.recursive ?? !1, i = e.force ?? !1;
1433
1429
  try {
1434
1430
  await s.removeEntry(n, { recursive: r });
@@ -1436,7 +1432,7 @@ async function fs(s, t, e = {}) {
1436
1432
  if (o.name === "NotFoundError") {
1437
1433
  if (!i)
1438
1434
  throw new F("file", t, o);
1439
- } else throw o.name === "InvalidModificationError" ? new rt("clear", t, o) : o.name === "TypeMismatchError" && !r ? new L("file", "directory", t, o) : new rt("remove", t, o);
1435
+ } else throw o.name === "InvalidModificationError" ? new rt("ENOTEMPTY", t, o) : o.name === "TypeMismatchError" && !r ? new z("directory", t, o) : new rt("RM_FAILED", t, o);
1440
1436
  }
1441
1437
  });
1442
1438
  }
@@ -1709,7 +1705,7 @@ class gs {
1709
1705
  async readFile(t) {
1710
1706
  await this.mount();
1711
1707
  try {
1712
- return await z(t, "shared", async () => {
1708
+ return await L(t, "shared", async () => {
1713
1709
  const e = await this.open(t);
1714
1710
  try {
1715
1711
  const { size: n } = await this.fstat(e), r = new Uint8Array(n);
@@ -1747,7 +1743,7 @@ class gs {
1747
1743
  async writeFile(t, e) {
1748
1744
  await this.mount();
1749
1745
  const n = e instanceof Uint8Array ? e : new Uint8Array(e);
1750
- await z(t, "exclusive", async () => {
1746
+ await L(t, "exclusive", async () => {
1751
1747
  const r = await this.exists(t), i = await this.open(t, { create: !0, truncate: !0 });
1752
1748
  try {
1753
1749
  await this.write(i, n, 0, n.length, null, !1), await this.fsync(i);
@@ -1782,7 +1778,7 @@ class gs {
1782
1778
  async appendFile(t, e) {
1783
1779
  await this.mount();
1784
1780
  const n = e instanceof Uint8Array ? e : new Uint8Array(e);
1785
- await z(t, "exclusive", async () => {
1781
+ await L(t, "exclusive", async () => {
1786
1782
  const r = await this.open(t, { create: !0 });
1787
1783
  try {
1788
1784
  const { size: i } = await this.fstat(r);
@@ -1823,7 +1819,7 @@ class gs {
1823
1819
  try {
1824
1820
  i = await i.getDirectoryHandle(a, { create: n || o === r.length - 1 });
1825
1821
  } catch (l) {
1826
- throw l.name === "NotFoundError" ? new F("directory", lt(r.slice(0, o + 1)), l) : l.name === "TypeMismatchError" ? new L("directory", "file", a, l) : new Q("create directory", a, l);
1822
+ throw l.name === "NotFoundError" ? new F("directory", lt(r.slice(0, o + 1)), l) : l.name === "TypeMismatchError" ? new z("file", a, l) : new Q("create directory", a, l);
1827
1823
  }
1828
1824
  }
1829
1825
  await this.notifyChange({ path: t, type: D.Added, isDirectory: !0 });
@@ -2032,7 +2028,7 @@ class gs {
2032
2028
  */
2033
2029
  async remove(t, e) {
2034
2030
  if (await this.mount(), t === "/")
2035
- throw new rt("root", t);
2031
+ throw new rt("EROOT", t);
2036
2032
  const { recursive: n = !1, force: r = !1 } = e || {}, i = await this.getDirectoryHandle(et(t), !1), o = await this.stat(t);
2037
2033
  await fs(i, t, { recursive: n, force: r }), await this.notifyChange({ path: t, type: D.Removed, isDirectory: o.isDirectory });
2038
2034
  }
@@ -2136,7 +2132,7 @@ class gs {
2136
2132
  await this.writeFile(e, h);
2137
2133
  } else {
2138
2134
  if (!r)
2139
- throw new L("file", "directory", t);
2135
+ throw new z("directory", t);
2140
2136
  await this.mkdir(e, { recursive: !0 });
2141
2137
  const h = await this.readDir(t);
2142
2138
  for (const c of h) {
@@ -2220,7 +2216,7 @@ class gs {
2220
2216
  await this.mount();
2221
2217
  const { create: n = !1, exclusive: r = !1, truncate: i = !1 } = e || {}, o = G(Et(t));
2222
2218
  try {
2223
- return n && r ? await z(o, "exclusive", async () => {
2219
+ return n && r ? await L(o, "exclusive", async () => {
2224
2220
  if (await this.exists(o))
2225
2221
  throw new K(o);
2226
2222
  return this._openFile(o, n, i);
@@ -2302,7 +2298,7 @@ class gs {
2302
2298
  const f = e.subarray(n, n + c), u = o.syncHandle.read(f, { at: a });
2303
2299
  return i == null && (o.position = a + u), B({ bytesRead: u, buffer: e }, [e.buffer]);
2304
2300
  } catch (a) {
2305
- throw _("read", t, o.path, a);
2301
+ throw j("read", t, o.path, a);
2306
2302
  }
2307
2303
  }
2308
2304
  /**
@@ -2333,7 +2329,7 @@ class gs {
2333
2329
  const h = i ?? a.position, c = e.subarray(n, n + l), f = a.syncHandle.write(c, { at: h });
2334
2330
  return (i == null || i === a.position) && (a.position = h + f), o && await this.notifyChange({ path: a.path, type: D.Changed, isDirectory: !1 }), f;
2335
2331
  } catch (h) {
2336
- throw _("write", t, a.path, h);
2332
+ throw j("write", t, a.path, h);
2337
2333
  }
2338
2334
  }
2339
2335
  /**
@@ -2381,7 +2377,7 @@ class gs {
2381
2377
  try {
2382
2378
  n.syncHandle.truncate(e), n.syncHandle.flush(), n.position > e && (n.position = e), await this.notifyChange({ path: n.path, type: D.Changed, isDirectory: !1 });
2383
2379
  } catch (r) {
2384
- throw _("truncate", t, n.path, r);
2380
+ throw j("truncate", t, n.path, r);
2385
2381
  }
2386
2382
  }
2387
2383
  /**
@@ -2403,7 +2399,7 @@ class gs {
2403
2399
  try {
2404
2400
  e.syncHandle.flush();
2405
2401
  } catch (n) {
2406
- throw _("sync", t, e.path, n);
2402
+ throw j("sync", t, e.path, n);
2407
2403
  }
2408
2404
  }
2409
2405
  /**
@@ -2460,7 +2456,7 @@ class gs {
2460
2456
  }
2461
2457
  }
2462
2458
  typeof globalThis < "u" && globalThis.constructor.name === "DedicatedWorkerGlobalScope" && ot(new gs());
2463
- //# sourceMappingURL=worker-1Wh1cr7P.js.map
2459
+ //# sourceMappingURL=worker-BeJaVyBV.js.map
2464
2460
  `, p = typeof self < "u" && self.Blob && new Blob(["URL.revokeObjectURL(import.meta.url);", f], { type: "text/javascript;charset=utf-8" });
2465
2461
  function m(a) {
2466
2462
  let n;
@@ -2747,45 +2743,43 @@ export {
2747
2743
  A as FileSystemOperationError,
2748
2744
  T as FileTypeError,
2749
2745
  R as IOError,
2750
- I as InitializationFailedError,
2751
- C as OPFSError,
2746
+ C as InitializationFailedError,
2747
+ I as OPFSError,
2752
2748
  y as OPFSFileSystem,
2753
2749
  $ as OPFSNotSupportedError,
2754
2750
  D as OperationAbortedError,
2755
2751
  _ as OperationNotSupportedError,
2756
2752
  N as PathError,
2757
- z as PathResolutionFailedError,
2758
- k as PermissionError,
2759
- M as StorageError,
2760
- j as TimeoutError,
2761
- W as ValidationError,
2762
- L as WatchEventType,
2763
- U as basename,
2764
- H as buffersEqual,
2765
- B as calculateFileHash,
2766
- G as calculateReadLength,
2767
- q as checkOPFSSupport,
2768
- Y as convertBlobToUint8Array,
2769
- V as createBuffer,
2770
- X as createFDError,
2771
- Z as createSyncHandleSafe,
2753
+ z as PermissionError,
2754
+ k as StorageError,
2755
+ M as ValidationError,
2756
+ j as WatchEventType,
2757
+ L as basename,
2758
+ W as buffersEqual,
2759
+ U as calculateFileHash,
2760
+ H as calculateReadLength,
2761
+ B as checkOPFSSupport,
2762
+ G as convertBlobToUint8Array,
2763
+ q as createBuffer,
2764
+ V as createFDError,
2765
+ Y as createSyncHandleSafe,
2772
2766
  b as createWorker,
2773
2767
  l as decodeBuffer,
2774
2768
  J as dirname,
2775
2769
  c as encodeString,
2776
- K as extname,
2770
+ X as extname,
2777
2771
  h as isBinaryFileExtension,
2778
- Q as isPathExcluded,
2779
- nn as joinPath,
2780
- tn as mapDomError,
2781
- en as matchMinimatch,
2782
- rn as normalizeMinimatch,
2783
- sn as normalizePath,
2784
- an as removeEntry,
2785
- on as resolvePath,
2786
- cn as safeCloseSyncHandle,
2787
- hn as splitPath,
2788
- ln as validateReadWriteArgs,
2789
- pn as withLock
2772
+ Z as isPathExcluded,
2773
+ K as joinPath,
2774
+ Q as mapDomError,
2775
+ nn as matchMinimatch,
2776
+ tn as normalizeMinimatch,
2777
+ en as normalizePath,
2778
+ rn as removeEntry,
2779
+ sn as resolvePath,
2780
+ an as safeCloseSyncHandle,
2781
+ on as splitPath,
2782
+ cn as validateReadWriteArgs,
2783
+ hn as withLock
2790
2784
  };
2791
2785
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../src/facade.ts","../src/index.ts"],"sourcesContent":["import { wrap } from 'comlink';\n\nimport { decodeBuffer, encodeString, isBinaryFileExtension } from './utils/encoder';\nimport WorkerCtor from './worker?worker&inline';\n\nimport type {\n BinaryEncoding,\n DirentData,\n Encoding,\n FileOpenOptions,\n FileStat,\n OPFSOptions,\n PathLike,\n RemoteOPFSWorker,\n RenameOptions,\n StringEncoding,\n WatchOptions\n} from './types';\n\n/**\n * Utility function to convert a PathLike to a string path\n * If it's a URI, extracts the pathname; otherwise returns the string as-is\n */\nfunction normalizePath(path: PathLike): string {\n if (path instanceof URL) {\n return path.pathname;\n }\n\n return path;\n}\n\n/**\n * Facade class that provides a clean interface for communicating with the OPFS worker\n * while hiding Comlink implementation details.\n */\nexport class OPFSFileSystem {\n #worker: RemoteOPFSWorker;\n promises: OPFSFileSystem = this;\n\n constructor(options?: OPFSOptions) {\n this.#worker = wrap<RemoteOPFSWorker>(new WorkerCtor());\n\n // Set up options if provided\n if (options) {\n // We can't pass a BroadcastChannel instance to the worker, so we need to convert it to a string first\n if (options.broadcastChannel && options.broadcastChannel instanceof BroadcastChannel) {\n options.broadcastChannel = options.broadcastChannel.name;\n }\n\n // Initialize options asynchronously\n void this.setOptions(options);\n }\n }\n\n /**\n * Start watching a file or directory for changes\n */\n watch(path: PathLike, options?: WatchOptions): () => void {\n const normalizedPath = normalizePath(path);\n\n void this.#worker.watch(normalizedPath, options);\n\n return () => this.unwatch(normalizedPath);\n }\n\n /**\n * Stop watching a previously watched path\n */\n unwatch(path: PathLike) {\n const normalizedPath = normalizePath(path);\n\n void this.#worker.unwatch(normalizedPath);\n }\n\n /**\n * Update configuration options\n */\n async setOptions(options: OPFSOptions) {\n return this.#worker.setOptions(options);\n }\n\n /**\n * Get a complete index of all files and directories in the file system\n */\n async index(): Promise<Map<string, FileStat>> {\n return this.#worker.index();\n }\n\n /**\n * Read a file from the file system\n */\n // Overload for explicit string encoding - returns string\n async readFile(path: PathLike, encoding: StringEncoding): Promise<string>;\n // Overload for explicit binary encoding - returns Uint8Array\n async readFile(path: PathLike, encoding: BinaryEncoding): Promise<Uint8Array>;\n // Overload for options object with string encoding - returns string\n async readFile(path: PathLike, options: { encoding: StringEncoding }): Promise<string>;\n // Overload for options object with binary encoding - returns Uint8Array\n async readFile(path: PathLike, options: { encoding: BinaryEncoding }): Promise<Uint8Array>;\n // Overload for no encoding (auto-detected) - returns string | Uint8Array based on file extension\n async readFile(path: PathLike): Promise<string | Uint8Array>;\n // Implementation\n async readFile(\n path: PathLike,\n optionsOrEncoding?: Encoding | { encoding?: Encoding }\n ): Promise<string | Uint8Array> {\n const normalizedPath = normalizePath(path);\n\n // Handle both options object and direct encoding parameter for backward compatibility\n let encoding: Encoding | undefined;\n\n if (typeof optionsOrEncoding === 'string') {\n encoding = optionsOrEncoding;\n }\n else if (optionsOrEncoding && typeof optionsOrEncoding === 'object') {\n encoding = optionsOrEncoding.encoding;\n }\n\n // Get binary data from worker\n const buffer = await this.#worker.readFile(normalizedPath);\n\n // If no encoding specified, auto-detect based on file extension\n if (!encoding) {\n encoding = isBinaryFileExtension(normalizedPath) ? 'binary' : 'utf-8';\n }\n\n // Return binary data or decode to string\n return (encoding === 'binary') ? buffer : decodeBuffer(buffer, encoding);\n }\n\n /**\n * Write data to a file\n */\n async writeFile(\n path: PathLike,\n data: string | Uint8Array | ArrayBuffer,\n options?: { encoding?: Encoding } | Encoding\n ): Promise<void> {\n const normalizedPath = normalizePath(path);\n\n let encoding: Encoding | undefined;\n\n if (typeof options === 'string') {\n encoding = options;\n }\n else if (options && typeof options === 'object') {\n encoding = options.encoding;\n }\n\n // If no encoding specified, auto-detect based on file extension\n if (!encoding) {\n encoding = (typeof data !== 'string' || isBinaryFileExtension(normalizedPath)) ? 'binary' : 'utf-8';\n }\n\n // Convert data to Uint8Array\n const buffer = typeof data === 'string'\n ? encodeString(data, encoding)\n : (data instanceof Uint8Array ? data : new Uint8Array(data));\n\n return this.#worker.writeFile(normalizedPath, buffer);\n }\n\n /**\n * Append data to a file\n */\n async appendFile(\n path: PathLike,\n data: string | Uint8Array | ArrayBuffer,\n encoding?: Encoding\n ): Promise<void> {\n const normalizedPath = normalizePath(path);\n\n // If no encoding specified, auto-detect based on file extension\n if (!encoding) {\n encoding = (typeof data !== 'string' || isBinaryFileExtension(normalizedPath)) ? 'binary' : 'utf-8';\n }\n\n // Convert data to Uint8Array\n const buffer = typeof data === 'string'\n ? encodeString(data, encoding)\n : (data instanceof Uint8Array ? data : new Uint8Array(data));\n\n return this.#worker.appendFile(normalizedPath, buffer);\n }\n\n /**\n * Create a directory\n */\n async mkdir(path: PathLike, mode?: number | { recursive?: boolean }): Promise<void> {\n const normalizedPath = normalizePath(path);\n\n let options: { recursive?: boolean } | undefined;\n\n // OPFS doesn't support file modes, so we ignore the mode parameter\n if (typeof mode === 'number') {\n options = { recursive: false };\n }\n else {\n options = mode;\n }\n\n return this.#worker.mkdir(normalizedPath, options);\n }\n\n /**\n * Get file or directory statistics\n */\n async stat(path: PathLike): Promise<FileStat> {\n const normalizedPath = normalizePath(path);\n\n return this.#worker.stat(normalizedPath);\n }\n\n /**\n * Read a directory's contents\n */\n async readDir(path: PathLike): Promise<DirentData[]> {\n const normalizedPath = normalizePath(path);\n\n return this.#worker.readDir(normalizedPath);\n }\n\n /**\n * Check if a file or directory exists\n */\n async exists(path: PathLike): Promise<boolean> {\n const normalizedPath = normalizePath(path);\n\n return this.#worker.exists(normalizedPath);\n }\n\n /**\n * Clear all contents of a directory without removing the directory itself\n */\n async clear(path?: PathLike): Promise<void> {\n const normalizedPath = path ? normalizePath(path) : undefined;\n\n return this.#worker.clear(normalizedPath);\n }\n\n /**\n * Remove files and directories\n */\n async remove(path: PathLike, options?: { recursive?: boolean; force?: boolean }): Promise<void> {\n const normalizedPath = normalizePath(path);\n\n return this.#worker.remove(normalizedPath, options);\n }\n\n /**\n * Alias for remove() for NodeJS like API compatibility\n */\n async unlink(path: PathLike): Promise<void> {\n return this.remove(path);\n }\n\n /**\n * Alias for remove() for NodeJS like API compatibility\n */\n async rm(path: PathLike, options?: { recursive?: boolean; force?: boolean }): Promise<void> {\n return this.remove(path, options);\n }\n\n /**\n * Alias for remove() for NodeJS like API compatibility\n */\n async rmdir(path: PathLike): Promise<void> {\n return this.remove(path);\n }\n\n /**\n * Alias for readDir() for NodeJS like API compatibility\n */\n async readdir(path: PathLike, _options?: unknown): Promise<DirentData[]> {\n return this.readDir(path);\n }\n\n /**\n * Alias for stat() for NodeJS like API compatibility\n */\n async lstat(path: PathLike): Promise<FileStat> {\n return this.stat(path);\n }\n\n /**\n * Note: OPFS doesn't support file modes, so this is a no-op and exists only for compatibility with tools like isomorphic-git\n */\n async chmod(_path: PathLike, _mode: number): Promise<void> {\n return Promise.resolve();\n }\n\n /**\n * Resolve a path to an absolute path\n */\n async realpath(path: PathLike): Promise<string> {\n const normalizedPath = normalizePath(path);\n\n return this.#worker.realpath(normalizedPath);\n }\n\n /**\n * Rename a file or directory\n */\n async rename(oldPath: PathLike, newPath: PathLike, options?: RenameOptions): Promise<void> {\n const normalizedOldPath = normalizePath(oldPath);\n const normalizedNewPath = normalizePath(newPath);\n\n return this.#worker.rename(normalizedOldPath, normalizedNewPath, options);\n }\n\n /**\n * Copy files and directories\n */\n async copy(source: PathLike, destination: PathLike, options?: { recursive?: boolean; overwrite?: boolean }): Promise<void> {\n const normalizedSource = normalizePath(source);\n const normalizedDestination = normalizePath(destination);\n\n return this.#worker.copy(normalizedSource, normalizedDestination, options);\n }\n\n /**\n * Open a file and return a file descriptor\n */\n async open(path: PathLike, options?: FileOpenOptions): Promise<number> {\n const normalizedPath = normalizePath(path);\n\n return this.#worker.open(normalizedPath, options);\n }\n\n /**\n * Close a file descriptor\n */\n async close(fd: number): Promise<void> {\n return this.#worker.close(fd);\n }\n\n /**\n * Read data from a file descriptor\n * \n * This method requires special handling due to Comlink transfer requirements.\n * The buffer is transferred to the worker and back, so the original buffer\n * becomes unusable after the call.\n */\n async read(\n fd: number,\n buffer: Uint8Array,\n offset: number,\n length: number,\n position?: number | null | undefined\n ): Promise<{ bytesRead: number; buffer: Uint8Array }> {\n const { bytesRead, buffer: transferred } = await this.#worker.read(\n fd,\n // Temp buffer to preserve the original buffer\n new Uint8Array(length),\n 0,\n length,\n position\n );\n\n // Copy the data from the transferred buffer to the original buffer\n if (bytesRead > 0) {\n buffer.set(transferred.subarray(0, bytesRead), offset);\n }\n\n return { bytesRead, buffer };\n }\n\n /**\n * Write data to a file descriptor\n */\n async write(\n fd: number,\n buffer: Uint8Array,\n offset?: number,\n length?: number,\n position?: number | null | undefined,\n emitEvent?: boolean\n ): Promise<number> {\n return this.#worker.write(fd, buffer, offset, length, position, emitEvent);\n }\n\n /**\n * Get file status information by file descriptor\n */\n async fstat(fd: number): Promise<FileStat> {\n return this.#worker.fstat(fd);\n }\n\n /**\n * Truncate file to specified size\n */\n async ftruncate(fd: number, size?: number): Promise<void> {\n return this.#worker.ftruncate(fd, size);\n }\n\n /**\n * Synchronize file data to storage (fsync equivalent)\n */\n async fsync(fd: number): Promise<void> {\n return this.#worker.fsync(fd);\n }\n\n /**\n * Dispose of resources and clean up the file system instance\n */\n dispose() {\n void this.#worker.dispose();\n }\n\n /**\n * Synchronize the file system with external data\n */\n async createIndex(entries: [PathLike, string | Uint8Array | Blob][]): Promise<void> {\n const normalizedEntries = entries.map(([path, data]) => [normalizePath(path), data] as [string, string | Uint8Array | Blob]);\n\n return this.#worker.createIndex(normalizedEntries);\n }\n\n /**\n * Read a file as text with automatic encoding detection\n */\n async readText(path: PathLike, encoding: Encoding = 'utf-8'): Promise<string> {\n const normalizedPath = normalizePath(path);\n const buffer = await this.#worker.readFile(normalizedPath);\n\n return decodeBuffer(buffer, encoding);\n }\n\n /**\n * Write text to a file with specified encoding\n */\n async writeText(path: PathLike, text: string, encoding: Encoding = 'utf-8'): Promise<void> {\n const normalizedPath = normalizePath(path);\n const buffer = encodeString(text, encoding);\n\n return this.#worker.writeFile(normalizedPath, buffer);\n }\n\n /**\n * Append text to a file with specified encoding\n */\n async appendText(path: PathLike, text: string, encoding: Encoding = 'utf-8'): Promise<void> {\n const normalizedPath = normalizePath(path);\n const buffer = encodeString(text, encoding);\n\n return this.#worker.appendFile(normalizedPath, buffer);\n }\n}\n","import { OPFSFileSystem } from './facade';\n\nimport type { OPFSOptions } from './types';\n\nexport * from './types';\nexport * from './utils/errors';\nexport * from './utils/helpers';\nexport * from './utils/encoder';\nexport * from './facade';\n\n/**\n * Creates a new file system instance with inline worker\n * @param options - Optional configuration options\n * @returns Promise resolving to the file system interface\n */\nexport function createWorker(\n options?: OPFSOptions\n): OPFSFileSystem {\n return new OPFSFileSystem(options);\n}\n"],"names":["normalizePath","path","OPFSFileSystem","#worker","options","wrap","WorkerCtor","normalizedPath","optionsOrEncoding","encoding","buffer","isBinaryFileExtension","decodeBuffer","data","encodeString","mode","_options","_path","_mode","oldPath","newPath","normalizedOldPath","normalizedNewPath","source","destination","normalizedSource","normalizedDestination","fd","offset","length","position","bytesRead","transferred","emitEvent","size","entries","normalizedEntries","text","createWorker"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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xC;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,UAAUR,GAAgBoC,GAAc5B,IAAqB,SAAwB;AACvF,UAAMF,IAAiBP,EAAcC,CAAI,GACnCS,IAASI,EAAauB,GAAM5B,CAAQ;AAE1C,WAAO,KAAKN,GAAQ,UAAUI,GAAgBG,CAAM;AAAA,EACxD;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,WAAWT,GAAgBoC,GAAc5B,IAAqB,SAAwB;AACxF,UAAMF,IAAiBP,EAAcC,CAAI,GACnCS,IAASI,EAAauB,GAAM5B,CAAQ;AAE1C,WAAO,KAAKN,GAAQ,WAAWI,GAAgBG,CAAM;AAAA,EACzD;AACJ;AChbO,SAAS4B,EACZlC,GACc;AACd,SAAO,IAAIF,EAAeE,CAAO;AACrC;"}
1
+ {"version":3,"file":"index.js","sources":["../src/facade.ts","../src/index.ts"],"sourcesContent":["import { wrap } from 'comlink';\n\nimport { decodeBuffer, encodeString, isBinaryFileExtension } from './utils/encoder';\nimport WorkerCtor from './worker?worker&inline';\n\nimport type {\n BinaryEncoding,\n DirentData,\n Encoding,\n FileOpenOptions,\n FileStat,\n OPFSOptions,\n PathLike,\n RemoteOPFSWorker,\n RenameOptions,\n StringEncoding,\n WatchOptions\n} from './types';\n\n/**\n * Utility function to convert a PathLike to a string path\n * If it's a URI, extracts the pathname; otherwise returns the string as-is\n */\nfunction normalizePath(path: PathLike): string {\n if (path instanceof URL) {\n return path.pathname;\n }\n\n return path;\n}\n\n/**\n * Facade class that provides a clean interface for communicating with the OPFS worker\n * while hiding Comlink implementation details.\n */\nexport class OPFSFileSystem {\n #worker: RemoteOPFSWorker;\n promises: OPFSFileSystem = this;\n\n constructor(options?: OPFSOptions) {\n this.#worker = wrap<RemoteOPFSWorker>(new WorkerCtor());\n\n // Set up options if provided\n if (options) {\n // We can't pass a BroadcastChannel instance to the worker, so we need to convert it to a string first\n if (options.broadcastChannel && options.broadcastChannel instanceof BroadcastChannel) {\n options.broadcastChannel = options.broadcastChannel.name;\n }\n\n // Initialize options asynchronously\n void this.setOptions(options);\n }\n }\n\n /**\n * Start watching a file or directory for changes\n */\n watch(path: PathLike, options?: WatchOptions): () => void {\n const normalizedPath = normalizePath(path);\n\n void this.#worker.watch(normalizedPath, options);\n\n return () => this.unwatch(normalizedPath);\n }\n\n /**\n * Stop watching a previously watched path\n */\n unwatch(path: PathLike) {\n const normalizedPath = normalizePath(path);\n\n void this.#worker.unwatch(normalizedPath);\n }\n\n /**\n * Update configuration options\n */\n async setOptions(options: OPFSOptions) {\n return this.#worker.setOptions(options);\n }\n\n /**\n * Get a complete index of all files and directories in the file system\n */\n async index(): Promise<Map<string, FileStat>> {\n return this.#worker.index();\n }\n\n /**\n * Read a file from the file system\n */\n // Overload for explicit string encoding - returns string\n async readFile(path: PathLike, encoding: StringEncoding): Promise<string>;\n // Overload for explicit binary encoding - returns Uint8Array\n async readFile(path: PathLike, encoding: BinaryEncoding): Promise<Uint8Array>;\n // Overload for options object with string encoding - returns string\n async readFile(path: PathLike, options: { encoding: StringEncoding }): Promise<string>;\n // Overload for options object with binary encoding - returns Uint8Array\n async readFile(path: PathLike, options: { encoding: BinaryEncoding }): Promise<Uint8Array>;\n // Overload for no encoding (auto-detected) - returns string | Uint8Array based on file extension\n async readFile(path: PathLike): Promise<string | Uint8Array>;\n // Implementation\n async readFile(\n path: PathLike,\n optionsOrEncoding?: Encoding | { encoding?: Encoding }\n ): Promise<string | Uint8Array> {\n const normalizedPath = normalizePath(path);\n\n // Handle both options object and direct encoding parameter for backward compatibility\n let encoding: Encoding | undefined;\n\n if (typeof optionsOrEncoding === 'string') {\n encoding = optionsOrEncoding;\n }\n else if (optionsOrEncoding && typeof optionsOrEncoding === 'object') {\n encoding = optionsOrEncoding.encoding;\n }\n\n // Get binary data from worker\n const buffer = await this.#worker.readFile(normalizedPath);\n\n // If no encoding specified, auto-detect based on file extension\n if (!encoding) {\n encoding = isBinaryFileExtension(normalizedPath) ? 'binary' : 'utf-8';\n }\n\n // Return binary data or decode to string\n return (encoding === 'binary') ? buffer : decodeBuffer(buffer, encoding);\n }\n\n /**\n * Write data to a file\n */\n async writeFile(\n path: PathLike,\n data: string | Uint8Array | ArrayBuffer,\n options?: { encoding?: Encoding } | Encoding\n ): Promise<void> {\n const normalizedPath = normalizePath(path);\n\n let encoding: Encoding | undefined;\n\n if (typeof options === 'string') {\n encoding = options;\n }\n else if (options && typeof options === 'object') {\n encoding = options.encoding;\n }\n\n // If no encoding specified, auto-detect based on file extension\n if (!encoding) {\n encoding = (typeof data !== 'string' || isBinaryFileExtension(normalizedPath)) ? 'binary' : 'utf-8';\n }\n\n // Convert data to Uint8Array\n const buffer = typeof data === 'string'\n ? encodeString(data, encoding)\n : (data instanceof Uint8Array ? data : new Uint8Array(data));\n\n return this.#worker.writeFile(normalizedPath, buffer);\n }\n\n /**\n * Append data to a file\n */\n async appendFile(\n path: PathLike,\n data: string | Uint8Array | ArrayBuffer,\n encoding?: Encoding\n ): Promise<void> {\n const normalizedPath = normalizePath(path);\n\n // If no encoding specified, auto-detect based on file extension\n if (!encoding) {\n encoding = (typeof data !== 'string' || isBinaryFileExtension(normalizedPath)) ? 'binary' : 'utf-8';\n }\n\n // Convert data to Uint8Array\n const buffer = typeof data === 'string'\n ? encodeString(data, encoding)\n : (data instanceof Uint8Array ? data : new Uint8Array(data));\n\n return this.#worker.appendFile(normalizedPath, buffer);\n }\n\n /**\n * Create a directory\n */\n async mkdir(path: PathLike, mode?: number | { recursive?: boolean }): Promise<void> {\n const normalizedPath = normalizePath(path);\n\n let options: { recursive?: boolean } | undefined;\n\n // OPFS doesn't support file modes, so we ignore the mode parameter\n if (typeof mode === 'number') {\n options = { recursive: false };\n }\n else {\n options = mode;\n }\n\n return this.#worker.mkdir(normalizedPath, options);\n }\n\n /**\n * Get file or directory statistics\n */\n async stat(path: PathLike): Promise<FileStat> {\n const normalizedPath = normalizePath(path);\n\n return this.#worker.stat(normalizedPath);\n }\n\n /**\n * Read a directory's contents\n */\n async readDir(path: PathLike): Promise<DirentData[]> {\n const normalizedPath = normalizePath(path);\n\n return this.#worker.readDir(normalizedPath);\n }\n\n /**\n * Check if a file or directory exists\n */\n async exists(path: PathLike): Promise<boolean> {\n const normalizedPath = normalizePath(path);\n\n return this.#worker.exists(normalizedPath);\n }\n\n /**\n * Clear all contents of a directory without removing the directory itself\n */\n async clear(path?: PathLike): Promise<void> {\n const normalizedPath = path ? normalizePath(path) : undefined;\n\n return this.#worker.clear(normalizedPath);\n }\n\n /**\n * Remove files and directories\n */\n async remove(path: PathLike, options?: { recursive?: boolean; force?: boolean }): Promise<void> {\n const normalizedPath = normalizePath(path);\n\n return this.#worker.remove(normalizedPath, options);\n }\n\n /**\n * Alias for remove() for NodeJS like API compatibility\n */\n async unlink(path: PathLike): Promise<void> {\n return this.remove(path);\n }\n\n /**\n * Alias for remove() for NodeJS like API compatibility\n */\n async rm(path: PathLike, options?: { recursive?: boolean; force?: boolean }): Promise<void> {\n return this.remove(path, options);\n }\n\n /**\n * Alias for remove() for NodeJS like API compatibility\n */\n async rmdir(path: PathLike): Promise<void> {\n return this.remove(path);\n }\n\n /**\n * Alias for readDir() for NodeJS like API compatibility\n */\n async readdir(path: PathLike, _options?: unknown): Promise<DirentData[]> {\n return this.readDir(path);\n }\n\n /**\n * Alias for stat() for NodeJS like API compatibility\n */\n async lstat(path: PathLike): Promise<FileStat> {\n return this.stat(path);\n }\n\n /**\n * Note: OPFS doesn't support file modes, so this is a no-op and exists only for compatibility with tools like isomorphic-git\n */\n async chmod(_path: PathLike, _mode: number): Promise<void> {\n return Promise.resolve();\n }\n\n /**\n * Resolve a path to an absolute path\n */\n async realpath(path: PathLike): Promise<string> {\n const normalizedPath = normalizePath(path);\n\n return this.#worker.realpath(normalizedPath);\n }\n\n /**\n * Rename a file or directory\n */\n async rename(oldPath: PathLike, newPath: PathLike, options?: RenameOptions): Promise<void> {\n const normalizedOldPath = normalizePath(oldPath);\n const normalizedNewPath = normalizePath(newPath);\n\n return this.#worker.rename(normalizedOldPath, normalizedNewPath, options);\n }\n\n /**\n * Copy files and directories\n */\n async copy(source: PathLike, destination: PathLike, options?: { recursive?: boolean; overwrite?: boolean }): Promise<void> {\n const normalizedSource = normalizePath(source);\n const normalizedDestination = normalizePath(destination);\n\n return this.#worker.copy(normalizedSource, normalizedDestination, options);\n }\n\n /**\n * Open a file and return a file descriptor\n */\n async open(path: PathLike, options?: FileOpenOptions): Promise<number> {\n const normalizedPath = normalizePath(path);\n\n return this.#worker.open(normalizedPath, options);\n }\n\n /**\n * Close a file descriptor\n */\n async close(fd: number): Promise<void> {\n return this.#worker.close(fd);\n }\n\n /**\n * Read data from a file descriptor\n * \n * This method requires special handling due to Comlink transfer requirements.\n * The buffer is transferred to the worker and back, so the original buffer\n * becomes unusable after the call.\n */\n async read(\n fd: number,\n buffer: Uint8Array,\n offset: number,\n length: number,\n position?: number | null | undefined\n ): Promise<{ bytesRead: number; buffer: Uint8Array }> {\n const { bytesRead, buffer: transferred } = await this.#worker.read(\n fd,\n // Temp buffer to preserve the original buffer\n new Uint8Array(length),\n 0,\n length,\n position\n );\n\n // Copy the data from the transferred buffer to the original buffer\n if (bytesRead > 0) {\n buffer.set(transferred.subarray(0, bytesRead), offset);\n }\n\n return { bytesRead, buffer };\n }\n\n /**\n * Write data to a file descriptor\n */\n async write(\n fd: number,\n buffer: Uint8Array,\n offset?: number,\n length?: number,\n position?: number | null | undefined,\n emitEvent?: boolean\n ): Promise<number> {\n return this.#worker.write(fd, buffer, offset, length, position, emitEvent);\n }\n\n /**\n * Get file status information by file descriptor\n */\n async fstat(fd: number): Promise<FileStat> {\n return this.#worker.fstat(fd);\n }\n\n /**\n * Truncate file to specified size\n */\n async ftruncate(fd: number, size?: number): Promise<void> {\n return this.#worker.ftruncate(fd, size);\n }\n\n /**\n * Synchronize file data to storage (fsync equivalent)\n */\n async fsync(fd: number): Promise<void> {\n return this.#worker.fsync(fd);\n }\n\n /**\n * Dispose of resources and clean up the file system instance\n */\n dispose() {\n void this.#worker.dispose();\n }\n\n /**\n * Synchronize the file system with external data\n */\n async createIndex(entries: [PathLike, string | Uint8Array | Blob][]): Promise<void> {\n const normalizedEntries = entries.map(([path, data]) => [normalizePath(path), data] as [string, string | Uint8Array | Blob]);\n\n return this.#worker.createIndex(normalizedEntries);\n }\n\n /**\n * Read a file as text with automatic encoding detection\n */\n async readText(path: PathLike, encoding: Encoding = 'utf-8'): Promise<string> {\n const normalizedPath = normalizePath(path);\n const buffer = await this.#worker.readFile(normalizedPath);\n\n return decodeBuffer(buffer, encoding);\n }\n\n /**\n * Write text to a file with specified encoding\n */\n async writeText(path: PathLike, text: string, encoding: Encoding = 'utf-8'): Promise<void> {\n const normalizedPath = normalizePath(path);\n const buffer = encodeString(text, encoding);\n\n return this.#worker.writeFile(normalizedPath, buffer);\n }\n\n /**\n * Append text to a file with specified encoding\n */\n async appendText(path: PathLike, text: string, encoding: Encoding = 'utf-8'): Promise<void> {\n const normalizedPath = normalizePath(path);\n const buffer = encodeString(text, encoding);\n\n return this.#worker.appendFile(normalizedPath, buffer);\n }\n}\n","import { OPFSFileSystem } from './facade';\n\nimport type { OPFSOptions } from './types';\n\nexport * from './types';\nexport * from './utils/errors';\nexport * from './utils/helpers';\nexport * from './utils/encoder';\nexport * from './facade';\n\n/**\n * Creates a new file system instance with inline worker\n * @param options - Optional configuration options\n * @returns Promise resolving to the file system interface\n */\nexport function createWorker(\n options?: OPFSOptions\n): OPFSFileSystem {\n return new OPFSFileSystem(options);\n}\n"],"names":["normalizePath","path","OPFSFileSystem","#worker","options","wrap","WorkerCtor","normalizedPath","optionsOrEncoding","encoding","buffer","isBinaryFileExtension","decodeBuffer","data","encodeString","mode","_options","_path","_mode","oldPath","newPath","normalizedOldPath","normalizedNewPath","source","destination","normalizedSource","normalizedDestination","fd","offset","length","position","bytesRead","transferred","emitEvent","size","entries","normalizedEntries","text","createWorker"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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ASI,CAAc;AAEzD,WAAOK,EAAaF,GAAQD,CAAQ;AAAA,EACxC;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,UAAUR,GAAgBoC,GAAc5B,IAAqB,SAAwB;AACvF,UAAMF,IAAiBP,EAAcC,CAAI,GACnCS,IAASI,EAAauB,GAAM5B,CAAQ;AAE1C,WAAO,KAAKN,GAAQ,UAAUI,GAAgBG,CAAM;AAAA,EACxD;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,WAAWT,GAAgBoC,GAAc5B,IAAqB,SAAwB;AACxF,UAAMF,IAAiBP,EAAcC,CAAI,GACnCS,IAASI,EAAauB,GAAM5B,CAAQ;AAE1C,WAAO,KAAKN,GAAQ,WAAWI,GAAgBG,CAAM;AAAA,EACzD;AACJ;AChbO,SAAS4B,EACZlC,GACc;AACd,SAAO,IAAIF,EAAeE,CAAO;AACrC;"}
package/dist/raw.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const f=require("comlink"),i=require("./helpers-CF7A2WQG.cjs");class d{root;watchers=new Map;mountingPromise=null;broadcastChannel=null;options={root:"/",namespace:"",maxFileSize:50*1024*1024,hashAlgorithm:"etag",broadcastChannel:"opfs-worker"};openFiles=new Map;nextFd=1;_getFileDescriptor(t){const e=this.openFiles.get(t);if(!e)throw new i.ValidationError("descriptor",`Invalid file descriptor: ${t}`);return e}async notifyChange(t){if(!this.options.broadcastChannel)return;const e=t.path;if(![...this.watchers.values()].some(s=>i.matchMinimatch(e,s.pattern)&&s.include.some(n=>n&&i.matchMinimatch(e,n))&&!s.exclude.some(n=>n&&i.matchMinimatch(e,n))))return;let r;if(this.options.hashAlgorithm)try{r=(await this.stat(e)).hash}catch{}try{this.broadcastChannel||(this.broadcastChannel=new BroadcastChannel(this.options.broadcastChannel));const s={namespace:this.options.namespace,timestamp:new Date().toISOString(),...t,...r&&{hash:r}};this.broadcastChannel.postMessage(s)}catch(s){console.warn("Failed to send event via BroadcastChannel:",s)}}constructor(t){i.checkOPFSSupport(),t&&this.setOptions(t)}async mount(){const t=this.options.root;return this.mountingPromise&&await this.mountingPromise,this.mountingPromise=new Promise(async(e,a)=>{try{const r=await navigator.storage.getDirectory();this.root=t==="/"?r:await this.getDirectoryHandle(t,!0,r),e(!0)}catch(r){a(new i.InitializationFailedError(t,r))}finally{this.mountingPromise=null}}),this.mountingPromise}async setOptions(t){t.hashAlgorithm!==void 0&&(this.options.hashAlgorithm=t.hashAlgorithm),t.maxFileSize!==void 0&&(this.options.maxFileSize=t.maxFileSize),t.broadcastChannel!==void 0&&(this.broadcastChannel&&this.options.broadcastChannel!==t.broadcastChannel&&(this.broadcastChannel.close(),this.broadcastChannel=null),this.options.broadcastChannel=t.broadcastChannel),t.namespace&&(this.options.namespace=t.namespace),t.root!==void 0&&(this.options.root=i.normalizePath(t.root),this.options.namespace||(this.options.namespace=`opfs-worker:${this.options.root}`),await this.mount())}async getDirectoryHandle(t,e=!1,a=this.root){const r=Array.isArray(t)?t:i.splitPath(t);let s=a;for(const n of r)s=await s.getDirectoryHandle(n,{create:e});return s}async getFileHandle(t,e=!1,a=this.root){const r=i.splitPath(t);if(r.length===0)throw new i.PathError("Path must not be empty",Array.isArray(t)?t.join("/"):t);const s=r.pop();return(await this.getDirectoryHandle(r,e,a)).getFileHandle(s,{create:e})}async index(){const t=new Map,e=async a=>{const r=await this.readDir(a);for(const s of r){const n=`${a==="/"?"":a}/${s.name}`;try{const o=await this.stat(n);t.set(n,o),o.isDirectory&&await e(n)}catch(o){console.warn(`Skipping broken entry: ${n}`,o)}}};return t.set("/",{kind:"directory",size:0,mtime:new Date(0).toISOString(),ctime:new Date(0).toISOString(),isFile:!1,isDirectory:!0}),await e("/"),t}async readFile(t){await this.mount();try{return await i.withLock(t,"shared",async()=>{const e=await this.open(t);try{const{size:a}=await this.fstat(e),r=new Uint8Array(a);return a>0&&await this.read(e,r,0,a,0),f.transfer(r,[r.buffer])}finally{await this.close(e)}})}catch(e){throw new i.ExistenceError("file",t,e)}}async writeFile(t,e){await this.mount();const a=e instanceof Uint8Array?e:new Uint8Array(e);await i.withLock(t,"exclusive",async()=>{const r=await this.exists(t),s=await this.open(t,{create:!0,truncate:!0});try{await this.write(s,a,0,a.length,null,!1),await this.fsync(s)}finally{await this.close(s)}await this.notifyChange({path:t,type:r?i.WatchEventType.Changed:i.WatchEventType.Added,isDirectory:!1})})}async appendFile(t,e){await this.mount();const a=e instanceof Uint8Array?e:new Uint8Array(e);await i.withLock(t,"exclusive",async()=>{const r=await this.open(t,{create:!0});try{const{size:s}=await this.fstat(r);await this.write(r,a,0,a.length,s,!1),await this.fsync(r)}finally{await this.close(r)}await this.notifyChange({path:t,type:i.WatchEventType.Changed,isDirectory:!1})})}async mkdir(t,e){await this.mount();const a=e?.recursive??!1,r=i.splitPath(t);let s=this.root;for(let n=0;n<r.length;n++){const o=r[n];try{s=await s.getDirectoryHandle(o,{create:a||n===r.length-1})}catch(c){throw c.name==="NotFoundError"?new i.ExistenceError("directory",i.joinPath(r.slice(0,n+1)),c):c.name==="TypeMismatchError"?new i.FileTypeError("directory","file",o,c):new i.FileSystemOperationError("create directory",o,c)}}await this.notifyChange({path:t,type:i.WatchEventType.Added,isDirectory:!0})}async stat(t){if(await this.mount(),t==="/")return{kind:"directory",size:0,mtime:new Date(0).toISOString(),ctime:new Date(0).toISOString(),isFile:!1,isDirectory:!0};const e=i.basename(t);let a;try{a=await this.getDirectoryHandle(i.dirname(t),!1);const r=this.options.hashAlgorithm,n=await(await a.getFileHandle(e,{create:!1})).getFile(),o={kind:"file",size:n.size,mtime:new Date(n.lastModified).toISOString(),ctime:new Date(n.lastModified).toISOString(),isFile:!0,isDirectory:!1};if(r==="etag")o.hash=`${n.lastModified.toString(36)}-${n.size.toString(36)}`;else if(typeof r=="string")try{const c=await i.calculateFileHash(n,r,this.options.maxFileSize);o.hash=c}catch(c){console.warn(`Failed to calculate hash for ${t}:`,c)}return o}catch(r){if(r.name==="NotFoundError")throw new i.ExistenceError("file",t,r);if(r.name!=="TypeMismatchError")throw new i.FileSystemOperationError("stat",t,r)}try{return await a.getDirectoryHandle(e,{create:!1}),{kind:"directory",size:0,mtime:new Date(0).toISOString(),ctime:new Date(0).toISOString(),isFile:!1,isDirectory:!0}}catch(r){throw new i.FileSystemOperationError("stat",t,r)}}async readDir(t){await this.mount();const e=await this.getDirectoryHandle(t,!1),a=[];for await(const[r,s]of e.entries()){const n=s.kind==="file";a.push({name:r,kind:s.kind,isFile:n,isDirectory:!n})}return a}async exists(t){if(await this.mount(),t==="/")return!0;const e=i.basename(t);let a=null;try{a=await this.getDirectoryHandle(i.dirname(t),!1)}catch(r){if(a=null,r.name!=="NotFoundError"&&r.name!=="TypeMismatchError")throw r}if(!a||!e)return!1;try{return await a.getFileHandle(e,{create:!1}),!0}catch(r){if(r.name!=="NotFoundError"&&r.name!=="TypeMismatchError")throw r;try{return await a.getDirectoryHandle(e,{create:!1}),!0}catch(s){if(s.name!=="NotFoundError"&&s.name!=="TypeMismatchError")throw s;return!1}}}async clear(t="/"){await this.mount();try{const e=await this.readDir(t);for(const a of e){const r=`${t==="/"?"":t}/${a.name}`;await this.remove(r,{recursive:!0})}await this.notifyChange({path:t,type:i.WatchEventType.Changed,isDirectory:!0})}catch(e){throw e instanceof i.OPFSError?e:i.mapDomError(e,{path:t,isDirectory:!0})}}async remove(t,e){if(await this.mount(),t==="/")throw new i.DirectoryOperationError("root",t);const{recursive:a=!1,force:r=!1}=e||{},s=await this.getDirectoryHandle(i.dirname(t),!1),n=await this.stat(t);await i.removeEntry(s,t,{recursive:a,force:r}),await this.notifyChange({path:t,type:i.WatchEventType.Removed,isDirectory:n.isDirectory})}async realpath(t){await this.mount();try{const e=i.resolvePath(t);if(!await this.exists(e))throw new i.ExistenceError("file",e);return e}catch(e){throw e instanceof i.OPFSError?e:i.mapDomError(e,{path:t})}}async rename(t,e,a){await this.mount();try{const r=a?.overwrite??!1,s=await this.stat(t);if(await this.exists(e)&&!r)throw new i.AlreadyExistsError(e);await this.copy(t,e,{recursive:!0,overwrite:r}),await this.remove(t,{recursive:!0}),await this.notifyChange({path:t,type:i.WatchEventType.Removed,isDirectory:s.isDirectory}),await this.notifyChange({path:e,type:i.WatchEventType.Added,isDirectory:s.isDirectory})}catch(r){throw r instanceof i.OPFSError?r:i.mapDomError(r,{path:t})}}async copy(t,e,a){await this.mount();try{const r=a?.recursive??!1,s=a?.overwrite??!0;if(!await this.exists(t))throw new i.ExistenceError("source",t);if(await this.exists(e)&&!s)throw new i.AlreadyExistsError(e);if((await this.stat(t)).isFile){const h=await this.readFile(t);await this.writeFile(e,h)}else{if(!r)throw new i.FileTypeError("file","directory",t);await this.mkdir(e,{recursive:!0});const h=await this.readDir(t);for(const l of h){const y=`${t}/${l.name}`,w=`${e}/${l.name}`;await this.copy(y,w,{recursive:!0,overwrite:s})}}}catch(r){throw r instanceof i.OPFSError?r:i.mapDomError(r,{path:t})}}async watch(t,e){if(!this.options.broadcastChannel)throw new i.OperationNotSupportedError("This instance is not configured to send events. Please specify options.broadcastChannel to enable watching.");const a={pattern:i.normalizeMinimatch(t,e?.recursive??!0),include:Array.isArray(e?.include)?e.include:[e?.include??"**"],exclude:Array.isArray(e?.exclude)?e.exclude:[e?.exclude??""]};this.watchers.set(t,a)}unwatch(t){this.watchers.delete(t)}async open(t,e){await this.mount();const{create:a=!1,exclusive:r=!1,truncate:s=!1}=e||{},n=i.normalizePath(i.resolvePath(t));try{return a&&r?await i.withLock(n,"exclusive",async()=>{if(await this.exists(n))throw new i.AlreadyExistsError(n);return this._openFile(n,a,s)}):await this._openFile(n,a,s)}catch(o){throw o instanceof i.OPFSError?o:i.mapDomError(o,{path:n,isDirectory:!1})}}async _openFile(t,e,a){const r=await this.getFileHandle(t,e);try{await r.getFile()}catch(o){throw i.mapDomError(o,{path:t,isDirectory:!0})}const s=await i.createSyncHandleSafe(r,t);a&&(s.truncate(0),s.flush());const n=this.nextFd++;return this.openFiles.set(n,{path:t,fileHandle:r,syncHandle:s,position:0}),n}async close(t){const e=this._getFileDescriptor(t);i.safeCloseSyncHandle(t,e.syncHandle,e.path),this.openFiles.delete(t)}async read(t,e,a,r,s){const n=this._getFileDescriptor(t);i.validateReadWriteArgs(e.length,a,r,s);try{const o=s??n.position,c=n.syncHandle.getSize(),{isEOF:h,actualLength:l}=i.calculateReadLength(o,r,c);if(h)return f.transfer({bytesRead:0,buffer:e},[e.buffer]);const y=e.subarray(a,a+l),w=n.syncHandle.read(y,{at:o});return s==null&&(n.position=o+w),f.transfer({bytesRead:w,buffer:e},[e.buffer])}catch(o){throw i.createFDError("read",t,n.path,o)}}async write(t,e,a=0,r,s,n=!0){const o=this._getFileDescriptor(t),c=r??e.length-a;i.validateReadWriteArgs(e.length,a,c,s);try{const h=s??o.position,l=e.subarray(a,a+c),y=o.syncHandle.write(l,{at:h});return(s==null||s===o.position)&&(o.position=h+y),n&&await this.notifyChange({path:o.path,type:i.WatchEventType.Changed,isDirectory:!1}),y}catch(h){throw i.createFDError("write",t,o.path,h)}}async fstat(t){const e=this._getFileDescriptor(t);return this.stat(e.path)}async ftruncate(t,e=0){const a=this._getFileDescriptor(t);if(e<0||!Number.isInteger(e))throw new i.ValidationError("argument","Invalid size");try{a.syncHandle.truncate(e),a.syncHandle.flush(),a.position>e&&(a.position=e),await this.notifyChange({path:a.path,type:i.WatchEventType.Changed,isDirectory:!1})}catch(r){throw i.createFDError("truncate",t,a.path,r)}}async fsync(t){const e=this._getFileDescriptor(t);try{e.syncHandle.flush()}catch(a){throw i.createFDError("sync",t,e.path,a)}}dispose(){this.broadcastChannel&&(this.broadcastChannel.close(),this.broadcastChannel=null),this.watchers.clear();for(const[t,e]of this.openFiles)i.safeCloseSyncHandle(t,e.syncHandle,e.path);this.openFiles.clear(),this.nextFd=1}async createIndex(t){await this.mount();try{for(const[e,a]of t){const r=i.normalizePath(e);let s;a instanceof Blob?s=await i.convertBlobToUint8Array(a):typeof a=="string"?s=new TextEncoder().encode(a):s=a,await this.writeFile(r,s)}}catch(e){throw e instanceof i.OPFSError?e:i.mapDomError(e)}}}typeof globalThis<"u"&&globalThis.constructor.name==="DedicatedWorkerGlobalScope"&&f.expose(new d);exports.OPFSWorker=d;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const f=require("comlink"),i=require("./helpers-CIiblZ8d.cjs");class d{root;watchers=new Map;mountingPromise=null;broadcastChannel=null;options={root:"/",namespace:"",maxFileSize:50*1024*1024,hashAlgorithm:"etag",broadcastChannel:"opfs-worker"};openFiles=new Map;nextFd=1;_getFileDescriptor(t){const e=this.openFiles.get(t);if(!e)throw new i.ValidationError("descriptor",`Invalid file descriptor: ${t}`);return e}async notifyChange(t){if(!this.options.broadcastChannel)return;const e=t.path;if(![...this.watchers.values()].some(s=>i.matchMinimatch(e,s.pattern)&&s.include.some(n=>n&&i.matchMinimatch(e,n))&&!s.exclude.some(n=>n&&i.matchMinimatch(e,n))))return;let r;if(this.options.hashAlgorithm)try{r=(await this.stat(e)).hash}catch{}try{this.broadcastChannel||(this.broadcastChannel=new BroadcastChannel(this.options.broadcastChannel));const s={namespace:this.options.namespace,timestamp:new Date().toISOString(),...t,...r&&{hash:r}};this.broadcastChannel.postMessage(s)}catch(s){console.warn("Failed to send event via BroadcastChannel:",s)}}constructor(t){i.checkOPFSSupport(),t&&this.setOptions(t)}async mount(){const t=this.options.root;return this.mountingPromise&&await this.mountingPromise,this.mountingPromise=new Promise(async(e,a)=>{try{const r=await navigator.storage.getDirectory();this.root=t==="/"?r:await this.getDirectoryHandle(t,!0,r),e(!0)}catch(r){a(new i.InitializationFailedError(t,r))}finally{this.mountingPromise=null}}),this.mountingPromise}async setOptions(t){t.hashAlgorithm!==void 0&&(this.options.hashAlgorithm=t.hashAlgorithm),t.maxFileSize!==void 0&&(this.options.maxFileSize=t.maxFileSize),t.broadcastChannel!==void 0&&(this.broadcastChannel&&this.options.broadcastChannel!==t.broadcastChannel&&(this.broadcastChannel.close(),this.broadcastChannel=null),this.options.broadcastChannel=t.broadcastChannel),t.namespace&&(this.options.namespace=t.namespace),t.root!==void 0&&(this.options.root=i.normalizePath(t.root),this.options.namespace||(this.options.namespace=`opfs-worker:${this.options.root}`),await this.mount())}async getDirectoryHandle(t,e=!1,a=this.root){const r=Array.isArray(t)?t:i.splitPath(t);let s=a;for(const n of r)s=await s.getDirectoryHandle(n,{create:e});return s}async getFileHandle(t,e=!1,a=this.root){const r=i.splitPath(t);if(r.length===0)throw new i.PathError("Path must not be empty",Array.isArray(t)?t.join("/"):t);const s=r.pop();return(await this.getDirectoryHandle(r,e,a)).getFileHandle(s,{create:e})}async index(){const t=new Map,e=async a=>{const r=await this.readDir(a);for(const s of r){const n=`${a==="/"?"":a}/${s.name}`;try{const o=await this.stat(n);t.set(n,o),o.isDirectory&&await e(n)}catch(o){console.warn(`Skipping broken entry: ${n}`,o)}}};return t.set("/",{kind:"directory",size:0,mtime:new Date(0).toISOString(),ctime:new Date(0).toISOString(),isFile:!1,isDirectory:!0}),await e("/"),t}async readFile(t){await this.mount();try{return await i.withLock(t,"shared",async()=>{const e=await this.open(t);try{const{size:a}=await this.fstat(e),r=new Uint8Array(a);return a>0&&await this.read(e,r,0,a,0),f.transfer(r,[r.buffer])}finally{await this.close(e)}})}catch(e){throw new i.ExistenceError("file",t,e)}}async writeFile(t,e){await this.mount();const a=e instanceof Uint8Array?e:new Uint8Array(e);await i.withLock(t,"exclusive",async()=>{const r=await this.exists(t),s=await this.open(t,{create:!0,truncate:!0});try{await this.write(s,a,0,a.length,null,!1),await this.fsync(s)}finally{await this.close(s)}await this.notifyChange({path:t,type:r?i.WatchEventType.Changed:i.WatchEventType.Added,isDirectory:!1})})}async appendFile(t,e){await this.mount();const a=e instanceof Uint8Array?e:new Uint8Array(e);await i.withLock(t,"exclusive",async()=>{const r=await this.open(t,{create:!0});try{const{size:s}=await this.fstat(r);await this.write(r,a,0,a.length,s,!1),await this.fsync(r)}finally{await this.close(r)}await this.notifyChange({path:t,type:i.WatchEventType.Changed,isDirectory:!1})})}async mkdir(t,e){await this.mount();const a=e?.recursive??!1,r=i.splitPath(t);let s=this.root;for(let n=0;n<r.length;n++){const o=r[n];try{s=await s.getDirectoryHandle(o,{create:a||n===r.length-1})}catch(c){throw c.name==="NotFoundError"?new i.ExistenceError("directory",i.joinPath(r.slice(0,n+1)),c):c.name==="TypeMismatchError"?new i.FileTypeError("file",o,c):new i.FileSystemOperationError("create directory",o,c)}}await this.notifyChange({path:t,type:i.WatchEventType.Added,isDirectory:!0})}async stat(t){if(await this.mount(),t==="/")return{kind:"directory",size:0,mtime:new Date(0).toISOString(),ctime:new Date(0).toISOString(),isFile:!1,isDirectory:!0};const e=i.basename(t);let a;try{a=await this.getDirectoryHandle(i.dirname(t),!1);const r=this.options.hashAlgorithm,n=await(await a.getFileHandle(e,{create:!1})).getFile(),o={kind:"file",size:n.size,mtime:new Date(n.lastModified).toISOString(),ctime:new Date(n.lastModified).toISOString(),isFile:!0,isDirectory:!1};if(r==="etag")o.hash=`${n.lastModified.toString(36)}-${n.size.toString(36)}`;else if(typeof r=="string")try{const c=await i.calculateFileHash(n,r,this.options.maxFileSize);o.hash=c}catch(c){console.warn(`Failed to calculate hash for ${t}:`,c)}return o}catch(r){if(r.name==="NotFoundError")throw new i.ExistenceError("file",t,r);if(r.name!=="TypeMismatchError")throw new i.FileSystemOperationError("stat",t,r)}try{return await a.getDirectoryHandle(e,{create:!1}),{kind:"directory",size:0,mtime:new Date(0).toISOString(),ctime:new Date(0).toISOString(),isFile:!1,isDirectory:!0}}catch(r){throw new i.FileSystemOperationError("stat",t,r)}}async readDir(t){await this.mount();const e=await this.getDirectoryHandle(t,!1),a=[];for await(const[r,s]of e.entries()){const n=s.kind==="file";a.push({name:r,kind:s.kind,isFile:n,isDirectory:!n})}return a}async exists(t){if(await this.mount(),t==="/")return!0;const e=i.basename(t);let a=null;try{a=await this.getDirectoryHandle(i.dirname(t),!1)}catch(r){if(a=null,r.name!=="NotFoundError"&&r.name!=="TypeMismatchError")throw r}if(!a||!e)return!1;try{return await a.getFileHandle(e,{create:!1}),!0}catch(r){if(r.name!=="NotFoundError"&&r.name!=="TypeMismatchError")throw r;try{return await a.getDirectoryHandle(e,{create:!1}),!0}catch(s){if(s.name!=="NotFoundError"&&s.name!=="TypeMismatchError")throw s;return!1}}}async clear(t="/"){await this.mount();try{const e=await this.readDir(t);for(const a of e){const r=`${t==="/"?"":t}/${a.name}`;await this.remove(r,{recursive:!0})}await this.notifyChange({path:t,type:i.WatchEventType.Changed,isDirectory:!0})}catch(e){throw e instanceof i.OPFSError?e:i.mapDomError(e,{path:t,isDirectory:!0})}}async remove(t,e){if(await this.mount(),t==="/")throw new i.DirectoryOperationError("EROOT",t);const{recursive:a=!1,force:r=!1}=e||{},s=await this.getDirectoryHandle(i.dirname(t),!1),n=await this.stat(t);await i.removeEntry(s,t,{recursive:a,force:r}),await this.notifyChange({path:t,type:i.WatchEventType.Removed,isDirectory:n.isDirectory})}async realpath(t){await this.mount();try{const e=i.resolvePath(t);if(!await this.exists(e))throw new i.ExistenceError("file",e);return e}catch(e){throw e instanceof i.OPFSError?e:i.mapDomError(e,{path:t})}}async rename(t,e,a){await this.mount();try{const r=a?.overwrite??!1,s=await this.stat(t);if(await this.exists(e)&&!r)throw new i.AlreadyExistsError(e);await this.copy(t,e,{recursive:!0,overwrite:r}),await this.remove(t,{recursive:!0}),await this.notifyChange({path:t,type:i.WatchEventType.Removed,isDirectory:s.isDirectory}),await this.notifyChange({path:e,type:i.WatchEventType.Added,isDirectory:s.isDirectory})}catch(r){throw r instanceof i.OPFSError?r:i.mapDomError(r,{path:t})}}async copy(t,e,a){await this.mount();try{const r=a?.recursive??!1,s=a?.overwrite??!0;if(!await this.exists(t))throw new i.ExistenceError("source",t);if(await this.exists(e)&&!s)throw new i.AlreadyExistsError(e);if((await this.stat(t)).isFile){const h=await this.readFile(t);await this.writeFile(e,h)}else{if(!r)throw new i.FileTypeError("directory",t);await this.mkdir(e,{recursive:!0});const h=await this.readDir(t);for(const l of h){const w=`${t}/${l.name}`,y=`${e}/${l.name}`;await this.copy(w,y,{recursive:!0,overwrite:s})}}}catch(r){throw r instanceof i.OPFSError?r:i.mapDomError(r,{path:t})}}async watch(t,e){if(!this.options.broadcastChannel)throw new i.OperationNotSupportedError("This instance is not configured to send events. Please specify options.broadcastChannel to enable watching.");const a={pattern:i.normalizeMinimatch(t,e?.recursive??!0),include:Array.isArray(e?.include)?e.include:[e?.include??"**"],exclude:Array.isArray(e?.exclude)?e.exclude:[e?.exclude??""]};this.watchers.set(t,a)}unwatch(t){this.watchers.delete(t)}async open(t,e){await this.mount();const{create:a=!1,exclusive:r=!1,truncate:s=!1}=e||{},n=i.normalizePath(i.resolvePath(t));try{return a&&r?await i.withLock(n,"exclusive",async()=>{if(await this.exists(n))throw new i.AlreadyExistsError(n);return this._openFile(n,a,s)}):await this._openFile(n,a,s)}catch(o){throw o instanceof i.OPFSError?o:i.mapDomError(o,{path:n,isDirectory:!1})}}async _openFile(t,e,a){const r=await this.getFileHandle(t,e);try{await r.getFile()}catch(o){throw i.mapDomError(o,{path:t,isDirectory:!0})}const s=await i.createSyncHandleSafe(r,t);a&&(s.truncate(0),s.flush());const n=this.nextFd++;return this.openFiles.set(n,{path:t,fileHandle:r,syncHandle:s,position:0}),n}async close(t){const e=this._getFileDescriptor(t);i.safeCloseSyncHandle(t,e.syncHandle,e.path),this.openFiles.delete(t)}async read(t,e,a,r,s){const n=this._getFileDescriptor(t);i.validateReadWriteArgs(e.length,a,r,s);try{const o=s??n.position,c=n.syncHandle.getSize(),{isEOF:h,actualLength:l}=i.calculateReadLength(o,r,c);if(h)return f.transfer({bytesRead:0,buffer:e},[e.buffer]);const w=e.subarray(a,a+l),y=n.syncHandle.read(w,{at:o});return s==null&&(n.position=o+y),f.transfer({bytesRead:y,buffer:e},[e.buffer])}catch(o){throw i.createFDError("read",t,n.path,o)}}async write(t,e,a=0,r,s,n=!0){const o=this._getFileDescriptor(t),c=r??e.length-a;i.validateReadWriteArgs(e.length,a,c,s);try{const h=s??o.position,l=e.subarray(a,a+c),w=o.syncHandle.write(l,{at:h});return(s==null||s===o.position)&&(o.position=h+w),n&&await this.notifyChange({path:o.path,type:i.WatchEventType.Changed,isDirectory:!1}),w}catch(h){throw i.createFDError("write",t,o.path,h)}}async fstat(t){const e=this._getFileDescriptor(t);return this.stat(e.path)}async ftruncate(t,e=0){const a=this._getFileDescriptor(t);if(e<0||!Number.isInteger(e))throw new i.ValidationError("argument","Invalid size");try{a.syncHandle.truncate(e),a.syncHandle.flush(),a.position>e&&(a.position=e),await this.notifyChange({path:a.path,type:i.WatchEventType.Changed,isDirectory:!1})}catch(r){throw i.createFDError("truncate",t,a.path,r)}}async fsync(t){const e=this._getFileDescriptor(t);try{e.syncHandle.flush()}catch(a){throw i.createFDError("sync",t,e.path,a)}}dispose(){this.broadcastChannel&&(this.broadcastChannel.close(),this.broadcastChannel=null),this.watchers.clear();for(const[t,e]of this.openFiles)i.safeCloseSyncHandle(t,e.syncHandle,e.path);this.openFiles.clear(),this.nextFd=1}async createIndex(t){await this.mount();try{for(const[e,a]of t){const r=i.normalizePath(e);let s;a instanceof Blob?s=await i.convertBlobToUint8Array(a):typeof a=="string"?s=new TextEncoder().encode(a):s=a,await this.writeFile(r,s)}}catch(e){throw e instanceof i.OPFSError?e:i.mapDomError(e)}}}typeof globalThis<"u"&&globalThis.constructor.name==="DedicatedWorkerGlobalScope"&&f.expose(new d);exports.OPFSWorker=d;
2
2
  //# sourceMappingURL=raw.cjs.map