opfs-worker 2.1.0 → 2.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/README.md +51 -37
  2. package/dist/BaseOPFS-Bu7FZtCb.cjs +2 -0
  3. package/dist/BaseOPFS-Bu7FZtCb.cjs.map +1 -0
  4. package/dist/{BaseOPFS-Cylz6ijk.js → BaseOPFS-C3NE4BKr.js} +804 -484
  5. package/dist/BaseOPFS-C3NE4BKr.js.map +1 -0
  6. package/dist/OPFSAsync-C0RsxCX5.cjs +2 -0
  7. package/dist/OPFSAsync-C0RsxCX5.cjs.map +1 -0
  8. package/dist/{OPFSAsync-BKSAJJeh.js → OPFSAsync-aeLUdIqd.js} +19 -19
  9. package/dist/OPFSAsync-aeLUdIqd.js.map +1 -0
  10. package/dist/OPFSFacade-BJv2yuWU.cjs +2 -0
  11. package/dist/OPFSFacade-BJv2yuWU.cjs.map +1 -0
  12. package/dist/OPFSFacade-DiogtQoq.js +308 -0
  13. package/dist/OPFSFacade-DiogtQoq.js.map +1 -0
  14. package/dist/OPFSSync-3qlSBYmz.cjs +2 -0
  15. package/dist/OPFSSync-3qlSBYmz.cjs.map +1 -0
  16. package/dist/{OPFSSync-CsSQkpk5.js → OPFSSync-CvSOswhW.js} +57 -57
  17. package/dist/OPFSSync-CvSOswhW.js.map +1 -0
  18. package/dist/assets/dedicated.worker-Bqqr9UBA.js.map +1 -0
  19. package/dist/core/BaseOPFS.d.ts +60 -9
  20. package/dist/core/BaseOPFS.d.ts.map +1 -1
  21. package/dist/core/OPFSAsync.d.ts.map +1 -1
  22. package/dist/core/OPFSSync.d.ts.map +1 -1
  23. package/dist/createOPFSAsync-B611B63X.js +10 -0
  24. package/dist/{createOPFSAsync-Y4Mg6qte.js.map → createOPFSAsync-B611B63X.js.map} +1 -1
  25. package/dist/createOPFSAsync-BATjJg8k.cjs +2 -0
  26. package/dist/{createOPFSAsync-BwKDmHsy.cjs.map → createOPFSAsync-BATjJg8k.cjs.map} +1 -1
  27. package/dist/createOPFSDedicated-DgudPTB8.js +2676 -0
  28. package/dist/createOPFSDedicated-DgudPTB8.js.map +1 -0
  29. package/dist/createOPFSDedicated-EmIwluQo.cjs +2597 -0
  30. package/dist/createOPFSDedicated-EmIwluQo.cjs.map +1 -0
  31. package/dist/{createOPFSShared-CGdd__PH.js → createOPFSShared-BWYln8jJ.js} +2 -2
  32. package/dist/{createOPFSShared-CGdd__PH.js.map → createOPFSShared-BWYln8jJ.js.map} +1 -1
  33. package/dist/{createOPFSShared-CskROt7U.cjs → createOPFSShared-DPJpCd7z.cjs} +2 -2
  34. package/dist/{createOPFSShared-CskROt7U.cjs.map → createOPFSShared-DPJpCd7z.cjs.map} +1 -1
  35. package/dist/dedicated.worker.js +1104 -790
  36. package/dist/dedicated.worker.js.map +1 -1
  37. package/dist/facade/OPFSFacade.d.ts +21 -3
  38. package/dist/facade/OPFSFacade.d.ts.map +1 -1
  39. package/dist/facade/createOPFSDedicated.d.ts +4 -2
  40. package/dist/facade/createOPFSDedicated.d.ts.map +1 -1
  41. package/dist/index.async.cjs +1 -1
  42. package/dist/index.async.js +33 -32
  43. package/dist/index.cjs +1 -1
  44. package/dist/index.d.ts +1 -5
  45. package/dist/index.d.ts.map +1 -1
  46. package/dist/index.js +44 -43
  47. package/dist/index.pure.cjs +1 -1
  48. package/dist/index.pure.js +38 -37
  49. package/dist/index.sharedworker.cjs +1 -1
  50. package/dist/index.sharedworker.js +34 -33
  51. package/dist/index.sync.cjs +1 -1
  52. package/dist/index.sync.d.ts +2 -0
  53. package/dist/index.sync.d.ts.map +1 -1
  54. package/dist/index.sync.js +34 -32
  55. package/dist/shared.worker.js +1101 -791
  56. package/dist/shared.worker.js.map +1 -1
  57. package/dist/types.d.ts +38 -5
  58. package/dist/types.d.ts.map +1 -1
  59. package/dist/utils/helpers.d.ts +13 -3
  60. package/dist/utils/helpers.d.ts.map +1 -1
  61. package/dist/worker/createDedicatedWorker.d.ts +8 -3
  62. package/dist/worker/createDedicatedWorker.d.ts.map +1 -1
  63. package/docs/README.md +13 -25
  64. package/docs/api/README.md +221 -0
  65. package/docs/api/file-descriptors.md +137 -0
  66. package/docs/guides/async.md +4 -4
  67. package/docs/guides/dedicated.md +10 -8
  68. package/docs/guides/hashing.md +3 -3
  69. package/docs/guides/pure.md +4 -4
  70. package/docs/guides/sharedworker.md +2 -2
  71. package/docs/guides/streaming.md +146 -12
  72. package/docs/guides/watching.md +3 -3
  73. package/docs/migration.md +10 -11
  74. package/docs/types.md +93 -155
  75. package/package.json +20 -9
  76. package/src/core/BaseOPFS.ts +194 -29
  77. package/src/core/OPFSAsync.ts +4 -5
  78. package/src/core/OPFSSync.ts +6 -7
  79. package/src/facade/OPFSFacade.ts +51 -4
  80. package/src/facade/createOPFSDedicated.ts +4 -2
  81. package/src/index.sync.ts +2 -0
  82. package/src/index.ts +1 -5
  83. package/src/types.ts +42 -3
  84. package/src/utils/helpers.ts +32 -6
  85. package/src/worker/createDedicatedWorker.ts +85 -7
  86. package/src/worker/dedicated.worker.ts +12 -1
  87. package/dist/BaseOPFS-BPw9AIQ-.cjs +0 -4
  88. package/dist/BaseOPFS-BPw9AIQ-.cjs.map +0 -1
  89. package/dist/BaseOPFS-Cylz6ijk.js.map +0 -1
  90. package/dist/OPFSAsync-BKSAJJeh.js.map +0 -1
  91. package/dist/OPFSAsync-s2P7y3sw.cjs +0 -2
  92. package/dist/OPFSAsync-s2P7y3sw.cjs.map +0 -1
  93. package/dist/OPFSFacade-DePnNRgt.cjs +0 -2
  94. package/dist/OPFSFacade-DePnNRgt.cjs.map +0 -1
  95. package/dist/OPFSFacade-XohWlHuu.js +0 -281
  96. package/dist/OPFSFacade-XohWlHuu.js.map +0 -1
  97. package/dist/OPFSSync-C7KBepe_.cjs +0 -2
  98. package/dist/OPFSSync-C7KBepe_.cjs.map +0 -1
  99. package/dist/OPFSSync-CsSQkpk5.js.map +0 -1
  100. package/dist/assets/dedicated.worker-nY3tK4zi.js.map +0 -1
  101. package/dist/createOPFSAsync-BwKDmHsy.cjs +0 -2
  102. package/dist/createOPFSAsync-Y4Mg6qte.js +0 -10
  103. package/dist/createOPFSDedicated-CsnV6MLP.js +0 -2333
  104. package/dist/createOPFSDedicated-CsnV6MLP.js.map +0 -1
  105. package/dist/createOPFSDedicated-pKTRWLdz.cjs +0 -2283
  106. package/dist/createOPFSDedicated-pKTRWLdz.cjs.map +0 -1
  107. package/docs/api/backend.md +0 -36
  108. package/docs/api/create.md +0 -82
  109. package/docs/api/facade.md +0 -52
  110. package/docs/choosing-a-mode.md +0 -41
  111. package/docs/file-descriptors.md +0 -695
