opfs-worker 0.2.6 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +117 -47
- package/dist/assets/worker-DilNsKoO.js.map +1 -0
- package/dist/helpers-B87wz5kv.cjs +2 -0
- package/dist/helpers-B87wz5kv.cjs.map +1 -0
- package/dist/{helpers-C0nyU6hv.js → helpers-DxFcNkZe.js} +51 -51
- package/dist/helpers-DxFcNkZe.js.map +1 -0
- package/dist/index.cjs +255 -234
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +2 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +284 -266
- package/dist/index.js.map +1 -1
- package/dist/raw.cjs +1 -1
- package/dist/raw.cjs.map +1 -1
- package/dist/raw.js +143 -122
- package/dist/raw.js.map +1 -1
- package/dist/types.d.ts +2 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/utils/helpers.d.ts +9 -0
- package/dist/utils/helpers.d.ts.map +1 -1
- package/dist/worker.d.ts +16 -27
- package/dist/worker.d.ts.map +1 -1
- package/package.json +1 -1
- package/dist/assets/worker-CHy3JxL1.js.map +0 -1
- package/dist/helpers-C0nyU6hv.js.map +0 -1
- package/dist/helpers-FvdHLObV.cjs +0 -2
- package/dist/helpers-FvdHLObV.cjs.map +0 -1
package/README.md
CHANGED
|
@@ -29,6 +29,7 @@ A robust TypeScript library for working with Origin Private File System (OPFS) t
|
|
|
29
29
|
- 📊 **File indexing**: Complete file system indexing with metadata
|
|
30
30
|
- 🔄 **Sync operations**: Bulk file synchronization from external data
|
|
31
31
|
- 👀 **File watching**: Polling-based change detection for files and directories
|
|
32
|
+
- 📡 **Event broadcasting**: Broadcast file system changes to other contexts (tabs, workers, etc.)
|
|
32
33
|
- 🛡️ **Error handling**: Comprehensive error types and handling
|
|
33
34
|
|
|
34
35
|
## Installation
|
|
@@ -163,7 +164,7 @@ async function advancedExample() {
|
|
|
163
164
|
}
|
|
164
165
|
|
|
165
166
|
// List directory contents
|
|
166
|
-
const files = await fs.
|
|
167
|
+
const files = await fs.readDir('/data');
|
|
167
168
|
files.forEach(item => {
|
|
168
169
|
console.log(`${item.name} - ${item.isFile ? 'file' : 'directory'}`);
|
|
169
170
|
});
|
|
@@ -201,14 +202,12 @@ async function hashExample() {
|
|
|
201
202
|
}
|
|
202
203
|
|
|
203
204
|
// Watch events will also include hash information
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
205
|
+
const channel = new BroadcastChannel('opfs-worker');
|
|
206
|
+
channel.onmessage = (event) => {
|
|
207
|
+
if (event.data.hash) {
|
|
208
|
+
console.log(`File ${event.data.path} changed, hash: ${event.data.hash}`);
|
|
207
209
|
}
|
|
208
|
-
}
|
|
209
|
-
|
|
210
|
-
// Disable hashing for better performance
|
|
211
|
-
fs.setOptions({ hashAlgorithm: null });
|
|
210
|
+
};
|
|
212
211
|
}
|
|
213
212
|
|
|
214
213
|
// Configure maximum file size for hashing
|
|
@@ -249,35 +248,90 @@ Check out the live demo powered by Vite and hosted on GitHub Pages.
|
|
|
249
248
|
|
|
250
249
|
## API Reference
|
|
251
250
|
|
|
252
|
-
- [
|
|
253
|
-
- [
|
|
254
|
-
- [
|
|
255
|
-
- [
|
|
256
|
-
- [
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
- [
|
|
262
|
-
- [
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
- [
|
|
274
|
-
- [
|
|
251
|
+
- [OPFS Worker](#opfs-worker)
|
|
252
|
+
- [Table of Contents](#table-of-contents)
|
|
253
|
+
- [Features](#features)
|
|
254
|
+
- [Installation](#installation)
|
|
255
|
+
- [Quick Start](#quick-start)
|
|
256
|
+
- [Inline Worker (Recommended)](#inline-worker-recommended)
|
|
257
|
+
- [Manual Worker Setup](#manual-worker-setup)
|
|
258
|
+
- [Advanced Usage](#advanced-usage)
|
|
259
|
+
- [Hash Algorithm Configuration](#hash-algorithm-configuration)
|
|
260
|
+
- [Demo](#demo)
|
|
261
|
+
- [API Reference](#api-reference)
|
|
262
|
+
- [Entry Points](#entry-points)
|
|
263
|
+
- [Mode 1: Inline Worker](#mode-1-inline-worker)
|
|
264
|
+
- [`createWorker(options?: OPFSOptions)`](#createworkeroptions-opfsoptions)
|
|
265
|
+
- [Mode 2: Manual Worker Setup](#mode-2-manual-worker-setup)
|
|
266
|
+
- [`OPFSWorker`](#opfsworker)
|
|
267
|
+
- [Core Methods](#core-methods)
|
|
268
|
+
- [Mount](#mount)
|
|
269
|
+
- [`mount(root?: string): Promise<boolean>`](#mountroot-string-promiseboolean)
|
|
270
|
+
- [Read File](#read-file)
|
|
271
|
+
- [`readFile(path: string, encoding?: BufferEncoding | 'binary'): Promise<string | Uint8Array>`](#readfilepath-string-encoding-bufferencoding--binary-promisestring--uint8array)
|
|
272
|
+
- [Write File](#write-file)
|
|
273
|
+
- [`writeFile(path: string, data: string | Uint8Array | ArrayBuffer, encoding?: BufferEncoding): Promise<void>`](#writefilepath-string-data-string--uint8array--arraybuffer-encoding-bufferencoding-promisevoid)
|
|
274
|
+
- [Append File](#append-file)
|
|
275
|
+
- [`appendFile(path: string, data: string | Uint8Array | ArrayBuffer, encoding?: BufferEncoding): Promise<void>`](#appendfilepath-string-data-string--uint8array--arraybuffer-encoding-bufferencoding-promisevoid)
|
|
276
|
+
- [Create Directory](#create-directory)
|
|
277
|
+
- [`mkdir(path: string, options?: { recursive?: boolean }): Promise<void>`](#mkdirpath-string-options--recursive-boolean--promisevoid)
|
|
278
|
+
- [Read Directory](#read-directory)
|
|
279
|
+
- [`readDir(path: string): Promise<DirentData[]>`](#readdirpath-string--promisedirentdata)
|
|
280
|
+
- [Get Stats](#get-stats)
|
|
281
|
+
- [`stat(path: string): Promise<FileStat>`](#statpath-string-promisefilestat)
|
|
282
|
+
- [Check Existence](#check-existence)
|
|
283
|
+
- [`exists(path: string): Promise<boolean>`](#existspath-string-promiseboolean)
|
|
284
|
+
- [Remove Path](#remove-path)
|
|
285
|
+
- [`remove(path: string, options?: { recursive?: boolean; force?: boolean }): Promise<void>`](#removepath-string-options--recursive-boolean-force-boolean--promisevoid)
|
|
286
|
+
- [Copy Path](#copy-path)
|
|
287
|
+
- [`copy(source: string, destination: string, options?: { recursive?: boolean; force?: boolean }): Promise<void>`](#copysource-string-destination-string-options--recursive-boolean-force-boolean--promisevoid)
|
|
288
|
+
- [Rename Path](#rename-path)
|
|
289
|
+
- [`rename(oldPath: string, newPath: string): Promise<void>`](#renameoldpath-string-newpath-string-promisevoid)
|
|
290
|
+
- [Clear Directory](#clear-directory)
|
|
291
|
+
- [`clear(path?: string): Promise<void>`](#clearpath-string-promisevoid)
|
|
292
|
+
- [Index File System](#index-file-system)
|
|
293
|
+
- [`index(): Promise<Map<string, FileStat>>`](#index-promisemapstring-filestat)
|
|
294
|
+
- [Sync File System](#sync-file-system)
|
|
295
|
+
- [`sync(entries: [string, string | Uint8Array | Blob][], options?: { cleanBefore?: boolean }): Promise<void>`](#syncentries-string-string--uint8array--blob-options--cleanbefore-boolean--promisevoid)
|
|
296
|
+
- [Watch](#watch)
|
|
297
|
+
- [`watch(path: string): Promise<void>`](#watchpath-string-promisevoid)
|
|
298
|
+
- [Unwatch](#unwatch)
|
|
299
|
+
- [`unwatch(path: string): void`](#unwatchpath-string-void)
|
|
300
|
+
- [Dispose](#dispose)
|
|
301
|
+
- [`dispose(): void`](#dispose-void)
|
|
302
|
+
- [Configuration](#configuration)
|
|
303
|
+
- [`setOptions(options: { watchInterval?: number; hashAlgorithm?: null | 'SHA-1' | 'SHA-256' | 'SHA-384' | 'SHA-512'; maxFileSize?: number }): void`](#setoptionsoptions--watchinterval-number-hashalgorithm-null--sha-1--sha-256--sha-384--sha-512-maxfilesize-number--void)
|
|
304
|
+
- [Resolve Path](#resolve-path)
|
|
305
|
+
- [`realpath(path: string): Promise<string>`](#realpathpath-string-promisestring)
|
|
306
|
+
- [Binary File Handling](#binary-file-handling)
|
|
307
|
+
- [Reading Binary Files](#reading-binary-files)
|
|
308
|
+
- [Writing Binary Files](#writing-binary-files)
|
|
309
|
+
- [Working with Different Data Types](#working-with-different-data-types)
|
|
310
|
+
- [File Upload and Download](#file-upload-and-download)
|
|
311
|
+
- [Supported Encodings](#supported-encodings)
|
|
312
|
+
- [Utility Functions](#utility-functions)
|
|
313
|
+
- [Path Utilities](#path-utilities)
|
|
314
|
+
- [Data Conversion](#data-conversion)
|
|
315
|
+
- [File System Utilities](#file-system-utilities)
|
|
316
|
+
- [Types](#types)
|
|
317
|
+
- [`FileStat`](#filestat)
|
|
318
|
+
- [`DirentData`](#direntdata)
|
|
319
|
+
- [`RemoteOPFSWorker`](#remoteopfsworker)
|
|
320
|
+
- [Error Types](#error-types)
|
|
321
|
+
- [Browser Support](#browser-support)
|
|
322
|
+
- [Development](#development)
|
|
323
|
+
- [Building](#building)
|
|
324
|
+
- [Development Server](#development-server)
|
|
325
|
+
- [Testing](#testing)
|
|
326
|
+
- [Linting](#linting)
|
|
327
|
+
- [License](#license)
|
|
328
|
+
- [Contributing](#contributing)
|
|
275
329
|
|
|
276
330
|
### Entry Points
|
|
277
331
|
|
|
278
332
|
#### Mode 1: Inline Worker
|
|
279
333
|
|
|
280
|
-
##### `createWorker(
|
|
334
|
+
##### `createWorker(options?: OPFSOptions)`
|
|
281
335
|
|
|
282
336
|
Creates a new file system instance with an inline worker.
|
|
283
337
|
|
|
@@ -287,22 +341,26 @@ import { createWorker } from 'opfs-worker/inline';
|
|
|
287
341
|
// Basic usage
|
|
288
342
|
const fs = await createWorker();
|
|
289
343
|
|
|
290
|
-
// With
|
|
291
|
-
const fs = await createWorker(
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
344
|
+
// With options
|
|
345
|
+
const fs = await createWorker({
|
|
346
|
+
watchInterval: 500,
|
|
347
|
+
hashAlgorithm: 'SHA-256',
|
|
348
|
+
broadcastChannel: 'my-app-events'
|
|
349
|
+
});
|
|
350
|
+
|
|
351
|
+
// Listen for file change events via BroadcastChannel
|
|
352
|
+
const channel = new BroadcastChannel('my-app-events');
|
|
353
|
+
channel.onmessage = (event) => {
|
|
354
|
+
console.log('File changed:', event.data);
|
|
355
|
+
};
|
|
298
356
|
```
|
|
299
357
|
|
|
300
358
|
**Parameters:**
|
|
301
359
|
|
|
302
|
-
- `watchCallback` (optional): Callback function for file change events
|
|
303
360
|
- `options` (optional): Configuration options
|
|
304
361
|
- `watchInterval` (optional): Polling interval in milliseconds for file watching
|
|
305
362
|
- `hashAlgorithm` (optional): Hash algorithm for file hashing
|
|
363
|
+
- `broadcastChannel` (optional): Custom name for the broadcast channel (default: 'opfs-worker')
|
|
306
364
|
|
|
307
365
|
**Returns:** `Promise<RemoteOPFSWorker>` - A remote file system interface
|
|
308
366
|
|
|
@@ -352,7 +410,7 @@ await fs.mount('/my-app');
|
|
|
352
410
|
|
|
353
411
|
**Note:** All file operations will automatically mount the OPFS root if no explicit mount has been performed.
|
|
354
412
|
|
|
355
|
-
**
|
|
413
|
+
**File Change Events:** File change events are sent via BroadcastChannel. Set the `broadcastChannel` option to customize the channel name, or use the default 'opfs-worker' channel.
|
|
356
414
|
|
|
357
415
|
### Read File
|
|
358
416
|
|
|
@@ -468,17 +526,17 @@ await fs.mkdir('/users/john/documents/projects', { recursive: true });
|
|
|
468
526
|
|
|
469
527
|
### Read Directory
|
|
470
528
|
|
|
471
|
-
#### `
|
|
529
|
+
#### `readDir(path: string): Promise<DirentData[]>`
|
|
472
530
|
|
|
473
531
|
Read a directory's contents.
|
|
474
532
|
|
|
475
533
|
```typescript
|
|
476
534
|
// Get simple list of names
|
|
477
|
-
const files = await fs.
|
|
535
|
+
const files = await fs.readDir('/users/john/documents');
|
|
478
536
|
console.log('Files:', files); // ['readme.txt', 'config.json', 'images']
|
|
479
537
|
|
|
480
538
|
// Get detailed information
|
|
481
|
-
const detailed = await fs.
|
|
539
|
+
const detailed = await fs.readDir('/users/john/documents');
|
|
482
540
|
detailed.forEach(item => {
|
|
483
541
|
console.log(`${item.name} - ${item.isFile ? 'file' : 'directory'}`);
|
|
484
542
|
});
|
|
@@ -486,8 +544,7 @@ detailed.forEach(item => {
|
|
|
486
544
|
|
|
487
545
|
**Returns:**
|
|
488
546
|
|
|
489
|
-
- `Promise<
|
|
490
|
-
- `Promise<DirentData[]>` when `withFileTypes` is true
|
|
547
|
+
- `Promise<DirentData[]>` - Always returns detailed file/directory information
|
|
491
548
|
|
|
492
549
|
### Get Stats
|
|
493
550
|
|
|
@@ -691,6 +748,19 @@ Stop watching a previously watched path.
|
|
|
691
748
|
fs.unwatch('/docs');
|
|
692
749
|
```
|
|
693
750
|
|
|
751
|
+
### Dispose
|
|
752
|
+
|
|
753
|
+
#### `dispose(): void`
|
|
754
|
+
|
|
755
|
+
Dispose of resources and clean up the file system instance. This method should be called when the file system instance is no longer needed to properly clean up resources like the broadcast channel and watch timers.
|
|
756
|
+
|
|
757
|
+
```typescript
|
|
758
|
+
// Clean up resources when done
|
|
759
|
+
fs.dispose();
|
|
760
|
+
```
|
|
761
|
+
|
|
762
|
+
**Note:** This method closes the broadcast channel, clears watch timers, and cleans up all watched paths. Call this when you're done with the file system instance to prevent memory leaks.
|
|
763
|
+
|
|
694
764
|
### Configuration
|
|
695
765
|
|
|
696
766
|
#### `setOptions(options: { watchInterval?: number; hashAlgorithm?: null | 'SHA-1' | 'SHA-256' | 'SHA-384' | 'SHA-512'; maxFileSize?: number }): void`
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"worker-DilNsKoO.js","sources":["../node_modules/comlink/dist/esm/comlink.mjs","../src/utils/errors.ts","../src/utils/encoder.ts","../src/utils/helpers.ts","../src/worker.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2019 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\nconst proxyMarker = Symbol(\"Comlink.proxy\");\nconst createEndpoint = Symbol(\"Comlink.endpoint\");\nconst releaseProxy = Symbol(\"Comlink.releaseProxy\");\nconst finalizer = Symbol(\"Comlink.finalizer\");\nconst throwMarker = Symbol(\"Comlink.thrown\");\nconst isObject = (val) => (typeof val === \"object\" && val !== null) || typeof val === \"function\";\n/**\n * Internal transfer handle to handle objects marked to proxy.\n */\nconst proxyTransferHandler = {\n canHandle: (val) => isObject(val) && val[proxyMarker],\n serialize(obj) {\n const { port1, port2 } = new MessageChannel();\n expose(obj, port1);\n return [port2, [port2]];\n },\n deserialize(port) {\n port.start();\n return wrap(port);\n },\n};\n/**\n * Internal transfer handler to handle thrown exceptions.\n */\nconst throwTransferHandler = {\n canHandle: (value) => isObject(value) && throwMarker in value,\n serialize({ value }) {\n let serialized;\n if (value instanceof Error) {\n serialized = {\n isError: true,\n value: {\n message: value.message,\n name: value.name,\n stack: value.stack,\n },\n };\n }\n else {\n serialized = { isError: false, value };\n }\n return [serialized, []];\n },\n deserialize(serialized) {\n if (serialized.isError) {\n throw Object.assign(new Error(serialized.value.message), serialized.value);\n }\n throw serialized.value;\n },\n};\n/**\n * Allows customizing the serialization of certain values.\n */\nconst transferHandlers = new Map([\n [\"proxy\", proxyTransferHandler],\n [\"throw\", throwTransferHandler],\n]);\nfunction isAllowedOrigin(allowedOrigins, origin) {\n for (const allowedOrigin of allowedOrigins) {\n if (origin === allowedOrigin || allowedOrigin === \"*\") {\n return true;\n }\n if (allowedOrigin instanceof RegExp && allowedOrigin.test(origin)) {\n return true;\n }\n }\n return false;\n}\nfunction expose(obj, ep = globalThis, allowedOrigins = [\"*\"]) {\n ep.addEventListener(\"message\", function callback(ev) {\n if (!ev || !ev.data) {\n return;\n }\n if (!isAllowedOrigin(allowedOrigins, ev.origin)) {\n console.warn(`Invalid origin '${ev.origin}' for comlink proxy`);\n return;\n }\n const { id, type, path } = Object.assign({ path: [] }, ev.data);\n const argumentList = (ev.data.argumentList || []).map(fromWireValue);\n let returnValue;\n try {\n const parent = path.slice(0, -1).reduce((obj, prop) => obj[prop], obj);\n const rawValue = path.reduce((obj, prop) => obj[prop], obj);\n switch (type) {\n case \"GET\" /* MessageType.GET */:\n {\n returnValue = rawValue;\n }\n break;\n case \"SET\" /* MessageType.SET */:\n {\n parent[path.slice(-1)[0]] = fromWireValue(ev.data.value);\n returnValue = true;\n }\n break;\n case \"APPLY\" /* MessageType.APPLY */:\n {\n returnValue = rawValue.apply(parent, argumentList);\n }\n break;\n case \"CONSTRUCT\" /* MessageType.CONSTRUCT */:\n {\n const value = new rawValue(...argumentList);\n returnValue = proxy(value);\n }\n break;\n case \"ENDPOINT\" /* MessageType.ENDPOINT */:\n {\n const { port1, port2 } = new MessageChannel();\n expose(obj, port2);\n returnValue = transfer(port1, [port1]);\n }\n break;\n case \"RELEASE\" /* MessageType.RELEASE */:\n {\n returnValue = undefined;\n }\n break;\n default:\n return;\n }\n }\n catch (value) {\n returnValue = { value, [throwMarker]: 0 };\n }\n Promise.resolve(returnValue)\n .catch((value) => {\n return { value, [throwMarker]: 0 };\n })\n .then((returnValue) => {\n const [wireValue, transferables] = toWireValue(returnValue);\n ep.postMessage(Object.assign(Object.assign({}, wireValue), { id }), transferables);\n if (type === \"RELEASE\" /* MessageType.RELEASE */) {\n // detach and deactive after sending release response above.\n ep.removeEventListener(\"message\", callback);\n closeEndPoint(ep);\n if (finalizer in obj && typeof obj[finalizer] === \"function\") {\n obj[finalizer]();\n }\n }\n })\n .catch((error) => {\n // Send Serialization Error To Caller\n const [wireValue, transferables] = toWireValue({\n value: new TypeError(\"Unserializable return value\"),\n [throwMarker]: 0,\n });\n ep.postMessage(Object.assign(Object.assign({}, wireValue), { id }), transferables);\n });\n });\n if (ep.start) {\n ep.start();\n }\n}\nfunction isMessagePort(endpoint) {\n return endpoint.constructor.name === \"MessagePort\";\n}\nfunction closeEndPoint(endpoint) {\n if (isMessagePort(endpoint))\n endpoint.close();\n}\nfunction wrap(ep, target) {\n const pendingListeners = new Map();\n ep.addEventListener(\"message\", function handleMessage(ev) {\n const { data } = ev;\n if (!data || !data.id) {\n return;\n }\n const resolver = pendingListeners.get(data.id);\n if (!resolver) {\n return;\n }\n try {\n resolver(data);\n }\n finally {\n pendingListeners.delete(data.id);\n }\n });\n return createProxy(ep, pendingListeners, [], target);\n}\nfunction throwIfProxyReleased(isReleased) {\n if (isReleased) {\n throw new Error(\"Proxy has been released and is not useable\");\n }\n}\nfunction releaseEndpoint(ep) {\n return requestResponseMessage(ep, new Map(), {\n type: \"RELEASE\" /* MessageType.RELEASE */,\n }).then(() => {\n closeEndPoint(ep);\n });\n}\nconst proxyCounter = new WeakMap();\nconst proxyFinalizers = \"FinalizationRegistry\" in globalThis &&\n new FinalizationRegistry((ep) => {\n const newCount = (proxyCounter.get(ep) || 0) - 1;\n proxyCounter.set(ep, newCount);\n if (newCount === 0) {\n releaseEndpoint(ep);\n }\n });\nfunction registerProxy(proxy, ep) {\n const newCount = (proxyCounter.get(ep) || 0) + 1;\n proxyCounter.set(ep, newCount);\n if (proxyFinalizers) {\n proxyFinalizers.register(proxy, ep, proxy);\n }\n}\nfunction unregisterProxy(proxy) {\n if (proxyFinalizers) {\n proxyFinalizers.unregister(proxy);\n }\n}\nfunction createProxy(ep, pendingListeners, path = [], target = function () { }) {\n let isProxyReleased = false;\n const proxy = new Proxy(target, {\n get(_target, prop) {\n throwIfProxyReleased(isProxyReleased);\n if (prop === releaseProxy) {\n return () => {\n unregisterProxy(proxy);\n releaseEndpoint(ep);\n pendingListeners.clear();\n isProxyReleased = true;\n };\n }\n if (prop === \"then\") {\n if (path.length === 0) {\n return { then: () => proxy };\n }\n const r = requestResponseMessage(ep, pendingListeners, {\n type: \"GET\" /* MessageType.GET */,\n path: path.map((p) => p.toString()),\n }).then(fromWireValue);\n return r.then.bind(r);\n }\n return createProxy(ep, pendingListeners, [...path, prop]);\n },\n set(_target, prop, rawValue) {\n throwIfProxyReleased(isProxyReleased);\n // FIXME: ES6 Proxy Handler `set` methods are supposed to return a\n // boolean. To show good will, we return true asynchronously ¯\\_(ツ)_/¯\n const [value, transferables] = toWireValue(rawValue);\n return requestResponseMessage(ep, pendingListeners, {\n type: \"SET\" /* MessageType.SET */,\n path: [...path, prop].map((p) => p.toString()),\n value,\n }, transferables).then(fromWireValue);\n },\n apply(_target, _thisArg, rawArgumentList) {\n throwIfProxyReleased(isProxyReleased);\n const last = path[path.length - 1];\n if (last === createEndpoint) {\n return requestResponseMessage(ep, pendingListeners, {\n type: \"ENDPOINT\" /* MessageType.ENDPOINT */,\n }).then(fromWireValue);\n }\n // We just pretend that `bind()` didn’t happen.\n if (last === \"bind\") {\n return createProxy(ep, pendingListeners, path.slice(0, -1));\n }\n const [argumentList, transferables] = processArguments(rawArgumentList);\n return requestResponseMessage(ep, pendingListeners, {\n type: \"APPLY\" /* MessageType.APPLY */,\n path: path.map((p) => p.toString()),\n argumentList,\n }, transferables).then(fromWireValue);\n },\n construct(_target, rawArgumentList) {\n throwIfProxyReleased(isProxyReleased);\n const [argumentList, transferables] = processArguments(rawArgumentList);\n return requestResponseMessage(ep, pendingListeners, {\n type: \"CONSTRUCT\" /* MessageType.CONSTRUCT */,\n path: path.map((p) => p.toString()),\n argumentList,\n }, transferables).then(fromWireValue);\n },\n });\n registerProxy(proxy, ep);\n return proxy;\n}\nfunction myFlat(arr) {\n return Array.prototype.concat.apply([], arr);\n}\nfunction processArguments(argumentList) {\n const processed = argumentList.map(toWireValue);\n return [processed.map((v) => v[0]), myFlat(processed.map((v) => v[1]))];\n}\nconst transferCache = new WeakMap();\nfunction transfer(obj, transfers) {\n transferCache.set(obj, transfers);\n return obj;\n}\nfunction proxy(obj) {\n return Object.assign(obj, { [proxyMarker]: true });\n}\nfunction windowEndpoint(w, context = globalThis, targetOrigin = \"*\") {\n return {\n postMessage: (msg, transferables) => w.postMessage(msg, targetOrigin, transferables),\n addEventListener: context.addEventListener.bind(context),\n removeEventListener: context.removeEventListener.bind(context),\n };\n}\nfunction toWireValue(value) {\n for (const [name, handler] of transferHandlers) {\n if (handler.canHandle(value)) {\n const [serializedValue, transferables] = handler.serialize(value);\n return [\n {\n type: \"HANDLER\" /* WireValueType.HANDLER */,\n name,\n value: serializedValue,\n },\n transferables,\n ];\n }\n }\n return [\n {\n type: \"RAW\" /* WireValueType.RAW */,\n value,\n },\n transferCache.get(value) || [],\n ];\n}\nfunction fromWireValue(value) {\n switch (value.type) {\n case \"HANDLER\" /* WireValueType.HANDLER */:\n return transferHandlers.get(value.name).deserialize(value.value);\n case \"RAW\" /* WireValueType.RAW */:\n return value.value;\n }\n}\nfunction requestResponseMessage(ep, pendingListeners, msg, transfers) {\n return new Promise((resolve) => {\n const id = generateUUID();\n pendingListeners.set(id, resolve);\n if (ep.start) {\n ep.start();\n }\n ep.postMessage(Object.assign({ id }, msg), transfers);\n });\n}\nfunction generateUUID() {\n return new Array(4)\n .fill(0)\n .map(() => Math.floor(Math.random() * Number.MAX_SAFE_INTEGER).toString(16))\n .join(\"-\");\n}\n\nexport { createEndpoint, expose, finalizer, proxy, proxyMarker, releaseProxy, transfer, transferHandlers, windowEndpoint, wrap };\n//# sourceMappingURL=comlink.mjs.map\n","/**\n * Base error class for all OPFS-related errors\n */\nexport class OPFSError extends Error {\n constructor(message: string, public readonly code: string, public readonly path?: string) {\n super(message);\n this.name = 'OPFSError';\n }\n}\n\n/**\n * Error thrown when OPFS is not supported in the current browser\n */\nexport class OPFSNotSupportedError extends OPFSError {\n constructor() {\n super('OPFS is not supported in this browser', 'OPFS_NOT_SUPPORTED');\n }\n}\n\n\n/**\n * Error thrown when OPFS is not mounted\n */\nexport class OPFSNotMountedError extends OPFSError {\n constructor() {\n super('OPFS is not mounted', 'OPFS_NOT_MOUNTED');\n }\n}\n\n/**\n * Error thrown for invalid paths or path traversal attempts\n */\nexport class PathError extends OPFSError {\n constructor(message: string, path: string) {\n super(message, 'INVALID_PATH', path);\n }\n}\n\n/**\n * Error thrown when a requested file doesn't exist\n */\nexport class FileNotFoundError extends OPFSError {\n constructor(path: string) {\n super(`File not found: ${ path }`, 'FILE_NOT_FOUND', path);\n }\n}\n\n/**\n * Error thrown when a requested directory doesn't exist\n */\nexport class DirectoryNotFoundError extends OPFSError {\n constructor(path: string) {\n super(`Directory not found: ${ path }`, 'DIRECTORY_NOT_FOUND', path);\n }\n}\n\n/**\n * Error thrown when permission is denied for an operation\n */\nexport class PermissionError extends OPFSError {\n constructor(path: string, operation: string) {\n super(`Permission denied for ${ operation } on: ${ path }`, 'PERMISSION_DENIED', path);\n }\n}\n\n/**\n * Error thrown when an operation fails due to insufficient storage\n */\nexport class StorageError extends OPFSError {\n constructor(message: string, path?: string) {\n super(message, 'STORAGE_ERROR', path);\n }\n}\n\n/**\n * Error thrown when an operation times out\n */\nexport class TimeoutError extends OPFSError {\n constructor(operation: string, path?: string) {\n super(`Operation timed out: ${ operation }`, 'TIMEOUT_ERROR', path);\n }\n}\n","import { OPFSError } from './errors';\n\nimport type { BufferEncoding } from 'typescript';\n\nexport function encodeString(data: string, encoding: BufferEncoding = 'utf-8'): Uint8Array {\n switch (encoding) {\n case 'utf8':\n case 'utf-8':\n return new TextEncoder().encode(data);\n\n case 'utf16le':\n case 'ucs2':\n case 'ucs-2':\n return encodeUtf16LE(data);\n\n case 'ascii':\n return encodeAscii(data);\n\n case 'latin1':\n return encodeLatin1(data);\n\n case 'binary':\n return Uint8Array.from(data, char => char.charCodeAt(0));\n\n case 'base64':\n return Uint8Array.from(atob(data), c => c.charCodeAt(0));\n\n case 'hex':\n if (!/^[\\da-f]+$/i.test(data) || data.length % 2 !== 0) {\n throw new OPFSError('Invalid hex string', 'INVALID_HEX_FORMAT');\n }\n\n return Uint8Array.from(data.match(/.{1,2}/g)!.map(b => parseInt(b, 16)));\n\n default:\n console.warn('Encoding not supported, falling back to UTF-8');\n\n return new TextEncoder().encode(data);\n }\n}\n\nexport function decodeBuffer(buffer: Uint8Array, encoding: BufferEncoding = 'utf-8'): string {\n switch (encoding) {\n case 'utf8':\n case 'utf-8':\n return new TextDecoder().decode(buffer);\n\n case 'utf16le':\n case 'ucs2':\n case 'ucs-2':\n return decodeUtf16LE(buffer);\n\n case 'latin1':\n return String.fromCharCode(...buffer);\n\n case 'binary':\n return String.fromCharCode(...buffer);\n\n case 'ascii':\n return String.fromCharCode(...buffer.map(b => b & 0x7F));\n\n case 'base64':\n return btoa(String.fromCharCode(...buffer));\n\n case 'hex':\n return Array.from(buffer).map(b => b.toString(16).padStart(2, '0')).join('');\n\n default:\n console.warn('Unsupported encoding, falling back to UTF-8');\n\n return new TextDecoder().decode(buffer);\n }\n}\n\nfunction encodeUtf16LE(str: string): Uint8Array {\n const buf = new Uint8Array(str.length * 2);\n\n for (let i = 0; i < str.length; i++) {\n const code = str.charCodeAt(i);\n\n buf[(i * 2)] = code & 0xFF;\n buf[(i * 2) + 1] = code >> 8;\n }\n\n return buf;\n}\n\nfunction decodeUtf16LE(buf: Uint8Array): string {\n if (buf.length % 2 !== 0) {\n console.warn('Invalid UTF-16LE buffer length, truncating last byte');\n buf = buf.slice(0, buf.length - 1);\n }\n\n const codeUnits = new Uint16Array(buf.buffer, buf.byteOffset, buf.byteLength / 2);\n\n return String.fromCharCode(...codeUnits);\n}\n\nfunction encodeLatin1(str: string): Uint8Array {\n const buf = new Uint8Array(str.length);\n\n for (let i = 0; i < str.length; i++) {\n buf[i] = str.charCodeAt(i) & 0xFF;\n }\n\n return buf;\n}\n\nfunction encodeAscii(str: string): Uint8Array {\n const buf = new Uint8Array(str.length);\n\n for (let i = 0; i < str.length; i++) {\n buf[i] = str.charCodeAt(i) & 0x7F;\n }\n\n return buf;\n}\n","import { encodeString } from './encoder';\nimport { OPFSError, OPFSNotSupportedError } from './errors';\n\nimport type { BufferEncoding } from 'typescript';\n\n/**\n * Check if the browser supports the OPFS API\n * \n * @throws {OPFSNotSupportedError} If the browser does not support the OPFS API\n */\nexport function checkOPFSSupport(): void {\n if (!('storage' in navigator) || !('getDirectory' in (navigator.storage as any))) {\n throw new OPFSNotSupportedError();\n }\n}\n\n/** \n * Split a path into an array of segments\n * \n * @param path - The path to split\n * @returns The array of segments\n * \n * @example\n * ```typescript\n * splitPath('/path/to/file'); // ['path', 'to', 'file']\n * splitPath('~/path/to/file'); // ['path', 'to', 'file'] (home dir handled)\n * splitPath('relative/path'); // ['relative', 'path']\n * ```\n */\nexport function splitPath(path: string | string[]): string[] {\n if (Array.isArray(path)) {\n return path;\n }\n\n const normalizedPath = path.startsWith('~/') ? path.slice(2) : path;\n\n return normalizedPath.split('/').filter(Boolean);\n}\n\n\n/**\n * Join an array of path segments into a single path\n * \n * @param segments - The array of path segments\n * @returns The joined path\n */\nexport function joinPath(segments: string[] | string): string {\n return typeof segments === 'string'\n ? (segments ?? '/')\n : `/${ segments.join('/') }`;\n}\n\n/**\n * Extract the filename from a path\n * \n * @param path - The file path\n * @returns The filename without the directory path\n * \n * @example\n * ```typescript\n * basename('/path/to/file.txt'); // 'file.txt'\n * basename('/path/to/directory/'); // ''\n * basename('file.txt'); // 'file.txt'\n * ```\n */\nexport function basename(path: string): string {\n const segments = splitPath(path);\n return segments[segments.length - 1] || '';\n}\n\n/**\n * Extract the directory path from a file path\n * \n * @param path - The file path\n * @returns The directory path without the filename\n * \n * @example\n * ```typescript\n * dirname('/path/to/file.txt'); // '/path/to'\n * dirname('/path/to/directory/'); // '/path/to/directory'\n * dirname('file.txt'); // '/'\n * ```\n */\nexport function dirname(path: string): string {\n const segments = splitPath(path);\n segments.pop();\n return joinPath(segments);\n}\n\n/**\n * Normalize a path to ensure it starts with '/'\n * \n * @param path - The path to normalize\n * @returns The normalized path\n * \n * @example\n * ```typescript\n * normalizePath('path/to/file'); // '/path/to/file'\n * normalizePath('/path/to/file'); // '/path/to/file'\n * normalizePath('~/path/to/file'); // '/path/to/file' (home dir normalized to root)\n * normalizePath(''); // '/'\n * ```\n */\nexport function normalizePath(path: string): string {\n if (!path || path === '/') {\n return '/';\n }\n \n if (path.startsWith('~/')) {\n return `/${path.slice(2)}`;\n }\n \n return path.startsWith('/') ? path : `/${path}`;\n}\n\n/**\n * Resolve a path to an absolute path, handling relative segments\n * \n * @param path - The path to resolve\n * @returns The resolved absolute path\n * \n * @example\n * ```typescript\n * resolvePath('./config/../data/file.txt'); // '/data/file.txt'\n * resolvePath('/path/to/../file.txt'); // '/path/file.txt'\n * resolvePath('../../file.txt'); // '/file.txt' (truncated to root)\n * resolvePath('~/config/../data/file.txt'); // '/data/file.txt' (home dir normalized to root)\n * ```\n */\nexport function resolvePath(path: string): string {\n // First normalize the path to handle home directory references\n const normalizedPath = normalizePath(path);\n const segments = splitPath(normalizedPath);\n const normalizedSegments: string[] = [];\n\n for (const segment of segments) {\n if (segment === '.' || segment === '') {\n // Skip current directory references and empty segments\n continue;\n }\n else if (segment === '..') {\n if (normalizedSegments.length === 0) {\n // Path escapes root, keep at root level\n continue;\n }\n // Go up one directory\n normalizedSegments.pop();\n }\n else {\n normalizedSegments.push(segment);\n }\n }\n\n return joinPath(normalizedSegments);\n}\n\n/**\n * Get the file extension from a path\n * \n * @param path - The file path\n * @returns The file extension including the dot, or empty string if no extension\n * \n * @example\n * ```typescript\n * extname('/path/to/file.txt'); // '.txt'\n * extname('/path/to/file'); // ''\n * extname('/path/to/file.name.ext'); // '.ext'\n * extname('/path/to/.hidden'); // ''\n * ```\n */\nexport function extname(path: string): string {\n const filename = basename(path);\n const lastDotIndex = filename.lastIndexOf('.');\n \n if (lastDotIndex <= 0 || lastDotIndex === filename.length - 1) {\n return '';\n }\n \n return filename.slice(lastDotIndex);\n}\n\nexport function createBuffer(data: string | Uint8Array | ArrayBuffer, encoding: BufferEncoding = 'utf-8'): Uint8Array {\n if (typeof data === 'string') {\n return encodeString(data, encoding);\n }\n\n return data instanceof Uint8Array ? data : new Uint8Array(data);\n}\n\n\n/**\n * Read raw binary data from a file using a file handle\n *\n * @param fileHandle - The file handle to read from\n * @returns The raw binary data as Uint8Array\n */\nexport async function readFileData(fileHandle: FileSystemFileHandle): Promise<Uint8Array> {\n const handle = await fileHandle.createSyncAccessHandle();\n\n try {\n const size = handle.getSize();\n const buffer = new Uint8Array(size);\n\n handle.read(buffer, { at: 0 });\n\n return buffer;\n }\n finally {\n handle.close();\n }\n}\n\n/**\n * Write data to a file using a file handle\n *\n * @param fileHandle - The file handle to write to\n * @param data - The data to write to the file\n * @param encoding - The encoding to use\n * @param options - Write options (truncate or append)\n */\nexport async function writeFileData(\n fileHandle: FileSystemFileHandle,\n data: string | Uint8Array | ArrayBuffer,\n encoding?: BufferEncoding,\n options: { truncate?: boolean; append?: boolean } = {}\n): Promise<void> {\n let handle: FileSystemSyncAccessHandle | null = null;\n\n try {\n handle = await fileHandle.createSyncAccessHandle();\n\n const buffer = createBuffer(data, encoding);\n const writeOffset = options.append ? handle.getSize() : 0;\n\n handle.write(buffer, { at: writeOffset });\n\n if (options.truncate && !options.append) {\n handle.truncate(buffer.byteLength);\n }\n\n handle.flush();\n }\n catch (error) {\n console.error(error);\n const operation = options.append ? 'append' : 'write';\n\n throw new OPFSError(`Failed to ${ operation } file`, `${ operation.toUpperCase() }_FAILED`);\n }\n finally {\n if (handle) {\n try {\n handle.close();\n }\n catch { /* ~ */ }\n }\n }\n}\n\n/**\n * Calculate file hash using Web Crypto API\n * \n * @param buffer - The file content as File, ArrayBuffer, or Uint8Array\n * @param algorithm - Hash algorithm to use (default: 'SHA-1')\n * @param maxSize - Maximum file size in bytes. If file is larger, throws error (default: 50MB)\n * @returns Promise that resolves to the hash string\n * @throws Error if file size exceeds maxSize\n */\nexport async function calculateFileHash(\n buffer: File | ArrayBuffer | Uint8Array, \n algorithm: string = 'SHA-1',\n maxSize: number = 50 * 1024 * 1024 // 50MB default\n): Promise<string> {\n if (buffer instanceof File) {\n buffer = await buffer.arrayBuffer();\n }\n \n // Check file size before processing\n if (buffer.byteLength > maxSize) {\n throw new Error(`File size ${buffer.byteLength} bytes exceeds maximum allowed size ${maxSize} bytes`);\n }\n\n const bufferSource = new Uint8Array(buffer);\n const hashBuffer = await crypto.subtle.digest(algorithm, bufferSource);\n const hashArray = Array.from(new Uint8Array(hashBuffer));\n\n return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');\n}\n\n/**\n * Convert a Blob to Uint8Array\n * \n * This function converts a Blob object to a Uint8Array for use with file operations.\n * It's useful when working with file uploads or other Blob data sources.\n * \n * @param blob - The Blob to convert\n * @returns Promise that resolves to the Uint8Array representation of the Blob\n * \n * @example\n * ```typescript\n * const fileInput = document.getElementById('file') as HTMLInputElement;\n * const file = fileInput.files?.[0];\n * if (file) {\n * const data = await convertBlobToUint8Array(file);\n * await fs.writeFile('/uploaded-file', data);\n * }\n * ```\n */\nexport async function convertBlobToUint8Array(blob: Blob): Promise<Uint8Array> {\n const arrayBuffer = await blob.arrayBuffer();\n return new Uint8Array(arrayBuffer);\n}\n","import { expose } from 'comlink';\n\nimport { decodeBuffer } from './utils/encoder';\nimport {\n FileNotFoundError,\n OPFSError,\n OPFSNotMountedError,\n PathError\n} from './utils/errors';\n\nimport { \n calculateFileHash, \n checkOPFSSupport, \n joinPath, \n readFileData, \n splitPath, \n writeFileData,\n basename,\n dirname,\n normalizePath,\n resolvePath,\n convertBlobToUint8Array\n} from './utils/helpers';\n\nimport type { DirentData, FileStat, WatchEvent, OPFSOptions } from './types';\nimport type { BufferEncoding } from 'typescript';\n\n/**\n * OPFS (Origin Private File System) File System implementation\n * \n * This class provides a high-level interface for working with the browser's\n * Origin Private File System API, offering file and directory operations\n * similar to Node.js fs module.\n * \n * @example\n * ```typescript\n * const fs = new OPFSFileSystem();\n * await fs.init('/my-app');\n * await fs.writeFile('/data/config.json', JSON.stringify({ theme: 'dark' }));\n * const config = await fs.readFile('/data/config.json');\n * ```\n */\nexport class OPFSWorker {\n /** Root directory handle for the file system */\n private root: FileSystemDirectoryHandle | null = null;\n\n /** Map of watched paths to their last known state */\n private watchers = new Map<string, Map<string, FileStat>>();\n\n /** Interval handle for polling watched paths */\n private watchTimer: ReturnType<typeof setInterval> | null = null;\n\n /** Flag to avoid concurrent scans */\n private scanning = false;\n\n /** Promise to prevent concurrent mount operations */\n private mountingPromise: Promise<boolean> | null = null;\n\n /** BroadcastChannel instance for sending events */\n private broadcastChannel: BroadcastChannel | null = null;\n\n /** Configuration options */\n private options: Required<OPFSOptions> = {\n watchInterval: 1000,\n maxFileSize: 50 * 1024 * 1024,\n hashAlgorithm: null,\n broadcastChannel: 'opfs-worker',\n };\n \n /**\n * Notify about internal changes to the file system\n * \n * This method is called by internal operations to notify clients about\n * changes, even when no specific paths are being watched.\n * \n * @param path - The path that was changed\n * @param type - The type of change (create, change, delete)\n */\n private async notifyChange(event: Omit<WatchEvent, 'timestamp' | 'hash'>): Promise<void> {\n if (!this.options.broadcastChannel) {\n return;\n }\n\n // Calculate hash if hashing is enabled and this is a file operation\n let hash: string | undefined;\n \n if (this.options.hashAlgorithm && !event.isDirectory && event.type !== 'removed') {\n try {\n const stats = await this.stat(event.path);\n\n if (stats.isFile && stats.hash) {\n hash = stats.hash;\n }\n } \n catch (error) {\n console.warn(`Failed to calculate hash for ${event.path}:`, error);\n }\n }\n\n // Send event via BroadcastChannel\n try {\n if (!this.broadcastChannel) {\n this.broadcastChannel = new BroadcastChannel(this.options.broadcastChannel);\n }\n \n const watchEvent: WatchEvent = {\n timestamp: new Date().toISOString(),\n ...event,\n ...(hash && { hash })\n };\n \n this.broadcastChannel.postMessage(watchEvent);\n } \n catch (error) {\n console.warn(`Failed to send event via BroadcastChannel:`, error);\n }\n }\n\n /**\n * Creates a new OPFSFileSystem instance\n * \n * @param options - Optional configuration options\n * @param options.watchInterval - Polling interval in milliseconds for file watching\n * @param options.hashAlgorithm - Hash algorithm for file hashing\n * @param options.maxFileSize - Maximum file size for hashing in bytes (default: 50MB)\n * @throws {OPFSError} If OPFS is not supported in the current browser\n */\n constructor(options?: OPFSOptions) {\n checkOPFSSupport();\n \n if (options) {\n this.setOptions(options);\n }\n \n void this.mount('/');\n }\n\n /**\n * Initialize the file system within a given directory\n * \n * This method sets up the root directory for all subsequent operations.\n * If no root is specified, it will use the OPFS root directory.\n * \n * @param root - The root path for the file system (default: '/')\n * @returns Promise that resolves to true if initialization was successful\n * @throws {OPFSError} If initialization fails\n * \n * @example\n * ```typescript\n * const fs = new OPFSFileSystem();\n * \n * // Use OPFS root (default)\n * await fs.mount();\n * \n * // Use custom directory\n * await fs.mount('/my-app');\n * ```\n */\n async mount(root: string = '/'): Promise<boolean> {\n // If already mounting, wait for previous operation to complete first\n if (this.mountingPromise) {\n await this.mountingPromise;\n }\n\n this.mountingPromise = new Promise<boolean>(async(resolve, reject) => {\n this.root = null;\n \n try {\n const rootDir = await navigator.storage.getDirectory();\n \n if (root === '/') {\n this.root = rootDir;\n } \n else {\n this.root = await this.getDirectoryHandle(root, true, rootDir);\n }\n resolve(true);\n }\n catch (error) {\n console.error(error);\n reject(new OPFSError('Failed to initialize OPFS', 'INIT_FAILED'));\n }\n finally {\n this.mountingPromise = null;\n }\n });\n\n return this.mountingPromise;\n }\n\n\n /**\n * Update configuration options\n * \n * @param options - Configuration options to update\n * @param options.watchInterval - Polling interval in milliseconds for file watching\n * @param options.hashAlgorithm - Hash algorithm for file hashing\n * @param options.maxFileSize - Maximum file size for hashing in bytes\n * @param options.broadcastChannel - Custom name for the broadcast channel\n */\n setOptions(options: OPFSOptions): void {\n if (options.watchInterval !== undefined) {\n this.options.watchInterval = options.watchInterval;\n }\n\n if (options.hashAlgorithm !== undefined) {\n this.options.hashAlgorithm = options.hashAlgorithm;\n }\n\n if (options.maxFileSize !== undefined) {\n this.options.maxFileSize = options.maxFileSize;\n }\n\n if (options.broadcastChannel !== undefined) {\n // Close existing channel if name changed\n if (this.broadcastChannel && this.options.broadcastChannel !== options.broadcastChannel) {\n this.broadcastChannel.close();\n this.broadcastChannel = null;\n }\n \n this.options.broadcastChannel = options.broadcastChannel;\n }\n }\n\n /**\n * Automatically mount the OPFS root if not already mounted\n * \n * This method is called internally when file operations are performed\n * without explicitly mounting first.\n * \n * @returns Promise that resolves when auto-mount is complete\n * @throws {OPFSError} If auto-mount fails\n */\n private async ensureMounted(): Promise<void> {\n // If already mounted, return immediately\n if (this.root) {\n return;\n }\n\n // If already mounting, wait for that operation to complete\n if (this.mountingPromise) {\n await this.mountingPromise;\n return;\n }\n\n throw new OPFSError('OPFS not mounted', 'NOT_MOUNTED');\n }\n\n /**\n * Get a directory handle from a path\n * \n * Navigates through the directory structure to find or create a directory\n * at the specified path.\n * \n * @param path - The path to the directory (string or array of segments)\n * @param create - Whether to create the directory if it doesn't exist (default: false)\n * @param from - The directory to start from (default: root directory)\n * @returns Promise that resolves to the directory handle\n * @throws {OPFSError} If the directory cannot be accessed or created\n * \n * @example\n * ```typescript\n * const docsDir = await fs.getDirectoryHandle('/users/john/documents', true);\n * const docsDir2 = await fs.getDirectoryHandle(['users', 'john', 'documents'], true);\n * ```\n */\n private async getDirectoryHandle(path: string | string[], create: boolean = false, from: FileSystemDirectoryHandle | null = this.root): Promise<FileSystemDirectoryHandle> {\n if (!from) {\n throw new OPFSNotMountedError();\n }\n\n const segments = Array.isArray(path) ? path : splitPath(path);\n let current = from;\n\n for (const segment of segments) {\n current = await current.getDirectoryHandle(segment, { create });\n }\n\n return current;\n }\n\n /**\n * Get a file handle from a path\n * \n * Navigates to the parent directory and retrieves or creates a file handle\n * for the specified file path.\n * \n * @param path - The path to the file (string or array of segments)\n * @param create - Whether to create the file if it doesn't exist (default: false)\n * @param from - The directory to start from (default: root directory)\n * @returns Promise that resolves to the file handle\n * @throws {PathError} If the path is empty\n * @throws {OPFSError} If the file cannot be accessed or created\n * \n * @example\n * ```typescript\n * const fileHandle = await fs.getFileHandle('/config/settings.json', true);\n * const fileHandle2 = await fs.getFileHandle(['config', 'settings.json'], true);\n * ```\n */\n private async getFileHandle(path: string | string[], create = false, from: FileSystemDirectoryHandle | null = this.root): Promise<FileSystemFileHandle> {\n if (!from) {\n throw new OPFSNotMountedError();\n }\n\n const segments = splitPath(path);\n\n if (segments.length === 0) {\n throw new PathError('Path must not be empty', Array.isArray(path) ? path.join('/') : path);\n }\n\n const fileName = segments.pop()!;\n const dir = await this.getDirectoryHandle(segments, create, from);\n\n return dir.getFileHandle(fileName, { create });\n }\n\n\n /**\n * Get a complete index of all files and directories in the file system\n * \n * This method recursively traverses the entire file system and returns\n * a Map containing FileStat objects for every file and directory.\n * \n * @returns Promise that resolves to a Map of paths to FileStat objects\n * @throws {OPFSError} If the file system is not mounted\n * \n * @example\n * ```typescript\n * const index = await fs.index();\n * const fileStats = index.get('/data/config.json');\n * if (fileStats) {\n * console.log(`File size: ${fileStats.size} bytes`);\n * if (fileStats.hash) console.log(`Hash: ${fileStats.hash}`);\n * }\n * ```\n */\n async index(): Promise<Map<string, FileStat>> {\n const result = new Map<string, FileStat>();\n\n const walk = async(dirPath: string) => {\n const items = await this.readDir(dirPath);\n\n for (const item of items) {\n const fullPath = `${ dirPath === '/' ? '' : dirPath }/${ item.name }`;\n\n try {\n const stat = await this.stat(fullPath);\n\n result.set(fullPath, stat);\n\n if (stat.isDirectory) {\n await walk(fullPath);\n }\n }\n catch (err) {\n console.warn(`Skipping broken entry: ${ fullPath }`, err);\n }\n }\n };\n\n result.set('/', {\n kind: 'directory',\n size: 0,\n mtime: new Date(0).toISOString(),\n ctime: new Date(0).toISOString(),\n isFile: false,\n isDirectory: true,\n });\n\n await walk('/');\n\n return result;\n }\n\n /**\n * Read a file from the file system\n * \n * Reads the contents of a file and returns it as a string or binary data\n * depending on the specified encoding.\n * \n * @param path - The path to the file to read\n * @param encoding - The encoding to use for reading the file\n * @returns Promise that resolves to the file contents\n * @throws {FileNotFoundError} If the file does not exist\n * @throws {OPFSError} If reading the file fails\n * \n * @example\n * ```typescript\n * // Read as text\n * const content = await fs.readFile('/config/settings.json');\n * \n * // Read as binary\n * const binaryData = await fs.readFile('/images/logo.png', 'binary');\n * \n * // Read with specific encoding\n * const utf8Content = await fs.readFile('/data/utf8.txt', 'utf-8');\n * ```\n */\n async readFile(path: string, encoding: 'binary'): Promise<Uint8Array>;\n async readFile(path: string, encoding?: BufferEncoding): Promise<string>;\n async readFile(\n path: string,\n encoding: BufferEncoding | 'binary' = 'utf-8'\n ): Promise<string | Uint8Array> {\n await this.ensureMounted();\n \n try {\n const fileHandle = await this.getFileHandle(path, false);\n const buffer = await readFileData(fileHandle);\n\n if (encoding === 'binary') {\n return buffer;\n }\n\n return decodeBuffer(buffer, encoding);\n }\n catch (err) {\n console.error(err);\n\n throw new FileNotFoundError(path);\n }\n }\n\n /**\n * Write data to a file\n * \n * Creates or overwrites a file with the specified data. If the file already\n * exists, it will be truncated before writing.\n * \n * @param path - The path to the file to write\n * @param data - The data to write to the file (string, Uint8Array, or ArrayBuffer)\n * @param encoding - The encoding to use when writing string data (default: 'utf-8')\n * @returns Promise that resolves when the write operation is complete\n * @throws {OPFSError} If writing the file fails\n * \n * @example\n * ```typescript\n * // Write text data\n * await fs.writeFile('/config/settings.json', JSON.stringify({ theme: 'dark' }));\n * \n * // Write binary data\n * const binaryData = new Uint8Array([1, 2, 3, 4, 5]);\n * await fs.writeFile('/data/binary.dat', binaryData);\n * \n * // Write with specific encoding\n * await fs.writeFile('/data/utf16.txt', 'Hello World', 'utf-16le');\n * ```\n */\n async writeFile(\n path: string,\n data: string | Uint8Array | ArrayBuffer,\n encoding?: BufferEncoding\n ): Promise<void> {\n await this.ensureMounted();\n \n const fileHandle = await this.getFileHandle(path, true);\n\n await writeFileData(fileHandle, data, encoding, { truncate: true });\n await this.notifyChange({ path, type: 'changed', isDirectory: false });\n }\n\n /**\n * Append data to a file\n * \n * Adds data to the end of an existing file. If the file doesn't exist,\n * it will be created.\n * \n * @param path - The path to the file to append to\n * @param data - The data to append to the file (string, Uint8Array, or ArrayBuffer)\n * @param encoding - The encoding to use when appending string data (default: 'utf-8')\n * @returns Promise that resolves when the append operation is complete\n * @throws {OPFSError} If appending to the file fails\n * \n * @example\n * ```typescript\n * // Append text to a log file\n * await fs.appendFile('/logs/app.log', `[${new Date().toISOString()}] User logged in\\n`);\n * \n * // Append binary data\n * const additionalData = new Uint8Array([6, 7, 8]);\n * await fs.appendFile('/data/binary.dat', additionalData);\n * ```\n */\n async appendFile(\n path: string,\n data: string | Uint8Array | ArrayBuffer,\n encoding?: BufferEncoding\n ): Promise<void> {\n await this.ensureMounted();\n \n const fileHandle = await this.getFileHandle(path, true);\n\n await writeFileData(fileHandle, data, encoding, { append: true });\n await this.notifyChange({ path, type: 'changed', isDirectory: false });\n }\n\n /**\n * Create a directory\n * \n * Creates a new directory at the specified path. If the recursive option\n * is enabled, parent directories will be created as needed.\n * \n * @param path - The path where the directory should be created\n * @param options - Options for directory creation\n * @param options.recursive - Whether to create parent directories if they don't exist (default: false)\n * @returns Promise that resolves when the directory is created\n * @throws {OPFSError} If the directory cannot be created\n * \n * @example\n * ```typescript\n * // Create a single directory\n * await fs.mkdir('/users/john');\n * \n * // Create nested directories\n * await fs.mkdir('/users/john/documents/projects', { recursive: true });\n * ```\n */\n async mkdir(path: string, options?: { recursive?: boolean }): Promise<void> {\n await this.ensureMounted();\n\n if (!this.root) {\n throw new OPFSNotMountedError();\n }\n\n const recursive = options?.recursive ?? false;\n const segments = splitPath(path);\n\n let current = this.root;\n\n for (let i = 0; i < segments.length; i++) {\n const segment = segments[i];\n\n try {\n current = await current.getDirectoryHandle(segment!, { create: recursive || i === segments.length - 1 });\n }\n catch (e: any) {\n if (e.name === 'NotFoundError') {\n throw new OPFSError(\n `Parent directory does not exist: ${ joinPath(segments.slice(0, i + 1)) }`,\n 'ENOENT'\n );\n }\n\n if (e.name === 'TypeMismatchError') {\n throw new OPFSError(`Path segment is not a directory: ${ segment }`, 'ENOTDIR');\n }\n\n throw new OPFSError('Failed to create directory', 'MKDIR_FAILED');\n }\n }\n await this.notifyChange({ path, type: 'added', isDirectory: true });\n }\n\n /**\n * Get file or directory statistics\n * \n * Returns detailed information about a file or directory, including\n * size, modification time, and optionally a hash of the file content.\n * \n * @param path - The path to the file or directory\n * @returns Promise that resolves to FileStat object\n * @throws {OPFSError} If the path does not exist or cannot be accessed\n * \n * @example\n * ```typescript\n * const stats = await fs.stat('/data/config.json');\n * console.log(`File size: ${stats.size} bytes`);\n * console.log(`Last modified: ${stats.mtime}`);\n * \n * // If hashing is enabled, hash will be included\n * if (stats.hash) {\n * console.log(`Hash: ${stats.hash}`);\n * }\n * ```\n */\n async stat(path: string): Promise<FileStat> {\n await this.ensureMounted();\n \n // Special handling for root directory\n if (path === '/') {\n return {\n kind: 'directory',\n size: 0,\n mtime: new Date(0).toISOString(),\n ctime: new Date(0).toISOString(),\n isFile: false,\n isDirectory: true,\n };\n }\n \n const name = basename(path);\n const parentDir = await this.getDirectoryHandle(dirname(path), false);\n const includeHash = this.options.hashAlgorithm !== null;\n\n try {\n const fileHandle = await parentDir.getFileHandle(name!, { create: false });\n const file = await fileHandle.getFile();\n\n const baseStat: FileStat = {\n kind: 'file',\n size: file.size,\n mtime: new Date(file.lastModified).toISOString(),\n ctime: new Date(file.lastModified).toISOString(),\n isFile: true,\n isDirectory: false,\n };\n\n if (includeHash && this.options.hashAlgorithm) {\n try {\n const hash = await calculateFileHash(file, this.options.hashAlgorithm, this.options.maxFileSize);\n\n baseStat.hash = hash;\n }\n catch (error) {\n console.warn(`Failed to calculate hash for ${ path }:`, error);\n }\n }\n\n return baseStat;\n }\n catch (e: any) {\n if (e.name !== 'TypeMismatchError' && e.name !== 'NotFoundError') {\n throw new OPFSError('Failed to stat (file)', 'STAT_FAILED');\n }\n }\n\n try {\n await parentDir.getDirectoryHandle(name!, { create: false });\n\n return {\n kind: 'directory',\n size: 0,\n mtime: new Date(0).toISOString(),\n ctime: new Date(0).toISOString(),\n isFile: false,\n isDirectory: true,\n };\n }\n catch (e: any) {\n if (e.name === 'NotFoundError') {\n throw new OPFSError(`No such file or directory: ${ path }`, 'ENOENT');\n }\n\n throw new OPFSError('Failed to stat (directory)', 'STAT_FAILED');\n }\n }\n\n /**\n * Read a directory's contents\n * \n * Lists all files and subdirectories within the specified directory.\n * \n * @param path - The path to the directory to read\n * @returns Promise that resolves to an array of detailed file/directory information\n * @throws {OPFSError} If the directory does not exist or cannot be accessed\n * \n * @example\n * ```typescript\n * // Get detailed information about files and directories\n * const detailed = await fs.readDir('/users/john/documents');\n * detailed.forEach(item => {\n * console.log(`${item.name} - ${item.isFile ? 'file' : 'directory'}`);\n * });\n * ```\n */\n async readDir(path: string): Promise<DirentData[]> {\n await this.ensureMounted();\n \n const dir = await this.getDirectoryHandle(path, false);\n\n const results: DirentData[] = [];\n\n for await (const [name, handle] of (dir as any).entries()) {\n const isFile = handle.kind === 'file';\n\n results.push({\n name,\n kind: handle.kind,\n isFile,\n isDirectory: !isFile,\n });\n }\n\n return results;\n }\n\n /**\n * Check if a file or directory exists\n * \n * Verifies if a file or directory exists at the specified path.\n * \n * @param path - The path to check\n * @returns Promise that resolves to true if the file or directory exists, false otherwise \n * \n * @example\n * ```typescript\n * const exists = await fs.exists('/config/settings.json');\n * console.log(`File exists: ${exists}`);\n * ```\n */\n async exists(path: string): Promise<boolean> {\n await this.ensureMounted();\n \n if (path === '/') {\n return true;\n }\n \n const name = basename(path);\n let dir: FileSystemDirectoryHandle | null = null;\n\n try {\n dir = await this.getDirectoryHandle(dirname(path), false);\n }\n catch (e: any) {\n if (e.name === 'NotFoundError' || e.name === 'TypeMismatchError') {\n dir = null;\n }\n\n throw e;\n }\n\n if (!dir || !name) {\n return false;\n }\n\n try {\n await dir.getFileHandle(name, { create: false });\n\n return true;\n }\n catch (e: any) {\n if (e.name !== 'NotFoundError' && e.name !== 'TypeMismatchError') {\n throw e;\n }\n }\n\n try {\n await dir.getDirectoryHandle(name, { create: false });\n\n return true;\n }\n catch (e: any) {\n if (e.name !== 'NotFoundError' && e.name !== 'TypeMismatchError') {\n throw e;\n }\n }\n\n return false;\n }\n\n /**\n * Clear all contents of a directory without removing the directory itself\n * \n * Removes all files and subdirectories within the specified directory,\n * but keeps the directory itself.\n * \n * @param path - The path to the directory to clear (default: '/')\n * @returns Promise that resolves when all contents are removed\n * @throws {OPFSError} If the operation fails\n * \n * @example\n * ```typescript\n * // Clear root directory contents\n * await fs.clear('/');\n * \n * // Clear specific directory contents\n * await fs.clear('/data');\n * ```\n */\n async clear(path: string = '/'): Promise<void> {\n await this.ensureMounted();\n \n try {\n const items = await this.readDir(path);\n\n for (const item of items) {\n const itemPath = `${ path === '/' ? '' : path }/${ item.name }`;\n\n await this.remove(itemPath, { recursive: true });\n }\n \n // Notify about the clear operation\n await this.notifyChange({ path, type: 'changed', isDirectory: true });\n }\n catch (error: any) {\n if (error instanceof OPFSError) {\n throw error;\n }\n\n throw new OPFSError(`Failed to clear directory: ${ path }`, 'CLEAR_FAILED');\n }\n }\n\n /**\n * Remove files and directories\n * \n * Removes files and directories. Similar to Node.js fs.rm().\n * \n * @param path - The path to remove\n * @param options - Options for removal\n * @param options.recursive - Whether to remove directories and their contents recursively (default: false)\n * @param options.force - Whether to ignore errors if the path doesn't exist (default: false)\n * @returns Promise that resolves when the removal is complete\n * @throws {OPFSError} If the removal fails\n * \n * @example\n * ```typescript\n * // Remove a file\n * await fs.rm('/path/to/file.txt');\n * \n * // Remove a directory and all its contents\n * await fs.rm('/path/to/directory', { recursive: true });\n * \n * // Remove with force (ignore if doesn't exist)\n * await fs.rm('/maybe/exists', { force: true });\n * ```\n */\n async remove(path: string, options?: { recursive?: boolean; force?: boolean }): Promise<void> {\n await this.ensureMounted();\n \n const recursive = options?.recursive ?? false;\n const force = options?.force ?? false;\n\n // Special handling for root directory\n if (path === '/') {\n throw new OPFSError('Cannot remove root directory', 'EROOT');\n }\n\n const name = basename(path);\n\n if (!name) {\n throw new PathError('Invalid path', path);\n }\n\n const parent = await this.getDirectoryHandle(dirname(path), false);\n\n try {\n await parent.removeEntry(name, { recursive });\n }\n catch (e: any) {\n if (e.name === 'NotFoundError') {\n if (!force) {\n throw new OPFSError(`No such file or directory: ${ path }`, 'ENOENT');\n }\n }\n else if (e.name === 'InvalidModificationError') {\n throw new OPFSError(`Directory not empty: ${ path }. Use recursive option to force removal.`, 'ENOTEMPTY');\n }\n else if (e.name === 'TypeMismatchError' && !recursive) {\n throw new OPFSError(`Cannot remove directory without recursive option: ${ path }`, 'EISDIR');\n }\n else {\n throw new OPFSError(`Failed to remove path: ${ path }`, 'RM_FAILED');\n }\n }\n \n await this.notifyChange({ path, type: 'removed', isDirectory: false });\n }\n\n /**\n * Resolve a path to an absolute path\n * \n * Resolves relative paths and normalizes path segments (like '..' and '.').\n * Similar to Node.js fs.realpath() but without symlink resolution since OPFS doesn't support symlinks.\n * \n * @param path - The path to resolve\n * @returns Promise that resolves to the absolute normalized path\n * @throws {FileNotFoundError} If the path does not exist\n * @throws {OPFSError} If path resolution fails\n * \n * @example\n * ```typescript\n * // Resolve relative path\n * const absolute = await fs.realpath('./config/../data/file.txt');\n * console.log(absolute); // '/data/file.txt'\n * ```\n */\n async realpath(path: string): Promise<string> {\n await this.ensureMounted();\n \n try {\n const normalizedPath = resolvePath(path);\n const exists = await this.exists(normalizedPath);\n\n if (!exists) {\n throw new FileNotFoundError(normalizedPath);\n }\n\n return normalizedPath;\n }\n catch (error) {\n if (error instanceof OPFSError) {\n throw error;\n }\n\n throw new OPFSError(`Failed to resolve path: ${ path }`, 'REALPATH_FAILED');\n }\n }\n\n /**\n * Rename a file or directory\n * \n * Changes the name of a file or directory. If the target path already exists,\n * it will be replaced.\n * \n * @param oldPath - The current path of the file or directory\n * @param newPath - The new path for the file or directory\n * @returns Promise that resolves when the rename operation is complete\n * @throws {OPFSError} If the rename operation fails\n * \n * @example\n * ```typescript\n * await fs.rename('/old/path/file.txt', '/new/path/renamed.txt');\n * ```\n */\n async rename(oldPath: string, newPath: string): Promise<void> {\n await this.ensureMounted();\n \n try {\n const sourceExists = await this.exists(oldPath);\n\n if (!sourceExists) {\n throw new FileNotFoundError(oldPath);\n }\n\n await this.copy(oldPath, newPath, { recursive: true });\n await this.remove(oldPath, { recursive: true });\n \n // Notify about the rename operation\n await this.notifyChange({ path: oldPath, type: 'removed', isDirectory: false });\n await this.notifyChange({ path: newPath, type: 'added', isDirectory: false });\n }\n catch (error) {\n if (error instanceof OPFSError) {\n throw error;\n }\n\n throw new OPFSError(`Failed to rename from ${ oldPath } to ${ newPath }`, 'RENAME_FAILED');\n }\n }\n\n /**\n * Copy files and directories\n * \n * Copies files and directories. Similar to Node.js fs.cp().\n * \n * @param source - The source path to copy from\n * @param destination - The destination path to copy to\n * @param options - Options for copying\n * @param options.recursive - Whether to copy directories recursively (default: false)\n * @param options.force - Whether to overwrite existing files (default: true)\n * @returns Promise that resolves when the copy operation is complete\n * @throws {OPFSError} If the copy operation fails\n * \n * @example\n * ```typescript\n * // Copy a file\n * await fs.copy('/source/file.txt', '/dest/file.txt');\n * \n * // Copy a directory and all its contents\n * await fs.copy('/source/dir', '/dest/dir', { recursive: true });\n * \n * // Copy without overwriting existing files\n * await fs.copy('/source', '/dest', { recursive: true, force: false });\n * ```\n */\n async copy(source: string, destination: string, options?: { recursive?: boolean; force?: boolean }): Promise<void> {\n await this.ensureMounted();\n \n try {\n const recursive = options?.recursive ?? false;\n const force = options?.force ?? true;\n\n const sourceExists = await this.exists(source);\n\n if (!sourceExists) {\n throw new OPFSError(`Source does not exist: ${ source }`, 'ENOENT');\n }\n\n const destExists = await this.exists(destination);\n\n if (destExists && !force) {\n throw new OPFSError(`Destination already exists: ${ destination }`, 'EEXIST');\n }\n\n const sourceStats = await this.stat(source);\n\n if (sourceStats.isFile) {\n const content = await this.readFile(source, 'binary');\n \n await this.writeFile(destination, content);\n }\n else {\n if (!recursive) {\n throw new OPFSError(`Cannot copy directory without recursive option: ${ source }`, 'EISDIR');\n }\n\n await this.mkdir(destination, { recursive: true });\n\n const items = await this.readDir(source);\n\n for (const item of items) {\n const sourceItemPath = `${ source }/${ item.name }`;\n const destItemPath = `${ destination }/${ item.name }`;\n\n await this.copy(sourceItemPath, destItemPath, { recursive: true, force });\n }\n }\n \n // Notify about the copy operation\n await this.notifyChange({ path: destination, type: 'added', isDirectory: false });\n }\n catch (error) {\n if (error instanceof OPFSError) {\n throw error;\n }\n\n throw new OPFSError(`Failed to copy from ${ source } to ${ destination }`, 'CP_FAILED');\n }\n }\n\n /**\n * Start watching a file or directory for changes\n */\n async watch(path: string): Promise<void> {\n await this.ensureMounted();\n \n const normalizedPath = normalizePath(path);\n const snapshot = await this.buildSnapshot(normalizedPath);\n\n this.watchers.set(normalizedPath, snapshot);\n\n if (!this.watchTimer) {\n this.watchTimer = setInterval(() => {\n void this.scanWatches();\n }, this.options.watchInterval);\n }\n }\n\n /**\n * Stop watching a previously watched path\n */\n unwatch(path: string): void {\n const normalizedPath = normalizePath(path);\n this.watchers.delete(normalizedPath);\n\n if (this.watchers.size === 0 && this.watchTimer) {\n clearInterval(this.watchTimer);\n this.watchTimer = null;\n }\n }\n\n /**\n * Dispose of resources and clean up the file system instance\n * \n * This method should be called when the file system instance is no longer needed\n * to properly clean up resources like the broadcast channel and watch timers.\n */\n dispose(): void {\n if (this.broadcastChannel) {\n this.broadcastChannel.close();\n this.broadcastChannel = null;\n }\n \n if (this.watchTimer) {\n clearInterval(this.watchTimer);\n this.watchTimer = null;\n }\n \n this.watchers.clear();\n }\n\n private async buildSnapshot(rootPath: string): Promise<Map<string, FileStat>> {\n const result = new Map<string, FileStat>();\n\n const walk = async (current: string) => {\n const stat = await this.stat(current);\n result.set(current, stat);\n\n if (stat.isDirectory) {\n const entries = await this.readDir(current);\n for (const entry of entries) {\n const child = `${ current === '/' ? '' : current }/${ entry.name }`;\n await walk(child);\n }\n }\n };\n\n await walk(rootPath);\n return result;\n }\n\n private async scanWatches(): Promise<void> {\n if (this.scanning) {\n return;\n }\n\n this.scanning = true;\n\n try {\n await Promise.all(\n [...this.watchers.entries()].map(async([rootPath, prev]) => {\n let next: Map<string, FileStat>;\n\n try {\n next = await this.buildSnapshot(rootPath);\n }\n catch (error) {\n next = new Map();\n }\n\n for (const [p, stat] of next) {\n const old = prev.get(p);\n \n if (!old) {\n await this.notifyChange({ path: p, type: 'added', isDirectory: stat.isDirectory });\n }\n else if (old.mtime !== stat.mtime || old.size !== stat.size) {\n await this.notifyChange({ path: p, type: 'changed', isDirectory: stat.isDirectory });\n }\n }\n\n for (const p of prev.keys()) {\n if (!next.has(p)) {\n const oldStat = prev.get(p);\n await this.notifyChange({ path: p, type: 'removed', isDirectory: oldStat?.isDirectory ?? false });\n }\n }\n\n this.watchers.set(rootPath, next);\n })\n );\n }\n finally {\n this.scanning = false;\n }\n }\n\n /**\n * Synchronize the file system with external data\n * \n * Syncs the file system with an array of entries containing paths and data.\n * This is useful for importing data from external sources or syncing with remote data.\n * \n * @param entries - Array of [path, data] tuples to sync\n * @param options - Options for synchronization\n * @param options.cleanBefore - Whether to clear the file system before syncing (default: false)\n * @returns Promise that resolves when synchronization is complete\n * @throws {OPFSError} If the synchronization fails\n * \n * @example\n * ```typescript\n * // Sync with external data\n * const entries: [string, string | Uint8Array | Blob][] = [\n * ['/config.json', JSON.stringify({ theme: 'dark' })],\n * ['/data/binary.dat', new Uint8Array([1, 2, 3, 4])],\n * ['/upload.txt', new Blob(['file content'], { type: 'text/plain' })]\n * ];\n * \n * // Sync without clearing existing files\n * await fs.sync(entries);\n * \n * // Clean file system and then sync\n * await fs.sync(entries, { cleanBefore: true });\n * ```\n */\n async sync(entries: [string, string | Uint8Array | Blob][], options?: { cleanBefore?: boolean }): Promise<void> {\n await this.ensureMounted();\n \n try {\n const cleanBefore = options?.cleanBefore ?? false;\n\n if (cleanBefore) {\n await this.clear('/');\n }\n\n for (const [path, data] of entries) {\n const normalizedPath = normalizePath(path);\n\n let fileData: string | Uint8Array;\n\n if (data instanceof Blob) {\n fileData = await convertBlobToUint8Array(data);\n }\n else {\n fileData = data;\n }\n\n await this.writeFile(normalizedPath, fileData);\n }\n \n // Notify about the sync operation\n await this.notifyChange({ path: '/', type: 'changed', isDirectory: true });\n }\n catch (error) {\n if (error instanceof OPFSError) {\n throw error;\n }\n\n throw new OPFSError('Failed to sync file system', 'SYNC_FAILED');\n }\n }\n}\n\n// Only expose the worker when running in a Web Worker environment\nif (typeof self !== 'undefined' && self.constructor.name === 'DedicatedWorkerGlobalScope') {\n expose(new OPFSWorker());\n}"],"names":["proxyMarker","createEndpoint","releaseProxy","finalizer","throwMarker","isObject","val","proxyTransferHandler","obj","port1","port2","expose","port","wrap","throwTransferHandler","value","serialized","transferHandlers","isAllowedOrigin","allowedOrigins","origin","allowedOrigin","ep","callback","ev","id","type","path","argumentList","fromWireValue","returnValue","parent","prop","rawValue","proxy","transfer","wireValue","transferables","toWireValue","closeEndPoint","error","isMessagePort","endpoint","target","pendingListeners","data","resolver","createProxy","throwIfProxyReleased","isReleased","releaseEndpoint","requestResponseMessage","proxyCounter","proxyFinalizers","newCount","registerProxy","unregisterProxy","isProxyReleased","_target","r","p","_thisArg","rawArgumentList","last","processArguments","myFlat","arr","processed","v","transferCache","transfers","name","handler","serializedValue","msg","resolve","generateUUID","OPFSError","message","code","OPFSNotSupportedError","OPFSNotMountedError","PathError","FileNotFoundError","encodeString","encoding","encodeUtf16LE","encodeAscii","encodeLatin1","char","c","b","decodeBuffer","buffer","decodeUtf16LE","str","buf","i","codeUnits","checkOPFSSupport","splitPath","joinPath","segments","basename","dirname","normalizePath","resolvePath","normalizedPath","normalizedSegments","segment","createBuffer","readFileData","fileHandle","handle","size","writeFileData","options","writeOffset","operation","calculateFileHash","algorithm","maxSize","bufferSource","hashBuffer","convertBlobToUint8Array","blob","arrayBuffer","OPFSWorker","event","hash","stats","watchEvent","root","reject","rootDir","create","from","current","fileName","result","walk","dirPath","items","item","fullPath","stat","err","recursive","e","parentDir","includeHash","file","baseStat","dir","results","isFile","itemPath","force","oldPath","newPath","source","destination","content","sourceItemPath","destItemPath","snapshot","rootPath","entries","entry","child","prev","next","old","oldStat","fileData"],"mappings":"AAAA;AAAA;AAAA;AAAA;AAAA;AAKA,MAAMA,IAAc,OAAO,eAAe,GACpCC,IAAiB,OAAO,kBAAkB,GAC1CC,IAAe,OAAO,sBAAsB,GAC5CC,IAAY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
|
|
|
1
|
+
"use strict";class c extends Error{constructor(r,t,n){super(r),this.code=t,this.path=n,this.name="OPFSError"}}class l extends c{constructor(){super("OPFS is not supported in this browser","OPFS_NOT_SUPPORTED")}}class g extends c{constructor(){super("OPFS is not mounted","OPFS_NOT_MOUNTED")}}class m extends c{constructor(r,t){super(r,"INVALID_PATH",t)}}class E extends c{constructor(r){super(`File not found: ${r}`,"FILE_NOT_FOUND",r)}}class S extends c{constructor(r){super(`Directory not found: ${r}`,"DIRECTORY_NOT_FOUND",r)}}class p extends c{constructor(r,t){super(`Permission denied for ${t} on: ${r}`,"PERMISSION_DENIED",r)}}class w extends c{constructor(r,t){super(r,"STORAGE_ERROR",t)}}class F extends c{constructor(r,t){super(`Operation timed out: ${r}`,"TIMEOUT_ERROR",t)}}function f(e,r="utf-8"){switch(r){case"utf8":case"utf-8":return new TextEncoder().encode(e);case"utf16le":case"ucs2":case"ucs-2":return P(e);case"ascii":return T(e);case"latin1":return U(e);case"binary":return Uint8Array.from(e,t=>t.charCodeAt(0));case"base64":return Uint8Array.from(atob(e),t=>t.charCodeAt(0));case"hex":if(!/^[\da-f]+$/i.test(e)||e.length%2!==0)throw new c("Invalid hex string","INVALID_HEX_FORMAT");return Uint8Array.from(e.match(/.{1,2}/g).map(t=>parseInt(t,16)));default:return console.warn("Encoding not supported, falling back to UTF-8"),new TextEncoder().encode(e)}}function A(e,r="utf-8"){switch(r){case"utf8":case"utf-8":return new TextDecoder().decode(e);case"utf16le":case"ucs2":case"ucs-2":return O(e);case"latin1":return String.fromCharCode(...e);case"binary":return String.fromCharCode(...e);case"ascii":return String.fromCharCode(...e.map(t=>t&127));case"base64":return btoa(String.fromCharCode(...e));case"hex":return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("");default:return console.warn("Unsupported encoding, falling back to UTF-8"),new TextDecoder().decode(e)}}function P(e){const r=new Uint8Array(e.length*2);for(let t=0;t<e.length;t++){const n=e.charCodeAt(t);r[t*2]=n&255,r[t*2+1]=n>>8}return r}function O(e){e.length%2!==0&&(console.warn("Invalid UTF-16LE buffer length, truncating last byte"),e=e.slice(0,e.length-1));const r=new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2);return String.fromCharCode(...r)}function U(e){const r=new Uint8Array(e.length);for(let t=0;t<e.length;t++)r[t]=e.charCodeAt(t)&255;return r}function T(e){const r=new Uint8Array(e.length);for(let t=0;t<e.length;t++)r[t]=e.charCodeAt(t)&127;return r}function x(){if(!("storage"in navigator)||!("getDirectory"in navigator.storage))throw new l}function a(e){return Array.isArray(e)?e:(e.startsWith("~/")?e.slice(2):e).split("/").filter(Boolean)}function u(e){return typeof e=="string"?e??"/":`/${e.join("/")}`}function d(e){const r=a(e);return r[r.length-1]||""}function D(e){const r=a(e);return r.pop(),u(r)}function h(e){return!e||e==="/"?"/":e.startsWith("~/")?`/${e.slice(2)}`:e.startsWith("/")?e:`/${e}`}function N(e){const r=h(e),t=a(r),n=[];for(const o of t)if(!(o==="."||o===""))if(o===".."){if(n.length===0)continue;n.pop()}else n.push(o);return u(n)}function C(e){const r=d(e),t=r.lastIndexOf(".");return t<=0||t===r.length-1?"":r.slice(t)}function y(e,r="utf-8"){return typeof e=="string"?f(e,r):e instanceof Uint8Array?e:new Uint8Array(e)}async function I(e){const r=await e.createSyncAccessHandle();try{const t=r.getSize(),n=new Uint8Array(t);return r.read(n,{at:0}),n}finally{r.close()}}async function _(e,r,t,n={}){let o=null;try{o=await e.createSyncAccessHandle();const i=y(r,t),s=n.append?o.getSize():0;o.write(i,{at:s}),n.truncate&&!n.append&&o.truncate(i.byteLength),o.flush()}catch(i){console.error(i);const s=n.append?"append":"write";throw new c(`Failed to ${s} file`,`${s.toUpperCase()}_FAILED`)}finally{if(o)try{o.close()}catch{}}}async function $(e,r="SHA-1",t=50*1024*1024){if(e instanceof File&&(e=await e.arrayBuffer()),e.byteLength>t)throw new Error(`File size ${e.byteLength} bytes exceeds maximum allowed size ${t} bytes`);const n=new Uint8Array(e),o=await crypto.subtle.digest(r,n);return Array.from(new Uint8Array(o)).map(s=>s.toString(16).padStart(2,"0")).join("")}async function b(e){const r=await e.arrayBuffer();return new Uint8Array(r)}exports.DirectoryNotFoundError=S;exports.FileNotFoundError=E;exports.OPFSError=c;exports.OPFSNotMountedError=g;exports.OPFSNotSupportedError=l;exports.PathError=m;exports.PermissionError=p;exports.StorageError=w;exports.TimeoutError=F;exports.basename=d;exports.calculateFileHash=$;exports.checkOPFSSupport=x;exports.convertBlobToUint8Array=b;exports.createBuffer=y;exports.decodeBuffer=A;exports.dirname=D;exports.encodeString=f;exports.extname=C;exports.joinPath=u;exports.normalizePath=h;exports.readFileData=I;exports.resolvePath=N;exports.splitPath=a;exports.writeFileData=_;
|
|
2
|
+
//# sourceMappingURL=helpers-B87wz5kv.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"helpers-B87wz5kv.cjs","sources":["../src/utils/errors.ts","../src/utils/encoder.ts","../src/utils/helpers.ts"],"sourcesContent":["/**\n * Base error class for all OPFS-related errors\n */\nexport class OPFSError extends Error {\n constructor(message: string, public readonly code: string, public readonly path?: string) {\n super(message);\n this.name = 'OPFSError';\n }\n}\n\n/**\n * Error thrown when OPFS is not supported in the current browser\n */\nexport class OPFSNotSupportedError extends OPFSError {\n constructor() {\n super('OPFS is not supported in this browser', 'OPFS_NOT_SUPPORTED');\n }\n}\n\n\n/**\n * Error thrown when OPFS is not mounted\n */\nexport class OPFSNotMountedError extends OPFSError {\n constructor() {\n super('OPFS is not mounted', 'OPFS_NOT_MOUNTED');\n }\n}\n\n/**\n * Error thrown for invalid paths or path traversal attempts\n */\nexport class PathError extends OPFSError {\n constructor(message: string, path: string) {\n super(message, 'INVALID_PATH', path);\n }\n}\n\n/**\n * Error thrown when a requested file doesn't exist\n */\nexport class FileNotFoundError extends OPFSError {\n constructor(path: string) {\n super(`File not found: ${ path }`, 'FILE_NOT_FOUND', path);\n }\n}\n\n/**\n * Error thrown when a requested directory doesn't exist\n */\nexport class DirectoryNotFoundError extends OPFSError {\n constructor(path: string) {\n super(`Directory not found: ${ path }`, 'DIRECTORY_NOT_FOUND', path);\n }\n}\n\n/**\n * Error thrown when permission is denied for an operation\n */\nexport class PermissionError extends OPFSError {\n constructor(path: string, operation: string) {\n super(`Permission denied for ${ operation } on: ${ path }`, 'PERMISSION_DENIED', path);\n }\n}\n\n/**\n * Error thrown when an operation fails due to insufficient storage\n */\nexport class StorageError extends OPFSError {\n constructor(message: string, path?: string) {\n super(message, 'STORAGE_ERROR', path);\n }\n}\n\n/**\n * Error thrown when an operation times out\n */\nexport class TimeoutError extends OPFSError {\n constructor(operation: string, path?: string) {\n super(`Operation timed out: ${ operation }`, 'TIMEOUT_ERROR', path);\n }\n}\n","import { OPFSError } from './errors';\n\nimport type { BufferEncoding } from 'typescript';\n\nexport function encodeString(data: string, encoding: BufferEncoding = 'utf-8'): Uint8Array {\n switch (encoding) {\n case 'utf8':\n case 'utf-8':\n return new TextEncoder().encode(data);\n\n case 'utf16le':\n case 'ucs2':\n case 'ucs-2':\n return encodeUtf16LE(data);\n\n case 'ascii':\n return encodeAscii(data);\n\n case 'latin1':\n return encodeLatin1(data);\n\n case 'binary':\n return Uint8Array.from(data, char => char.charCodeAt(0));\n\n case 'base64':\n return Uint8Array.from(atob(data), c => c.charCodeAt(0));\n\n case 'hex':\n if (!/^[\\da-f]+$/i.test(data) || data.length % 2 !== 0) {\n throw new OPFSError('Invalid hex string', 'INVALID_HEX_FORMAT');\n }\n\n return Uint8Array.from(data.match(/.{1,2}/g)!.map(b => parseInt(b, 16)));\n\n default:\n console.warn('Encoding not supported, falling back to UTF-8');\n\n return new TextEncoder().encode(data);\n }\n}\n\nexport function decodeBuffer(buffer: Uint8Array, encoding: BufferEncoding = 'utf-8'): string {\n switch (encoding) {\n case 'utf8':\n case 'utf-8':\n return new TextDecoder().decode(buffer);\n\n case 'utf16le':\n case 'ucs2':\n case 'ucs-2':\n return decodeUtf16LE(buffer);\n\n case 'latin1':\n return String.fromCharCode(...buffer);\n\n case 'binary':\n return String.fromCharCode(...buffer);\n\n case 'ascii':\n return String.fromCharCode(...buffer.map(b => b & 0x7F));\n\n case 'base64':\n return btoa(String.fromCharCode(...buffer));\n\n case 'hex':\n return Array.from(buffer).map(b => b.toString(16).padStart(2, '0')).join('');\n\n default:\n console.warn('Unsupported encoding, falling back to UTF-8');\n\n return new TextDecoder().decode(buffer);\n }\n}\n\nfunction encodeUtf16LE(str: string): Uint8Array {\n const buf = new Uint8Array(str.length * 2);\n\n for (let i = 0; i < str.length; i++) {\n const code = str.charCodeAt(i);\n\n buf[(i * 2)] = code & 0xFF;\n buf[(i * 2) + 1] = code >> 8;\n }\n\n return buf;\n}\n\nfunction decodeUtf16LE(buf: Uint8Array): string {\n if (buf.length % 2 !== 0) {\n console.warn('Invalid UTF-16LE buffer length, truncating last byte');\n buf = buf.slice(0, buf.length - 1);\n }\n\n const codeUnits = new Uint16Array(buf.buffer, buf.byteOffset, buf.byteLength / 2);\n\n return String.fromCharCode(...codeUnits);\n}\n\nfunction encodeLatin1(str: string): Uint8Array {\n const buf = new Uint8Array(str.length);\n\n for (let i = 0; i < str.length; i++) {\n buf[i] = str.charCodeAt(i) & 0xFF;\n }\n\n return buf;\n}\n\nfunction encodeAscii(str: string): Uint8Array {\n const buf = new Uint8Array(str.length);\n\n for (let i = 0; i < str.length; i++) {\n buf[i] = str.charCodeAt(i) & 0x7F;\n }\n\n return buf;\n}\n","import { encodeString } from './encoder';\nimport { OPFSError, OPFSNotSupportedError } from './errors';\n\nimport type { BufferEncoding } from 'typescript';\n\n/**\n * Check if the browser supports the OPFS API\n * \n * @throws {OPFSNotSupportedError} If the browser does not support the OPFS API\n */\nexport function checkOPFSSupport(): void {\n if (!('storage' in navigator) || !('getDirectory' in (navigator.storage as any))) {\n throw new OPFSNotSupportedError();\n }\n}\n\n/** \n * Split a path into an array of segments\n * \n * @param path - The path to split\n * @returns The array of segments\n * \n * @example\n * ```typescript\n * splitPath('/path/to/file'); // ['path', 'to', 'file']\n * splitPath('~/path/to/file'); // ['path', 'to', 'file'] (home dir handled)\n * splitPath('relative/path'); // ['relative', 'path']\n * ```\n */\nexport function splitPath(path: string | string[]): string[] {\n if (Array.isArray(path)) {\n return path;\n }\n\n const normalizedPath = path.startsWith('~/') ? path.slice(2) : path;\n\n return normalizedPath.split('/').filter(Boolean);\n}\n\n\n/**\n * Join an array of path segments into a single path\n * \n * @param segments - The array of path segments\n * @returns The joined path\n */\nexport function joinPath(segments: string[] | string): string {\n return typeof segments === 'string'\n ? (segments ?? '/')\n : `/${ segments.join('/') }`;\n}\n\n/**\n * Extract the filename from a path\n * \n * @param path - The file path\n * @returns The filename without the directory path\n * \n * @example\n * ```typescript\n * basename('/path/to/file.txt'); // 'file.txt'\n * basename('/path/to/directory/'); // ''\n * basename('file.txt'); // 'file.txt'\n * ```\n */\nexport function basename(path: string): string {\n const segments = splitPath(path);\n return segments[segments.length - 1] || '';\n}\n\n/**\n * Extract the directory path from a file path\n * \n * @param path - The file path\n * @returns The directory path without the filename\n * \n * @example\n * ```typescript\n * dirname('/path/to/file.txt'); // '/path/to'\n * dirname('/path/to/directory/'); // '/path/to/directory'\n * dirname('file.txt'); // '/'\n * ```\n */\nexport function dirname(path: string): string {\n const segments = splitPath(path);\n segments.pop();\n return joinPath(segments);\n}\n\n/**\n * Normalize a path to ensure it starts with '/'\n * \n * @param path - The path to normalize\n * @returns The normalized path\n * \n * @example\n * ```typescript\n * normalizePath('path/to/file'); // '/path/to/file'\n * normalizePath('/path/to/file'); // '/path/to/file'\n * normalizePath('~/path/to/file'); // '/path/to/file' (home dir normalized to root)\n * normalizePath(''); // '/'\n * ```\n */\nexport function normalizePath(path: string): string {\n if (!path || path === '/') {\n return '/';\n }\n \n if (path.startsWith('~/')) {\n return `/${path.slice(2)}`;\n }\n \n return path.startsWith('/') ? path : `/${path}`;\n}\n\n/**\n * Resolve a path to an absolute path, handling relative segments\n * \n * @param path - The path to resolve\n * @returns The resolved absolute path\n * \n * @example\n * ```typescript\n * resolvePath('./config/../data/file.txt'); // '/data/file.txt'\n * resolvePath('/path/to/../file.txt'); // '/path/file.txt'\n * resolvePath('../../file.txt'); // '/file.txt' (truncated to root)\n * resolvePath('~/config/../data/file.txt'); // '/data/file.txt' (home dir normalized to root)\n * ```\n */\nexport function resolvePath(path: string): string {\n // First normalize the path to handle home directory references\n const normalizedPath = normalizePath(path);\n const segments = splitPath(normalizedPath);\n const normalizedSegments: string[] = [];\n\n for (const segment of segments) {\n if (segment === '.' || segment === '') {\n // Skip current directory references and empty segments\n continue;\n }\n else if (segment === '..') {\n if (normalizedSegments.length === 0) {\n // Path escapes root, keep at root level\n continue;\n }\n // Go up one directory\n normalizedSegments.pop();\n }\n else {\n normalizedSegments.push(segment);\n }\n }\n\n return joinPath(normalizedSegments);\n}\n\n/**\n * Get the file extension from a path\n * \n * @param path - The file path\n * @returns The file extension including the dot, or empty string if no extension\n * \n * @example\n * ```typescript\n * extname('/path/to/file.txt'); // '.txt'\n * extname('/path/to/file'); // ''\n * extname('/path/to/file.name.ext'); // '.ext'\n * extname('/path/to/.hidden'); // ''\n * ```\n */\nexport function extname(path: string): string {\n const filename = basename(path);\n const lastDotIndex = filename.lastIndexOf('.');\n \n if (lastDotIndex <= 0 || lastDotIndex === filename.length - 1) {\n return '';\n }\n \n return filename.slice(lastDotIndex);\n}\n\nexport function createBuffer(data: string | Uint8Array | ArrayBuffer, encoding: BufferEncoding = 'utf-8'): Uint8Array {\n if (typeof data === 'string') {\n return encodeString(data, encoding);\n }\n\n return data instanceof Uint8Array ? data : new Uint8Array(data);\n}\n\n\n/**\n * Read raw binary data from a file using a file handle\n *\n * @param fileHandle - The file handle to read from\n * @returns The raw binary data as Uint8Array\n */\nexport async function readFileData(fileHandle: FileSystemFileHandle): Promise<Uint8Array> {\n const handle = await fileHandle.createSyncAccessHandle();\n\n try {\n const size = handle.getSize();\n const buffer = new Uint8Array(size);\n\n handle.read(buffer, { at: 0 });\n\n return buffer;\n }\n finally {\n handle.close();\n }\n}\n\n/**\n * Write data to a file using a file handle\n *\n * @param fileHandle - The file handle to write to\n * @param data - The data to write to the file\n * @param encoding - The encoding to use\n * @param options - Write options (truncate or append)\n */\nexport async function writeFileData(\n fileHandle: FileSystemFileHandle,\n data: string | Uint8Array | ArrayBuffer,\n encoding?: BufferEncoding,\n options: { truncate?: boolean; append?: boolean } = {}\n): Promise<void> {\n let handle: FileSystemSyncAccessHandle | null = null;\n\n try {\n handle = await fileHandle.createSyncAccessHandle();\n\n const buffer = createBuffer(data, encoding);\n const writeOffset = options.append ? handle.getSize() : 0;\n\n handle.write(buffer, { at: writeOffset });\n\n if (options.truncate && !options.append) {\n handle.truncate(buffer.byteLength);\n }\n\n handle.flush();\n }\n catch (error) {\n console.error(error);\n const operation = options.append ? 'append' : 'write';\n\n throw new OPFSError(`Failed to ${ operation } file`, `${ operation.toUpperCase() }_FAILED`);\n }\n finally {\n if (handle) {\n try {\n handle.close();\n }\n catch { /* ~ */ }\n }\n }\n}\n\n/**\n * Calculate file hash using Web Crypto API\n * \n * @param buffer - The file content as File, ArrayBuffer, or Uint8Array\n * @param algorithm - Hash algorithm to use (default: 'SHA-1')\n * @param maxSize - Maximum file size in bytes. If file is larger, throws error (default: 50MB)\n * @returns Promise that resolves to the hash string\n * @throws Error if file size exceeds maxSize\n */\nexport async function calculateFileHash(\n buffer: File | ArrayBuffer | Uint8Array, \n algorithm: string = 'SHA-1',\n maxSize: number = 50 * 1024 * 1024 // 50MB default\n): Promise<string> {\n if (buffer instanceof File) {\n buffer = await buffer.arrayBuffer();\n }\n \n // Check file size before processing\n if (buffer.byteLength > maxSize) {\n throw new Error(`File size ${buffer.byteLength} bytes exceeds maximum allowed size ${maxSize} bytes`);\n }\n\n const bufferSource = new Uint8Array(buffer);\n const hashBuffer = await crypto.subtle.digest(algorithm, bufferSource);\n const hashArray = Array.from(new Uint8Array(hashBuffer));\n\n return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');\n}\n\n/**\n * Convert a Blob to Uint8Array\n * \n * This function converts a Blob object to a Uint8Array for use with file operations.\n * It's useful when working with file uploads or other Blob data sources.\n * \n * @param blob - The Blob to convert\n * @returns Promise that resolves to the Uint8Array representation of the Blob\n * \n * @example\n * ```typescript\n * const fileInput = document.getElementById('file') as HTMLInputElement;\n * const file = fileInput.files?.[0];\n * if (file) {\n * const data = await convertBlobToUint8Array(file);\n * await fs.writeFile('/uploaded-file', data);\n * }\n * ```\n */\nexport async function convertBlobToUint8Array(blob: Blob): Promise<Uint8Array> {\n const arrayBuffer = await blob.arrayBuffer();\n return new Uint8Array(arrayBuffer);\n}\n"],"names":["OPFSError","message","code","path","OPFSNotSupportedError","OPFSNotMountedError","PathError","FileNotFoundError","DirectoryNotFoundError","PermissionError","operation","StorageError","TimeoutError","encodeString","data","encoding","encodeUtf16LE","encodeAscii","encodeLatin1","char","c","b","decodeBuffer","buffer","decodeUtf16LE","str","buf","i","codeUnits","checkOPFSSupport","splitPath","joinPath","segments","basename","dirname","normalizePath","resolvePath","normalizedPath","normalizedSegments","segment","extname","filename","lastDotIndex","createBuffer","readFileData","fileHandle","handle","size","writeFileData","options","writeOffset","error","calculateFileHash","algorithm","maxSize","bufferSource","hashBuffer","convertBlobToUint8Array","blob","arrayBuffer"],"mappings":"aAGO,MAAMA,UAAkB,KAAM,CACjC,YAAYC,EAAiCC,EAA8BC,EAAe,CACtF,MAAMF,CAAO,EAD4B,KAAA,KAAAC,EAA8B,KAAA,KAAAC,EAEvE,KAAK,KAAO,WAChB,CACJ,CAKO,MAAMC,UAA8BJ,CAAU,CACjD,aAAc,CACV,MAAM,wCAAyC,oBAAoB,CACvE,CACJ,CAMO,MAAMK,UAA4BL,CAAU,CAC/C,aAAc,CACV,MAAM,sBAAuB,kBAAkB,CACnD,CACJ,CAKO,MAAMM,UAAkBN,CAAU,CACrC,YAAYC,EAAiBE,EAAc,CACvC,MAAMF,EAAS,eAAgBE,CAAI,CACvC,CACJ,CAKO,MAAMI,UAA0BP,C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