opfs-worker 1.3.2 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (149) hide show
  1. package/README.md +64 -458
  2. package/dist/BaseOPFS-BPw9AIQ-.cjs +4 -0
  3. package/dist/BaseOPFS-BPw9AIQ-.cjs.map +1 -0
  4. package/dist/BaseOPFS-Cylz6ijk.js +2036 -0
  5. package/dist/BaseOPFS-Cylz6ijk.js.map +1 -0
  6. package/dist/OPFSAsync-BKSAJJeh.js +124 -0
  7. package/dist/OPFSAsync-BKSAJJeh.js.map +1 -0
  8. package/dist/OPFSAsync-s2P7y3sw.cjs +2 -0
  9. package/dist/OPFSAsync-s2P7y3sw.cjs.map +1 -0
  10. package/dist/OPFSFacade-DePnNRgt.cjs +2 -0
  11. package/dist/OPFSFacade-DePnNRgt.cjs.map +1 -0
  12. package/dist/OPFSFacade-XohWlHuu.js +281 -0
  13. package/dist/OPFSFacade-XohWlHuu.js.map +1 -0
  14. package/dist/OPFSSync-C7KBepe_.cjs +2 -0
  15. package/dist/OPFSSync-C7KBepe_.cjs.map +1 -0
  16. package/dist/OPFSSync-CsSQkpk5.js +208 -0
  17. package/dist/OPFSSync-CsSQkpk5.js.map +1 -0
  18. package/dist/assets/dedicated.worker-nY3tK4zi.js.map +1 -0
  19. package/dist/{worker.d.ts → core/BaseOPFS.d.ts} +34 -300
  20. package/dist/core/BaseOPFS.d.ts.map +1 -0
  21. package/dist/core/OPFSAsync.d.ts +55 -0
  22. package/dist/core/OPFSAsync.d.ts.map +1 -0
  23. package/dist/core/OPFSSync.d.ts +54 -0
  24. package/dist/core/OPFSSync.d.ts.map +1 -0
  25. package/dist/createOPFSAsync-BwKDmHsy.cjs +2 -0
  26. package/dist/createOPFSAsync-BwKDmHsy.cjs.map +1 -0
  27. package/dist/createOPFSAsync-Y4Mg6qte.js +10 -0
  28. package/dist/createOPFSAsync-Y4Mg6qte.js.map +1 -0
  29. package/dist/createOPFSDedicated-CsnV6MLP.js +2333 -0
  30. package/dist/createOPFSDedicated-CsnV6MLP.js.map +1 -0
  31. package/dist/createOPFSDedicated-pKTRWLdz.cjs +2283 -0
  32. package/dist/createOPFSDedicated-pKTRWLdz.cjs.map +1 -0
  33. package/dist/createOPFSShared-CGdd__PH.js +23 -0
  34. package/dist/createOPFSShared-CGdd__PH.js.map +1 -0
  35. package/dist/createOPFSShared-CskROt7U.cjs +2 -0
  36. package/dist/createOPFSShared-CskROt7U.cjs.map +1 -0
  37. package/dist/dedicated.worker.js +2281 -0
  38. package/dist/dedicated.worker.js.map +1 -0
  39. package/dist/{facade.d.ts → facade/OPFSFacade.d.ts} +35 -10
  40. package/dist/facade/OPFSFacade.d.ts.map +1 -0
  41. package/dist/facade/createOPFSAsync.d.ts +16 -0
  42. package/dist/facade/createOPFSAsync.d.ts.map +1 -0
  43. package/dist/facade/createOPFSDedicated.d.ts +17 -0
  44. package/dist/facade/createOPFSDedicated.d.ts.map +1 -0
  45. package/dist/facade/createOPFSShared.d.ts +24 -0
  46. package/dist/facade/createOPFSShared.d.ts.map +1 -0
  47. package/dist/index.async.cjs +2 -0
  48. package/dist/index.async.cjs.map +1 -0
  49. package/dist/index.async.d.ts +10 -0
  50. package/dist/index.async.d.ts.map +1 -0
  51. package/dist/index.async.js +55 -0
  52. package/dist/index.async.js.map +1 -0
  53. package/dist/index.cjs +1 -2466
  54. package/dist/index.cjs.map +1 -1
  55. package/dist/index.d.ts +15 -7
  56. package/dist/index.d.ts.map +1 -1
  57. package/dist/index.js +61 -2799
  58. package/dist/index.js.map +1 -1
  59. package/dist/index.pure.cjs +2 -0
  60. package/dist/index.pure.cjs.map +1 -0
  61. package/dist/index.pure.d.ts +8 -0
  62. package/dist/index.pure.d.ts.map +1 -0
  63. package/dist/index.pure.js +53 -0
  64. package/dist/index.pure.js.map +1 -0
  65. package/dist/index.sharedworker.cjs +2 -0
  66. package/dist/index.sharedworker.cjs.map +1 -0
  67. package/dist/index.sharedworker.d.ts +11 -0
  68. package/dist/index.sharedworker.d.ts.map +1 -0
  69. package/dist/index.sharedworker.js +55 -0
  70. package/dist/index.sharedworker.js.map +1 -0
  71. package/dist/index.sync.cjs +2 -0
  72. package/dist/index.sync.cjs.map +1 -0
  73. package/dist/index.sync.d.ts +11 -0
  74. package/dist/index.sync.d.ts.map +1 -0
  75. package/dist/index.sync.js +55 -0
  76. package/dist/index.sync.js.map +1 -0
  77. package/dist/shared.worker.js +2166 -0
  78. package/dist/shared.worker.js.map +1 -0
  79. package/dist/types.d.ts +9 -4
  80. package/dist/types.d.ts.map +1 -1
  81. package/dist/utils/helpers.d.ts +11 -1
  82. package/dist/utils/helpers.d.ts.map +1 -1
  83. package/dist/worker/createDedicatedWorker.d.ts +30 -0
  84. package/dist/worker/createDedicatedWorker.d.ts.map +1 -0
  85. package/dist/worker/createSharedWorker.d.ts +37 -0
  86. package/dist/worker/createSharedWorker.d.ts.map +1 -0
  87. package/dist/worker/dedicated.worker.d.ts +2 -0
  88. package/dist/worker/dedicated.worker.d.ts.map +1 -0
  89. package/dist/worker/shared.worker.d.ts +2 -0
  90. package/dist/worker/shared.worker.d.ts.map +1 -0
  91. package/docs/README.md +30 -0
  92. package/docs/api/backend.md +36 -0
  93. package/docs/api/create.md +82 -0
  94. package/docs/api/facade.md +52 -0
  95. package/docs/choosing-a-mode.md +41 -0
  96. package/docs/file-descriptors.md +695 -0
  97. package/docs/guides/async.md +36 -0
  98. package/docs/guides/dedicated.md +76 -0
  99. package/docs/guides/hashing.md +34 -0
  100. package/docs/guides/pure.md +46 -0
  101. package/docs/guides/sharedworker.md +57 -0
  102. package/docs/guides/streaming.md +51 -0
  103. package/docs/guides/watching.md +35 -0
  104. package/docs/migration.md +41 -0
  105. package/docs/types.md +246 -0
  106. package/package.json +55 -10
  107. package/src/core/BaseOPFS.ts +951 -0
  108. package/src/core/OPFSAsync.ts +248 -0
  109. package/src/core/OPFSSync.ts +460 -0
  110. package/src/facade/OPFSFacade.ts +489 -0
  111. package/src/facade/createOPFSAsync.ts +22 -0
  112. package/src/facade/createOPFSDedicated.ts +23 -0
  113. package/src/facade/createOPFSShared.ts +30 -0
  114. package/src/index.async.ts +11 -0
  115. package/src/index.pure.ts +8 -0
  116. package/src/index.sharedworker.ts +12 -0
  117. package/src/index.sync.ts +12 -0
  118. package/src/index.ts +44 -0
  119. package/src/types.ts +103 -0
  120. package/src/utils/encoder.ts +205 -0
  121. package/src/utils/errors.ts +297 -0
  122. package/src/utils/helpers.ts +465 -0
  123. package/src/worker/createDedicatedWorker.ts +74 -0
  124. package/src/worker/createSharedWorker.ts +67 -0
  125. package/src/worker/dedicated.worker.ts +13 -0
  126. package/src/worker/shared.worker.ts +17 -0
  127. package/dist/assets/worker-1Wh1cr7P.js.map +0 -1
  128. package/dist/assets/worker-BeJaVyBV.js.map +0 -1
  129. package/dist/assets/worker-DYYLzR1Y.js.map +0 -1
  130. package/dist/facade.d.ts.map +0 -1
  131. package/dist/helpers-BuGfPAg0.js +0 -1439
  132. package/dist/helpers-BuGfPAg0.js.map +0 -1
  133. package/dist/helpers-CF7A2WQG.cjs +0 -4
  134. package/dist/helpers-CF7A2WQG.cjs.map +0 -1
  135. package/dist/helpers-CIiblZ8d.cjs +0 -4
  136. package/dist/helpers-CIiblZ8d.cjs.map +0 -1
  137. package/dist/helpers-CKOebsbw.js +0 -1423
  138. package/dist/helpers-CKOebsbw.js.map +0 -1
  139. package/dist/helpers-Ca2c767K.js +0 -1427
  140. package/dist/helpers-Ca2c767K.js.map +0 -1
  141. package/dist/helpers-Dwc92hv9.cjs +0 -4
  142. package/dist/helpers-Dwc92hv9.cjs.map +0 -1
  143. package/dist/raw.cjs +0 -2
  144. package/dist/raw.cjs.map +0 -1
  145. package/dist/raw.d.ts +0 -13
  146. package/dist/raw.d.ts.map +0 -1
  147. package/dist/raw.js +0 -1001
  148. package/dist/raw.js.map +0 -1
  149. package/dist/worker.d.ts.map +0 -1