@@ -0,0 +1,2597 @@
1
+ "use strict";const b=require("./OPFSFacade-BJv2yuWU.cjs"),v=require("comlink"),g=require("./BaseOPFS-Bu7FZtCb.cjs"),y=`const Ot = /* @__PURE__ */ Symbol("Comlink.proxy"), Bt = /* @__PURE__ */ Symbol("Comlink.endpoint"), Gt = /* @__PURE__ */ Symbol("Comlink.releaseProxy"), X = /* @__PURE__ */ Symbol("Comlink.finalizer"), H = /* @__PURE__ */ Symbol("Comlink.thrown"), Dt = (n) => typeof n == "object" && n !== null || typeof n == "function", Ut = {
2
+ canHandle: (n) => Dt(n) && n[Ot],
3
+ serialize(n) {
4
+ const { port1: t, port2: e } = new MessageChannel();
5
+ return U(n, t), [e, [e]];
6
+ },
7
+ deserialize(n) {
8
+ return n.start(), Yt(n);
9
+ }
10
+ }, qt = {
11
+ canHandle: (n) => Dt(n) && H in n,
12
+ serialize({ value: n }) {
13
+ let t;
14
+ return n instanceof Error ? t = {
15
+ isError: !0,
16
+ value: {
17
+ message: n.message,
18
+ name: n.name,
19
+ stack: n.stack
20
+ }
21
+ } : t = { isError: !1, value: n }, [t, []];
22
+ },
23
+ deserialize(n) {
24
+ throw n.isError ? Object.assign(new Error(n.value.message), n.value) : n.value;
25
+ }
26
+ }, Mt = /* @__PURE__ */ new Map([
27
+ ["proxy", Ut],
28
+ ["throw", qt]
29
+ ]);
30
+ function Vt(n, t) {
31
+ for (const e of n)
32
+ if (t === e || e === "*" || e instanceof RegExp && e.test(t))
33
+ return !0;
34
+ return !1;
35
+ }
36
+ function U(n, t = globalThis, e = ["*"]) {
37
+ t.addEventListener("message", function s(r) {
38
+ if (!r || !r.data)
39
+ return;
40
+ if (!Vt(e, r.origin)) {
41
+ console.warn(\`Invalid origin '\${r.origin}' for comlink proxy\`);
42
+ return;
43
+ }
44
+ const { id: i, type: o, path: a } = Object.assign({ path: [] }, r.data), c = (r.data.argumentList || []).map(T);
45
+ let l;
46
+ try {
47
+ const h = a.slice(0, -1).reduce((f, p) => f[p], n), u = a.reduce((f, p) => f[p], n);
48
+ switch (o) {
49
+ case "GET":
50
+ l = u;
51
+ break;
52
+ case "SET":
53
+ h[a.slice(-1)[0]] = T(r.data.value), l = !0;
54
+ break;
55
+ case "APPLY":
56
+ l = u.apply(h, c);
57
+ break;
58
+ case "CONSTRUCT":
59
+ {
60
+ const f = new u(...c);
61
+ l = Kt(f);
62
+ }
63
+ break;
64
+ case "ENDPOINT":
65
+ {
66
+ const { port1: f, port2: p } = new MessageChannel();
67
+ U(n, p), l = z(f, [f]);
68
+ }
69
+ break;
70
+ case "RELEASE":
71
+ l = void 0;
72
+ break;
73
+ default:
74
+ return;
75
+ }
76
+ } catch (h) {
77
+ l = { value: h, [H]: 0 };
78
+ }
79
+ Promise.resolve(l).catch((h) => ({ value: h, [H]: 0 })).then((h) => {
80
+ const [u, f] = B(h);
81
+ t.postMessage(Object.assign(Object.assign({}, u), { id: i }), f), o === "RELEASE" && (t.removeEventListener("message", s), $t(t), X in n && typeof n[X] == "function" && n[X]());
82
+ }).catch((h) => {
83
+ const [u, f] = B({
84
+ value: new TypeError("Unserializable return value"),
85
+ [H]: 0
86
+ });
87
+ t.postMessage(Object.assign(Object.assign({}, u), { id: i }), f);
88
+ });
89
+ }), t.start && t.start();
90
+ }
91
+ function Xt(n) {
92
+ return n.constructor.name === "MessagePort";
93
+ }
94
+ function $t(n) {
95
+ Xt(n) && n.close();
96
+ }
97
+ function Yt(n, t) {
98
+ const e = /* @__PURE__ */ new Map();
99
+ return n.addEventListener("message", function(r) {
100
+ const { data: i } = r;
101
+ if (!i || !i.id)
102
+ return;
103
+ const o = e.get(i.id);
104
+ if (o)
105
+ try {
106
+ o(i);
107
+ } finally {
108
+ e.delete(i.id);
109
+ }
110
+ }), K(n, e, [], t);
111
+ }
112
+ function k(n) {
113
+ if (n)
114
+ throw new Error("Proxy has been released and is not useable");
115
+ }
116
+ function Tt(n) {
117
+ return N(n, /* @__PURE__ */ new Map(), {
118
+ type: "RELEASE"
119
+ }).then(() => {
120
+ $t(n);
121
+ });
122
+ }
123
+ const W = /* @__PURE__ */ new WeakMap(), j = "FinalizationRegistry" in globalThis && new FinalizationRegistry((n) => {
124
+ const t = (W.get(n) || 0) - 1;
125
+ W.set(n, t), t === 0 && Tt(n);
126
+ });
127
+ function Zt(n, t) {
128
+ const e = (W.get(t) || 0) + 1;
129
+ W.set(t, e), j && j.register(n, t, n);
130
+ }
131
+ function Jt(n) {
132
+ j && j.unregister(n);
133
+ }
134
+ function K(n, t, e = [], s = function() {
135
+ }) {
136
+ let r = !1;
137
+ const i = new Proxy(s, {
138
+ get(o, a) {
139
+ if (k(r), a === Gt)
140
+ return () => {
141
+ Jt(i), Tt(n), t.clear(), r = !0;
142
+ };
143
+ if (a === "then") {
144
+ if (e.length === 0)
145
+ return { then: () => i };
146
+ const c = N(n, t, {
147
+ type: "GET",
148
+ path: e.map((l) => l.toString())
149
+ }).then(T);
150
+ return c.then.bind(c);
151
+ }
152
+ return K(n, t, [...e, a]);
153
+ },
154
+ set(o, a, c) {
155
+ k(r);
156
+ const [l, h] = B(c);
157
+ return N(n, t, {
158
+ type: "SET",
159
+ path: [...e, a].map((u) => u.toString()),
160
+ value: l
161
+ }, h).then(T);
162
+ },
163
+ apply(o, a, c) {
164
+ k(r);
165
+ const l = e[e.length - 1];
166
+ if (l === Bt)
167
+ return N(n, t, {
168
+ type: "ENDPOINT"
169
+ }).then(T);
170
+ if (l === "bind")
171
+ return K(n, t, e.slice(0, -1));
172
+ const [h, u] = ut(c);
173
+ return N(n, t, {
174
+ type: "APPLY",
175
+ path: e.map((f) => f.toString()),
176
+ argumentList: h
177
+ }, u).then(T);
178
+ },
179
+ construct(o, a) {
180
+ k(r);
181
+ const [c, l] = ut(a);
182
+ return N(n, t, {
183
+ type: "CONSTRUCT",
184
+ path: e.map((h) => h.toString()),
185
+ argumentList: c
186
+ }, l).then(T);
187
+ }
188
+ });
189
+ return Zt(i, n), i;
190
+ }
191
+ function Qt(n) {
192
+ return Array.prototype.concat.apply([], n);
193
+ }
194
+ function ut(n) {
195
+ const t = n.map(B);
196
+ return [t.map((e) => e[0]), Qt(t.map((e) => e[1]))];
197
+ }
198
+ const Nt = /* @__PURE__ */ new WeakMap();
199
+ function z(n, t) {
200
+ return Nt.set(n, t), n;
201
+ }
202
+ function Kt(n) {
203
+ return Object.assign(n, { [Ot]: !0 });
204
+ }
205
+ function B(n) {
206
+ for (const [t, e] of Mt)
207
+ if (e.canHandle(n)) {
208
+ const [s, r] = e.serialize(n);
209
+ return [
210
+ {
211
+ type: "HANDLER",
212
+ name: t,
213
+ value: s
214
+ },
215
+ r
216
+ ];
217
+ }
218
+ return [
219
+ {
220
+ type: "RAW",
221
+ value: n
222
+ },
223
+ Nt.get(n) || []
224
+ ];
225
+ }
226
+ function T(n) {
227
+ switch (n.type) {
228
+ case "HANDLER":
229
+ return Mt.get(n.name).deserialize(n.value);
230
+ case "RAW":
231
+ return n.value;
232
+ }
233
+ }
234
+ function N(n, t, e, s) {
235
+ return new Promise((r) => {
236
+ const i = te();
237
+ t.set(i, r), n.start && n.start(), n.postMessage(Object.assign({ id: i }, e), s);
238
+ });
239
+ }
240
+ function te() {
241
+ return new Array(4).fill(0).map(() => Math.floor(Math.random() * Number.MAX_SAFE_INTEGER).toString(16)).join("-");
242
+ }
243
+ var O = /* @__PURE__ */ ((n) => (n.Added = "added", n.Changed = "changed", n.Removed = "removed", n))(O || {});
244
+ const ee = {
245
+ ENOENT: -2,
246
+ // No such file or directory
247
+ EISDIR: -21,
248
+ // Is a directory
249
+ ENOTDIR: -20,
250
+ // Not a directory
251
+ EACCES: -13,
252
+ // Permission denied
253
+ EEXIST: -17,
254
+ // File exists
255
+ ENOTEMPTY: -39,
256
+ // Directory not empty
257
+ EINVAL: -22,
258
+ // Invalid argument
259
+ EIO: -5,
260
+ // I/O error
261
+ ENOSPC: -28,
262
+ // No space left on device
263
+ EBUSY: -16,
264
+ // Device or resource busy
265
+ EINTR: -4,
266
+ // Interrupted system call
267
+ ENOTSUP: -95,
268
+ // Operation not supported
269
+ ERANGE: -34,
270
+ // Result too large
271
+ EBADF: -9,
272
+ // Bad file descriptor
273
+ EROOT: -1
274
+ // Custom: Cannot remove root directory
275
+ };
276
+ class y extends Error {
277
+ errno;
278
+ syscall;
279
+ path;
280
+ constructor(t, e, s, r, i) {
281
+ super(t, { cause: i }), this.name = e, this.errno = ee[e] || -1, this.path = s, this.syscall = r;
282
+ }
283
+ }
284
+ class se extends y {
285
+ constructor(t) {
286
+ super("OPFS is not supported in this browser", "ENOTSUP", void 0, void 0, t);
287
+ }
288
+ }
289
+ class ne extends y {
290
+ constructor(t, e, s) {
291
+ super(t, "INVALID_PATH", e, "access", s);
292
+ }
293
+ }
294
+ class _ extends y {
295
+ constructor(t, e, s) {
296
+ const r = {
297
+ file: \`File not found: \${e}\`,
298
+ directory: \`Directory not found: \${e}\`,
299
+ source: \`Source does not exist: \${e}\`
300
+ };
301
+ super(r[t], "ENOENT", e, "access", s);
302
+ }
303
+ }
304
+ class re extends y {
305
+ constructor(t, e, s) {
306
+ super(\`Permission denied for \${e} on: \${t}\`, "EACCES", t, e, s);
307
+ }
308
+ }
309
+ class ie extends y {
310
+ constructor(t, e, s) {
311
+ super(t, "ENOSPC", e, "write", s);
312
+ }
313
+ }
314
+ class oe extends y {
315
+ constructor(t, e) {
316
+ super(\`File is busy: \${t}\`, "EBUSY", t, "open", e);
317
+ }
318
+ }
319
+ class tt extends y {
320
+ constructor(t, e, s) {
321
+ const r = t === "directory" ? \`Is a directory: \${e}\` : \`Not a directory: \${e}\`, i = t === "directory" ? "EISDIR" : "ENOTDIR";
322
+ super(r, i, e, "access", s);
323
+ }
324
+ }
325
+ class $ extends y {
326
+ constructor(t, e, s, r) {
327
+ const i = {
328
+ argument: "EINVAL",
329
+ format: "INVALID_FORMAT",
330
+ descriptor: "EBADF",
331
+ overflow: "ERANGE"
332
+ };
333
+ super(e, i[t], s, "validate", r);
334
+ }
335
+ }
336
+ class ae extends y {
337
+ constructor(t, e) {
338
+ super(\`Operation aborted: \${t}\`, "EINTR", t, "interrupt", e);
339
+ }
340
+ }
341
+ class ft extends y {
342
+ constructor(t, e, s) {
343
+ super(t, "EIO", e, "io", s);
344
+ }
345
+ }
346
+ class Ct extends y {
347
+ constructor(t, e) {
348
+ super(\`Operation not supported: \${t}\`, "ENOTSUP", t, "operation", e);
349
+ }
350
+ }
351
+ class et extends y {
352
+ constructor(t, e, s) {
353
+ const r = {
354
+ RM_FAILED: \`Failed to remove entry: \${e}\`,
355
+ ENOTEMPTY: \`Directory not empty: \${e}. Use recursive option to force removal.\`,
356
+ EROOT: "Cannot remove root directory"
357
+ };
358
+ super(r[t] || \`Directory operation failed: \${e}\`, t, e, "unlink", s);
359
+ }
360
+ }
361
+ class ce extends y {
362
+ constructor(t, e) {
363
+ super("Failed to initialize OPFS", "INIT_FAILED", t, "init", e);
364
+ }
365
+ }
366
+ class Y extends y {
367
+ constructor(t, e, s) {
368
+ super(\`Failed to \${t}: \${e}\`, \`\${t.toUpperCase()}_FAILED\`, e, t, s);
369
+ }
370
+ }
371
+ class st extends y {
372
+ constructor(t, e) {
373
+ super(\`Destination already exists: \${t}\`, "EEXIST", t, "open", e);
374
+ }
375
+ }
376
+ function I(n, t, e, s) {
377
+ const r = \`\${n.toUpperCase()}_FAILED\`;
378
+ return new y(\`Failed to \${n} file descriptor: \${t}\`, r, e, n, s);
379
+ }
380
+ function A(n, t) {
381
+ const e = t?.path, s = t?.isDirectory, r = t?.existenceType ?? "file", i = t?.operation;
382
+ switch (n.name) {
383
+ case "InvalidStateError":
384
+ return new oe(e || "unknown", n);
385
+ case "QuotaExceededError":
386
+ return new ie(\`No space left on device: \${e || "unknown"}\`, e, n);
387
+ case "NotFoundError":
388
+ return new _(r, e, n);
389
+ case "TypeMismatchError":
390
+ return s !== void 0 ? s ? new tt("directory", e || "unknown", n) : new tt("file", e || "unknown", n) : new $("argument", \`Type mismatch: \${e || "unknown"}\`, e, n);
391
+ case "NotAllowedError":
392
+ case "SecurityError":
393
+ return new re(e, "unknown", n);
394
+ case "InvalidModificationError":
395
+ return i === "remove" ? new et("ENOTEMPTY", e, n) : new $("argument", \`Invalid modification: \${e || "unknown"}\`, e, n);
396
+ case "AbortError":
397
+ return new ae(e || "unknown", n);
398
+ case "OperationError":
399
+ return new ft(\`Operation failed: \${e || "unknown"}\`, e, n);
400
+ case "TypeError":
401
+ return new Ct(e || "unknown", n);
402
+ default:
403
+ return i === "remove" ? new et("RM_FAILED", e, n) : new ft(\`I/O error: \${e || "unknown"}\`, e, n);
404
+ }
405
+ }
406
+ const vt = (n, t, e) => {
407
+ const s = n instanceof RegExp ? pt(n, e) : n, r = t instanceof RegExp ? pt(t, e) : t, i = s !== null && r != null && le(s, r, e);
408
+ return i && {
409
+ start: i[0],
410
+ end: i[1],
411
+ pre: e.slice(0, i[0]),
412
+ body: e.slice(i[0] + s.length, i[1]),
413
+ post: e.slice(i[1] + r.length)
414
+ };
415
+ }, pt = (n, t) => {
416
+ const e = t.match(n);
417
+ return e ? e[0] : null;
418
+ }, le = (n, t, e) => {
419
+ let s, r, i, o, a, c = e.indexOf(n), l = e.indexOf(t, c + 1), h = c;
420
+ if (c >= 0 && l > 0) {
421
+ if (n === t)
422
+ return [c, l];
423
+ for (s = [], i = e.length; h >= 0 && !a; ) {
424
+ if (h === c)
425
+ s.push(h), c = e.indexOf(n, h + 1);
426
+ else if (s.length === 1) {
427
+ const u = s.pop();
428
+ u !== void 0 && (a = [u, l]);
429
+ } else
430
+ r = s.pop(), r !== void 0 && r < i && (i = r, o = l), l = e.indexOf(t, h + 1);
431
+ h = c < l && c >= 0 ? c : l;
432
+ }
433
+ s.length && o !== void 0 && (a = [i, o]);
434
+ }
435
+ return a;
436
+ }, Ft = "\\0SLASH" + Math.random() + "\\0", Pt = "\\0OPEN" + Math.random() + "\\0", ot = "\\0CLOSE" + Math.random() + "\\0", Rt = "\\0COMMA" + Math.random() + "\\0", kt = "\\0PERIOD" + Math.random() + "\\0", he = new RegExp(Ft, "g"), ue = new RegExp(Pt, "g"), fe = new RegExp(ot, "g"), pe = new RegExp(Rt, "g"), de = new RegExp(kt, "g"), ge = /\\\\\\\\/g, ye = /\\\\{/g, we = /\\\\}/g, me = /\\\\,/g, Ee = /\\\\\\./g, Se = 1e5, be = 4e6;
437
+ function Z(n) {
438
+ return isNaN(n) ? n.charCodeAt(0) : parseInt(n, 10);
439
+ }
440
+ function xe(n) {
441
+ return n.replace(ge, Ft).replace(ye, Pt).replace(we, ot).replace(me, Rt).replace(Ee, kt);
442
+ }
443
+ function Ae(n) {
444
+ return n.replace(he, "\\\\").replace(ue, "{").replace(fe, "}").replace(pe, ",").replace(de, ".");
445
+ }
446
+ function It(n) {
447
+ if (!n)
448
+ return [""];
449
+ const t = [], e = vt("{", "}", n);
450
+ if (!e)
451
+ return n.split(",");
452
+ const { pre: s, body: r, post: i } = e, o = s.split(",");
453
+ o[o.length - 1] += "{" + r + "}";
454
+ const a = It(i);
455
+ return i.length && (o[o.length - 1] += a.shift(), o.push.apply(o, a)), t.push.apply(t, o), t;
456
+ }
457
+ function Oe(n, t = {}) {
458
+ if (!n)
459
+ return [];
460
+ const { max: e = Se, maxLength: s = be } = t;
461
+ return n.slice(0, 2) === "{}" && (n = "\\\\{\\\\}" + n.slice(2)), nt(xe(n), e, s, !0).map(Ae);
462
+ }
463
+ function De(n) {
464
+ return "{" + n + "}";
465
+ }
466
+ function Me(n) {
467
+ return /^-?0\\d/.test(n);
468
+ }
469
+ function $e(n, t) {
470
+ return n <= t;
471
+ }
472
+ function Te(n, t) {
473
+ return n >= t;
474
+ }
475
+ function F(n, t, e, s, r, i) {
476
+ const o = [];
477
+ let a = 0;
478
+ for (let c = 0; c < n.length; c++)
479
+ for (let l = 0; l < e.length; l++) {
480
+ if (o.length >= s)
481
+ return o;
482
+ const h = n[c] + t + e[l];
483
+ if (!(i && !h)) {
484
+ if (a + h.length > r)
485
+ return o;
486
+ o.push(h), a += h.length;
487
+ }
488
+ }
489
+ return o;
490
+ }
491
+ function Ne(n, t, e) {
492
+ const s = n.split(/\\.\\./), r = [];
493
+ if (s[0] === void 0 || s[1] === void 0)
494
+ return r;
495
+ const i = Z(s[0]), o = Z(s[1]), a = Math.max(s[0].length, s[1].length);
496
+ let c = s.length === 3 && s[2] !== void 0 ? Math.max(Math.abs(Z(s[2])), 1) : 1, l = $e;
497
+ o < i && (c *= -1, l = Te);
498
+ const u = s.some(Me);
499
+ for (let f = i; l(f, o) && r.length < e; f += c) {
500
+ let p;
501
+ if (t)
502
+ p = String.fromCharCode(f), p === "\\\\" && (p = "");
503
+ else if (p = String(f), u) {
504
+ const g = a - p.length;
505
+ if (g > 0) {
506
+ const d = new Array(g + 1).join("0");
507
+ f < 0 ? p = "-" + d + p.slice(1) : p = d + p;
508
+ }
509
+ }
510
+ r.push(p);
511
+ }
512
+ return r;
513
+ }
514
+ function nt(n, t, e, s) {
515
+ let r = [""], i = !1, o = !0;
516
+ for (; ; ) {
517
+ const a = vt("{", "}", n);
518
+ if (!a)
519
+ return F(r, n, [""], t, e, i);
520
+ const c = a.pre;
521
+ if (/\\$$/.test(c)) {
522
+ if (r = F(r, c + "{" + a.body + "}", [""], t, e, i && !a.post.length), o = !1, !a.post.length)
523
+ break;
524
+ n = a.post;
525
+ continue;
526
+ }
527
+ const l = /^-?\\d+\\.\\.-?\\d+(?:\\.\\.-?\\d+)?$/.test(a.body), h = /^[a-zA-Z]\\.\\.[a-zA-Z](?:\\.\\.-?\\d+)?$/.test(a.body), u = l || h, f = a.body.indexOf(",") >= 0;
528
+ if (!u && !f) {
529
+ if (a.post.match(/,(?!,).*\\}/)) {
530
+ n = a.pre + "{" + a.body + ot + a.post, s = !0;
531
+ continue;
532
+ }
533
+ return F(r, c + "{" + a.body + "}" + a.post, [""], t, e, i);
534
+ }
535
+ o && (i = s && !u, o = !1);
536
+ let p;
537
+ if (u)
538
+ p = Ne(a.body, h, t);
539
+ else {
540
+ let g = It(a.body);
541
+ if (g.length === 1 && g[0] !== void 0 && (g = nt(g[0], t, e, !1).map(De), g.length === 1)) {
542
+ if (r = F(r, c + g[0], [""], t, e, i && !a.post.length), !a.post.length)
543
+ break;
544
+ n = a.post;
545
+ continue;
546
+ }
547
+ p = [];
548
+ for (let d = 0; d < g.length; d++)
549
+ p.push.apply(p, nt(g[d], t, e, !1));
550
+ }
551
+ if (r = F(r, c, p, t, e, i && !a.post.length), !a.post.length)
552
+ break;
553
+ n = a.post;
554
+ }
555
+ return r;
556
+ }
557
+ const Ce = 1024 * 64, G = (n) => {
558
+ if (typeof n != "string")
559
+ throw new TypeError("invalid pattern");
560
+ if (n.length > Ce)
561
+ throw new TypeError("pattern is too long");
562
+ }, ve = {
563
+ "[:alnum:]": ["\\\\p{L}\\\\p{Nl}\\\\p{Nd}", !0],
564
+ "[:alpha:]": ["\\\\p{L}\\\\p{Nl}", !0],
565
+ "[:ascii:]": ["\\\\x00-\\\\x7f", !1],
566
+ "[:blank:]": ["\\\\p{Zs}\\\\t", !0],
567
+ "[:cntrl:]": ["\\\\p{Cc}", !0],
568
+ "[:digit:]": ["\\\\p{Nd}", !0],
569
+ "[:graph:]": ["\\\\p{Z}\\\\p{C}", !0, !0],
570
+ "[:lower:]": ["\\\\p{Ll}", !0],
571
+ "[:print:]": ["\\\\p{C}", !0],
572
+ "[:punct:]": ["\\\\p{P}", !0],
573
+ "[:space:]": ["\\\\p{Z}\\\\t\\\\r\\\\n\\\\v\\\\f", !0],
574
+ "[:upper:]": ["\\\\p{Lu}", !0],
575
+ "[:word:]": ["\\\\p{L}\\\\p{Nl}\\\\p{Nd}\\\\p{Pc}", !0],
576
+ "[:xdigit:]": ["A-Fa-f0-9", !1]
577
+ }, P = (n) => n.replace(/[[\\]\\\\-]/g, "\\\\$&"), Fe = (n) => n.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, "\\\\$&"), dt = (n) => n.join(""), Pe = (n, t) => {
578
+ const e = t;
579
+ if (n.charAt(e) !== "[")
580
+ throw new Error("not in a brace expression");
581
+ const s = [], r = [];
582
+ let i = e + 1, o = !1, a = !1, c = !1, l = !1, h = e, u = "";
583
+ t: for (; i < n.length; ) {
584
+ const d = n.charAt(i);
585
+ if ((d === "!" || d === "^") && i === e + 1) {
586
+ l = !0, i++;
587
+ continue;
588
+ }
589
+ if (d === "]" && o && !c) {
590
+ h = i + 1;
591
+ break;
592
+ }
593
+ if (o = !0, d === "\\\\" && !c) {
594
+ c = !0, i++;
595
+ continue;
596
+ }
597
+ if (d === "[" && !c) {
598
+ for (const [E, [w, m, M]] of Object.entries(ve))
599
+ if (n.startsWith(E, i)) {
600
+ if (u)
601
+ return ["$.", !1, n.length - e, !0];
602
+ i += E.length, M ? r.push(w) : s.push(w), a = a || m;
603
+ continue t;
604
+ }
605
+ }
606
+ if (c = !1, u) {
607
+ d > u ? s.push(P(u) + "-" + P(d)) : d === u && s.push(P(d)), u = "", i++;
608
+ continue;
609
+ }
610
+ if (n.startsWith("-]", i + 1)) {
611
+ s.push(P(d + "-")), i += 2;
612
+ continue;
613
+ }
614
+ if (n.startsWith("-", i + 1)) {
615
+ u = d, i += 2;
616
+ continue;
617
+ }
618
+ s.push(P(d)), i++;
619
+ }
620
+ if (h < i)
621
+ return ["", !1, 0, !1];
622
+ if (!s.length && !r.length)
623
+ return ["$.", !1, n.length - e, !0];
624
+ if (r.length === 0 && s.length === 1 && /^\\\\?.$/.test(s[0]) && !l) {
625
+ const d = s[0].length === 2 ? s[0].slice(-1) : s[0];
626
+ return [Fe(d), !1, h - e, !1];
627
+ }
628
+ const f = "[" + (l ? "^" : "") + dt(s) + "]", p = "[" + (l ? "" : "^") + dt(r) + "]";
629
+ return [s.length && r.length ? "(" + f + "|" + p + ")" : s.length ? f : p, a, h - e, !0];
630
+ }, R = (n, { windowsPathsNoEscape: t = !1, magicalBraces: e = !0 } = {}) => e ? t ? n.replace(/\\[([^/\\\\])\\]/g, "$1") : n.replace(/((?!\\\\).|^)\\[([^/\\\\])\\]/g, "$1$2").replace(/\\\\([^/])/g, "$1") : t ? n.replace(/\\[([^/\\\\{}])\\]/g, "$1") : n.replace(/((?!\\\\).|^)\\[([^/\\\\{}])\\]/g, "$1$2").replace(/\\\\([^/{}])/g, "$1");
631
+ var x;
632
+ const Re = /* @__PURE__ */ new Set(["!", "?", "+", "*", "@"]), rt = (n) => Re.has(n), gt = (n) => rt(n.type), ke = /* @__PURE__ */ new Map([
633
+ ["!", ["@"]],
634
+ ["?", ["?", "@"]],
635
+ ["@", ["@"]],
636
+ ["*", ["*", "+", "?", "@"]],
637
+ ["+", ["+", "@"]]
638
+ ]), Ie = /* @__PURE__ */ new Map([
639
+ ["!", ["?"]],
640
+ ["@", ["?"]],
641
+ ["+", ["?", "*"]]
642
+ ]), Le = /* @__PURE__ */ new Map([
643
+ ["!", ["?", "@"]],
644
+ ["?", ["?", "@"]],
645
+ ["@", ["?", "@"]],
646
+ ["*", ["*", "+", "?", "@"]],
647
+ ["+", ["+", "@", "?", "*"]]
648
+ ]), yt = /* @__PURE__ */ new Map([
649
+ ["!", /* @__PURE__ */ new Map([["!", "@"]])],
650
+ [
651
+ "?",
652
+ /* @__PURE__ */ new Map([
653
+ ["*", "*"],
654
+ ["+", "*"]
655
+ ])
656
+ ],
657
+ [
658
+ "@",
659
+ /* @__PURE__ */ new Map([
660
+ ["!", "!"],
661
+ ["?", "?"],
662
+ ["@", "@"],
663
+ ["*", "*"],
664
+ ["+", "+"]
665
+ ])
666
+ ],
667
+ [
668
+ "+",
669
+ /* @__PURE__ */ new Map([
670
+ ["?", "*"],
671
+ ["*", "*"]
672
+ ])
673
+ ]
674
+ ]), He = "(?!(?:^|/)\\\\.\\\\.?(?:$|/))", L = "(?!\\\\.)", ze = /* @__PURE__ */ new Set(["[", "."]), _e = /* @__PURE__ */ new Set(["..", "."]), We = new Set("().*{}+?[]^$\\\\!"), je = (n) => n.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, "\\\\$&"), at = "[^/]", wt = at + "*?", mt = at + "+?";
675
+ let Be = 0;
676
+ class ct {
677
+ type;
678
+ #s;
679
+ #n;
680
+ #r = !1;
681
+ #t = [];
682
+ #e;
683
+ #a;
684
+ #l;
685
+ #c = !1;
686
+ #i;
687
+ #o;
688
+ // set to true if it's an extglob with no children
689
+ // (which really means one child of '')
690
+ #h = !1;
691
+ id = ++Be;
692
+ get depth() {
693
+ return (this.#e?.depth ?? -1) + 1;
694
+ }
695
+ [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
696
+ return {
697
+ "@@type": "AST",
698
+ id: this.id,
699
+ type: this.type,
700
+ root: this.#s.id,
701
+ parent: this.#e?.id,
702
+ depth: this.depth,
703
+ partsLength: this.#t.length,
704
+ parts: this.#t
705
+ };
706
+ }
707
+ constructor(t, e, s = {}) {
708
+ this.type = t, t && (this.#n = !0), this.#e = e, this.#s = this.#e ? this.#e.#s : this, this.#i = this.#s === this ? s : this.#s.#i, this.#l = this.#s === this ? [] : this.#s.#l, t === "!" && !this.#s.#c && this.#l.push(this), this.#a = this.#e ? this.#e.#t.length : 0;
709
+ }
710
+ get hasMagic() {
711
+ if (this.#n !== void 0)
712
+ return this.#n;
713
+ for (const t of this.#t)
714
+ if (typeof t != "string" && (t.type || t.hasMagic))
715
+ return this.#n = !0;
716
+ return this.#n;
717
+ }
718
+ // reconstructs the pattern
719
+ toString() {
720
+ return this.#o !== void 0 ? this.#o : this.type ? this.#o = this.type + "(" + this.#t.map((t) => String(t)).join("|") + ")" : this.#o = this.#t.map((t) => String(t)).join("");
721
+ }
722
+ #w() {
723
+ if (this !== this.#s)
724
+ throw new Error("should only call on root");
725
+ if (this.#c)
726
+ return this;
727
+ this.toString(), this.#c = !0;
728
+ let t;
729
+ for (; t = this.#l.pop(); ) {
730
+ if (t.type !== "!")
731
+ continue;
732
+ let e = t, s = e.#e;
733
+ for (; s; ) {
734
+ for (let r = e.#a + 1; !s.type && r < s.#t.length; r++)
735
+ for (const i of t.#t) {
736
+ if (typeof i == "string")
737
+ throw new Error("string part in extglob AST??");
738
+ i.copyIn(s.#t[r]);
739
+ }
740
+ e = s, s = e.#e;
741
+ }
742
+ }
743
+ return this;
744
+ }
745
+ push(...t) {
746
+ for (const e of t)
747
+ if (e !== "") {
748
+ if (typeof e != "string" && !(e instanceof x && e.#e === this))
749
+ throw new Error("invalid part: " + e);
750
+ this.#t.push(e);
751
+ }
752
+ }
753
+ toJSON() {
754
+ const t = this.type === null ? this.#t.slice().map((e) => typeof e == "string" ? e : e.toJSON()) : [this.type, ...this.#t.map((e) => e.toJSON())];
755
+ return this.isStart() && !this.type && t.unshift([]), this.isEnd() && (this === this.#s || this.#s.#c && this.#e?.type === "!") && t.push({}), t;
756
+ }
757
+ isStart() {
758
+ if (this.#s === this)
759
+ return !0;
760
+ if (!this.#e?.isStart())
761
+ return !1;
762
+ if (this.#a === 0)
763
+ return !0;
764
+ const t = this.#e;
765
+ for (let e = 0; e < this.#a; e++) {
766
+ const s = t.#t[e];
767
+ if (!(s instanceof x && s.type === "!"))
768
+ return !1;
769
+ }
770
+ return !0;
771
+ }
772
+ isEnd() {
773
+ if (this.#s === this || this.#e?.type === "!")
774
+ return !0;
775
+ if (!this.#e?.isEnd())
776
+ return !1;
777
+ if (!this.type)
778
+ return this.#e?.isEnd();
779
+ const t = this.#e ? this.#e.#t.length : 0;
780
+ return this.#a === t - 1;
781
+ }
782
+ copyIn(t) {
783
+ typeof t == "string" ? this.push(t) : this.push(t.clone(this));
784
+ }
785
+ clone(t) {
786
+ const e = new x(this.type, t);
787
+ for (const s of this.#t)
788
+ e.copyIn(s);
789
+ return e;
790
+ }
791
+ static #u(t, e, s, r, i) {
792
+ const o = r.maxExtglobRecursion ?? 2;
793
+ let a = !1, c = !1, l = -1, h = !1;
794
+ if (e.type === null) {
795
+ let d = s, E = "";
796
+ for (; d < t.length; ) {
797
+ const w = t.charAt(d++);
798
+ if (a || w === "\\\\") {
799
+ a = !a, E += w;
800
+ continue;
801
+ }
802
+ if (c) {
803
+ d === l + 1 ? (w === "^" || w === "!") && (h = !0) : w === "]" && !(d === l + 2 && h) && (c = !1), E += w;
804
+ continue;
805
+ } else if (w === "[") {
806
+ c = !0, l = d, h = !1, E += w;
807
+ continue;
808
+ }
809
+ if (!r.noext && rt(w) && t.charAt(d) === "(" && i <= o) {
810
+ e.push(E), E = "";
811
+ const M = new x(w, e);
812
+ d = x.#u(t, M, d, r, i + 1), e.push(M);
813
+ continue;
814
+ }
815
+ E += w;
816
+ }
817
+ return e.push(E), d;
818
+ }
819
+ let u = s + 1, f = new x(null, e);
820
+ const p = [];
821
+ let g = "";
822
+ for (; u < t.length; ) {
823
+ const d = t.charAt(u++);
824
+ if (a || d === "\\\\") {
825
+ a = !a, g += d;
826
+ continue;
827
+ }
828
+ if (c) {
829
+ u === l + 1 ? (d === "^" || d === "!") && (h = !0) : d === "]" && !(u === l + 2 && h) && (c = !1), g += d;
830
+ continue;
831
+ } else if (d === "[") {
832
+ c = !0, l = u, h = !1, g += d;
833
+ continue;
834
+ }
835
+ if (!r.noext && rt(d) && t.charAt(u) === "(" && /* c8 ignore start - the maxDepth is sufficient here */
836
+ (i <= o || e && e.#f(d))) {
837
+ const w = e && e.#f(d) ? 0 : 1;
838
+ f.push(g), g = "";
839
+ const m = new x(d, f);
840
+ f.push(m), u = x.#u(t, m, u, r, i + w);
841
+ continue;
842
+ }
843
+ if (d === "|") {
844
+ f.push(g), g = "", p.push(f), f = new x(null, e);
845
+ continue;
846
+ }
847
+ if (d === ")")
848
+ return g === "" && e.#t.length === 0 && (e.#h = !0), f.push(g), g = "", e.push(...p, f), u;
849
+ g += d;
850
+ }
851
+ return e.type = null, e.#n = void 0, e.#t = [t.substring(s - 1)], u;
852
+ }
853
+ #m(t) {
854
+ return this.#d(t, Ie);
855
+ }
856
+ #d(t, e = ke) {
857
+ if (!t || typeof t != "object" || t.type !== null || t.#t.length !== 1 || this.type === null)
858
+ return !1;
859
+ const s = t.#t[0];
860
+ return !s || typeof s != "object" || s.type === null ? !1 : this.#f(s.type, e);
861
+ }
862
+ #f(t, e = Le) {
863
+ return !!e.get(this.type)?.includes(t);
864
+ }
865
+ #E(t, e) {
866
+ const s = t.#t[0], r = new x(null, s, this.options);
867
+ r.#t.push(""), s.push(r), this.#g(t, e);
868
+ }
869
+ #g(t, e) {
870
+ const s = t.#t[0];
871
+ this.#t.splice(e, 1, ...s.#t);
872
+ for (const r of s.#t)
873
+ typeof r == "object" && (r.#e = this);
874
+ this.#o = void 0;
875
+ }
876
+ #S(t) {
877
+ return !!yt.get(this.type)?.has(t);
878
+ }
879
+ #b(t) {
880
+ if (!t || typeof t != "object" || t.type !== null || t.#t.length !== 1 || this.type === null || this.#t.length !== 1)
881
+ return !1;
882
+ const e = t.#t[0];
883
+ return !e || typeof e != "object" || e.type === null ? !1 : this.#S(e.type);
884
+ }
885
+ #x(t) {
886
+ const e = yt.get(this.type), s = t.#t[0], r = e?.get(s.type);
887
+ if (!r)
888
+ return !1;
889
+ this.#t = s.#t;
890
+ for (const i of this.#t)
891
+ typeof i == "object" && (i.#e = this);
892
+ this.type = r, this.#o = void 0, this.#h = !1;
893
+ }
894
+ static fromGlob(t, e = {}) {
895
+ const s = new x(null, void 0, e);
896
+ return x.#u(t, s, 0, e, 0), s;
897
+ }
898
+ // returns the regular expression if there's magic, or the unescaped
899
+ // string if not.
900
+ toMMPattern() {
901
+ if (this !== this.#s)
902
+ return this.#s.toMMPattern();
903
+ const t = this.toString(), [e, s, r, i] = this.toRegExpSource();
904
+ if (!(r || this.#n || this.#i.nocase && !this.#i.nocaseMagicOnly && t.toUpperCase() !== t.toLowerCase()))
905
+ return s;
906
+ const a = (this.#i.nocase ? "i" : "") + (i ? "u" : "");
907
+ return Object.assign(new RegExp(\`^\${e}$\`, a), {
908
+ _src: e,
909
+ _glob: t
910
+ });
911
+ }
912
+ get options() {
913
+ return this.#i;
914
+ }
915
+ // returns the string match, the regexp source, whether there's magic
916
+ // in the regexp (so a regular expression is required) and whether or
917
+ // not the uflag is needed for the regular expression (for posix classes)
918
+ // TODO: instead of injecting the start/end at this point, just return
919
+ // the BODY of the regexp, along with the start/end portions suitable
920
+ // for binding the start/end in either a joined full-path makeRe context
921
+ // (where we bind to (^|/), or a standalone matchPart context (where
922
+ // we bind to ^, and not /). Otherwise slashes get duped!
923
+ //
924
+ // In part-matching mode, the start is:
925
+ // - if not isStart: nothing
926
+ // - if traversal possible, but not allowed: ^(?!\\.\\.?$)
927
+ // - if dots allowed or not possible: ^
928
+ // - if dots possible and not allowed: ^(?!\\.)
929
+ // end is:
930
+ // - if not isEnd(): nothing
931
+ // - else: $
932
+ //
933
+ // In full-path matching mode, we put the slash at the START of the
934
+ // pattern, so start is:
935
+ // - if first pattern: same as part-matching mode
936
+ // - if not isStart(): nothing
937
+ // - if traversal possible, but not allowed: /(?!\\.\\.?(?:$|/))
938
+ // - if dots allowed or not possible: /
939
+ // - if dots possible and not allowed: /(?!\\.)
940
+ // end is:
941
+ // - if last pattern, same as part-matching mode
942
+ // - else nothing
943
+ //
944
+ // Always put the (?:$|/) on negated tails, though, because that has to be
945
+ // there to bind the end of the negated pattern portion, and it's easier to
946
+ // just stick it in now rather than try to inject it later in the middle of
947
+ // the pattern.
948
+ //
949
+ // We can just always return the same end, and leave it up to the caller
950
+ // to know whether it's going to be used joined or in parts.
951
+ // And, if the start is adjusted slightly, can do the same there:
952
+ // - if not isStart: nothing
953
+ // - if traversal possible, but not allowed: (?:/|^)(?!\\.\\.?$)
954
+ // - if dots allowed or not possible: (?:/|^)
955
+ // - if dots possible and not allowed: (?:/|^)(?!\\.)
956
+ //
957
+ // But it's better to have a simpler binding without a conditional, for
958
+ // performance, so probably better to return both start options.
959
+ //
960
+ // Then the caller just ignores the end if it's not the first pattern,
961
+ // and the start always gets applied.
962
+ //
963
+ // But that's always going to be $ if it's the ending pattern, or nothing,
964
+ // so the caller can just attach $ at the end of the pattern when building.
965
+ //
966
+ // So the todo is:
967
+ // - better detect what kind of start is needed
968
+ // - return both flavors of starting pattern
969
+ // - attach $ at the end of the pattern when creating the actual RegExp
970
+ //
971
+ // Ah, but wait, no, that all only applies to the root when the first pattern
972
+ // is not an extglob. If the first pattern IS an extglob, then we need all
973
+ // that dot prevention biz to live in the extglob portions, because eg
974
+ // +(*|.x*) can match .xy but not .yx.
975
+ //
976
+ // So, return the two flavors if it's #root and the first child is not an
977
+ // AST, otherwise leave it to the child AST to handle it, and there,
978
+ // use the (?:^|/) style of start binding.
979
+ //
980
+ // Even simplified further:
981
+ // - Since the start for a join is eg /(?!\\.) and the start for a part
982
+ // is ^(?!\\.), we can just prepend (?!\\.) to the pattern (either root
983
+ // or start or whatever) and prepend ^ or / at the Regexp construction.
984
+ toRegExpSource(t) {
985
+ const e = t ?? !!this.#i.dot;
986
+ if (this.#s === this && (this.#p(), this.#w()), !gt(this)) {
987
+ const c = this.isStart() && this.isEnd() && !this.#t.some((p) => typeof p != "string"), l = this.#t.map((p) => {
988
+ const [g, d, E, w] = typeof p == "string" ? x.#A(p, this.#n, c) : p.toRegExpSource(t);
989
+ return this.#n = this.#n || E, this.#r = this.#r || w, g;
990
+ }).join("");
991
+ let h = "";
992
+ if (this.isStart() && typeof this.#t[0] == "string" && !(this.#t.length === 1 && _e.has(this.#t[0]))) {
993
+ const g = ze, d = (
994
+ // dots are allowed, and the pattern starts with [ or .
995
+ e && g.has(l.charAt(0)) || // the pattern starts with \\., and then [ or .
996
+ l.startsWith("\\\\.") && g.has(l.charAt(2)) || // the pattern starts with \\.\\., and then [ or .
997
+ l.startsWith("\\\\.\\\\.") && g.has(l.charAt(4))
998
+ ), E = !e && !t && g.has(l.charAt(0));
999
+ h = d ? He : E ? L : "";
1000
+ }
1001
+ let u = "";
1002
+ return this.isEnd() && this.#s.#c && this.#e?.type === "!" && (u = "(?:$|\\\\/)"), [
1003
+ h + l + u,
1004
+ R(l),
1005
+ this.#n = !!this.#n,
1006
+ this.#r
1007
+ ];
1008
+ }
1009
+ const s = this.type === "*" || this.type === "+", r = this.type === "!" ? "(?:(?!(?:" : "(?:";
1010
+ let i = this.#y(e);
1011
+ if (this.isStart() && this.isEnd() && !i && this.type !== "!") {
1012
+ const c = this.toString(), l = this;
1013
+ return l.#t = [c], l.type = null, l.#n = void 0, [c, R(this.toString()), !1, !1];
1014
+ }
1015
+ let o = !s || t || e || !L ? "" : this.#y(!0);
1016
+ o === i && (o = ""), o && (i = \`(?:\${i})(?:\${o})*?\`);
1017
+ let a = "";
1018
+ if (this.type === "!" && this.#h)
1019
+ a = (this.isStart() && !e ? L : "") + mt;
1020
+ else {
1021
+ const c = this.type === "!" ? (
1022
+ // !() must match something,but !(x) can match ''
1023
+ "))" + (this.isStart() && !e && !t ? L : "") + wt + ")"
1024
+ ) : this.type === "@" ? ")" : this.type === "?" ? ")?" : this.type === "+" && o ? ")" : this.type === "*" && o ? ")?" : \`)\${this.type}\`;
1025
+ a = r + i + c;
1026
+ }
1027
+ return [
1028
+ a,
1029
+ R(i),
1030
+ this.#n = !!this.#n,
1031
+ this.#r
1032
+ ];
1033
+ }
1034
+ #p() {
1035
+ if (gt(this)) {
1036
+ let t = 0, e = !1;
1037
+ do {
1038
+ e = !0;
1039
+ for (let s = 0; s < this.#t.length; s++) {
1040
+ const r = this.#t[s];
1041
+ typeof r == "object" && (r.#p(), this.#d(r) ? (e = !1, this.#g(r, s)) : this.#m(r) ? (e = !1, this.#E(r, s)) : this.#b(r) && (e = !1, this.#x(r)));
1042
+ }
1043
+ } while (!e && ++t < 10);
1044
+ } else
1045
+ for (const t of this.#t)
1046
+ typeof t == "object" && t.#p();
1047
+ this.#o = void 0;
1048
+ }
1049
+ #y(t) {
1050
+ return this.#t.map((e) => {
1051
+ if (typeof e == "string")
1052
+ throw new Error("string type in extglob ast??");
1053
+ const [s, r, i, o] = e.toRegExpSource(t);
1054
+ return this.#r = this.#r || o, s;
1055
+ }).filter((e) => !(this.isStart() && this.isEnd()) || !!e).join("|");
1056
+ }
1057
+ static #A(t, e, s = !1) {
1058
+ let r = !1, i = "", o = !1, a = !1;
1059
+ for (let c = 0; c < t.length; c++) {
1060
+ const l = t.charAt(c);
1061
+ if (r) {
1062
+ r = !1, i += (We.has(l) ? "\\\\" : "") + l;
1063
+ continue;
1064
+ }
1065
+ if (l === "*") {
1066
+ if (a)
1067
+ continue;
1068
+ a = !0, i += s && /^[*]+$/.test(t) ? mt : wt, e = !0;
1069
+ continue;
1070
+ } else
1071
+ a = !1;
1072
+ if (l === "\\\\") {
1073
+ c === t.length - 1 ? i += "\\\\\\\\" : r = !0;
1074
+ continue;
1075
+ }
1076
+ if (l === "[") {
1077
+ const [h, u, f, p] = Pe(t, c);
1078
+ if (f) {
1079
+ i += h, o = o || u, c += f - 1, e = e || p;
1080
+ continue;
1081
+ }
1082
+ }
1083
+ if (l === "?") {
1084
+ i += at, e = !0;
1085
+ continue;
1086
+ }
1087
+ i += je(l);
1088
+ }
1089
+ return [i, R(t), !!e, o];
1090
+ }
1091
+ }
1092
+ x = ct;
1093
+ const Ge = (n, { windowsPathsNoEscape: t = !1, magicalBraces: e = !1 } = {}) => e ? t ? n.replace(/[?*()[\\]{}]/g, "[$&]") : n.replace(/[?*()[\\]\\\\{}]/g, "\\\\$&") : t ? n.replace(/[?*()[\\]]/g, "[$&]") : n.replace(/[?*()[\\]\\\\]/g, "\\\\$&"), b = (n, t, e = {}) => (G(t), !e.nocomment && t.charAt(0) === "#" ? !1 : new q(t, e).match(n)), Ue = /^\\*+([^+@!?*[(]*)$/, qe = (n) => (t) => !t.startsWith(".") && t.endsWith(n), Ve = (n) => (t) => t.endsWith(n), Xe = (n) => (n = n.toLowerCase(), (t) => !t.startsWith(".") && t.toLowerCase().endsWith(n)), Ye = (n) => (n = n.toLowerCase(), (t) => t.toLowerCase().endsWith(n)), Ze = /^\\*+\\.\\*+$/, Je = (n) => !n.startsWith(".") && n.includes("."), Qe = (n) => n !== "." && n !== ".." && n.includes("."), Ke = /^\\.\\*+$/, ts = (n) => n !== "." && n !== ".." && n.startsWith("."), es = /^\\*+$/, ss = (n) => n.length !== 0 && !n.startsWith("."), ns = (n) => n.length !== 0 && n !== "." && n !== "..", rs = /^\\?+([^+@!?*[(]*)?$/, is = ([n, t = ""]) => {
1094
+ const e = Lt([n]);
1095
+ return t ? (t = t.toLowerCase(), (s) => e(s) && s.toLowerCase().endsWith(t)) : e;
1096
+ }, os = ([n, t = ""]) => {
1097
+ const e = Ht([n]);
1098
+ return t ? (t = t.toLowerCase(), (s) => e(s) && s.toLowerCase().endsWith(t)) : e;
1099
+ }, as = ([n, t = ""]) => {
1100
+ const e = Ht([n]);
1101
+ return t ? (s) => e(s) && s.endsWith(t) : e;
1102
+ }, cs = ([n, t = ""]) => {
1103
+ const e = Lt([n]);
1104
+ return t ? (s) => e(s) && s.endsWith(t) : e;
1105
+ }, Lt = ([n]) => {
1106
+ const t = n.length;
1107
+ return (e) => e.length === t && !e.startsWith(".");
1108
+ }, Ht = ([n]) => {
1109
+ const t = n.length;
1110
+ return (e) => e.length === t && e !== "." && e !== "..";
1111
+ }, zt = typeof process == "object" && process ? typeof process.env == "object" && process.env && process.env.__MINIMATCH_TESTING_PLATFORM__ || process.platform : "posix", Et = {
1112
+ win32: { sep: "\\\\" },
1113
+ posix: { sep: "/" }
1114
+ }, ls = zt === "win32" ? Et.win32.sep : Et.posix.sep;
1115
+ b.sep = ls;
1116
+ const S = /* @__PURE__ */ Symbol("globstar **");
1117
+ b.GLOBSTAR = S;
1118
+ const hs = "[^/]", us = hs + "*?", fs = "(?:(?!(?:\\\\/|^)(?:\\\\.{1,2})($|\\\\/)).)*?", ps = "(?:(?!(?:\\\\/|^)\\\\.).)*?", ds = (n, t = {}) => (e) => b(e, n, t);
1119
+ b.filter = ds;
1120
+ const D = (n, t = {}) => Object.assign({}, n, t), gs = (n) => {
1121
+ if (!n || typeof n != "object" || !Object.keys(n).length)
1122
+ return b;
1123
+ const t = b;
1124
+ return Object.assign((s, r, i = {}) => t(s, r, D(n, i)), {
1125
+ Minimatch: class extends t.Minimatch {
1126
+ constructor(r, i = {}) {
1127
+ super(r, D(n, i));
1128
+ }
1129
+ static defaults(r) {
1130
+ return t.defaults(D(n, r)).Minimatch;
1131
+ }
1132
+ },
1133
+ AST: class extends t.AST {
1134
+ /* c8 ignore start */
1135
+ constructor(r, i, o = {}) {
1136
+ super(r, i, D(n, o));
1137
+ }
1138
+ /* c8 ignore stop */
1139
+ static fromGlob(r, i = {}) {
1140
+ return t.AST.fromGlob(r, D(n, i));
1141
+ }
1142
+ },
1143
+ unescape: (s, r = {}) => t.unescape(s, D(n, r)),
1144
+ escape: (s, r = {}) => t.escape(s, D(n, r)),
1145
+ filter: (s, r = {}) => t.filter(s, D(n, r)),
1146
+ defaults: (s) => t.defaults(D(n, s)),
1147
+ makeRe: (s, r = {}) => t.makeRe(s, D(n, r)),
1148
+ braceExpand: (s, r = {}) => t.braceExpand(s, D(n, r)),
1149
+ match: (s, r, i = {}) => t.match(s, r, D(n, i)),
1150
+ sep: t.sep,
1151
+ GLOBSTAR: S
1152
+ });
1153
+ };
1154
+ b.defaults = gs;
1155
+ const _t = (n, t = {}) => (G(n), t.nobrace || !/\\{(?:(?!\\{).)*\\}/.test(n) ? [n] : Oe(n, { max: t.braceExpandMax }));
1156
+ b.braceExpand = _t;
1157
+ const ys = (n, t = {}) => new q(n, t).makeRe();
1158
+ b.makeRe = ys;
1159
+ const ws = (n, t, e = {}) => {
1160
+ const s = new q(t, e);
1161
+ return n = n.filter((r) => s.match(r)), s.options.nonull && !n.length && n.push(t), n;
1162
+ };
1163
+ b.match = ws;
1164
+ const St = /[?*]|[+@!]\\(.*?\\)|\\[|\\]/, ms = (n) => n.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, "\\\\$&");
1165
+ class q {
1166
+ options;
1167
+ set;
1168
+ pattern;
1169
+ windowsPathsNoEscape;
1170
+ nonegate;
1171
+ negate;
1172
+ comment;
1173
+ empty;
1174
+ preserveMultipleSlashes;
1175
+ partial;
1176
+ globSet;
1177
+ globParts;
1178
+ nocase;
1179
+ isWindows;
1180
+ platform;
1181
+ windowsNoMagicRoot;
1182
+ maxGlobstarRecursion;
1183
+ regexp;
1184
+ constructor(t, e = {}) {
1185
+ G(t), e = e || {}, this.options = e, this.maxGlobstarRecursion = e.maxGlobstarRecursion ?? 200, this.pattern = t, this.platform = e.platform || zt, this.isWindows = this.platform === "win32";
1186
+ const s = "allowWindowsEscape";
1187
+ this.windowsPathsNoEscape = !!e.windowsPathsNoEscape || e[s] === !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();
1188
+ }
1189
+ hasMagic() {
1190
+ if (this.options.magicalBraces && this.set.length > 1)
1191
+ return !0;
1192
+ for (const t of this.set)
1193
+ for (const e of t)
1194
+ if (typeof e != "string")
1195
+ return !0;
1196
+ return !1;
1197
+ }
1198
+ debug(...t) {
1199
+ }
1200
+ make() {
1201
+ const t = this.pattern, e = this.options;
1202
+ if (!e.nocomment && t.charAt(0) === "#") {
1203
+ this.comment = !0;
1204
+ return;
1205
+ }
1206
+ if (!t) {
1207
+ this.empty = !0;
1208
+ return;
1209
+ }
1210
+ this.parseNegate(), this.globSet = [...new Set(this.braceExpand())], e.debug && (this.debug = (...i) => console.error(...i)), this.debug(this.pattern, this.globSet);
1211
+ const s = this.globSet.map((i) => this.slashSplit(i));
1212
+ this.globParts = this.preprocess(s), this.debug(this.pattern, this.globParts);
1213
+ let r = this.globParts.map((i, o, a) => {
1214
+ if (this.isWindows && this.windowsNoMagicRoot) {
1215
+ const c = i[0] === "" && i[1] === "" && (i[2] === "?" || !St.test(i[2])) && !St.test(i[3]), l = /^[a-z]:/i.test(i[0]);
1216
+ if (c)
1217
+ return [
1218
+ ...i.slice(0, 4),
1219
+ ...i.slice(4).map((h) => this.parse(h))
1220
+ ];
1221
+ if (l)
1222
+ return [i[0], ...i.slice(1).map((h) => this.parse(h))];
1223
+ }
1224
+ return i.map((c) => this.parse(c));
1225
+ });
1226
+ if (this.debug(this.pattern, r), this.set = r.filter((i) => i.indexOf(!1) === -1), this.isWindows)
1227
+ for (let i = 0; i < this.set.length; i++) {
1228
+ const o = this.set[i];
1229
+ o[0] === "" && o[1] === "" && this.globParts[i][2] === "?" && typeof o[3] == "string" && /^[a-z]:$/i.test(o[3]) && (o[2] = "?");
1230
+ }
1231
+ this.debug(this.pattern, this.set);
1232
+ }
1233
+ // various transforms to equivalent pattern sets that are
1234
+ // faster to process in a filesystem walk. The goal is to
1235
+ // eliminate what we can, and push all ** patterns as far
1236
+ // to the right as possible, even if it increases the number
1237
+ // of patterns that we have to process.
1238
+ preprocess(t) {
1239
+ if (this.options.noglobstar)
1240
+ for (const s of t)
1241
+ for (let r = 0; r < s.length; r++)
1242
+ s[r] === "**" && (s[r] = "*");
1243
+ const { optimizationLevel: e = 1 } = this.options;
1244
+ return e >= 2 ? (t = this.firstPhasePreProcess(t), t = this.secondPhasePreProcess(t)) : e >= 1 ? t = this.levelOneOptimize(t) : t = this.adjascentGlobstarOptimize(t), t;
1245
+ }
1246
+ // just get rid of adjascent ** portions
1247
+ adjascentGlobstarOptimize(t) {
1248
+ return t.map((e) => {
1249
+ let s = -1;
1250
+ for (; (s = e.indexOf("**", s + 1)) !== -1; ) {
1251
+ let r = s;
1252
+ for (; e[r + 1] === "**"; )
1253
+ r++;
1254
+ r !== s && e.splice(s, r - s);
1255
+ }
1256
+ return e;
1257
+ });
1258
+ }
1259
+ // get rid of adjascent ** and resolve .. portions
1260
+ levelOneOptimize(t) {
1261
+ return t.map((e) => (e = e.reduce((s, r) => {
1262
+ const i = s[s.length - 1];
1263
+ return r === "**" && i === "**" ? s : r === ".." && i && i !== ".." && i !== "." && i !== "**" ? (s.pop(), s) : (s.push(r), s);
1264
+ }, []), e.length === 0 ? [""] : e));
1265
+ }
1266
+ levelTwoFileOptimize(t) {
1267
+ Array.isArray(t) || (t = this.slashSplit(t));
1268
+ let e = !1;
1269
+ do {
1270
+ if (e = !1, !this.preserveMultipleSlashes) {
1271
+ for (let r = 1; r < t.length - 1; r++) {
1272
+ const i = t[r];
1273
+ r === 1 && i === "" && t[0] === "" || (i === "." || i === "") && (e = !0, t.splice(r, 1), r--);
1274
+ }
1275
+ t[0] === "." && t.length === 2 && (t[1] === "." || t[1] === "") && (e = !0, t.pop());
1276
+ }
1277
+ let s = 0;
1278
+ for (; (s = t.indexOf("..", s + 1)) !== -1; ) {
1279
+ const r = t[s - 1];
1280
+ r && r !== "." && r !== ".." && r !== "**" && !(this.isWindows && /^[a-z]:$/i.test(r)) && (e = !0, t.splice(s - 1, 2), s -= 2);
1281
+ }
1282
+ } while (e);
1283
+ return t.length === 0 ? [""] : t;
1284
+ }
1285
+ // First phase: single-pattern processing
1286
+ // <pre> is 1 or more portions
1287
+ // <rest> is 1 or more portions
1288
+ // <p> is any portion other than ., .., '', or **
1289
+ // <e> is . or ''
1290
+ //
1291
+ // **/.. is *brutal* for filesystem walking performance, because
1292
+ // it effectively resets the recursive walk each time it occurs,
1293
+ // and ** cannot be reduced out by a .. pattern part like a regexp
1294
+ // or most strings (other than .., ., and '') can be.
1295
+ //
1296
+ // <pre>/**/../<p>/<p>/<rest> -> {<pre>/../<p>/<p>/<rest>,<pre>/**/<p>/<p>/<rest>}
1297
+ // <pre>/<e>/<rest> -> <pre>/<rest>
1298
+ // <pre>/<p>/../<rest> -> <pre>/<rest>
1299
+ // **/**/<rest> -> **/<rest>
1300
+ //
1301
+ // **/*/<rest> -> */**/<rest> <== not valid because ** doesn't follow
1302
+ // this WOULD be allowed if ** did follow symlinks, or * didn't
1303
+ firstPhasePreProcess(t) {
1304
+ let e = !1;
1305
+ do {
1306
+ e = !1;
1307
+ for (let s of t) {
1308
+ let r = -1;
1309
+ for (; (r = s.indexOf("**", r + 1)) !== -1; ) {
1310
+ let o = r;
1311
+ for (; s[o + 1] === "**"; )
1312
+ o++;
1313
+ o > r && s.splice(r + 1, o - r);
1314
+ let a = s[r + 1];
1315
+ const c = s[r + 2], l = s[r + 3];
1316
+ if (a !== ".." || !c || c === "." || c === ".." || !l || l === "." || l === "..")
1317
+ continue;
1318
+ e = !0, s.splice(r, 1);
1319
+ const h = s.slice(0);
1320
+ h[r] = "**", t.push(h), r--;
1321
+ }
1322
+ if (!this.preserveMultipleSlashes) {
1323
+ for (let o = 1; o < s.length - 1; o++) {
1324
+ const a = s[o];
1325
+ o === 1 && a === "" && s[0] === "" || (a === "." || a === "") && (e = !0, s.splice(o, 1), o--);
1326
+ }
1327
+ s[0] === "." && s.length === 2 && (s[1] === "." || s[1] === "") && (e = !0, s.pop());
1328
+ }
1329
+ let i = 0;
1330
+ for (; (i = s.indexOf("..", i + 1)) !== -1; ) {
1331
+ const o = s[i - 1];
1332
+ if (o && o !== "." && o !== ".." && o !== "**") {
1333
+ e = !0;
1334
+ const c = i === 1 && s[i + 1] === "**" ? ["."] : [];
1335
+ s.splice(i - 1, 2, ...c), s.length === 0 && s.push(""), i -= 2;
1336
+ }
1337
+ }
1338
+ }
1339
+ } while (e);
1340
+ return t;
1341
+ }
1342
+ // second phase: multi-pattern dedupes
1343
+ // {<pre>/*/<rest>,<pre>/<p>/<rest>} -> <pre>/*/<rest>
1344
+ // {<pre>/<rest>,<pre>/<rest>} -> <pre>/<rest>
1345
+ // {<pre>/**/<rest>,<pre>/<rest>} -> <pre>/**/<rest>
1346
+ //
1347
+ // {<pre>/**/<rest>,<pre>/**/<p>/<rest>} -> <pre>/**/<rest>
1348
+ // ^-- not valid because ** doens't follow symlinks
1349
+ secondPhasePreProcess(t) {
1350
+ for (let e = 0; e < t.length - 1; e++)
1351
+ for (let s = e + 1; s < t.length; s++) {
1352
+ const r = this.partsMatch(t[e], t[s], !this.preserveMultipleSlashes);
1353
+ if (r) {
1354
+ t[e] = [], t[s] = r;
1355
+ break;
1356
+ }
1357
+ }
1358
+ return t.filter((e) => e.length);
1359
+ }
1360
+ partsMatch(t, e, s = !1) {
1361
+ let r = 0, i = 0, o = [], a = "";
1362
+ for (; r < t.length && i < e.length; )
1363
+ if (t[r] === e[i])
1364
+ o.push(a === "b" ? e[i] : t[r]), r++, i++;
1365
+ else if (s && t[r] === "**" && e[i] === t[r + 1])
1366
+ o.push(t[r]), r++;
1367
+ else if (s && e[i] === "**" && t[r] === e[i + 1])
1368
+ o.push(e[i]), i++;
1369
+ else if (t[r] === "*" && e[i] && (this.options.dot || !e[i].startsWith(".")) && e[i] !== "**") {
1370
+ if (a === "b")
1371
+ return !1;
1372
+ a = "a", o.push(t[r]), r++, i++;
1373
+ } else if (e[i] === "*" && t[r] && (this.options.dot || !t[r].startsWith(".")) && t[r] !== "**") {
1374
+ if (a === "a")
1375
+ return !1;
1376
+ a = "b", o.push(e[i]), r++, i++;
1377
+ } else
1378
+ return !1;
1379
+ return t.length === e.length && o;
1380
+ }
1381
+ parseNegate() {
1382
+ if (this.nonegate)
1383
+ return;
1384
+ const t = this.pattern;
1385
+ let e = !1, s = 0;
1386
+ for (let r = 0; r < t.length && t.charAt(r) === "!"; r++)
1387
+ e = !e, s++;
1388
+ s && (this.pattern = t.slice(s)), this.negate = e;
1389
+ }
1390
+ // set partial to true to test if, for example,
1391
+ // "/a/b" matches the start of "/*/b/*/d"
1392
+ // Partial means, if you run out of file before you run
1393
+ // out of pattern, then that's fine, as long as all
1394
+ // the parts match.
1395
+ matchOne(t, e, s = !1) {
1396
+ let r = 0, i = 0;
1397
+ if (this.isWindows) {
1398
+ const a = typeof t[0] == "string" && /^[a-z]:$/i.test(t[0]), c = !a && t[0] === "" && t[1] === "" && t[2] === "?" && /^[a-z]:$/i.test(t[3]), l = typeof e[0] == "string" && /^[a-z]:$/i.test(e[0]), h = !l && e[0] === "" && e[1] === "" && e[2] === "?" && typeof e[3] == "string" && /^[a-z]:$/i.test(e[3]), u = c ? 3 : a ? 0 : void 0, f = h ? 3 : l ? 0 : void 0;
1399
+ if (typeof u == "number" && typeof f == "number") {
1400
+ const [p, g] = [
1401
+ t[u],
1402
+ e[f]
1403
+ ];
1404
+ p.toLowerCase() === g.toLowerCase() && (e[f] = p, i = f, r = u);
1405
+ }
1406
+ }
1407
+ const { optimizationLevel: o = 1 } = this.options;
1408
+ return o >= 2 && (t = this.levelTwoFileOptimize(t)), e.includes(S) ? this.#s(t, e, s, r, i) : this.#r(t, e, s, r, i);
1409
+ }
1410
+ #s(t, e, s, r, i) {
1411
+ const o = e.indexOf(S, i), a = e.lastIndexOf(S), [c, l, h] = s ? [
1412
+ e.slice(i, o),
1413
+ e.slice(o + 1),
1414
+ []
1415
+ ] : [
1416
+ e.slice(i, o),
1417
+ e.slice(o + 1, a),
1418
+ e.slice(a + 1)
1419
+ ];
1420
+ if (c.length) {
1421
+ const m = t.slice(r, r + c.length);
1422
+ if (!this.#r(m, c, s, 0, 0))
1423
+ return !1;
1424
+ r += c.length, i += c.length;
1425
+ }
1426
+ let u = 0;
1427
+ if (h.length) {
1428
+ if (h.length + r > t.length)
1429
+ return !1;
1430
+ let m = t.length - h.length;
1431
+ if (this.#r(t, h, s, m, 0))
1432
+ u = h.length;
1433
+ else {
1434
+ if (t[t.length - 1] !== "" || r + h.length === t.length || (m--, !this.#r(t, h, s, m, 0)))
1435
+ return !1;
1436
+ u = h.length + 1;
1437
+ }
1438
+ }
1439
+ if (!l.length) {
1440
+ let m = !!u;
1441
+ for (let M = r; M < t.length - u; M++) {
1442
+ const V = String(t[M]);
1443
+ if (m = !0, V === "." || V === ".." || !this.options.dot && V.startsWith("."))
1444
+ return !1;
1445
+ }
1446
+ return s || m;
1447
+ }
1448
+ const f = [[[], 0]];
1449
+ let p = f[0], g = 0;
1450
+ const d = [0];
1451
+ for (const m of l)
1452
+ m === S ? (d.push(g), p = [[], 0], f.push(p)) : (p[0].push(m), g++);
1453
+ let E = f.length - 1;
1454
+ const w = t.length - u;
1455
+ for (const m of f)
1456
+ m[1] = w - (d[E--] + m[0].length);
1457
+ return !!this.#n(t, f, r, 0, s, 0, !!u);
1458
+ }
1459
+ // return false for "nope, not matching"
1460
+ // return null for "not matching, cannot keep trying"
1461
+ #n(t, e, s, r, i, o, a) {
1462
+ const c = e[r];
1463
+ if (!c) {
1464
+ for (let u = s; u < t.length; u++) {
1465
+ a = !0;
1466
+ const f = t[u];
1467
+ if (f === "." || f === ".." || !this.options.dot && f.startsWith("."))
1468
+ return !1;
1469
+ }
1470
+ return a;
1471
+ }
1472
+ const [l, h] = c;
1473
+ for (; s <= h; ) {
1474
+ if (this.#r(t.slice(0, s + l.length), l, i, s, 0) && o < this.maxGlobstarRecursion) {
1475
+ const p = this.#n(t, e, s + l.length, r + 1, i, o + 1, a);
1476
+ if (p !== !1)
1477
+ return p;
1478
+ }
1479
+ const f = t[s];
1480
+ if (f === "." || f === ".." || !this.options.dot && f.startsWith("."))
1481
+ return !1;
1482
+ s++;
1483
+ }
1484
+ return i || null;
1485
+ }
1486
+ #r(t, e, s, r, i) {
1487
+ let o, a, c, l;
1488
+ for (o = r, a = i, l = t.length, c = e.length; o < l && a < c; o++, a++) {
1489
+ this.debug("matchOne loop");
1490
+ let h = e[a], u = t[o];
1491
+ if (this.debug(e, h, u), h === !1 || h === S)
1492
+ return !1;
1493
+ let f;
1494
+ if (typeof h == "string" ? (f = u === h, this.debug("string match", h, u, f)) : (f = h.test(u), this.debug("pattern match", h, u, f)), !f)
1495
+ return !1;
1496
+ }
1497
+ if (o === l && a === c)
1498
+ return !0;
1499
+ if (o === l)
1500
+ return s;
1501
+ if (a === c)
1502
+ return o === l - 1 && t[o] === "";
1503
+ throw new Error("wtf?");
1504
+ }
1505
+ braceExpand() {
1506
+ return _t(this.pattern, this.options);
1507
+ }
1508
+ parse(t) {
1509
+ G(t);
1510
+ const e = this.options;
1511
+ if (t === "**")
1512
+ return S;
1513
+ if (t === "")
1514
+ return "";
1515
+ let s, r = null;
1516
+ (s = t.match(es)) ? r = e.dot ? ns : ss : (s = t.match(Ue)) ? r = (e.nocase ? e.dot ? Ye : Xe : e.dot ? Ve : qe)(s[1]) : (s = t.match(rs)) ? r = (e.nocase ? e.dot ? os : is : e.dot ? as : cs)(s) : (s = t.match(Ze)) ? r = e.dot ? Qe : Je : (s = t.match(Ke)) && (r = ts);
1517
+ const i = ct.fromGlob(t, this.options).toMMPattern();
1518
+ return r && typeof i == "object" && Reflect.defineProperty(i, "test", { value: r }), i;
1519
+ }
1520
+ makeRe() {
1521
+ if (this.regexp || this.regexp === !1)
1522
+ return this.regexp;
1523
+ const t = this.set;
1524
+ if (!t.length)
1525
+ return this.regexp = !1, this.regexp;
1526
+ const e = this.options, s = e.noglobstar ? us : e.dot ? fs : ps, r = new Set(e.nocase ? ["i"] : []);
1527
+ let i = t.map((c) => {
1528
+ const l = c.map((u) => {
1529
+ if (u instanceof RegExp)
1530
+ for (const f of u.flags.split(""))
1531
+ r.add(f);
1532
+ return typeof u == "string" ? ms(u) : u === S ? S : u._src;
1533
+ });
1534
+ l.forEach((u, f) => {
1535
+ const p = l[f + 1], g = l[f - 1];
1536
+ u !== S || g === S || (g === void 0 ? p !== void 0 && p !== S ? l[f + 1] = "(?:\\\\/|" + s + "\\\\/)?" + p : l[f] = s : p === void 0 ? l[f - 1] = g + "(?:\\\\/|\\\\/" + s + ")?" : p !== S && (l[f - 1] = g + "(?:\\\\/|\\\\/" + s + "\\\\/)" + p, l[f + 1] = S));
1537
+ });
1538
+ const h = l.filter((u) => u !== S);
1539
+ if (this.partial && h.length >= 1) {
1540
+ const u = [];
1541
+ for (let f = 1; f <= h.length; f++)
1542
+ u.push(h.slice(0, f).join("/"));
1543
+ return "(?:" + u.join("|") + ")";
1544
+ }
1545
+ return h.join("/");
1546
+ }).join("|");
1547
+ const [o, a] = t.length > 1 ? ["(?:", ")"] : ["", ""];
1548
+ i = "^" + o + i + a + "$", this.partial && (i = "^(?:\\\\/|" + o + i.slice(1, -1) + a + ")$"), this.negate && (i = "^(?!" + i + ").+$");
1549
+ try {
1550
+ this.regexp = new RegExp(i, [...r].join(""));
1551
+ } catch {
1552
+ this.regexp = !1;
1553
+ }
1554
+ return this.regexp;
1555
+ }
1556
+ slashSplit(t) {
1557
+ return this.preserveMultipleSlashes ? t.split("/") : this.isWindows && /^\\/\\/[^/]+/.test(t) ? ["", ...t.split(/\\/+/)] : t.split(/\\/+/);
1558
+ }
1559
+ match(t, e = this.partial) {
1560
+ if (this.debug("match", t, this.pattern), this.comment)
1561
+ return !1;
1562
+ if (this.empty)
1563
+ return t === "";
1564
+ if (t === "/" && e)
1565
+ return !0;
1566
+ const s = this.options;
1567
+ this.isWindows && (t = t.split("\\\\").join("/"));
1568
+ const r = this.slashSplit(t);
1569
+ this.debug(this.pattern, "split", r);
1570
+ const i = this.set;
1571
+ this.debug(this.pattern, "set", i);
1572
+ let o = r[r.length - 1];
1573
+ if (!o)
1574
+ for (let a = r.length - 2; !o && a >= 0; a--)
1575
+ o = r[a];
1576
+ for (const a of i) {
1577
+ let c = r;
1578
+ if (s.matchBase && a.length === 1 && (c = [o]), this.matchOne(c, a, e))
1579
+ return s.flipNegate ? !0 : !this.negate;
1580
+ }
1581
+ return s.flipNegate ? !1 : this.negate;
1582
+ }
1583
+ static defaults(t) {
1584
+ return b.defaults(t).Minimatch;
1585
+ }
1586
+ }
1587
+ b.AST = ct;
1588
+ b.Minimatch = q;
1589
+ b.escape = Ge;
1590
+ b.unescape = R;
1591
+ function Es() {
1592
+ if (!("storage" in navigator) || !("getDirectory" in navigator.storage))
1593
+ throw new se();
1594
+ }
1595
+ function Ss(n, t) {
1596
+ const e = v(n || "/"), s = v(ht(t));
1597
+ return e === "/" ? s : s === "/" ? e : \`\${e.replace(/\\/$/, "")}\${s}\`;
1598
+ }
1599
+ async function Wt(n, t, e = "/") {
1600
+ if (typeof navigator < "u" && navigator.locks?.request) {
1601
+ const s = Ss(e, n).replace(/\\/+/g, "/");
1602
+ return navigator.locks.request(\`opfs:\${s}\`, { mode: "exclusive" }, t);
1603
+ }
1604
+ return t();
1605
+ }
1606
+ function C(n) {
1607
+ return Array.isArray(n) ? n : (n.startsWith("~/") ? n.slice(2) : n).split("/").filter(Boolean);
1608
+ }
1609
+ function lt(n) {
1610
+ return typeof n == "string" ? n ?? "/" : \`/\${n.join("/")}\`;
1611
+ }
1612
+ function it(n) {
1613
+ const t = C(n);
1614
+ return t[t.length - 1] || "";
1615
+ }
1616
+ function J(n) {
1617
+ const t = C(n);
1618
+ return t.pop(), lt(t);
1619
+ }
1620
+ function v(n) {
1621
+ return !n || n === "/" ? "/" : n.startsWith("~/") ? \`/\${n.slice(2)}\` : n.startsWith("/") ? n : \`/\${n}\`;
1622
+ }
1623
+ function bs(n, t = !1) {
1624
+ return n = n.replace(/\\/$/, ""), t && !n.includes("*") ? \`\${n}/**\` : n;
1625
+ }
1626
+ function Q(n, t) {
1627
+ return b(n, t, {
1628
+ dot: !0,
1629
+ matchBase: !0
1630
+ });
1631
+ }
1632
+ function ht(n) {
1633
+ const t = v(n), e = C(t), s = [];
1634
+ for (const r of e)
1635
+ if (!(r === "." || r === ""))
1636
+ if (r === "..") {
1637
+ if (s.length === 0)
1638
+ continue;
1639
+ s.pop();
1640
+ } else
1641
+ s.push(r);
1642
+ return lt(s);
1643
+ }
1644
+ async function xs(n, t = "SHA-1", e = 50 * 1024 * 1024) {
1645
+ if (n instanceof File && (n = await n.arrayBuffer()), n.byteLength > e)
1646
+ throw new Error(\`File size \${n.byteLength} bytes exceeds maximum allowed size \${e} bytes\`);
1647
+ const s = new Uint8Array(n), r = await crypto.subtle.digest(t, s);
1648
+ return Array.from(new Uint8Array(r)).map((o) => o.toString(16).padStart(2, "0")).join("");
1649
+ }
1650
+ async function As(n, t, e = {}) {
1651
+ const s = it(t);
1652
+ return Wt(t, async () => {
1653
+ const r = e.recursive ?? !1, i = e.force ?? !1;
1654
+ try {
1655
+ await n.removeEntry(s, { recursive: r });
1656
+ } catch (o) {
1657
+ if (o.name === "NotFoundError" && i)
1658
+ return;
1659
+ const a = o.name === "TypeMismatchError" && !r;
1660
+ throw A(o, {
1661
+ path: t,
1662
+ operation: "remove",
1663
+ isDirectory: a
1664
+ });
1665
+ }
1666
+ }, e.root ?? "/");
1667
+ }
1668
+ function bt(n, t, e, s) {
1669
+ if (!Number.isInteger(t) || !Number.isInteger(e))
1670
+ throw new $("argument", "Invalid offset or length");
1671
+ if (t < 0 || e < 0)
1672
+ throw new $("argument", "Negative offset or length not allowed");
1673
+ if (t + e > n)
1674
+ throw new $("overflow", "Operation would overflow buffer");
1675
+ if (s != null && (!Number.isInteger(s) || s < 0))
1676
+ throw new $("argument", "Invalid position");
1677
+ }
1678
+ function xt(n, t, e) {
1679
+ try {
1680
+ t.flush(), t.close();
1681
+ } catch (s) {
1682
+ console.warn(\`Warning: Failed to properly close file descriptor \${n} (\${e}):\`, s);
1683
+ }
1684
+ }
1685
+ function Os(n, t, e) {
1686
+ if (n >= e)
1687
+ return { isEOF: !0, actualLength: 0 };
1688
+ const s = Math.min(t, e - n);
1689
+ return s <= 0 ? { isEOF: !0, actualLength: 0 } : { isEOF: !1, actualLength: s };
1690
+ }
1691
+ async function Ds(n, t) {
1692
+ try {
1693
+ return await n.createSyncAccessHandle();
1694
+ } catch (e) {
1695
+ throw A(e, { path: t, isDirectory: !1 });
1696
+ }
1697
+ }
1698
+ class Ms {
1699
+ /** Root directory handle for the file system */
1700
+ root;
1701
+ /** Map of watched paths and options */
1702
+ watchers = /* @__PURE__ */ new Map();
1703
+ /** Promise to prevent concurrent mount operations */
1704
+ mountingPromise = null;
1705
+ /** BroadcastChannel instance for sending events */
1706
+ broadcastChannel = null;
1707
+ /** Configuration options */
1708
+ options = {
1709
+ root: "/",
1710
+ namespace: "",
1711
+ maxFileSize: 50 * 1024 * 1024,
1712
+ hashAlgorithm: "etag",
1713
+ broadcastChannel: "opfs-worker"
1714
+ };
1715
+ /**
1716
+ * Notify about internal changes to the file system
1717
+ *
1718
+ * This method is called by internal operations to notify clients about
1719
+ * changes, even when no specific paths are being watched.
1720
+ *
1721
+ * @param event - The event describing the change
1722
+ */
1723
+ async notifyChange(t) {
1724
+ if (!this.options.broadcastChannel)
1725
+ return;
1726
+ const e = t.path;
1727
+ if (![...this.watchers.values()].some((i) => Q(e, i.pattern) && i.include.some((o) => o && Q(e, o)) && !i.exclude.some((o) => o && Q(e, o))))
1728
+ return;
1729
+ let r;
1730
+ if (this.options.hashAlgorithm)
1731
+ try {
1732
+ r = (await this.stat(e)).hash;
1733
+ } catch {
1734
+ }
1735
+ try {
1736
+ this.broadcastChannel || (this.broadcastChannel = new BroadcastChannel(this.options.broadcastChannel));
1737
+ const i = {
1738
+ namespace: this.options.namespace,
1739
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1740
+ ...t,
1741
+ ...r && { hash: r }
1742
+ };
1743
+ this.broadcastChannel.postMessage(i);
1744
+ } catch (i) {
1745
+ console.warn("Failed to send event via BroadcastChannel:", i);
1746
+ }
1747
+ }
1748
+ constructor(t) {
1749
+ Es(), t && this.setOptions(t);
1750
+ }
1751
+ /** Exclusive path lock keyed by absolute OPFS path (\`root\` + API path). */
1752
+ async withPathLock(t, e) {
1753
+ return Wt(t, e, this.options.root);
1754
+ }
1755
+ /**
1756
+ * Initialize the file system within a given directory.
1757
+ * If no root is specified, uses the OPFS root directory.
1758
+ */
1759
+ async mount() {
1760
+ const t = this.options.root;
1761
+ return this.mountingPromise && await this.mountingPromise, this.mountingPromise = new Promise(async (e, s) => {
1762
+ try {
1763
+ const r = await navigator.storage.getDirectory();
1764
+ this.root = t === "/" ? r : await this.getDirectoryHandle(t, !0, r), e(!0);
1765
+ } catch (r) {
1766
+ s(new ce(t, r));
1767
+ } finally {
1768
+ this.mountingPromise = null;
1769
+ }
1770
+ }), this.mountingPromise;
1771
+ }
1772
+ /**
1773
+ * Update configuration options
1774
+ *
1775
+ * @param options - Configuration options to update
1776
+ * @param options.root - Root path for the file system
1777
+ * @param options.watchInterval - Polling interval in milliseconds for file watching
1778
+ * @param options.hashAlgorithm - Hash algorithm for file hashing
1779
+ * @param options.maxFileSize - Maximum file size for hashing in bytes
1780
+ * @param options.broadcastChannel - Custom name for the broadcast channel
1781
+ */
1782
+ async setOptions(t) {
1783
+ 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 = v(t.root), this.options.namespace || (this.options.namespace = \`opfs-worker:\${this.options.root}\`), await this.mount());
1784
+ }
1785
+ /**
1786
+ * Get a directory handle from a path
1787
+ *
1788
+ * Navigates through the directory structure to find or create a directory
1789
+ * at the specified path.
1790
+ *
1791
+ * @param path - The path to the directory (string or array of segments)
1792
+ * @param create - Whether to create the directory if it doesn't exist (default: false)
1793
+ * @param from - The directory to start from (default: root directory)
1794
+ * @returns Promise that resolves to the directory handle
1795
+ * @throws {OPFSError} If the directory cannot be accessed or created
1796
+ *
1797
+ * @example
1798
+ * \`\`\`typescript
1799
+ * const docsDir = await fs.getDirectoryHandle('/users/john/documents', true);
1800
+ * const docsDir2 = await fs.getDirectoryHandle(['users', 'john', 'documents'], true);
1801
+ * \`\`\`
1802
+ */
1803
+ async getDirectoryHandle(t, e = !1, s = this.root) {
1804
+ const r = Array.isArray(t) ? t : C(t);
1805
+ let i = s;
1806
+ for (const o of r)
1807
+ i = await i.getDirectoryHandle(o, { create: e });
1808
+ return i;
1809
+ }
1810
+ /**
1811
+ * Get a file handle from a path
1812
+ *
1813
+ * Navigates to the parent directory and retrieves or creates a file handle
1814
+ * for the specified file path.
1815
+ *
1816
+ * @param path - The path to the file (string or array of segments)
1817
+ * @param create - Whether to create the file if it doesn't exist (default: false)
1818
+ * @param _from - The directory to start from (default: root directory)
1819
+ * @returns Promise that resolves to the file handle
1820
+ * @throws {PathError} If the path is empty
1821
+ * @throws {OPFSError} If the file cannot be accessed or created
1822
+ *
1823
+ * @example
1824
+ * \`\`\`typescript
1825
+ * const fileHandle = await fs.getFileHandle('/config/settings.json', true);
1826
+ * const fileHandle2 = await fs.getFileHandle(['config', 'settings.json'], true);
1827
+ * \`\`\`
1828
+ */
1829
+ async getFileHandle(t, e = !1, s = this.root) {
1830
+ const r = C(t);
1831
+ if (r.length === 0)
1832
+ throw new ne("Path must not be empty", Array.isArray(t) ? t.join("/") : t);
1833
+ const i = r.pop();
1834
+ return (await this.getDirectoryHandle(r, e, s)).getFileHandle(i, { create: e });
1835
+ }
1836
+ /**
1837
+ * Get a complete index of all files and directories in the file system
1838
+ *
1839
+ * This method recursively traverses the entire file system and returns
1840
+ * a Map containing FileStat objects for every file and directory.
1841
+ *
1842
+ * @returns Promise that resolves to a Map of paths to FileStat objects
1843
+ * @throws {OPFSError} If the file system is not mounted
1844
+ *
1845
+ * @example
1846
+ * \`\`\`typescript
1847
+ * const index = await fs.index();
1848
+ * const fileStats = index.get('/data/config.json');
1849
+ * if (fileStats) {
1850
+ * console.log(\`File size: \${fileStats.size} bytes\`);
1851
+ * if (fileStats.hash) console.log(\`Hash: \${fileStats.hash}\`);
1852
+ * }
1853
+ * \`\`\`
1854
+ */
1855
+ async index() {
1856
+ const t = /* @__PURE__ */ new Map(), e = async (s) => {
1857
+ const r = await this.readDir(s);
1858
+ for (const i of r) {
1859
+ const o = \`\${s === "/" ? "" : s}/\${i.name}\`;
1860
+ try {
1861
+ const a = await this.stat(o);
1862
+ t.set(o, a), a.isDirectory && await e(o);
1863
+ } catch (a) {
1864
+ console.warn(\`Skipping broken entry: \${o}\`, a);
1865
+ }
1866
+ }
1867
+ };
1868
+ return t.set("/", {
1869
+ kind: "directory",
1870
+ size: 0,
1871
+ mtime: (/* @__PURE__ */ new Date(0)).toISOString(),
1872
+ ctime: (/* @__PURE__ */ new Date(0)).toISOString(),
1873
+ isFile: !1,
1874
+ isDirectory: !0
1875
+ }), await e("/"), t;
1876
+ }
1877
+ /**
1878
+ * Create a directory
1879
+ *
1880
+ * Creates a new directory at the specified path. If the recursive option
1881
+ * is enabled, parent directories will be created as needed.
1882
+ *
1883
+ * @param path - The path where the directory should be created
1884
+ * @param options - Options for directory creation
1885
+ * @param options.recursive - Whether to create parent directories if they don't exist (default: false)
1886
+ * @returns Promise that resolves when the directory is created
1887
+ * @throws {OPFSError} If the directory cannot be created
1888
+ *
1889
+ * @example
1890
+ * \`\`\`typescript
1891
+ * // Create a single directory
1892
+ * await fs.mkdir('/users/john');
1893
+ *
1894
+ * // Create nested directories
1895
+ * await fs.mkdir('/users/john/documents/projects', { recursive: true });
1896
+ * \`\`\`
1897
+ */
1898
+ async mkdir(t, e) {
1899
+ await this.mount();
1900
+ const s = e?.recursive ?? !1, r = C(t);
1901
+ let i = this.root;
1902
+ for (let o = 0; o < r.length; o++) {
1903
+ const a = r[o];
1904
+ try {
1905
+ i = await i.getDirectoryHandle(a, { create: s || o === r.length - 1 });
1906
+ } catch (c) {
1907
+ throw c.name === "NotFoundError" ? A(c, {
1908
+ path: lt(r.slice(0, o + 1)),
1909
+ existenceType: "directory"
1910
+ }) : c.name === "TypeMismatchError" ? A(c, { path: a, isDirectory: !1 }) : new Y("create directory", a, c);
1911
+ }
1912
+ }
1913
+ await this.notifyChange({ path: t, type: O.Added, isDirectory: !0 });
1914
+ }
1915
+ /**
1916
+ * Get file or directory statistics
1917
+ *
1918
+ * Returns detailed information about a file or directory, including
1919
+ * size, modification time, and optionally a hash of the file content.
1920
+ *
1921
+ * @param path - The path to the file or directory
1922
+ * @returns Promise that resolves to FileStat object
1923
+ * @throws {OPFSError} If the path does not exist or cannot be accessed
1924
+ *
1925
+ * @example
1926
+ * \`\`\`typescript
1927
+ * const stats = await fs.stat('/data/config.json');
1928
+ * console.log(\`File size: \${stats.size} bytes\`);
1929
+ * console.log(\`Last modified: \${stats.mtime}\`);
1930
+ *
1931
+ * // If hashing is enabled, hash will be included
1932
+ * if (stats.hash) {
1933
+ * console.log(\`Hash: \${stats.hash}\`);
1934
+ * }
1935
+ * \`\`\`
1936
+ */
1937
+ async stat(t) {
1938
+ if (await this.mount(), t === "/")
1939
+ return {
1940
+ kind: "directory",
1941
+ size: 0,
1942
+ mtime: (/* @__PURE__ */ new Date(0)).toISOString(),
1943
+ ctime: (/* @__PURE__ */ new Date(0)).toISOString(),
1944
+ isFile: !1,
1945
+ isDirectory: !0
1946
+ };
1947
+ const e = it(t);
1948
+ let s;
1949
+ try {
1950
+ s = await this.getDirectoryHandle(J(t), !1);
1951
+ const r = this.options.hashAlgorithm, o = await (await s.getFileHandle(e, { create: !1 })).getFile(), a = {
1952
+ kind: "file",
1953
+ size: o.size,
1954
+ mtime: new Date(o.lastModified).toISOString(),
1955
+ ctime: new Date(o.lastModified).toISOString(),
1956
+ isFile: !0,
1957
+ isDirectory: !1
1958
+ };
1959
+ if (r === "etag")
1960
+ a.hash = \`\${o.lastModified.toString(36)}-\${o.size.toString(36)}\`;
1961
+ else if (typeof r == "string")
1962
+ try {
1963
+ const c = await xs(o, r, this.options.maxFileSize);
1964
+ a.hash = c;
1965
+ } catch (c) {
1966
+ console.warn(\`Failed to calculate hash for \${t}:\`, c);
1967
+ }
1968
+ return a;
1969
+ } catch (r) {
1970
+ if (r.name === "NotFoundError")
1971
+ throw new _("file", t, r);
1972
+ if (r.name !== "TypeMismatchError")
1973
+ throw new Y("stat", t, r);
1974
+ }
1975
+ try {
1976
+ return await s.getDirectoryHandle(e, { create: !1 }), {
1977
+ kind: "directory",
1978
+ size: 0,
1979
+ mtime: (/* @__PURE__ */ new Date(0)).toISOString(),
1980
+ ctime: (/* @__PURE__ */ new Date(0)).toISOString(),
1981
+ isFile: !1,
1982
+ isDirectory: !0
1983
+ };
1984
+ } catch (r) {
1985
+ throw new Y("stat", t, r);
1986
+ }
1987
+ }
1988
+ /**
1989
+ * Read a directory's contents
1990
+ *
1991
+ * Lists all files and subdirectories within the specified directory.
1992
+ *
1993
+ * @param path - The path to the directory to read
1994
+ * @returns Promise that resolves to an array of detailed file/directory information
1995
+ * @throws {OPFSError} If the directory does not exist or cannot be accessed
1996
+ *
1997
+ * @example
1998
+ * \`\`\`typescript
1999
+ * // Get detailed information about files and directories
2000
+ * const detailed = await fs.readDir('/users/john/documents');
2001
+ * detailed.forEach(item => {
2002
+ * console.log(\`\${item.name} - \${item.isFile ? 'file' : 'directory'}\`);
2003
+ * });
2004
+ * \`\`\`
2005
+ */
2006
+ async readDir(t) {
2007
+ await this.mount();
2008
+ const e = await this.getDirectoryHandle(t, !1), s = [];
2009
+ for await (const [r, i] of e.entries()) {
2010
+ const o = i.kind === "file";
2011
+ s.push({
2012
+ name: r,
2013
+ kind: i.kind,
2014
+ isFile: o,
2015
+ isDirectory: !o
2016
+ });
2017
+ }
2018
+ return s;
2019
+ }
2020
+ /**
2021
+ * Check if a file or directory exists
2022
+ *
2023
+ * Verifies if a file or directory exists at the specified path.
2024
+ *
2025
+ * @param path - The path to check
2026
+ * @returns Promise that resolves to true if the file or directory exists, false otherwise
2027
+ *
2028
+ * @example
2029
+ * \`\`\`typescript
2030
+ * const exists = await fs.exists('/config/settings.json');
2031
+ * console.log(\`File exists: \${exists}\`);
2032
+ * \`\`\`
2033
+ */
2034
+ async exists(t) {
2035
+ if (await this.mount(), t === "/")
2036
+ return !0;
2037
+ const e = it(t);
2038
+ let s = null;
2039
+ try {
2040
+ s = await this.getDirectoryHandle(J(t), !1);
2041
+ } catch (r) {
2042
+ if (s = null, r.name !== "NotFoundError" && r.name !== "TypeMismatchError")
2043
+ throw r;
2044
+ }
2045
+ if (!s || !e)
2046
+ return !1;
2047
+ try {
2048
+ return await s.getFileHandle(e, { create: !1 }), !0;
2049
+ } catch (r) {
2050
+ if (r.name !== "NotFoundError" && r.name !== "TypeMismatchError")
2051
+ throw r;
2052
+ try {
2053
+ return await s.getDirectoryHandle(e, { create: !1 }), !0;
2054
+ } catch (i) {
2055
+ if (i.name !== "NotFoundError" && i.name !== "TypeMismatchError")
2056
+ throw i;
2057
+ return !1;
2058
+ }
2059
+ }
2060
+ }
2061
+ /**
2062
+ * Clear all contents of a directory without removing the directory itself
2063
+ *
2064
+ * Removes all files and subdirectories within the specified directory,
2065
+ * but keeps the directory itself.
2066
+ *
2067
+ * @param path - The path to the directory to clear (default: '/')
2068
+ * @returns Promise that resolves when all contents are removed
2069
+ * @throws {OPFSError} If the operation fails
2070
+ *
2071
+ * @example
2072
+ * \`\`\`typescript
2073
+ * // Clear root directory contents
2074
+ * await fs.clear('/');
2075
+ *
2076
+ * // Clear specific directory contents
2077
+ * await fs.clear('/data');
2078
+ * \`\`\`
2079
+ */
2080
+ async clear(t = "/") {
2081
+ await this.mount();
2082
+ try {
2083
+ const e = await this.readDir(t);
2084
+ for (const s of e) {
2085
+ const r = \`\${t === "/" ? "" : t}/\${s.name}\`;
2086
+ await this.remove(r, { recursive: !0 });
2087
+ }
2088
+ await this.notifyChange({ path: t, type: O.Changed, isDirectory: !0 });
2089
+ } catch (e) {
2090
+ throw e instanceof y ? e : A(e, { path: t, isDirectory: !0 });
2091
+ }
2092
+ }
2093
+ /**
2094
+ * Remove files and directories
2095
+ *
2096
+ * Removes files and directories. Similar to Node.js fs.rm().
2097
+ *
2098
+ * @param path - The path to remove
2099
+ * @param options - Options for removal
2100
+ * @param options.recursive - Whether to remove directories and their contents recursively (default: false)
2101
+ * @param options.force - Whether to ignore errors if the path doesn't exist (default: false)
2102
+ * @returns Promise that resolves when the removal is complete
2103
+ * @throws {OPFSError} If the removal fails
2104
+ *
2105
+ * @example
2106
+ * \`\`\`typescript
2107
+ * // Remove a file
2108
+ * await fs.rm('/path/to/file.txt');
2109
+ *
2110
+ * // Remove a directory and all its contents
2111
+ * await fs.rm('/path/to/directory', { recursive: true });
2112
+ *
2113
+ * // Remove with force (ignore if doesn't exist)
2114
+ * await fs.rm('/maybe/exists', { force: true });
2115
+ * \`\`\`
2116
+ */
2117
+ async remove(t, e) {
2118
+ if (await this.mount(), t === "/")
2119
+ throw new et("EROOT", t);
2120
+ const { recursive: s = !1, force: r = !1 } = e || {}, i = await this.getDirectoryHandle(J(t), !1), o = await this.stat(t);
2121
+ await As(i, t, { recursive: s, force: r, root: this.options.root }), await this.notifyChange({ path: t, type: O.Removed, isDirectory: o.isDirectory });
2122
+ }
2123
+ /**
2124
+ * Resolve a path to an absolute path
2125
+ *
2126
+ * Resolves relative paths and normalizes path segments (like '..' and '.').
2127
+ * Similar to Node.js fs.realpath() but without symlink resolution since OPFS doesn't support symlinks.
2128
+ *
2129
+ * @param path - The path to resolve
2130
+ * @returns Promise that resolves to the absolute normalized path
2131
+ * @throws {FileNotFoundError} If the path does not exist
2132
+ * @throws {OPFSError} If path resolution fails
2133
+ *
2134
+ * @example
2135
+ * \`\`\`typescript
2136
+ * // Resolve relative path
2137
+ * const absolute = await fs.realpath('./config/../data/file.txt');
2138
+ * console.log(absolute); // '/data/file.txt'
2139
+ * \`\`\`
2140
+ */
2141
+ async realpath(t) {
2142
+ await this.mount();
2143
+ try {
2144
+ const e = ht(t);
2145
+ if (!await this.exists(e))
2146
+ throw new _("file", e);
2147
+ return e;
2148
+ } catch (e) {
2149
+ throw e instanceof y ? e : A(e, { path: t });
2150
+ }
2151
+ }
2152
+ /**
2153
+ * Rename a file or directory
2154
+ *
2155
+ * Changes the name of a file or directory. If the target path already exists,
2156
+ * it will be replaced only if overwrite option is enabled.
2157
+ *
2158
+ * @param oldPath - The current path of the file or directory
2159
+ * @param newPath - The new path for the file or directory
2160
+ * @param options - Options for renaming
2161
+ * @param options.overwrite - Whether to overwrite existing files (default: false)
2162
+ * @returns Promise that resolves when the rename operation is complete
2163
+ * @throws {OPFSError} If the rename operation fails
2164
+ *
2165
+ * @example
2166
+ * \`\`\`typescript
2167
+ * // Basic rename (fails if target exists)
2168
+ * await fs.rename('/old/path/file.txt', '/new/path/renamed.txt');
2169
+ *
2170
+ * // Rename with overwrite
2171
+ * await fs.rename('/old/path/file.txt', '/new/path/renamed.txt', { overwrite: true });
2172
+ * \`\`\`
2173
+ */
2174
+ async rename(t, e, s) {
2175
+ await this.mount();
2176
+ try {
2177
+ const r = s?.overwrite ?? !1, i = await this.stat(t);
2178
+ if (await this.exists(e) && !r)
2179
+ throw new st(e);
2180
+ await this.copy(t, e, { recursive: !0, overwrite: r }), await this.remove(t, { recursive: !0 }), await this.notifyChange({ path: t, type: O.Removed, isDirectory: i.isDirectory }), await this.notifyChange({ path: e, type: O.Added, isDirectory: i.isDirectory });
2181
+ } catch (r) {
2182
+ throw r instanceof y ? r : A(r, { path: t });
2183
+ }
2184
+ }
2185
+ /**
2186
+ * Copy files and directories
2187
+ *
2188
+ * Copies files and directories. Similar to Node.js fs.cp().
2189
+ *
2190
+ * @param source - The source path to copy from
2191
+ * @param destination - The destination path to copy to
2192
+ * @param options - Options for copying
2193
+ * @param options.recursive - Whether to copy directories recursively (default: false)
2194
+ * @param options.overwrite - Whether to overwrite existing files (default: true)
2195
+ * @returns Promise that resolves when the copy operation is complete
2196
+ * @throws {OPFSError} If the copy operation fails
2197
+ *
2198
+ * @example
2199
+ * \`\`\`typescript
2200
+ * // Copy a file
2201
+ * await fs.copy('/source/file.txt', '/dest/file.txt');
2202
+ *
2203
+ * // Copy a directory and all its contents
2204
+ * await fs.copy('/source/dir', '/dest/dir', { recursive: true });
2205
+ *
2206
+ * // Copy without overwriting existing files
2207
+ * await fs.copy('/source', '/dest', { recursive: true, overwrite: false });
2208
+ * \`\`\`
2209
+ */
2210
+ async copy(t, e, s) {
2211
+ await this.mount();
2212
+ try {
2213
+ const r = s?.recursive ?? !1, i = s?.overwrite ?? !0;
2214
+ if (!await this.exists(t))
2215
+ throw new _("source", t);
2216
+ if (await this.exists(e) && !i)
2217
+ throw new st(e);
2218
+ if ((await this.stat(t)).isFile) {
2219
+ const l = await this.readFile(t);
2220
+ await this.writeFile(e, l);
2221
+ } else {
2222
+ if (!r)
2223
+ throw new tt("directory", t);
2224
+ await this.mkdir(e, { recursive: !0 });
2225
+ const l = await this.readDir(t);
2226
+ for (const h of l) {
2227
+ const u = \`\${t}/\${h.name}\`, f = \`\${e}/\${h.name}\`;
2228
+ await this.copy(u, f, { recursive: !0, overwrite: i });
2229
+ }
2230
+ }
2231
+ } catch (r) {
2232
+ throw r instanceof y ? r : A(r, { path: t });
2233
+ }
2234
+ }
2235
+ /**
2236
+ * Start watching a file or directory for changes
2237
+ *
2238
+ * @param path - The path to watch (minimatch syntax allowed)
2239
+ * @param options - Watch options
2240
+ * @param options.recursive - Whether to watch recursively (default: true)
2241
+ * @param options.exclude - Glob pattern(s) to exclude (minimatch).
2242
+ * @returns Promise that resolves when watching starts
2243
+ *
2244
+ * @example
2245
+ * \`\`\`typescript
2246
+ * // Watch entire directory tree recursively (default)
2247
+ * await fs.watch('/data');
2248
+ *
2249
+ * // Watch only immediate children (shallow)
2250
+ * await fs.watch('/data', { recursive: false });
2251
+ *
2252
+ * // Watch a single file
2253
+ * await fs.watch('/config.json', { recursive: false });
2254
+ *
2255
+ * // Watch all json files but not in dist directory
2256
+ * await fs.watch('/**\\/*.json', { recursive: false, exclude: ['dist/**'] });
2257
+ *
2258
+ * \`\`\`
2259
+ */
2260
+ async watch(t, e) {
2261
+ if (!this.options.broadcastChannel)
2262
+ throw new Ct("This instance is not configured to send events. Please specify options.broadcastChannel to enable watching.");
2263
+ const s = {
2264
+ pattern: bs(t, e?.recursive ?? !0),
2265
+ include: Array.isArray(e?.include) ? e.include : [e?.include ?? "**"],
2266
+ exclude: Array.isArray(e?.exclude) ? e.exclude : [e?.exclude ?? ""]
2267
+ };
2268
+ this.watchers.set(t, s);
2269
+ }
2270
+ /**
2271
+ * Stop watching a previously watched path
2272
+ */
2273
+ unwatch(t) {
2274
+ this.watchers.delete(t);
2275
+ }
2276
+ /**
2277
+ * Read a file as a \`Blob\` without copying its bytes into memory.
2278
+ *
2279
+ * OPFS hands back a disk-backed \`File\`, so the browser can stream it on
2280
+ * demand — pass it to \`URL.createObjectURL()\` for \`<video>\` / \`<audio>\` /
2281
+ * \`<img>\` and only the played range is actually read. Structured clone keeps
2282
+ * the reference intact when the file system runs in a worker.
2283
+ *
2284
+ * @param path - Path to the file
2285
+ * @returns Lazy \`File\` handle backed by OPFS storage
2286
+ * @throws {OPFSError} If the path is missing or is a directory
2287
+ *
2288
+ * @example
2289
+ * \`\`\`typescript
2290
+ * const blob = await fs.readBlob('/media/clip.mp4');
2291
+ * video.src = URL.createObjectURL(blob);
2292
+ * \`\`\`
2293
+ */
2294
+ async readBlob(t) {
2295
+ await this.mount();
2296
+ try {
2297
+ return await (await this.getFileHandle(t, !1)).getFile();
2298
+ } catch (e) {
2299
+ throw e instanceof y ? e : A(e, { path: t, isDirectory: e?.name === "TypeMismatchError" });
2300
+ }
2301
+ }
2302
+ /**
2303
+ * Bulk-import files from \`[path, data]\` entries (strings, bytes, Blobs, or Files).
2304
+ * Each entry is written via {@link writeStream} so large Blobs/Files are not
2305
+ * fully buffered in memory.
2306
+ *
2307
+ * Accepts an array of tuples, a \`Map\`, or any iterable of \`[path, data]\` pairs.
2308
+ *
2309
+ * @param entries - Files to write
2310
+ * @param onProgress - Per-chunk progress with path, index, and byte counts
2311
+ * @returns Written paths, count, and total bytes
2312
+ * @throws {OPFSError} If a write fails
2313
+ *
2314
+ * @example
2315
+ * \`\`\`typescript
2316
+ * const result = await fs.importFiles([
2317
+ * ['/config.json', JSON.stringify({ theme: 'dark' })],
2318
+ * ['/data/binary.dat', new Uint8Array([1, 2, 3, 4])],
2319
+ * ['/upload.txt', fileFromInput],
2320
+ * ], (p) => console.log(\`\${p.path}: \${p.bytesWritten}/\${p.bytesTotal}\`));
2321
+ *
2322
+ * console.log(result.count, result.bytesWritten, result.paths);
2323
+ * \`\`\`
2324
+ */
2325
+ async importFiles(t, e) {
2326
+ await this.mount();
2327
+ const s = [...t].map(([c, l]) => [v(c), l]), r = s.length, i = s.map(([c]) => c), o = s.reduce((c, [, l]) => c + $s(l), 0);
2328
+ let a = 0;
2329
+ try {
2330
+ for (let c = 0; c < r; c++) {
2331
+ const [l, h] = s[c], { stream: u, size: f } = Ts(h), p = a, g = await this.writeStream(
2332
+ l,
2333
+ u,
2334
+ e ? (d) => e({
2335
+ path: l,
2336
+ index: c,
2337
+ count: r,
2338
+ bytesWritten: d,
2339
+ bytesTotal: f,
2340
+ totalBytesWritten: p + d,
2341
+ totalBytes: o
2342
+ }) : void 0
2343
+ );
2344
+ a += g;
2345
+ }
2346
+ return {
2347
+ paths: i,
2348
+ count: r,
2349
+ bytesWritten: a
2350
+ };
2351
+ } catch (c) {
2352
+ throw c instanceof y ? c : A(c);
2353
+ }
2354
+ }
2355
+ /**
2356
+ * @deprecated Use {@link importFiles} instead.
2357
+ */
2358
+ async createIndex(t) {
2359
+ Ns(), await this.importFiles(t);
2360
+ }
2361
+ /**
2362
+ * Dispose of resources and clean up the file system instance
2363
+ */
2364
+ dispose() {
2365
+ this.broadcastChannel && (this.broadcastChannel.close(), this.broadcastChannel = null), this.watchers.clear();
2366
+ }
2367
+ }
2368
+ function $s(n) {
2369
+ return typeof n == "string" ? new TextEncoder().encode(n).byteLength : n instanceof Blob ? n.size : n.byteLength;
2370
+ }
2371
+ function Ts(n) {
2372
+ if (n instanceof Blob)
2373
+ return { stream: n.stream(), size: n.size };
2374
+ const t = typeof n == "string" ? new TextEncoder().encode(n) : n;
2375
+ return {
2376
+ size: t.byteLength,
2377
+ stream: new ReadableStream({
2378
+ start(e) {
2379
+ e.enqueue(t), e.close();
2380
+ }
2381
+ })
2382
+ };
2383
+ }
2384
+ let At = !1;
2385
+ function Ns() {
2386
+ At || (At = !0, console.warn("[opfs-worker] createIndex() is deprecated; use importFiles() instead"));
2387
+ }
2388
+ class Cs extends Ms {
2389
+ /** Shared sync handles per path (OPFS allows only one handle per file) */
2390
+ openHandles = /* @__PURE__ */ new Map();
2391
+ /** Map of open file descriptors to their metadata */
2392
+ openFiles = /* @__PURE__ */ new Map();
2393
+ /** Next available file descriptor number */
2394
+ nextFd = 1;
2395
+ constructor(t) {
2396
+ super(t);
2397
+ }
2398
+ /**
2399
+ * Get file info by descriptor with validation
2400
+ * @private
2401
+ */
2402
+ _getFileDescriptor(t) {
2403
+ const e = this.openFiles.get(t);
2404
+ if (!e)
2405
+ throw new $("descriptor", \`Invalid file descriptor: \${t}\`);
2406
+ return e;
2407
+ }
2408
+ async readFile(t) {
2409
+ await this.mount();
2410
+ try {
2411
+ return await this.withPathLock(t, async () => {
2412
+ const e = await this.open(t);
2413
+ try {
2414
+ const { size: s } = await this.fstat(e), r = new Uint8Array(s);
2415
+ return s > 0 && await this.read(e, r, 0, s, 0), z(r, [r.buffer]);
2416
+ } finally {
2417
+ await this.close(e);
2418
+ }
2419
+ });
2420
+ } catch (e) {
2421
+ throw e instanceof y ? e : A(e, { path: t, isDirectory: !1 });
2422
+ }
2423
+ }
2424
+ async writeFile(t, e) {
2425
+ await this.mount();
2426
+ const s = e instanceof Uint8Array ? e : new Uint8Array(e);
2427
+ await this.withPathLock(t, async () => {
2428
+ const r = await this.exists(t), i = await this.open(t, { create: !0, truncate: !0 });
2429
+ try {
2430
+ await this.write(i, s, 0, s.length, null, !1), await this.fsync(i);
2431
+ } finally {
2432
+ await this.close(i);
2433
+ }
2434
+ await this.notifyChange({ path: t, type: r ? O.Changed : O.Added, isDirectory: !1 });
2435
+ });
2436
+ }
2437
+ async appendFile(t, e) {
2438
+ await this.mount();
2439
+ const s = e instanceof Uint8Array ? e : new Uint8Array(e);
2440
+ await this.withPathLock(t, async () => {
2441
+ const r = await this.open(t, { create: !0 });
2442
+ try {
2443
+ const { size: i } = await this.fstat(r);
2444
+ await this.write(r, s, 0, s.length, i, !1), await this.fsync(r);
2445
+ } finally {
2446
+ await this.close(r);
2447
+ }
2448
+ await this.notifyChange({ path: t, type: O.Changed, isDirectory: !1 });
2449
+ });
2450
+ }
2451
+ async writeStream(t, e, s) {
2452
+ return await this.mount(), this.withPathLock(t, async () => {
2453
+ const r = await this.exists(t), i = await this.open(t, { create: !0, truncate: !0 }), o = e.getReader();
2454
+ let a = 0;
2455
+ try {
2456
+ for (; ; ) {
2457
+ const { done: c, value: l } = await o.read();
2458
+ if (c)
2459
+ break;
2460
+ let h = 0;
2461
+ for (; h < l.byteLength; )
2462
+ h += await this.write(
2463
+ i,
2464
+ l,
2465
+ h,
2466
+ l.byteLength - h,
2467
+ null,
2468
+ !1
2469
+ );
2470
+ a += l.byteLength, await s?.(a);
2471
+ }
2472
+ await this.fsync(i);
2473
+ } catch (c) {
2474
+ throw await o.cancel(c).catch(() => {
2475
+ }), c;
2476
+ } finally {
2477
+ o.releaseLock(), await this.close(i);
2478
+ }
2479
+ return await this.notifyChange({
2480
+ path: t,
2481
+ type: r ? O.Changed : O.Added,
2482
+ isDirectory: !1
2483
+ }), a;
2484
+ });
2485
+ }
2486
+ async open(t, e) {
2487
+ await this.mount();
2488
+ const { create: s = !1, exclusive: r = !1, truncate: i = !1 } = e || {}, o = v(ht(t));
2489
+ try {
2490
+ return s && r ? await this.withPathLock(o, async () => {
2491
+ if (await this.exists(o))
2492
+ throw new st(o);
2493
+ return this._openFile(o, s, i);
2494
+ }) : await this._openFile(o, s, i);
2495
+ } catch (a) {
2496
+ if (a instanceof y)
2497
+ throw a;
2498
+ const c = a && a.name === "TypeMismatchError";
2499
+ throw A(a, {
2500
+ path: o,
2501
+ isDirectory: !!c
2502
+ });
2503
+ }
2504
+ }
2505
+ /**
2506
+ * Internal method to open a file (without locking)
2507
+ *
2508
+ * Multiple FDs for the same path share one sync access handle (OPFS limit),
2509
+ * with independent per-FD positions — similar to Node.js.
2510
+ * @private
2511
+ */
2512
+ async _openFile(t, e, s) {
2513
+ let r = this.openHandles.get(t);
2514
+ if (!r) {
2515
+ const o = await this.getFileHandle(t, e);
2516
+ try {
2517
+ await o.getFile();
2518
+ } catch (c) {
2519
+ throw A(c, { path: t, isDirectory: !0 });
2520
+ }
2521
+ const a = await Ds(o, t);
2522
+ r = { fileHandle: o, syncHandle: a, refCount: 0 }, this.openHandles.set(t, r);
2523
+ }
2524
+ r.refCount++, s && (r.syncHandle.truncate(0), r.syncHandle.flush());
2525
+ const i = this.nextFd++;
2526
+ return this.openFiles.set(i, {
2527
+ path: t,
2528
+ fileHandle: r.fileHandle,
2529
+ syncHandle: r.syncHandle,
2530
+ position: 0
2531
+ }), i;
2532
+ }
2533
+ async close(t) {
2534
+ const e = this._getFileDescriptor(t);
2535
+ this.openFiles.delete(t);
2536
+ const s = this.openHandles.get(e.path);
2537
+ s && (s.refCount--, s.refCount <= 0 && (xt(t, s.syncHandle, e.path), this.openHandles.delete(e.path)));
2538
+ }
2539
+ async read(t, e, s, r, i) {
2540
+ const o = this._getFileDescriptor(t);
2541
+ bt(e.length, s, r, i);
2542
+ try {
2543
+ const a = i ?? o.position, c = o.syncHandle.getSize(), { isEOF: l, actualLength: h } = Os(a, r, c);
2544
+ if (l)
2545
+ return z({ bytesRead: 0, buffer: e }, [e.buffer]);
2546
+ const u = e.subarray(s, s + h), f = o.syncHandle.read(u, { at: a });
2547
+ return i == null && (o.position = a + f), z({ bytesRead: f, buffer: e }, [e.buffer]);
2548
+ } catch (a) {
2549
+ throw I("read", t, o.path, a);
2550
+ }
2551
+ }
2552
+ async write(t, e, s = 0, r, i, o = !0) {
2553
+ const a = this._getFileDescriptor(t), c = r ?? e.length - s;
2554
+ bt(e.length, s, c, i);
2555
+ try {
2556
+ const l = i ?? a.position, h = e.subarray(s, s + c), u = a.syncHandle.write(h, { at: l });
2557
+ return (i == null || i === a.position) && (a.position = l + u), o && await this.notifyChange({ path: a.path, type: O.Changed, isDirectory: !1 }), u;
2558
+ } catch (l) {
2559
+ throw I("write", t, a.path, l);
2560
+ }
2561
+ }
2562
+ async fstat(t) {
2563
+ const e = this._getFileDescriptor(t);
2564
+ return this.stat(e.path);
2565
+ }
2566
+ async ftruncate(t, e = 0) {
2567
+ const s = this._getFileDescriptor(t);
2568
+ if (e < 0 || !Number.isInteger(e))
2569
+ throw new $("argument", "Invalid size");
2570
+ try {
2571
+ s.syncHandle.truncate(e), s.syncHandle.flush(), s.position > e && (s.position = e), await this.notifyChange({ path: s.path, type: O.Changed, isDirectory: !1 });
2572
+ } catch (r) {
2573
+ throw I("truncate", t, s.path, r);
2574
+ }
2575
+ }
2576
+ async fsync(t) {
2577
+ const e = this._getFileDescriptor(t);
2578
+ try {
2579
+ e.syncHandle.flush();
2580
+ } catch (s) {
2581
+ throw I("sync", t, e.path, s);
2582
+ }
2583
+ }
2584
+ dispose() {
2585
+ for (const [t, e] of this.openHandles)
2586
+ xt(-1, e.syncHandle, t);
2587
+ this.openHandles.clear(), this.openFiles.clear(), this.nextFd = 1, super.dispose();
2588
+ }
2589
+ }
2590
+ const jt = new Cs();
2591
+ U(jt);
2592
+ addEventListener("message", (n) => {
2593
+ n.data?.type === "opfs-connect" && n.data.port instanceof MessagePort && U(jt, n.data.port);
2594
+ });
2595
+ //# sourceMappingURL=dedicated.worker-Bqqr9UBA.js.map
2596
+ `,f=typeof self<"u"&&self.Blob&&new Blob(["URL.revokeObjectURL(import.meta.url);",y],{type:"text/javascript;charset=utf-8"});function E(t){let n;try{if(n=f&&(self.URL||self.webkitURL).createObjectURL(f),!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(y),{type:"module",name:t?.name})}}const x=E,c=new Map;function S(t,n){return`${g.normalizePath(t)}\0${n?.toString()??"inline"}`}function u(t,n){n&&(n.broadcastChannel instanceof BroadcastChannel&&(n.broadcastChannel=n.broadcastChannel.name),t.setOptions(n))}function d(t){const{port1:n,port2:e}=new MessageChannel;return t.postMessage({type:"opfs-connect",port:e},[e]),{fs:v.wrap(n),port:n}}function _(t={}){const{url:n,worker:e,...r}=t,w=g.normalizePath(r.root??"/");if(e){const{fs:s,port:l}=d(e);return u(s,r),{fs:s,worker:e,dispose(){l.close()}}}const a=S(w,n);let i=c.get(a);i||(i={worker:n?new Worker(n,{type:"module"}):new x,refs:0},c.set(a,i)),i.refs+=1;const{worker:o}=i,{fs:h,port:m}=d(o);u(h,r);let p=!1;return{fs:h,worker:o,dispose(){p||(p=!0,(async()=>{const s=c.get(a),l=!!s&&s.worker===o&&s.refs<=1;try{l&&await h.dispose()}finally{m.close()}!s||s.worker!==o||(s.refs-=1,s.refs<=0&&(c.delete(a),o.terminate()))})())}}}function P(t){const{fs:n,worker:e,dispose:r}=_(t);return new b.OPFSFacade({fs:n,worker:e,dispose:r})}exports.createOPFSDedicated=P;
2597
+ //# sourceMappingURL=createOPFSDedicated-EmIwluQo.cjs.map