opfs-worker 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +500 -0
- package/dist/assets/opfs.worker-BiWuxhcz.js.map +1 -0
- package/dist/index.cjs +2 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.js +752 -0
- package/dist/index.js.map +1 -0
- package/dist/inline.cjs +997 -0
- package/dist/inline.cjs.map +1 -0
- package/dist/inline.d.ts +24 -0
- package/dist/inline.d.ts.map +1 -0
- package/dist/inline.js +24 -0
- package/dist/inline.js.map +1 -0
- package/dist/opfs.worker.d.ts +447 -0
- package/dist/opfs.worker.d.ts.map +1 -0
- package/dist/opfs.worker.js +765 -0
- package/dist/types.d.ts +19 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +1 -0
- package/dist/utils/encoder.d.ts +4 -0
- package/dist/utils/encoder.d.ts.map +1 -0
- package/dist/utils/encoder.js +86 -0
- package/dist/utils/errors.d.ts +57 -0
- package/dist/utils/errors.d.ts.map +1 -0
- package/dist/utils/errors.js +77 -0
- package/dist/utils/helpers.d.ts +33 -0
- package/dist/utils/helpers.d.ts.map +1 -0
- package/dist/utils/helpers.js +96 -0
- package/package.json +83 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,752 @@
|
|
|
1
|
+
import { expose as p } from "comlink";
|
|
2
|
+
class s extends Error {
|
|
3
|
+
constructor(e, t, n) {
|
|
4
|
+
super(e), this.code = t, this.path = n, this.name = "OPFSError";
|
|
5
|
+
}
|
|
6
|
+
}
|
|
7
|
+
class A extends s {
|
|
8
|
+
constructor() {
|
|
9
|
+
super("OPFS is not supported in this browser", "OPFS_NOT_SUPPORTED");
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
class y extends s {
|
|
13
|
+
constructor() {
|
|
14
|
+
super("OPFS is not mounted", "OPFS_NOT_MOUNTED");
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
class g extends s {
|
|
18
|
+
constructor(e, t) {
|
|
19
|
+
super(e, "INVALID_PATH", t);
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
class m extends s {
|
|
23
|
+
constructor(e) {
|
|
24
|
+
super(`File not found: ${e}`, "FILE_NOT_FOUND", e);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
function S(r, e = "utf-8") {
|
|
28
|
+
switch (e) {
|
|
29
|
+
case "utf8":
|
|
30
|
+
case "utf-8":
|
|
31
|
+
return new TextEncoder().encode(r);
|
|
32
|
+
case "utf16le":
|
|
33
|
+
case "ucs2":
|
|
34
|
+
case "ucs-2":
|
|
35
|
+
return I(r);
|
|
36
|
+
case "ascii":
|
|
37
|
+
return H(r);
|
|
38
|
+
case "latin1":
|
|
39
|
+
return N(r);
|
|
40
|
+
case "binary":
|
|
41
|
+
return Uint8Array.from(r, (t) => t.charCodeAt(0));
|
|
42
|
+
case "base64":
|
|
43
|
+
return Uint8Array.from(atob(r), (t) => t.charCodeAt(0));
|
|
44
|
+
case "hex":
|
|
45
|
+
if (!/^[\da-f]+$/i.test(r) || r.length % 2 !== 0)
|
|
46
|
+
throw new s("Invalid hex string", "INVALID_HEX_FORMAT");
|
|
47
|
+
return Uint8Array.from(r.match(/.{1,2}/g).map((t) => parseInt(t, 16)));
|
|
48
|
+
default:
|
|
49
|
+
return console.warn("Encoding not supported, falling back to UTF-8"), new TextEncoder().encode(r);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
function D(r, e = "utf-8") {
|
|
53
|
+
switch (e) {
|
|
54
|
+
case "utf8":
|
|
55
|
+
case "utf-8":
|
|
56
|
+
return new TextDecoder().decode(r);
|
|
57
|
+
case "utf16le":
|
|
58
|
+
case "ucs2":
|
|
59
|
+
case "ucs-2":
|
|
60
|
+
return T(r);
|
|
61
|
+
case "latin1":
|
|
62
|
+
return String.fromCharCode(...r);
|
|
63
|
+
case "binary":
|
|
64
|
+
return String.fromCharCode(...r);
|
|
65
|
+
case "ascii":
|
|
66
|
+
return String.fromCharCode(...r.map((t) => t & 127));
|
|
67
|
+
case "base64":
|
|
68
|
+
return btoa(String.fromCharCode(...r));
|
|
69
|
+
case "hex":
|
|
70
|
+
return Array.from(r).map((t) => t.toString(16).padStart(2, "0")).join("");
|
|
71
|
+
default:
|
|
72
|
+
return console.warn("Unsupported encoding, falling back to UTF-8"), new TextDecoder().decode(r);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
function I(r) {
|
|
76
|
+
const e = new Uint8Array(r.length * 2);
|
|
77
|
+
for (let t = 0; t < r.length; t++) {
|
|
78
|
+
const n = r.charCodeAt(t);
|
|
79
|
+
e[t * 2] = n & 255, e[t * 2 + 1] = n >> 8;
|
|
80
|
+
}
|
|
81
|
+
return e;
|
|
82
|
+
}
|
|
83
|
+
function T(r) {
|
|
84
|
+
r.length % 2 !== 0 && (console.warn("Invalid UTF-16LE buffer length, truncating last byte"), r = r.slice(0, r.length - 1));
|
|
85
|
+
const e = new Uint16Array(r.buffer, r.byteOffset, r.byteLength / 2);
|
|
86
|
+
return String.fromCharCode(...e);
|
|
87
|
+
}
|
|
88
|
+
function N(r) {
|
|
89
|
+
const e = new Uint8Array(r.length);
|
|
90
|
+
for (let t = 0; t < r.length; t++)
|
|
91
|
+
e[t] = r.charCodeAt(t) & 255;
|
|
92
|
+
return e;
|
|
93
|
+
}
|
|
94
|
+
function H(r) {
|
|
95
|
+
const e = new Uint8Array(r.length);
|
|
96
|
+
for (let t = 0; t < r.length; t++)
|
|
97
|
+
e[t] = r.charCodeAt(t) & 127;
|
|
98
|
+
return e;
|
|
99
|
+
}
|
|
100
|
+
function $() {
|
|
101
|
+
if (!("storage" in navigator) || !("getDirectory" in navigator.storage))
|
|
102
|
+
throw new A();
|
|
103
|
+
}
|
|
104
|
+
function u(r) {
|
|
105
|
+
return Array.isArray(r) ? r : r.split("/").filter(Boolean);
|
|
106
|
+
}
|
|
107
|
+
function F(r) {
|
|
108
|
+
return typeof r == "string" ? r ?? "/" : `/${r.join("/")}`;
|
|
109
|
+
}
|
|
110
|
+
function O(r, e = "utf-8") {
|
|
111
|
+
return typeof r == "string" ? S(r, e) : r instanceof Uint8Array ? r : new Uint8Array(r);
|
|
112
|
+
}
|
|
113
|
+
async function x(r) {
|
|
114
|
+
const e = await r.createSyncAccessHandle();
|
|
115
|
+
try {
|
|
116
|
+
const t = e.getSize(), n = new Uint8Array(t);
|
|
117
|
+
return e.read(n, { at: 0 }), n;
|
|
118
|
+
} finally {
|
|
119
|
+
e.close();
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
async function E(r, e, t, n = {}) {
|
|
123
|
+
let o = null;
|
|
124
|
+
try {
|
|
125
|
+
o = await r.createSyncAccessHandle();
|
|
126
|
+
const i = O(e, t), a = n.append ? o.getSize() : 0;
|
|
127
|
+
o.write(i, { at: a }), n.truncate && !n.append && o.truncate(i.byteLength), o.flush();
|
|
128
|
+
} catch (i) {
|
|
129
|
+
console.error(i);
|
|
130
|
+
const a = n.append ? "append" : "write";
|
|
131
|
+
throw new s(`Failed to ${a} file`, `${a.toUpperCase()}_FAILED`);
|
|
132
|
+
} finally {
|
|
133
|
+
if (o)
|
|
134
|
+
try {
|
|
135
|
+
o.close();
|
|
136
|
+
} catch {
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
async function v(r, e = "SHA-1") {
|
|
141
|
+
try {
|
|
142
|
+
const t = new Uint8Array(r), n = await crypto.subtle.digest(e, t);
|
|
143
|
+
return Array.from(new Uint8Array(n)).map((i) => i.toString(16).padStart(2, "0")).join("");
|
|
144
|
+
} catch (t) {
|
|
145
|
+
throw console.warn(`Failed to calculate ${e} hash:`, t), t;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
class U {
|
|
149
|
+
/** Root directory handle for the file system */
|
|
150
|
+
root = null;
|
|
151
|
+
/**
|
|
152
|
+
* Creates a new OPFSFileSystem instance
|
|
153
|
+
*
|
|
154
|
+
* @throws {OPFSError} If OPFS is not supported in the current browser
|
|
155
|
+
*/
|
|
156
|
+
constructor() {
|
|
157
|
+
$();
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* Initialize the file system within a given directory
|
|
161
|
+
*
|
|
162
|
+
* This method sets up the root directory for all subsequent operations.
|
|
163
|
+
* It must be called before any other file system operations.
|
|
164
|
+
*
|
|
165
|
+
* @param root - The root path for the file system (default: '/')
|
|
166
|
+
* @returns Promise that resolves to true if initialization was successful
|
|
167
|
+
* @throws {OPFSError} If initialization fails
|
|
168
|
+
*
|
|
169
|
+
* @example
|
|
170
|
+
* ```typescript
|
|
171
|
+
* const fs = new OPFSFileSystem();
|
|
172
|
+
* const success = await fs.init('/my-app');
|
|
173
|
+
* ```
|
|
174
|
+
*/
|
|
175
|
+
async mount(e = "/") {
|
|
176
|
+
try {
|
|
177
|
+
const t = await navigator.storage.getDirectory();
|
|
178
|
+
return this.root = await this.getDirectoryHandle(e, !0, t), !0;
|
|
179
|
+
} catch (t) {
|
|
180
|
+
throw console.error(t), new s("Failed to initialize OPFS", "INIT_FAILED");
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
/**
|
|
184
|
+
* Get a directory handle from a path
|
|
185
|
+
*
|
|
186
|
+
* Navigates through the directory structure to find or create a directory
|
|
187
|
+
* at the specified path.
|
|
188
|
+
*
|
|
189
|
+
* @param path - The path to the directory (string or array of segments)
|
|
190
|
+
* @param create - Whether to create the directory if it doesn't exist (default: false)
|
|
191
|
+
* @param from - The directory to start from (default: root directory)
|
|
192
|
+
* @returns Promise that resolves to the directory handle
|
|
193
|
+
* @throws {OPFSError} If the directory cannot be accessed or created
|
|
194
|
+
*
|
|
195
|
+
* @example
|
|
196
|
+
* ```typescript
|
|
197
|
+
* const docsDir = await fs.getDirectoryHandle('/users/john/documents', true);
|
|
198
|
+
* const docsDir2 = await fs.getDirectoryHandle(['users', 'john', 'documents'], true);
|
|
199
|
+
* ```
|
|
200
|
+
*/
|
|
201
|
+
async getDirectoryHandle(e, t = !1, n = this.root) {
|
|
202
|
+
if (!n)
|
|
203
|
+
throw new y();
|
|
204
|
+
const o = Array.isArray(e) ? e : u(e);
|
|
205
|
+
let i = n;
|
|
206
|
+
for (const a of o)
|
|
207
|
+
i = await i.getDirectoryHandle(a, { create: t });
|
|
208
|
+
return i;
|
|
209
|
+
}
|
|
210
|
+
/**
|
|
211
|
+
* Get a file handle from a path
|
|
212
|
+
*
|
|
213
|
+
* Navigates to the parent directory and retrieves or creates a file handle
|
|
214
|
+
* for the specified file path.
|
|
215
|
+
*
|
|
216
|
+
* @param path - The path to the file (string or array of segments)
|
|
217
|
+
* @param create - Whether to create the file if it doesn't exist (default: false)
|
|
218
|
+
* @param from - The directory to start from (default: root directory)
|
|
219
|
+
* @returns Promise that resolves to the file handle
|
|
220
|
+
* @throws {PathError} If the path is empty
|
|
221
|
+
* @throws {OPFSError} If the file cannot be accessed or created
|
|
222
|
+
*
|
|
223
|
+
* @example
|
|
224
|
+
* ```typescript
|
|
225
|
+
* const fileHandle = await fs.getFileHandle('/config/settings.json', true);
|
|
226
|
+
* const fileHandle2 = await fs.getFileHandle(['config', 'settings.json'], true);
|
|
227
|
+
* ```
|
|
228
|
+
*/
|
|
229
|
+
async getFileHandle(e, t = !1, n = this.root) {
|
|
230
|
+
if (!n)
|
|
231
|
+
throw new y();
|
|
232
|
+
const o = u(e);
|
|
233
|
+
if (o.length === 0)
|
|
234
|
+
throw new g("Path must not be empty", Array.isArray(e) ? e.join("/") : e);
|
|
235
|
+
const i = o.pop();
|
|
236
|
+
return (await this.getDirectoryHandle(o, t, n)).getFileHandle(i, { create: t });
|
|
237
|
+
}
|
|
238
|
+
/**
|
|
239
|
+
* Recursively list all files and directories with their stats
|
|
240
|
+
*
|
|
241
|
+
* Traverses the entire file system starting from the root and returns
|
|
242
|
+
* a Map containing all paths and their corresponding file statistics.
|
|
243
|
+
*
|
|
244
|
+
* @param options - Options for indexing
|
|
245
|
+
* @param options.includeHash - Whether to calculate file hash (default: false)
|
|
246
|
+
* @param options.hashAlgorithm - Hash algorithm to use (default: 'SHA-1', fastest)
|
|
247
|
+
* @returns Promise that resolves to a Map of path => FileStat
|
|
248
|
+
* @throws {OPFSError} If the indexing operation fails
|
|
249
|
+
*
|
|
250
|
+
* @example
|
|
251
|
+
* ```typescript
|
|
252
|
+
* // Basic index without hash
|
|
253
|
+
* const index = await fs.index();
|
|
254
|
+
*
|
|
255
|
+
* // Index with file hash
|
|
256
|
+
* const indexWithHash = await fs.index({
|
|
257
|
+
* includeHash: true,
|
|
258
|
+
* hashAlgorithm: 'SHA-1'
|
|
259
|
+
* });
|
|
260
|
+
*
|
|
261
|
+
* // Iterate through all files and directories
|
|
262
|
+
* for (const [path, stat] of index) {
|
|
263
|
+
* console.log(`${path}: ${stat.isFile ? 'file' : 'directory'} (${stat.size} bytes)`);
|
|
264
|
+
* if (stat.hash) console.log(` Hash: ${stat.hash}`);
|
|
265
|
+
* }
|
|
266
|
+
*
|
|
267
|
+
* // Get specific file stats
|
|
268
|
+
* const fileStats = index.get('/data/config.json');
|
|
269
|
+
* if (fileStats) {
|
|
270
|
+
* console.log(`File size: ${fileStats.size} bytes`);
|
|
271
|
+
* if (fileStats.hash) console.log(`Hash: ${fileStats.hash}`);
|
|
272
|
+
* }
|
|
273
|
+
* ```
|
|
274
|
+
*/
|
|
275
|
+
async index(e) {
|
|
276
|
+
const t = /* @__PURE__ */ new Map(), n = async (o) => {
|
|
277
|
+
const i = await this.readdir(o, { withFileTypes: !0 });
|
|
278
|
+
for (const a of i) {
|
|
279
|
+
const l = `${o === "/" ? "" : o}/${a.name}`;
|
|
280
|
+
try {
|
|
281
|
+
const c = await this.stat(l, e);
|
|
282
|
+
t.set(l, c), c.isDirectory && await n(l);
|
|
283
|
+
} catch (c) {
|
|
284
|
+
console.warn(`Skipping broken entry: ${l}`, c);
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
};
|
|
288
|
+
return t.set("/", {
|
|
289
|
+
kind: "directory",
|
|
290
|
+
size: 0,
|
|
291
|
+
mtime: (/* @__PURE__ */ new Date(0)).toISOString(),
|
|
292
|
+
ctime: (/* @__PURE__ */ new Date(0)).toISOString(),
|
|
293
|
+
isFile: !1,
|
|
294
|
+
isDirectory: !0
|
|
295
|
+
}), await n("/"), t;
|
|
296
|
+
}
|
|
297
|
+
async readFile(e, t = "utf-8") {
|
|
298
|
+
try {
|
|
299
|
+
const n = await this.getFileHandle(e, !1), o = await x(n);
|
|
300
|
+
return t === "binary" ? o : D(o, t);
|
|
301
|
+
} catch (n) {
|
|
302
|
+
throw console.error(n), new m(e);
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
/**
|
|
306
|
+
* Write data to a file
|
|
307
|
+
*
|
|
308
|
+
* Creates or overwrites a file with the specified data. If the file already
|
|
309
|
+
* exists, it will be truncated before writing.
|
|
310
|
+
*
|
|
311
|
+
* @param path - The path to the file to write
|
|
312
|
+
* @param data - The data to write to the file (string, Uint8Array, or ArrayBuffer)
|
|
313
|
+
* @param encoding - The encoding to use when writing string data (default: 'utf-8')
|
|
314
|
+
* @returns Promise that resolves when the write operation is complete
|
|
315
|
+
* @throws {OPFSError} If writing the file fails
|
|
316
|
+
*
|
|
317
|
+
* @example
|
|
318
|
+
* ```typescript
|
|
319
|
+
* // Write text data
|
|
320
|
+
* await fs.writeFile('/config/settings.json', JSON.stringify({ theme: 'dark' }));
|
|
321
|
+
*
|
|
322
|
+
* // Write binary data
|
|
323
|
+
* const binaryData = new Uint8Array([1, 2, 3, 4, 5]);
|
|
324
|
+
* await fs.writeFile('/data/binary.dat', binaryData);
|
|
325
|
+
*
|
|
326
|
+
* // Write with specific encoding
|
|
327
|
+
* await fs.writeFile('/data/utf16.txt', 'Hello World', 'utf-16le');
|
|
328
|
+
* ```
|
|
329
|
+
*/
|
|
330
|
+
async writeFile(e, t, n) {
|
|
331
|
+
const o = await this.getFileHandle(e, !0);
|
|
332
|
+
await E(o, t, n, { truncate: !0 });
|
|
333
|
+
}
|
|
334
|
+
/**
|
|
335
|
+
* Append data to a file
|
|
336
|
+
*
|
|
337
|
+
* Adds data to the end of an existing file. If the file doesn't exist,
|
|
338
|
+
* it will be created.
|
|
339
|
+
*
|
|
340
|
+
* @param path - The path to the file to append to
|
|
341
|
+
* @param data - The data to append to the file (string, Uint8Array, or ArrayBuffer)
|
|
342
|
+
* @param encoding - The encoding to use when appending string data (default: 'utf-8')
|
|
343
|
+
* @returns Promise that resolves when the append operation is complete
|
|
344
|
+
* @throws {OPFSError} If appending to the file fails
|
|
345
|
+
*
|
|
346
|
+
* @example
|
|
347
|
+
* ```typescript
|
|
348
|
+
* // Append text to a log file
|
|
349
|
+
* await fs.appendFile('/logs/app.log', `[${new Date().toISOString()}] User logged in\n`);
|
|
350
|
+
*
|
|
351
|
+
* // Append binary data
|
|
352
|
+
* const additionalData = new Uint8Array([6, 7, 8]);
|
|
353
|
+
* await fs.appendFile('/data/binary.dat', additionalData);
|
|
354
|
+
* ```
|
|
355
|
+
*/
|
|
356
|
+
async appendFile(e, t, n) {
|
|
357
|
+
const o = await this.getFileHandle(e, !0);
|
|
358
|
+
await E(o, t, n, { append: !0 });
|
|
359
|
+
}
|
|
360
|
+
/**
|
|
361
|
+
* Create a directory
|
|
362
|
+
*
|
|
363
|
+
* Creates a new directory at the specified path. If the recursive option
|
|
364
|
+
* is enabled, parent directories will be created as needed.
|
|
365
|
+
*
|
|
366
|
+
* @param path - The path where the directory should be created
|
|
367
|
+
* @param options - Options for directory creation
|
|
368
|
+
* @param options.recursive - Whether to create parent directories if they don't exist (default: false)
|
|
369
|
+
* @returns Promise that resolves when the directory is created
|
|
370
|
+
* @throws {OPFSError} If the directory cannot be created
|
|
371
|
+
*
|
|
372
|
+
* @example
|
|
373
|
+
* ```typescript
|
|
374
|
+
* // Create a single directory
|
|
375
|
+
* await fs.mkdir('/users/john');
|
|
376
|
+
*
|
|
377
|
+
* // Create nested directories
|
|
378
|
+
* await fs.mkdir('/users/john/documents/projects', { recursive: true });
|
|
379
|
+
* ```
|
|
380
|
+
*/
|
|
381
|
+
async mkdir(e, t) {
|
|
382
|
+
if (!this.root)
|
|
383
|
+
throw new y();
|
|
384
|
+
const n = t?.recursive ?? !1, o = u(e);
|
|
385
|
+
let i = this.root;
|
|
386
|
+
for (let a = 0; a < o.length; a++) {
|
|
387
|
+
const l = o[a];
|
|
388
|
+
try {
|
|
389
|
+
i = await i.getDirectoryHandle(l, { create: n || a === o.length - 1 });
|
|
390
|
+
} catch (c) {
|
|
391
|
+
throw c.name === "NotFoundError" ? new s(
|
|
392
|
+
`Parent directory does not exist: ${F(o.slice(0, a + 1))}`,
|
|
393
|
+
"ENOENT"
|
|
394
|
+
) : c.name === "TypeMismatchError" ? new s(`Path segment is not a directory: ${l}`, "ENOTDIR") : new s("Failed to create directory", "MKDIR_FAILED");
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
/**
|
|
399
|
+
* Get file or directory stats
|
|
400
|
+
*
|
|
401
|
+
* Retrieves metadata about a file or directory, including size, modification time,
|
|
402
|
+
* type information, and optionally file hashes.
|
|
403
|
+
*
|
|
404
|
+
* @param path - The path to the file or directory
|
|
405
|
+
* @param options - Options for stat operation
|
|
406
|
+
* @param options.includeHash - Whether to calculate file hash (default: false, only for files)
|
|
407
|
+
* @param options.hashAlgorithm - Hash algorithm to use (default: 'SHA-1', fastest)
|
|
408
|
+
* @returns Promise that resolves to file/directory statistics
|
|
409
|
+
* @throws {OPFSError} If the file or directory does not exist or cannot be accessed
|
|
410
|
+
*
|
|
411
|
+
* @example
|
|
412
|
+
* ```typescript
|
|
413
|
+
* // Basic stats
|
|
414
|
+
* const stats = await fs.stat('/config/settings.json');
|
|
415
|
+
* console.log(`File size: ${stats.size} bytes`);
|
|
416
|
+
* console.log(`Is file: ${stats.isFile}`);
|
|
417
|
+
* console.log(`Modified: ${stats.mtime}`);
|
|
418
|
+
*
|
|
419
|
+
* // Stats with hash (SHA-1 is fastest)
|
|
420
|
+
* const statsWithHash = await fs.stat('/config/settings.json', {
|
|
421
|
+
* includeHash: true,
|
|
422
|
+
* hashAlgorithm: 'SHA-1'
|
|
423
|
+
* });
|
|
424
|
+
* console.log(`Hash: ${statsWithHash.hash}`);
|
|
425
|
+
* ```
|
|
426
|
+
*/
|
|
427
|
+
async stat(e, t) {
|
|
428
|
+
const n = u(e), o = n.pop(), i = await this.getDirectoryHandle(n, !1), a = t?.includeHash ?? !1, l = t?.hashAlgorithm ?? "SHA-1";
|
|
429
|
+
try {
|
|
430
|
+
const f = await (await i.getFileHandle(o, { create: !1 })).getFile(), h = {
|
|
431
|
+
kind: "file",
|
|
432
|
+
size: f.size,
|
|
433
|
+
mtime: new Date(f.lastModified).toISOString(),
|
|
434
|
+
ctime: new Date(f.lastModified).toISOString(),
|
|
435
|
+
isFile: !0,
|
|
436
|
+
isDirectory: !1
|
|
437
|
+
};
|
|
438
|
+
if (a)
|
|
439
|
+
try {
|
|
440
|
+
const w = new Uint8Array(await f.arrayBuffer()), d = await v(w, l);
|
|
441
|
+
h.hash = d;
|
|
442
|
+
} catch (w) {
|
|
443
|
+
console.warn(`Failed to calculate hash for ${e}:`, w);
|
|
444
|
+
}
|
|
445
|
+
return h;
|
|
446
|
+
} catch (c) {
|
|
447
|
+
if (c.name !== "TypeMismatchError" && c.name !== "NotFoundError")
|
|
448
|
+
throw new s("Failed to stat (file)", "STAT_FAILED");
|
|
449
|
+
}
|
|
450
|
+
try {
|
|
451
|
+
return await i.getDirectoryHandle(o, { create: !1 }), {
|
|
452
|
+
kind: "directory",
|
|
453
|
+
size: 0,
|
|
454
|
+
mtime: (/* @__PURE__ */ new Date(0)).toISOString(),
|
|
455
|
+
ctime: (/* @__PURE__ */ new Date(0)).toISOString(),
|
|
456
|
+
isFile: !1,
|
|
457
|
+
isDirectory: !0
|
|
458
|
+
// Directories don't have hashes
|
|
459
|
+
};
|
|
460
|
+
} catch (c) {
|
|
461
|
+
throw c.name === "NotFoundError" ? new s(`No such file or directory: ${e}`, "ENOENT") : new s("Failed to stat (directory)", "STAT_FAILED");
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
async readdir(e, t) {
|
|
465
|
+
const n = t?.withFileTypes ?? !1, o = await this.getDirectoryHandle(e, !1);
|
|
466
|
+
if (n) {
|
|
467
|
+
const i = [];
|
|
468
|
+
for await (const [a, l] of o.entries()) {
|
|
469
|
+
const c = l.kind === "file";
|
|
470
|
+
i.push({
|
|
471
|
+
name: a,
|
|
472
|
+
kind: l.kind,
|
|
473
|
+
isFile: c,
|
|
474
|
+
isDirectory: !c
|
|
475
|
+
});
|
|
476
|
+
}
|
|
477
|
+
return i;
|
|
478
|
+
} else {
|
|
479
|
+
const i = [];
|
|
480
|
+
for await (const [a] of o.entries())
|
|
481
|
+
i.push(a);
|
|
482
|
+
return i;
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
/**
|
|
486
|
+
* Check if a file or directory exists
|
|
487
|
+
*
|
|
488
|
+
* Verifies if a file or directory exists at the specified path.
|
|
489
|
+
*
|
|
490
|
+
* @param path - The path to check
|
|
491
|
+
* @returns Promise that resolves to true if the file or directory exists, false otherwise
|
|
492
|
+
*
|
|
493
|
+
* @example
|
|
494
|
+
* ```typescript
|
|
495
|
+
* const exists = await fs.exists('/config/settings.json');
|
|
496
|
+
* console.log(`File exists: ${exists}`);
|
|
497
|
+
* ```
|
|
498
|
+
*/
|
|
499
|
+
async exists(e) {
|
|
500
|
+
const t = u(e), n = t.pop();
|
|
501
|
+
let o = null;
|
|
502
|
+
try {
|
|
503
|
+
o = await this.getDirectoryHandle(t, !1);
|
|
504
|
+
} catch (i) {
|
|
505
|
+
throw (i.name === "NotFoundError" || i.name === "TypeMismatchError") && (o = null), i;
|
|
506
|
+
}
|
|
507
|
+
if (!o || !n)
|
|
508
|
+
return !1;
|
|
509
|
+
try {
|
|
510
|
+
return await o.getFileHandle(n, { create: !1 }), !0;
|
|
511
|
+
} catch (i) {
|
|
512
|
+
if (i.name !== "NotFoundError" && i.name !== "TypeMismatchError")
|
|
513
|
+
throw i;
|
|
514
|
+
}
|
|
515
|
+
try {
|
|
516
|
+
return await o.getDirectoryHandle(n, { create: !1 }), !0;
|
|
517
|
+
} catch (i) {
|
|
518
|
+
if (i.name !== "NotFoundError" && i.name !== "TypeMismatchError")
|
|
519
|
+
throw i;
|
|
520
|
+
}
|
|
521
|
+
return !1;
|
|
522
|
+
}
|
|
523
|
+
/**
|
|
524
|
+
* Clear all contents of a directory without removing the directory itself
|
|
525
|
+
*
|
|
526
|
+
* Removes all files and subdirectories within the specified directory,
|
|
527
|
+
* but keeps the directory itself.
|
|
528
|
+
*
|
|
529
|
+
* @param path - The path to the directory to clear (default: '/')
|
|
530
|
+
* @returns Promise that resolves when all contents are removed
|
|
531
|
+
* @throws {OPFSError} If the operation fails
|
|
532
|
+
*
|
|
533
|
+
* @example
|
|
534
|
+
* ```typescript
|
|
535
|
+
* // Clear root directory contents
|
|
536
|
+
* await fs.clear('/');
|
|
537
|
+
*
|
|
538
|
+
* // Clear specific directory contents
|
|
539
|
+
* await fs.clear('/data');
|
|
540
|
+
* ```
|
|
541
|
+
*/
|
|
542
|
+
async clear(e = "/") {
|
|
543
|
+
try {
|
|
544
|
+
const t = await this.readdir(e, { withFileTypes: !0 });
|
|
545
|
+
for (const n of t) {
|
|
546
|
+
const o = `${e === "/" ? "" : e}/${n.name}`;
|
|
547
|
+
await this.remove(o, { recursive: !0 });
|
|
548
|
+
}
|
|
549
|
+
} catch (t) {
|
|
550
|
+
throw t instanceof s ? t : new s(`Failed to clear directory: ${e}`, "CLEAR_FAILED");
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
/**
|
|
554
|
+
* Remove files and directories
|
|
555
|
+
*
|
|
556
|
+
* Removes files and directories. Similar to Node.js fs.rm().
|
|
557
|
+
*
|
|
558
|
+
* @param path - The path to remove
|
|
559
|
+
* @param options - Options for removal
|
|
560
|
+
* @param options.recursive - Whether to remove directories and their contents recursively (default: false)
|
|
561
|
+
* @param options.force - Whether to ignore errors if the path doesn't exist (default: false)
|
|
562
|
+
* @returns Promise that resolves when the removal is complete
|
|
563
|
+
* @throws {OPFSError} If the removal fails
|
|
564
|
+
*
|
|
565
|
+
* @example
|
|
566
|
+
* ```typescript
|
|
567
|
+
* // Remove a file
|
|
568
|
+
* await fs.rm('/path/to/file.txt');
|
|
569
|
+
*
|
|
570
|
+
* // Remove a directory and all its contents
|
|
571
|
+
* await fs.rm('/path/to/directory', { recursive: true });
|
|
572
|
+
*
|
|
573
|
+
* // Remove with force (ignore if doesn't exist)
|
|
574
|
+
* await fs.rm('/maybe/exists', { force: true });
|
|
575
|
+
* ```
|
|
576
|
+
*/
|
|
577
|
+
async remove(e, t) {
|
|
578
|
+
const n = t?.recursive ?? !1, o = t?.force ?? !1, i = u(e), a = i.pop();
|
|
579
|
+
if (!a)
|
|
580
|
+
throw new g("Invalid path", e);
|
|
581
|
+
const l = await this.getDirectoryHandle(i, !1);
|
|
582
|
+
try {
|
|
583
|
+
await l.removeEntry(a, { recursive: n });
|
|
584
|
+
} catch (c) {
|
|
585
|
+
if (c.name === "NotFoundError") {
|
|
586
|
+
if (!o)
|
|
587
|
+
throw new s(`No such file or directory: ${e}`, "ENOENT");
|
|
588
|
+
} else throw c.name === "InvalidModificationError" ? new s(`Directory not empty: ${e}. Use recursive option to force removal.`, "ENOTEMPTY") : c.name === "TypeMismatchError" && !n ? new s(`Cannot remove directory without recursive option: ${e}`, "EISDIR") : new s(`Failed to remove path: ${e}`, "RM_FAILED");
|
|
589
|
+
}
|
|
590
|
+
}
|
|
591
|
+
/**
|
|
592
|
+
* Resolve a path to an absolute path
|
|
593
|
+
*
|
|
594
|
+
* Resolves relative paths and normalizes path segments (like '..' and '.').
|
|
595
|
+
* Similar to Node.js fs.realpath() but without symlink resolution since OPFS doesn't support symlinks.
|
|
596
|
+
*
|
|
597
|
+
* @param path - The path to resolve
|
|
598
|
+
* @returns Promise that resolves to the absolute normalized path
|
|
599
|
+
* @throws {FileNotFoundError} If the path does not exist
|
|
600
|
+
* @throws {OPFSError} If path resolution fails
|
|
601
|
+
*
|
|
602
|
+
* @example
|
|
603
|
+
* ```typescript
|
|
604
|
+
* // Resolve relative path
|
|
605
|
+
* const absolute = await fs.realpath('./config/../data/file.txt');
|
|
606
|
+
* console.log(absolute); // '/data/file.txt'
|
|
607
|
+
* ```
|
|
608
|
+
*/
|
|
609
|
+
async realpath(e) {
|
|
610
|
+
try {
|
|
611
|
+
const t = u(e), n = [];
|
|
612
|
+
for (const a of t)
|
|
613
|
+
if (!(a === "." || a === ""))
|
|
614
|
+
if (a === "..") {
|
|
615
|
+
if (n.length === 0)
|
|
616
|
+
throw new s("Path escapes root", "EINVAL");
|
|
617
|
+
n.length > 0 && n.pop();
|
|
618
|
+
} else
|
|
619
|
+
n.push(a);
|
|
620
|
+
const o = F(n);
|
|
621
|
+
if (!await this.exists(o))
|
|
622
|
+
throw new m(o);
|
|
623
|
+
return o;
|
|
624
|
+
} catch (t) {
|
|
625
|
+
throw t instanceof s ? t : new s(`Failed to resolve path: ${e}`, "REALPATH_FAILED");
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
/**
|
|
629
|
+
* Rename a file or directory
|
|
630
|
+
*
|
|
631
|
+
* Changes the name of a file or directory. If the target path already exists,
|
|
632
|
+
* it will be replaced.
|
|
633
|
+
*
|
|
634
|
+
* @param oldPath - The current path of the file or directory
|
|
635
|
+
* @param newPath - The new path for the file or directory
|
|
636
|
+
* @returns Promise that resolves when the rename operation is complete
|
|
637
|
+
* @throws {OPFSError} If the rename operation fails
|
|
638
|
+
*
|
|
639
|
+
* @example
|
|
640
|
+
* ```typescript
|
|
641
|
+
* await fs.rename('/old/path/file.txt', '/new/path/renamed.txt');
|
|
642
|
+
* ```
|
|
643
|
+
*/
|
|
644
|
+
async rename(e, t) {
|
|
645
|
+
try {
|
|
646
|
+
if (!await this.exists(e))
|
|
647
|
+
throw new m(e);
|
|
648
|
+
await this.copy(e, t, { recursive: !0 }), await this.remove(e, { recursive: !0 });
|
|
649
|
+
} catch (n) {
|
|
650
|
+
throw n instanceof s ? n : new s(`Failed to rename from ${e} to ${t}`, "RENAME_FAILED");
|
|
651
|
+
}
|
|
652
|
+
}
|
|
653
|
+
/**
|
|
654
|
+
* Copy files and directories
|
|
655
|
+
*
|
|
656
|
+
* Copies files and directories. Similar to Node.js fs.cp().
|
|
657
|
+
*
|
|
658
|
+
* @param source - The source path to copy from
|
|
659
|
+
* @param destination - The destination path to copy to
|
|
660
|
+
* @param options - Options for copying
|
|
661
|
+
* @param options.recursive - Whether to copy directories recursively (default: false)
|
|
662
|
+
* @param options.force - Whether to overwrite existing files (default: true)
|
|
663
|
+
* @returns Promise that resolves when the copy operation is complete
|
|
664
|
+
* @throws {OPFSError} If the copy operation fails
|
|
665
|
+
*
|
|
666
|
+
* @example
|
|
667
|
+
* ```typescript
|
|
668
|
+
* // Copy a file
|
|
669
|
+
* await fs.cp('/source/file.txt', '/dest/file.txt');
|
|
670
|
+
*
|
|
671
|
+
* // Copy a directory and all its contents
|
|
672
|
+
* await fs.cp('/source/dir', '/dest/dir', { recursive: true });
|
|
673
|
+
*
|
|
674
|
+
* // Copy without overwriting existing files
|
|
675
|
+
* await fs.cp('/source', '/dest', { recursive: true, force: false });
|
|
676
|
+
* ```
|
|
677
|
+
*/
|
|
678
|
+
async copy(e, t, n) {
|
|
679
|
+
try {
|
|
680
|
+
const o = n?.recursive ?? !1, i = n?.force ?? !0;
|
|
681
|
+
if (!await this.exists(e))
|
|
682
|
+
throw new s(`Source does not exist: ${e}`, "ENOENT");
|
|
683
|
+
if (await this.exists(t) && !i)
|
|
684
|
+
throw new s(`Destination already exists: ${t}`, "EEXIST");
|
|
685
|
+
if ((await this.stat(e)).isFile) {
|
|
686
|
+
const f = await this.readFile(e, "binary");
|
|
687
|
+
await this.writeFile(t, f);
|
|
688
|
+
} else {
|
|
689
|
+
if (!o)
|
|
690
|
+
throw new s(`Cannot copy directory without recursive option: ${e}`, "EISDIR");
|
|
691
|
+
await this.mkdir(t, { recursive: !0 });
|
|
692
|
+
const f = await this.readdir(e, { withFileTypes: !0 });
|
|
693
|
+
for (const h of f) {
|
|
694
|
+
const w = `${e}/${h.name}`, d = `${t}/${h.name}`;
|
|
695
|
+
await this.copy(w, d, { recursive: !0, force: i });
|
|
696
|
+
}
|
|
697
|
+
}
|
|
698
|
+
} catch (o) {
|
|
699
|
+
throw o instanceof s ? o : new s(`Failed to copy from ${e} to ${t}`, "CP_FAILED");
|
|
700
|
+
}
|
|
701
|
+
}
|
|
702
|
+
/**
|
|
703
|
+
* Synchronize the file system with external data
|
|
704
|
+
*
|
|
705
|
+
* Syncs the file system with an array of entries containing paths and data.
|
|
706
|
+
* This is useful for importing data from external sources or syncing with remote data.
|
|
707
|
+
*
|
|
708
|
+
* @param entries - Array of [path, data] tuples to sync
|
|
709
|
+
* @param options - Options for synchronization
|
|
710
|
+
* @param options.cleanBefore - Whether to clear the file system before syncing (default: false)
|
|
711
|
+
* @returns Promise that resolves when synchronization is complete
|
|
712
|
+
* @throws {OPFSError} If the synchronization fails
|
|
713
|
+
*
|
|
714
|
+
* @example
|
|
715
|
+
* ```typescript
|
|
716
|
+
* // Sync with external data
|
|
717
|
+
* const entries: [string, string | Uint8Array | Blob][] = [
|
|
718
|
+
* ['/config.json', JSON.stringify({ theme: 'dark' })],
|
|
719
|
+
* ['/data/binary.dat', new Uint8Array([1, 2, 3, 4])],
|
|
720
|
+
* ['/upload.txt', new Blob(['file content'], { type: 'text/plain' })]
|
|
721
|
+
* ];
|
|
722
|
+
*
|
|
723
|
+
* // Sync without clearing existing files
|
|
724
|
+
* await fs.sync(entries);
|
|
725
|
+
*
|
|
726
|
+
* // Clean file system and then sync
|
|
727
|
+
* await fs.sync(entries, { cleanBefore: true });
|
|
728
|
+
* ```
|
|
729
|
+
*/
|
|
730
|
+
async sync(e, t) {
|
|
731
|
+
try {
|
|
732
|
+
(t?.cleanBefore ?? !1) && await this.clear("/");
|
|
733
|
+
for (const [o, i] of e) {
|
|
734
|
+
const a = o.startsWith("/") ? o : `/${o}`;
|
|
735
|
+
let l;
|
|
736
|
+
if (i instanceof Blob) {
|
|
737
|
+
const c = await i.arrayBuffer();
|
|
738
|
+
l = new Uint8Array(c);
|
|
739
|
+
} else
|
|
740
|
+
l = i;
|
|
741
|
+
await this.writeFile(a, l);
|
|
742
|
+
}
|
|
743
|
+
} catch (n) {
|
|
744
|
+
throw n instanceof s ? n : new s("Failed to sync file system", "SYNC_FAILED");
|
|
745
|
+
}
|
|
746
|
+
}
|
|
747
|
+
}
|
|
748
|
+
p(new U());
|
|
749
|
+
export {
|
|
750
|
+
U as OPFSWorker
|
|
751
|
+
};
|
|
752
|
+
//# sourceMappingURL=index.js.map
|