package/dist/raw.js DELETED
@@ -1,1001 +0,0 @@
1
- import { expose as O, transfer as p } from "comlink";
2
- import { V as E, t as D, l as k, h as z, q as F, s as v, P, w as u, E as m, m as l, n as M, j as x, W as h, o as b, p as S, z as T, O as f, D as $, G as _, v as H, A as C, c as N, g as R, r as B, L as U, J as A, H as I, K as W, k as g, C as L } from "./helpers-Ca2c767K.js";
3
- class j {
4
- /** Root directory handle for the file system */
5
- root;
6
- /** Map of watched paths and options */
7
- watchers = /* @__PURE__ */ new Map();
8
- /** Promise to prevent concurrent mount operations */
9
- mountingPromise = null;
10
- /** BroadcastChannel instance for sending events */
11
- broadcastChannel = null;
12
- /** Configuration options */
13
- options = {
14
- root: "/",
15
- namespace: "",
16
- maxFileSize: 50 * 1024 * 1024,
17
- hashAlgorithm: "etag",
18
- broadcastChannel: "opfs-worker"
19
- };
20
- /** Map of open file descriptors to their metadata */
21
- openFiles = /* @__PURE__ */ new Map();
22
- /** Next available file descriptor number */
23
- nextFd = 1;
24
- /**
25
- * Get file info by descriptor with validation
26
- * @private
27
- */
28
- _getFileDescriptor(t) {
29
- const e = this.openFiles.get(t);
30
- if (!e)
31
- throw new E("descriptor", `Invalid file descriptor: ${t}`);
32
- return e;
33
- }
34
- /**
35
- * Notify about internal changes to the file system
36
- *
37
- * This method is called by internal operations to notify clients about
38
- * changes, even when no specific paths are being watched.
39
- *
40
- * @param event - The event describing the change
41
- */
42
- async notifyChange(t) {
43
- if (!this.options.broadcastChannel)
44
- return;
45
- const e = t.path;
46
- if (![...this.watchers.values()].some((r) => D(e, r.pattern) && r.include.some((s) => s && D(e, s)) && !r.exclude.some((s) => s && D(e, s))))
47
- return;
48
- let i;
49
- if (this.options.hashAlgorithm)
50
- try {
51
- i = (await this.stat(e)).hash;
52
- } catch {
53
- }
54
- try {
55
- this.broadcastChannel || (this.broadcastChannel = new BroadcastChannel(this.options.broadcastChannel));
56
- const r = {
57
- namespace: this.options.namespace,
58
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
59
- ...t,
60
- ...i && { hash: i }
61
- };
62
- this.broadcastChannel.postMessage(r);
63
- } catch (r) {
64
- console.warn("Failed to send event via BroadcastChannel:", r);
65
- }
66
- }
67
- /**
68
- * Creates a new OPFSFileSystem instance
69
- *
70
- * @param options - Optional configuration options
71
- * @param options.root - Root path for the file system (default: '/')
72
- * @param options.watchInterval - Polling interval in milliseconds for file watching
73
- * @param options.hashAlgorithm - Hash algorithm for file hashing
74
- * @param options.maxFileSize - Maximum file size for hashing in bytes (default: 50MB)
75
- * @throws {OPFSError} If OPFS is not supported in the current browser
76
- */
77
- constructor(t) {
78
- k(), t && this.setOptions(t);
79
- }
80
- /**
81
- * Initialize the file system within a given directory
82
- *
83
- * This method sets up the root directory for all subsequent operations.
84
- * If no root is specified, it will use the OPFS root directory.
85
- *
86
- * @returns Promise that resolves to true if initialization was successful
87
- * @throws {OPFSError} If initialization fails
88
- *
89
- * @example
90
- * ```typescript
91
- * const fs = new OPFSFileSystem();
92
- *
93
- * // Use OPFS root (default)
94
- * await fs.mount();
95
- *
96
- * // Use custom directory
97
- * await fs.mount('/my-app');
98
- * ```
99
- */
100
- async mount() {
101
- const t = this.options.root;
102
- return this.mountingPromise && await this.mountingPromise, this.mountingPromise = new Promise(async (e, a) => {
103
- try {
104
- const i = await navigator.storage.getDirectory();
105
- this.root = t === "/" ? i : await this.getDirectoryHandle(t, !0, i), e(!0);
106
- } catch (i) {
107
- a(new z(t, i));
108
- } finally {
109
- this.mountingPromise = null;
110
- }
111
- }), this.mountingPromise;
112
- }
113
- /**
114
- * Update configuration options
115
- *
116
- * @param options - Configuration options to update
117
- * @param options.root - Root path for the file system
118
- * @param options.watchInterval - Polling interval in milliseconds for file watching
119
- * @param options.hashAlgorithm - Hash algorithm for file hashing
120
- * @param options.maxFileSize - Maximum file size for hashing in bytes
121
- * @param options.broadcastChannel - Custom name for the broadcast channel
122
- */
123
- async setOptions(t) {
124
- 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 = F(t.root), this.options.namespace || (this.options.namespace = `opfs-worker:${this.options.root}`), await this.mount());
125
- }
126
- /**
127
- * Get a directory handle from a path
128
- *
129
- * Navigates through the directory structure to find or create a directory
130
- * at the specified path.
131
- *
132
- * @param path - The path to the directory (string or array of segments)
133
- * @param create - Whether to create the directory if it doesn't exist (default: false)
134
- * @param from - The directory to start from (default: root directory)
135
- * @returns Promise that resolves to the directory handle
136
- * @throws {OPFSError} If the directory cannot be accessed or created
137
- *
138
- * @example
139
- * ```typescript
140
- * const docsDir = await fs.getDirectoryHandle('/users/john/documents', true);
141
- * const docsDir2 = await fs.getDirectoryHandle(['users', 'john', 'documents'], true);
142
- * ```
143
- */
144
- async getDirectoryHandle(t, e = !1, a = this.root) {
145
- const i = Array.isArray(t) ? t : v(t);
146
- let r = a;
147
- for (const s of i)
148
- r = await r.getDirectoryHandle(s, { create: e });
149
- return r;
150
- }
151
- /**
152
- * Get a file handle from a path
153
- *
154
- * Navigates to the parent directory and retrieves or creates a file handle
155
- * for the specified file path.
156
- *
157
- * @param path - The path to the file (string or array of segments)
158
- * @param create - Whether to create the file if it doesn't exist (default: false)
159
- * @param _from - The directory to start from (default: root directory)
160
- * @returns Promise that resolves to the file handle
161
- * @throws {PathError} If the path is empty
162
- * @throws {OPFSError} If the file cannot be accessed or created
163
- *
164
- * @example
165
- * ```typescript
166
- * const fileHandle = await fs.getFileHandle('/config/settings.json', true);
167
- * const fileHandle2 = await fs.getFileHandle(['config', 'settings.json'], true);
168
- * ```
169
- */
170
- async getFileHandle(t, e = !1, a = this.root) {
171
- const i = v(t);
172
- if (i.length === 0)
173
- throw new P("Path must not be empty", Array.isArray(t) ? t.join("/") : t);
174
- const r = i.pop();
175
- return (await this.getDirectoryHandle(i, e, a)).getFileHandle(r, { create: e });
176
- }
177
- /**
178
- * Get a complete index of all files and directories in the file system
179
- *
180
- * This method recursively traverses the entire file system and returns
181
- * a Map containing FileStat objects for every file and directory.
182
- *
183
- * @returns Promise that resolves to a Map of paths to FileStat objects
184
- * @throws {OPFSError} If the file system is not mounted
185
- *
186
- * @example
187
- * ```typescript
188
- * const index = await fs.index();
189
- * const fileStats = index.get('/data/config.json');
190
- * if (fileStats) {
191
- * console.log(`File size: ${fileStats.size} bytes`);
192
- * if (fileStats.hash) console.log(`Hash: ${fileStats.hash}`);
193
- * }
194
- * ```
195
- */
196
- async index() {
197
- const t = /* @__PURE__ */ new Map(), e = async (a) => {
198
- const i = await this.readDir(a);
199
- for (const r of i) {
200
- const s = `${a === "/" ? "" : a}/${r.name}`;
201
- try {
202
- const n = await this.stat(s);
203
- t.set(s, n), n.isDirectory && await e(s);
204
- } catch (n) {
205
- console.warn(`Skipping broken entry: ${s}`, n);
206
- }
207
- }
208
- };
209
- return t.set("/", {
210
- kind: "directory",
211
- size: 0,
212
- mtime: (/* @__PURE__ */ new Date(0)).toISOString(),
213
- ctime: (/* @__PURE__ */ new Date(0)).toISOString(),
214
- isFile: !1,
215
- isDirectory: !0
216
- }), await e("/"), t;
217
- }
218
- /**
219
- * Read a file from the file system
220
- *
221
- * Reads the contents of a file and returns it as binary data.
222
- *
223
- * @param path - The path to the file to read
224
- * @returns Promise that resolves to the file contents as Uint8Array
225
- * @throws {FileNotFoundError} If the file does not exist
226
- * @throws {OPFSError} If reading the file fails
227
- *
228
- * @example
229
- * ```typescript
230
- * // Read as binary data
231
- * const content = await fs.readFile('/config/settings.json');
232
- *
233
- * // Read binary file
234
- * const binaryData = await fs.readFile('/images/logo.png');
235
- * ```
236
- */
237
- async readFile(t) {
238
- await this.mount();
239
- try {
240
- return await u(t, "shared", async () => {
241
- const e = await this.open(t);
242
- try {
243
- const { size: a } = await this.fstat(e), i = new Uint8Array(a);
244
- return a > 0 && await this.read(e, i, 0, a, 0), p(i, [i.buffer]);
245
- } finally {
246
- await this.close(e);
247
- }
248
- });
249
- } catch (e) {
250
- throw new m("file", t, e);
251
- }
252
- }
253
- /**
254
- * Write data to a file
255
- *
256
- * Creates or overwrites a file with the specified binary data. If the file already
257
- * exists, it will be truncated before writing.
258
- *
259
- * @param path - The path to the file to write
260
- * @param data - The binary data to write to the file (Uint8Array or ArrayBuffer)
261
- * @returns Promise that resolves when the write operation is complete
262
- * @throws {OPFSError} If writing the file fails
263
- *
264
- * @example
265
- * ```typescript
266
- * // Write binary data
267
- * const binaryData = new Uint8Array([1, 2, 3, 4, 5]);
268
- * await fs.writeFile('/data/binary.dat', binaryData);
269
- *
270
- * // Write from ArrayBuffer
271
- * const arrayBuffer = new ArrayBuffer(10);
272
- * await fs.writeFile('/data/buffer.dat', arrayBuffer);
273
- * ```
274
- */
275
- async writeFile(t, e) {
276
- await this.mount();
277
- const a = e instanceof Uint8Array ? e : new Uint8Array(e);
278
- await u(t, "exclusive", async () => {
279
- const i = await this.exists(t), r = await this.open(t, { create: !0, truncate: !0 });
280
- try {
281
- await this.write(r, a, 0, a.length, null, !1), await this.fsync(r);
282
- } finally {
283
- await this.close(r);
284
- }
285
- await this.notifyChange({ path: t, type: i ? h.Changed : h.Added, isDirectory: !1 });
286
- });
287
- }
288
- /**
289
- * Append data to a file
290
- *
291
- * Adds binary data to the end of an existing file. If the file doesn't exist,
292
- * it will be created.
293
- *
294
- * @param path - The path to the file to append to
295
- * @param data - The binary data to append to the file (Uint8Array or ArrayBuffer)
296
- * @returns Promise that resolves when the append operation is complete
297
- * @throws {OPFSError} If appending to the file fails
298
- *
299
- * @example
300
- * ```typescript
301
- * // Append binary data
302
- * const additionalData = new Uint8Array([6, 7, 8]);
303
- * await fs.appendFile('/data/binary.dat', additionalData);
304
- *
305
- * // Append from ArrayBuffer
306
- * const arrayBuffer = new ArrayBuffer(5);
307
- * await fs.appendFile('/data/buffer.dat', arrayBuffer);
308
- * ```
309
- */
310
- async appendFile(t, e) {
311
- await this.mount();
312
- const a = e instanceof Uint8Array ? e : new Uint8Array(e);
313
- await u(t, "exclusive", async () => {
314
- const i = await this.open(t, { create: !0 });
315
- try {
316
- const { size: r } = await this.fstat(i);
317
- await this.write(i, a, 0, a.length, r, !1), await this.fsync(i);
318
- } finally {
319
- await this.close(i);
320
- }
321
- await this.notifyChange({ path: t, type: h.Changed, isDirectory: !1 });
322
- });
323
- }
324
- /**
325
- * Create a directory
326
- *
327
- * Creates a new directory at the specified path. If the recursive option
328
- * is enabled, parent directories will be created as needed.
329
- *
330
- * @param path - The path where the directory should be created
331
- * @param options - Options for directory creation
332
- * @param options.recursive - Whether to create parent directories if they don't exist (default: false)
333
- * @returns Promise that resolves when the directory is created
334
- * @throws {OPFSError} If the directory cannot be created
335
- *
336
- * @example
337
- * ```typescript
338
- * // Create a single directory
339
- * await fs.mkdir('/users/john');
340
- *
341
- * // Create nested directories
342
- * await fs.mkdir('/users/john/documents/projects', { recursive: true });
343
- * ```
344
- */
345
- async mkdir(t, e) {
346
- await this.mount();
347
- const a = e?.recursive ?? !1, i = v(t);
348
- let r = this.root;
349
- for (let s = 0; s < i.length; s++) {
350
- const n = i[s];
351
- try {
352
- r = await r.getDirectoryHandle(n, { create: a || s === i.length - 1 });
353
- } catch (o) {
354
- throw o.name === "NotFoundError" ? l(o, {
355
- path: M(i.slice(0, s + 1)),
356
- existenceType: "directory"
357
- }) : o.name === "TypeMismatchError" ? l(o, { path: n, isDirectory: !1 }) : new x("create directory", n, o);
358
- }
359
- }
360
- await this.notifyChange({ path: t, type: h.Added, isDirectory: !0 });
361
- }
362
- /**
363
- * Get file or directory statistics
364
- *
365
- * Returns detailed information about a file or directory, including
366
- * size, modification time, and optionally a hash of the file content.
367
- *
368
- * @param path - The path to the file or directory
369
- * @returns Promise that resolves to FileStat object
370
- * @throws {OPFSError} If the path does not exist or cannot be accessed
371
- *
372
- * @example
373
- * ```typescript
374
- * const stats = await fs.stat('/data/config.json');
375
- * console.log(`File size: ${stats.size} bytes`);
376
- * console.log(`Last modified: ${stats.mtime}`);
377
- *
378
- * // If hashing is enabled, hash will be included
379
- * if (stats.hash) {
380
- * console.log(`Hash: ${stats.hash}`);
381
- * }
382
- * ```
383
- */
384
- async stat(t) {
385
- if (await this.mount(), t === "/")
386
- return {
387
- kind: "directory",
388
- size: 0,
389
- mtime: (/* @__PURE__ */ new Date(0)).toISOString(),
390
- ctime: (/* @__PURE__ */ new Date(0)).toISOString(),
391
- isFile: !1,
392
- isDirectory: !0
393
- };
394
- const e = b(t);
395
- let a;
396
- try {
397
- a = await this.getDirectoryHandle(S(t), !1);
398
- const i = this.options.hashAlgorithm, s = await (await a.getFileHandle(e, { create: !1 })).getFile(), n = {
399
- kind: "file",
400
- size: s.size,
401
- mtime: new Date(s.lastModified).toISOString(),
402
- ctime: new Date(s.lastModified).toISOString(),
403
- isFile: !0,
404
- isDirectory: !1
405
- };
406
- if (i === "etag")
407
- n.hash = `${s.lastModified.toString(36)}-${s.size.toString(36)}`;
408
- else if (typeof i == "string")
409
- try {
410
- const o = await T(s, i, this.options.maxFileSize);
411
- n.hash = o;
412
- } catch (o) {
413
- console.warn(`Failed to calculate hash for ${t}:`, o);
414
- }
415
- return n;
416
- } catch (i) {
417
- if (i.name === "NotFoundError")
418
- throw new m("file", t, i);
419
- if (i.name !== "TypeMismatchError")
420
- throw new x("stat", t, i);
421
- }
422
- try {
423
- return await a.getDirectoryHandle(e, { create: !1 }), {
424
- kind: "directory",
425
- size: 0,
426
- mtime: (/* @__PURE__ */ new Date(0)).toISOString(),
427
- ctime: (/* @__PURE__ */ new Date(0)).toISOString(),
428
- isFile: !1,
429
- isDirectory: !0
430
- };
431
- } catch (i) {
432
- throw new x("stat", t, i);
433
- }
434
- }
435
- /**
436
- * Read a directory's contents
437
- *
438
- * Lists all files and subdirectories within the specified directory.
439
- *
440
- * @param path - The path to the directory to read
441
- * @returns Promise that resolves to an array of detailed file/directory information
442
- * @throws {OPFSError} If the directory does not exist or cannot be accessed
443
- *
444
- * @example
445
- * ```typescript
446
- * // Get detailed information about files and directories
447
- * const detailed = await fs.readDir('/users/john/documents');
448
- * detailed.forEach(item => {
449
- * console.log(`${item.name} - ${item.isFile ? 'file' : 'directory'}`);
450
- * });
451
- * ```
452
- */
453
- async readDir(t) {
454
- await this.mount();
455
- const e = await this.getDirectoryHandle(t, !1), a = [];
456
- for await (const [i, r] of e.entries()) {
457
- const s = r.kind === "file";
458
- a.push({
459
- name: i,
460
- kind: r.kind,
461
- isFile: s,
462
- isDirectory: !s
463
- });
464
- }
465
- return a;
466
- }
467
- /**
468
- * Check if a file or directory exists
469
- *
470
- * Verifies if a file or directory exists at the specified path.
471
- *
472
- * @param path - The path to check
473
- * @returns Promise that resolves to true if the file or directory exists, false otherwise
474
- *
475
- * @example
476
- * ```typescript
477
- * const exists = await fs.exists('/config/settings.json');
478
- * console.log(`File exists: ${exists}`);
479
- * ```
480
- */
481
- async exists(t) {
482
- if (await this.mount(), t === "/")
483
- return !0;
484
- const e = b(t);
485
- let a = null;
486
- try {
487
- a = await this.getDirectoryHandle(S(t), !1);
488
- } catch (i) {
489
- if (a = null, i.name !== "NotFoundError" && i.name !== "TypeMismatchError")
490
- throw i;
491
- }
492
- if (!a || !e)
493
- return !1;
494
- try {
495
- return await a.getFileHandle(e, { create: !1 }), !0;
496
- } catch (i) {
497
- if (i.name !== "NotFoundError" && i.name !== "TypeMismatchError")
498
- throw i;
499
- try {
500
- return await a.getDirectoryHandle(e, { create: !1 }), !0;
501
- } catch (r) {
502
- if (r.name !== "NotFoundError" && r.name !== "TypeMismatchError")
503
- throw r;
504
- return !1;
505
- }
506
- }
507
- }
508
- /**
509
- * Clear all contents of a directory without removing the directory itself
510
- *
511
- * Removes all files and subdirectories within the specified directory,
512
- * but keeps the directory itself.
513
- *
514
- * @param path - The path to the directory to clear (default: '/')
515
- * @returns Promise that resolves when all contents are removed
516
- * @throws {OPFSError} If the operation fails
517
- *
518
- * @example
519
- * ```typescript
520
- * // Clear root directory contents
521
- * await fs.clear('/');
522
- *
523
- * // Clear specific directory contents
524
- * await fs.clear('/data');
525
- * ```
526
- */
527
- async clear(t = "/") {
528
- await this.mount();
529
- try {
530
- const e = await this.readDir(t);
531
- for (const a of e) {
532
- const i = `${t === "/" ? "" : t}/${a.name}`;
533
- await this.remove(i, { recursive: !0 });
534
- }
535
- await this.notifyChange({ path: t, type: h.Changed, isDirectory: !0 });
536
- } catch (e) {
537
- throw e instanceof f ? e : l(e, { path: t, isDirectory: !0 });
538
- }
539
- }
540
- /**
541
- * Remove files and directories
542
- *
543
- * Removes files and directories. Similar to Node.js fs.rm().
544
- *
545
- * @param path - The path to remove
546
- * @param options - Options for removal
547
- * @param options.recursive - Whether to remove directories and their contents recursively (default: false)
548
- * @param options.force - Whether to ignore errors if the path doesn't exist (default: false)
549
- * @returns Promise that resolves when the removal is complete
550
- * @throws {OPFSError} If the removal fails
551
- *
552
- * @example
553
- * ```typescript
554
- * // Remove a file
555
- * await fs.rm('/path/to/file.txt');
556
- *
557
- * // Remove a directory and all its contents
558
- * await fs.rm('/path/to/directory', { recursive: true });
559
- *
560
- * // Remove with force (ignore if doesn't exist)
561
- * await fs.rm('/maybe/exists', { force: true });
562
- * ```
563
- */
564
- async remove(t, e) {
565
- if (await this.mount(), t === "/")
566
- throw new $("EROOT", t);
567
- const { recursive: a = !1, force: i = !1 } = e || {}, r = await this.getDirectoryHandle(S(t), !1), s = await this.stat(t);
568
- await _(r, t, { recursive: a, force: i }), await this.notifyChange({ path: t, type: h.Removed, isDirectory: s.isDirectory });
569
- }
570
- /**
571
- * Resolve a path to an absolute path
572
- *
573
- * Resolves relative paths and normalizes path segments (like '..' and '.').
574
- * Similar to Node.js fs.realpath() but without symlink resolution since OPFS doesn't support symlinks.
575
- *
576
- * @param path - The path to resolve
577
- * @returns Promise that resolves to the absolute normalized path
578
- * @throws {FileNotFoundError} If the path does not exist
579
- * @throws {OPFSError} If path resolution fails
580
- *
581
- * @example
582
- * ```typescript
583
- * // Resolve relative path
584
- * const absolute = await fs.realpath('./config/../data/file.txt');
585
- * console.log(absolute); // '/data/file.txt'
586
- * ```
587
- */
588
- async realpath(t) {
589
- await this.mount();
590
- try {
591
- const e = H(t);
592
- if (!await this.exists(e))
593
- throw new m("file", e);
594
- return e;
595
- } catch (e) {
596
- throw e instanceof f ? e : l(e, { path: t });
597
- }
598
- }
599
- /**
600
- * Rename a file or directory
601
- *
602
- * Changes the name of a file or directory. If the target path already exists,
603
- * it will be replaced only if overwrite option is enabled.
604
- *
605
- * @param oldPath - The current path of the file or directory
606
- * @param newPath - The new path for the file or directory
607
- * @param options - Options for renaming
608
- * @param options.overwrite - Whether to overwrite existing files (default: false)
609
- * @returns Promise that resolves when the rename operation is complete
610
- * @throws {OPFSError} If the rename operation fails
611
- *
612
- * @example
613
- * ```typescript
614
- * // Basic rename (fails if target exists)
615
- * await fs.rename('/old/path/file.txt', '/new/path/renamed.txt');
616
- *
617
- * // Rename with overwrite
618
- * await fs.rename('/old/path/file.txt', '/new/path/renamed.txt', { overwrite: true });
619
- * ```
620
- */
621
- async rename(t, e, a) {
622
- await this.mount();
623
- try {
624
- const i = a?.overwrite ?? !1, r = await this.stat(t);
625
- if (await this.exists(e) && !i)
626
- throw new C(e);
627
- await this.copy(t, e, { recursive: !0, overwrite: i }), await this.remove(t, { recursive: !0 }), await this.notifyChange({ path: t, type: h.Removed, isDirectory: r.isDirectory }), await this.notifyChange({ path: e, type: h.Added, isDirectory: r.isDirectory });
628
- } catch (i) {
629
- throw i instanceof f ? i : l(i, { path: t });
630
- }
631
- }
632
- /**
633
- * Copy files and directories
634
- *
635
- * Copies files and directories. Similar to Node.js fs.cp().
636
- *
637
- * @param source - The source path to copy from
638
- * @param destination - The destination path to copy to
639
- * @param options - Options for copying
640
- * @param options.recursive - Whether to copy directories recursively (default: false)
641
- * @param options.overwrite - Whether to overwrite existing files (default: true)
642
- * @returns Promise that resolves when the copy operation is complete
643
- * @throws {OPFSError} If the copy operation fails
644
- *
645
- * @example
646
- * ```typescript
647
- * // Copy a file
648
- * await fs.copy('/source/file.txt', '/dest/file.txt');
649
- *
650
- * // Copy a directory and all its contents
651
- * await fs.copy('/source/dir', '/dest/dir', { recursive: true });
652
- *
653
- * // Copy without overwriting existing files
654
- * await fs.copy('/source', '/dest', { recursive: true, overwrite: false });
655
- * ```
656
- */
657
- async copy(t, e, a) {
658
- await this.mount();
659
- try {
660
- const i = a?.recursive ?? !1, r = a?.overwrite ?? !0;
661
- if (!await this.exists(t))
662
- throw new m("source", t);
663
- if (await this.exists(e) && !r)
664
- throw new C(e);
665
- if ((await this.stat(t)).isFile) {
666
- const c = await this.readFile(t);
667
- await this.writeFile(e, c);
668
- } else {
669
- if (!i)
670
- throw new N("directory", t);
671
- await this.mkdir(e, { recursive: !0 });
672
- const c = await this.readDir(t);
673
- for (const w of c) {
674
- const y = `${t}/${w.name}`, d = `${e}/${w.name}`;
675
- await this.copy(y, d, { recursive: !0, overwrite: r });
676
- }
677
- }
678
- } catch (i) {
679
- throw i instanceof f ? i : l(i, { path: t });
680
- }
681
- }
682
- /**
683
- * Start watching a file or directory for changes
684
- *
685
- * @param path - The path to watch (minimatch syntax allowed)
686
- * @param options - Watch options
687
- * @param options.recursive - Whether to watch recursively (default: true)
688
- * @param options.exclude - Glob pattern(s) to exclude (minimatch).
689
- * @returns Promise that resolves when watching starts
690
- *
691
- * @example
692
- * ```typescript
693
- * // Watch entire directory tree recursively (default)
694
- * await fs.watch('/data');
695
- *
696
- * // Watch only immediate children (shallow)
697
- * await fs.watch('/data', { recursive: false });
698
- *
699
- * // Watch a single file
700
- * await fs.watch('/config.json', { recursive: false });
701
- *
702
- * // Watch all json files but not in dist directory
703
- * await fs.watch('/**\/*.json', { recursive: false, exclude: ['dist/**'] });
704
- *
705
- * ```
706
- */
707
- async watch(t, e) {
708
- if (!this.options.broadcastChannel)
709
- throw new R("This instance is not configured to send events. Please specify options.broadcastChannel to enable watching.");
710
- const a = {
711
- pattern: B(t, e?.recursive ?? !0),
712
- include: Array.isArray(e?.include) ? e.include : [e?.include ?? "**"],
713
- exclude: Array.isArray(e?.exclude) ? e.exclude : [e?.exclude ?? ""]
714
- };
715
- this.watchers.set(t, a);
716
- }
717
- /**
718
- * Stop watching a previously watched path
719
- */
720
- unwatch(t) {
721
- this.watchers.delete(t);
722
- }
723
- /**
724
- * Open a file and return a file descriptor
725
- *
726
- * @param path - The path to the file to open
727
- * @param options - Options for opening the file
728
- * @param options.create - Whether to create the file if it doesn't exist (default: false)
729
- * @param options.exclusive - If true and create is true, fails if file already exists (default: false)
730
- * Note: This is best-effort in OPFS, not fully atomic due to browser limitations
731
- * @param options.truncate - Whether to truncate the file to zero length (default: false)
732
- * @returns Promise that resolves to a file descriptor number
733
- * @throws {OPFSError} If opening the file fails
734
- *
735
- * @example
736
- * ```typescript
737
- * // Open existing file for reading
738
- * const fd = await fs.open('/data/config.json');
739
- *
740
- * // Create new file for writing
741
- * const fd = await fs.open('/data/new.txt', { create: true });
742
- *
743
- * // Create file exclusively (fails if exists)
744
- * const fd = await fs.open('/data/unique.txt', { create: true, exclusive: true });
745
- *
746
- * // Open and truncate file
747
- * const fd = await fs.open('/data/log.txt', { create: true, truncate: true });
748
- * ```
749
- */
750
- async open(t, e) {
751
- await this.mount();
752
- const { create: a = !1, exclusive: i = !1, truncate: r = !1 } = e || {}, s = F(H(t));
753
- try {
754
- return a && i ? await u(s, "exclusive", async () => {
755
- if (await this.exists(s))
756
- throw new C(s);
757
- return this._openFile(s, a, r);
758
- }) : await this._openFile(s, a, r);
759
- } catch (n) {
760
- if (n instanceof f)
761
- throw n;
762
- const o = n && n.name === "TypeMismatchError";
763
- throw l(n, {
764
- path: s,
765
- isDirectory: !!o
766
- });
767
- }
768
- }
769
- /**
770
- * Internal method to open a file (without locking)
771
- * @private
772
- */
773
- async _openFile(t, e, a) {
774
- const i = await this.getFileHandle(t, e);
775
- try {
776
- await i.getFile();
777
- } catch (n) {
778
- throw l(n, { path: t, isDirectory: !0 });
779
- }
780
- const r = await U(i, t);
781
- a && (r.truncate(0), r.flush());
782
- const s = this.nextFd++;
783
- return this.openFiles.set(s, {
784
- path: t,
785
- fileHandle: i,
786
- syncHandle: r,
787
- position: 0
788
- }), s;
789
- }
790
- /**
791
- * Close a file descriptor
792
- *
793
- * @param fd - The file descriptor to close
794
- * @returns Promise that resolves when the file descriptor is closed
795
- * @throws {OPFSError} If the file descriptor is invalid or closing fails
796
- *
797
- * @example
798
- * ```typescript
799
- * const fd = await fs.open('/data/file.txt');
800
- * // ... use the file descriptor ...
801
- * await fs.close(fd);
802
- * ```
803
- */
804
- async close(t) {
805
- const e = this._getFileDescriptor(t);
806
- A(t, e.syncHandle, e.path), this.openFiles.delete(t);
807
- }
808
- /**
809
- * Read data from a file descriptor
810
- *
811
- * @param fd - The file descriptor to read from
812
- * @param buffer - The buffer to read data into
813
- * @param offset - The offset in the buffer to start writing at
814
- * @param length - The number of bytes to read
815
- * @param position - The position in the file to read from (null for current position)
816
- * @returns Promise that resolves to the number of bytes read and the modified buffer
817
- * @throws {OPFSError} If the file descriptor is invalid or reading fails
818
- *
819
- * @note This method uses Comlink.transfer() to efficiently pass the buffer as a Transferable Object,
820
- * ensuring zero-copy performance across Web Worker boundaries.
821
- *
822
- * @example
823
- * ```typescript
824
- * const fd = await fs.open('/data/file.txt');
825
- * const buffer = new Uint8Array(1024);
826
- * const { bytesRead, buffer: modifiedBuffer } = await fs.read(fd, buffer, 0, 1024, null);
827
- * console.log(`Read ${bytesRead} bytes`);
828
- * // Use modifiedBuffer which contains the actual data
829
- * await fs.close(fd);
830
- * ```
831
- */
832
- async read(t, e, a, i, r) {
833
- const s = this._getFileDescriptor(t);
834
- I(e.length, a, i, r);
835
- try {
836
- const n = r ?? s.position, o = s.syncHandle.getSize(), { isEOF: c, actualLength: w } = W(n, i, o);
837
- if (c)
838
- return p({ bytesRead: 0, buffer: e }, [e.buffer]);
839
- const y = e.subarray(a, a + w), d = s.syncHandle.read(y, { at: n });
840
- return r == null && (s.position = n + d), p({ bytesRead: d, buffer: e }, [e.buffer]);
841
- } catch (n) {
842
- throw g("read", t, s.path, n);
843
- }
844
- }
845
- /**
846
- * Write data to a file descriptor
847
- *
848
- * @param fd - The file descriptor to write to
849
- * @param buffer - The buffer containing data to write
850
- * @param offset - The offset in the buffer to start reading from (default: 0)
851
- * @param length - The number of bytes to write (default: entire buffer)
852
- * @param position - The position in the file to write to (null/undefined for current position)
853
- * @param emitEvent - Whether to emit a change event (default: true)
854
- * @returns Promise that resolves to the number of bytes written
855
- * @throws {OPFSError} If the file descriptor is invalid or writing fails
856
- *
857
- * @example
858
- * ```typescript
859
- * const fd = await fs.open('/data/file.txt', { create: true });
860
- * const data = new TextEncoder().encode('Hello, World!');
861
- * const bytesWritten = await fs.write(fd, data, 0, data.length, null);
862
- * console.log(`Wrote ${bytesWritten} bytes`);
863
- * await fs.close(fd);
864
- * ```
865
- */
866
- async write(t, e, a = 0, i, r, s = !0) {
867
- const n = this._getFileDescriptor(t), o = i ?? e.length - a;
868
- I(e.length, a, o, r);
869
- try {
870
- const c = r ?? n.position, w = e.subarray(a, a + o), y = n.syncHandle.write(w, { at: c });
871
- return (r == null || r === n.position) && (n.position = c + y), s && await this.notifyChange({ path: n.path, type: h.Changed, isDirectory: !1 }), y;
872
- } catch (c) {
873
- throw g("write", t, n.path, c);
874
- }
875
- }
876
- /**
877
- * Get file status information by file descriptor
878
- *
879
- * @param fd - The file descriptor
880
- * @returns Promise that resolves to FileStat object
881
- * @throws {OPFSError} If the file descriptor is invalid
882
- *
883
- * @example
884
- * ```typescript
885
- * const fd = await fs.open('/data/file.txt');
886
- * const stats = await fs.fstat(fd);
887
- * console.log(`File size: ${stats.size} bytes`);
888
- * console.log(`Last modified: ${stats.mtime}`);
889
- *
890
- * // If hashing is enabled, hash will be included
891
- * if (stats.hash) {
892
- * console.log(`Hash: ${stats.hash}`);
893
- * }
894
- * ```
895
- */
896
- async fstat(t) {
897
- const e = this._getFileDescriptor(t);
898
- return this.stat(e.path);
899
- }
900
- /**
901
- * Truncate file to specified size
902
- *
903
- * @param fd - The file descriptor
904
- * @param size - The new size of the file (default: 0)
905
- * @returns Promise that resolves when truncation is complete
906
- * @throws {OPFSError} If the file descriptor is invalid or truncation fails
907
- *
908
- * @example
909
- * ```typescript
910
- * const fd = await fs.open('/data/file.txt', { create: true });
911
- * await fs.truncate(fd, 100); // Truncate to 100 bytes
912
- * ```
913
- */
914
- async ftruncate(t, e = 0) {
915
- const a = this._getFileDescriptor(t);
916
- if (e < 0 || !Number.isInteger(e))
917
- throw new E("argument", "Invalid size");
918
- try {
919
- a.syncHandle.truncate(e), a.syncHandle.flush(), a.position > e && (a.position = e), await this.notifyChange({ path: a.path, type: h.Changed, isDirectory: !1 });
920
- } catch (i) {
921
- throw g("truncate", t, a.path, i);
922
- }
923
- }
924
- /**
925
- * Synchronize file data to storage (fsync equivalent)
926
- *
927
- * @param fd - The file descriptor
928
- * @returns Promise that resolves when synchronization is complete
929
- * @throws {OPFSError} If the file descriptor is invalid or sync fails
930
- *
931
- * @example
932
- * ```typescript
933
- * const fd = await fs.open('/data/file.txt', { create: true });
934
- * await fs.write(fd, data);
935
- * await fs.fsync(fd); // Ensure data is written to storage
936
- * ```
937
- */
938
- async fsync(t) {
939
- const e = this._getFileDescriptor(t);
940
- try {
941
- e.syncHandle.flush();
942
- } catch (a) {
943
- throw g("sync", t, e.path, a);
944
- }
945
- }
946
- /**
947
- * Dispose of resources and clean up the file system instance
948
- *
949
- * This method should be called when the file system instance is no longer needed
950
- * to properly clean up resources like the broadcast channel and watch timers.
951
- */
952
- dispose() {
953
- this.broadcastChannel && (this.broadcastChannel.close(), this.broadcastChannel = null), this.watchers.clear();
954
- for (const [t, e] of this.openFiles)
955
- A(t, e.syncHandle, e.path);
956
- this.openFiles.clear(), this.nextFd = 1;
957
- }
958
- /**
959
- * Synchronize the file system with external data
960
- *
961
- * Syncs the file system with an array of entries containing paths and data.
962
- * This is useful for importing data from external sources or syncing with remote data.
963
- *
964
- * @param entries - Array of [path, data] tuples to sync
965
- * @returns Promise that resolves when synchronization is complete
966
- * @throws {OPFSError} If the synchronization fails
967
- *
968
- * @example
969
- * ```typescript
970
- * // Sync with external data
971
- * const entries: [string, string | Uint8Array | Blob][] = [
972
- * ['/config.json', JSON.stringify({ theme: 'dark' })],
973
- * ['/data/binary.dat', new Uint8Array([1, 2, 3, 4])],
974
- * ['/upload.txt', new Blob(['file content'], { type: 'text/plain' })]
975
- * ];
976
- *
977
- * // Sync without clearing existing files
978
- * await fs.sync(entries);
979
- *
980
- * // Clean file system and then sync
981
- * await fs.sync(entries, { cleanBefore: true });
982
- * ```
983
- */
984
- async createIndex(t) {
985
- await this.mount();
986
- try {
987
- for (const [e, a] of t) {
988
- const i = F(e);
989
- let r;
990
- a instanceof Blob ? r = await L(a) : typeof a == "string" ? r = new TextEncoder().encode(a) : r = a, await this.writeFile(i, r);
991
- }
992
- } catch (e) {
993
- throw e instanceof f ? e : l(e);
994
- }
995
- }
996
- }
997
- typeof globalThis < "u" && globalThis.constructor.name === "DedicatedWorkerGlobalScope" && O(new j());
998
- export {
999
- j as OPFSWorker
1000
- };
1001
- //# sourceMappingURL=raw.js.map