opfs-worker 0.2.2 → 0.2.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/worker-CRHhlrlS.js.map +1 -0
- package/dist/index.cjs +316 -304
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +318 -306
- package/dist/index.js.map +1 -1
- package/dist/raw.cjs +1 -1
- package/dist/raw.cjs.map +1 -1
- package/dist/raw.js +24 -12
- package/dist/raw.js.map +1 -1
- package/dist/worker.d.ts.map +1 -1
- package/package.json +1 -1
- package/dist/assets/worker-CMvl9yOu.js.map +0 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../src/index.ts"],"sourcesContent":["import { wrap, proxy } from 'comlink';\n\nimport WorkerCtor from './worker?worker&inline';\n\nimport type { OPFSWorker, RemoteOPFSWorker, WatchEvent } from './types';\n\nexport * from './types';\nexport * from './utils/errors';\nexport * from './utils/helpers';\nexport * from './utils/encoder';\n\n/**\n * Creates a new file system instance with inline worker\n * @param watchCallback - Optional callback for file change events\n * @param watchOptions - Optional configuration for watching\n * @returns Promise resolving to the file system interface\n */\nexport function createWorker(\n watchCallback?: (event: WatchEvent) => void,\n watchOptions?: { watchInterval?: number }\n): RemoteOPFSWorker {\n const wrapped = wrap<OPFSWorker>(new WorkerCtor());\n \n // Set up watch callback if provided\n if (watchCallback) {\n wrapped.setWatchCallback(proxy(watchCallback), watchOptions);\n }\n \n return wrapped;\n}\n"],"names":["createWorker","watchCallback","watchOptions","wrapped","wrap","WorkerCtor","proxy"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../src/index.ts"],"sourcesContent":["import { wrap, proxy } from 'comlink';\n\nimport WorkerCtor from './worker?worker&inline';\n\nimport type { OPFSWorker, RemoteOPFSWorker, WatchEvent } from './types';\n\nexport * from './types';\nexport * from './utils/errors';\nexport * from './utils/helpers';\nexport * from './utils/encoder';\n\n/**\n * Creates a new file system instance with inline worker\n * @param watchCallback - Optional callback for file change events\n * @param watchOptions - Optional configuration for watching\n * @returns Promise resolving to the file system interface\n */\nexport function createWorker(\n watchCallback?: (event: WatchEvent) => void,\n watchOptions?: { watchInterval?: number }\n): RemoteOPFSWorker {\n const wrapped = wrap<OPFSWorker>(new WorkerCtor());\n \n // Set up watch callback if provided\n if (watchCallback) {\n wrapped.setWatchCallback(proxy(watchCallback), watchOptions);\n }\n \n return wrapped;\n}\n"],"names":["createWorker","watchCallback","watchOptions","wrapped","wrap","WorkerCtor","proxy"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiBO,SAASA,EACZC,GACAC,GACgB;AAChB,QAAMC,IAAUC,EAAiB,IAAIC,GAAY;AAGjD,SAAIJ,KACAE,EAAQ,iBAAiBG,EAAML,CAAa,GAAGC,CAAY,GAGxDC;AACX;"}
|
package/dist/raw.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const d=require("comlink"),a=require("./helpers-hEpet7x7.cjs");class u{root=null;watchCallback=null;watchers=new Map;watchTimer=null;watchInterval=1e3;scanning=!1;mountingPromise=null;constructor(t,e){a.checkOPFSSupport(),t&&(this.watchCallback=t,e?.watchInterval&&(this.watchInterval=e.watchInterval)),this.mount("/")}async mount(t="/"){return this.mountingPromise&&await this.mountingPromise,this.mountingPromise=new Promise(async(e,i)=>{this.root=null;try{const r=await navigator.storage.getDirectory();t==="/"?this.root=r:this.root=await this.getDirectoryHandle(t,!0,r),e(!0)}catch(r){console.error(r),i(new a.OPFSError("Failed to initialize OPFS","INIT_FAILED"))}finally{this.mountingPromise=null}}),this.mountingPromise}setWatchCallback(t,e){this.watchCallback=t,e?.watchInterval&&(this.watchInterval=e.watchInterval)}async ensureMounted(){if(!this.root){if(this.mountingPromise){await this.mountingPromise;return}throw new a.OPFSError("OPFS not mounted","NOT_MOUNTED")}}async getDirectoryHandle(t,e=!1,i=this.root){if(!i)throw new a.OPFSNotMountedError;const r=Array.isArray(t)?t:a.splitPath(t);let s=i;for(const o of r)s=await s.getDirectoryHandle(o,{create:e});return s}async getFileHandle(t,e=!1,i=this.root){if(!i)throw new a.OPFSNotMountedError;const r=a.splitPath(t);if(r.length===0)throw new a.PathError("Path must not be empty",Array.isArray(t)?t.join("/"):t);const s=r.pop();return(await this.getDirectoryHandle(r,e,i)).getFileHandle(s,{create:e})}async index(t){const e=new Map,i=async r=>{const s=await this.readdir(r,{withFileTypes:!0});for(const o of s){const n=`${r==="/"?"":r}/${o.name}`;try{const c=await this.stat(n,t);e.set(n,c),c.isDirectory&&await i(n)}catch(c){console.warn(`Skipping broken entry: ${n}`,c)}}};return e.set("/",{kind:"directory",size:0,mtime:new Date(0).toISOString(),ctime:new Date(0).toISOString(),isFile:!1,isDirectory:!0}),await i("/"),e}async readFile(t,e="utf-8"){await this.ensureMounted();try{const i=await this.getFileHandle(t,!1),r=await a.readFileData(i);return e==="binary"?r:a.decodeBuffer(r,e)}catch(i){throw console.error(i),new a.FileNotFoundError(t)}}async writeFile(t,e,i){await this.ensureMounted();const r=await this.getFileHandle(t,!0);await a.writeFileData(r,e,i,{truncate:!0})}async appendFile(t,e,i){await this.ensureMounted();const r=await this.getFileHandle(t,!0);await a.writeFileData(r,e,i,{append:!0})}async mkdir(t,e){if(await this.ensureMounted(),!this.root)throw new a.OPFSNotMountedError;const i=e?.recursive??!1,r=a.splitPath(t);let s=this.root;for(let o=0;o<r.length;o++){const n=r[o];try{s=await s.getDirectoryHandle(n,{create:i||o===r.length-1})}catch(c){throw c.name==="NotFoundError"?new a.OPFSError(`Parent directory does not exist: ${a.joinPath(r.slice(0,o+1))}`,"ENOENT"):c.name==="TypeMismatchError"?new a.OPFSError(`Path segment is not a directory: ${n}`,"ENOTDIR"):new a.OPFSError("Failed to create directory","MKDIR_FAILED")}}}async stat(t,e){await this.ensureMounted();const i=a.basename(t),r=await this.getDirectoryHandle(a.dirname(t),!1),s=e?.includeHash??!1,o=e?.hashAlgorithm??"SHA-1";try{const c=await(await r.getFileHandle(i,{create:!1})).getFile(),l={kind:"file",size:c.size,mtime:new Date(c.lastModified).toISOString(),ctime:new Date(c.lastModified).toISOString(),isFile:!0,isDirectory:!1};if(s)try{const h=new Uint8Array(await c.arrayBuffer()),w=await a.calculateFileHash(h,o);l.hash=w}catch(h){console.warn(`Failed to calculate hash for ${t}:`,h)}return l}catch(n){if(n.name!=="TypeMismatchError"&&n.name!=="NotFoundError")throw new a.OPFSError("Failed to stat (file)","STAT_FAILED")}try{return await r.getDirectoryHandle(i,{create:!1}),{kind:"directory",size:0,mtime:new Date(0).toISOString(),ctime:new Date(0).toISOString(),isFile:!1,isDirectory:!0}}catch(n){throw n.name==="NotFoundError"?new a.OPFSError(`No such file or directory: ${t}`,"ENOENT"):new a.OPFSError("Failed to stat (directory)","STAT_FAILED")}}async readdir(t,e){await this.ensureMounted();const i=e?.withFileTypes??!1,r=await this.getDirectoryHandle(t,!1);if(i){const s=[];for await(const[o,n]of r.entries()){const c=n.kind==="file";s.push({name:o,kind:n.kind,isFile:c,isDirectory:!c})}return s}else{const s=[];for await(const[o]of r.entries())s.push(o);return s}}async exists(t){await this.ensureMounted();const e=a.basename(t);let i=null;try{i=await this.getDirectoryHandle(a.dirname(t),!1)}catch(r){throw(r.name==="NotFoundError"||r.name==="TypeMismatchError")&&(i=null),r}if(!i||!e)return!1;try{return await i.getFileHandle(e,{create:!1}),!0}catch(r){if(r.name!=="NotFoundError"&&r.name!=="TypeMismatchError")throw r}try{return await i.getDirectoryHandle(e,{create:!1}),!0}catch(r){if(r.name!=="NotFoundError"&&r.name!=="TypeMismatchError")throw r}return!1}async clear(t="/"){await this.ensureMounted();try{const e=await this.readdir(t,{withFileTypes:!0});for(const i of e){const r=`${t==="/"?"":t}/${i.name}`;await this.remove(r,{recursive:!0})}}catch(e){throw e instanceof a.OPFSError?e:new a.OPFSError(`Failed to clear directory: ${t}`,"CLEAR_FAILED")}}async remove(t,e){await this.ensureMounted();const i=e?.recursive??!1,r=e?.force??!1,s=a.basename(t);if(!s)throw new a.PathError("Invalid path",t);const o=await this.getDirectoryHandle(a.dirname(t),!1);try{await o.removeEntry(s,{recursive:i})}catch(n){if(n.name==="NotFoundError"){if(!r)throw new a.OPFSError(`No such file or directory: ${t}`,"ENOENT")}else throw n.name==="InvalidModificationError"?new a.OPFSError(`Directory not empty: ${t}. Use recursive option to force removal.`,"ENOTEMPTY"):n.name==="TypeMismatchError"&&!i?new a.OPFSError(`Cannot remove directory without recursive option: ${t}`,"EISDIR"):new a.OPFSError(`Failed to remove path: ${t}`,"RM_FAILED")}}async realpath(t){await this.ensureMounted();try{const e=a.resolvePath(t);if(!await this.exists(e))throw new a.FileNotFoundError(e);return e}catch(e){throw e instanceof a.OPFSError?e:new a.OPFSError(`Failed to resolve path: ${t}`,"REALPATH_FAILED")}}async rename(t,e){await this.ensureMounted();try{if(!await this.exists(t))throw new a.FileNotFoundError(t);await this.copy(t,e,{recursive:!0}),await this.remove(t,{recursive:!0})}catch(i){throw i instanceof a.OPFSError?i:new a.OPFSError(`Failed to rename from ${t} to ${e}`,"RENAME_FAILED")}}async copy(t,e,i){await this.ensureMounted();try{const r=i?.recursive??!1,s=i?.force??!0;if(!await this.exists(t))throw new a.OPFSError(`Source does not exist: ${t}`,"ENOENT");if(await this.exists(e)&&!s)throw new a.OPFSError(`Destination already exists: ${e}`,"EEXIST");if((await this.stat(t)).isFile){const l=await this.readFile(t,"binary");await this.writeFile(e,l)}else{if(!r)throw new a.OPFSError(`Cannot copy directory without recursive option: ${t}`,"EISDIR");await this.mkdir(e,{recursive:!0});const l=await this.readdir(t,{withFileTypes:!0});for(const h of l){const w=`${t}/${h.name}`,f=`${e}/${h.name}`;await this.copy(w,f,{recursive:!0,force:s})}}}catch(r){throw r instanceof a.OPFSError?r:new a.OPFSError(`Failed to copy from ${t} to ${e}`,"CP_FAILED")}}async watch(t){await this.ensureMounted();const e=a.normalizePath(t),i=await this.buildSnapshot(e);this.watchers.set(e,i),this.watchTimer||(this.watchTimer=setInterval(()=>{this.scanWatches()},this.watchInterval))}unwatch(t){const e=a.normalizePath(t);this.watchers.delete(e),this.watchers.size===0&&this.watchTimer&&(clearInterval(this.watchTimer),this.watchTimer=null)}async buildSnapshot(t){const e=new Map,i=async r=>{const s=await this.stat(r);if(e.set(r,s),s.isDirectory){const o=await this.readdir(r,{withFileTypes:!0});for(const n of o){const c=`${r==="/"?"":r}/${n.name}`;await i(c)}}};return await i(t),e}async scanWatches(){if(!this.scanning){this.scanning=!0;try{await Promise.all([...this.watchers.entries()].map(async([t,e])=>{let i;try{i=await this.buildSnapshot(t)}catch{i=new Map}const r=[];for(const[s,o]of i){const n=e.get(s);n?(n.mtime!==o.mtime||n.size!==o.size)&&r.push({path:s,type:"change"}):r.push({path:s,type:"create"})}for(const s of e.keys())i.has(s)||r.push({path:s,type:"delete"});if(r.length&&this.watchCallback)for(const s of r)this.watchCallback(s);this.watchers.set(t,i)}))}finally{this.scanning=!1}}}async sync(t,e){await this.ensureMounted();try{(e?.cleanBefore??!1)&&await this.clear("/");for(const[r,s]of t){const o=a.normalizePath(r);let n;s instanceof Blob?n=await a.convertBlobToUint8Array(s):n=s,await this.writeFile(o,n)}}catch(i){throw i instanceof a.OPFSError?i:new a.OPFSError("Failed to sync file system","SYNC_FAILED")}}}typeof self<"u"&&self.constructor.name==="DedicatedWorkerGlobalScope"&&d.expose(new u);exports.OPFSWorker=u;
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const d=require("comlink"),a=require("./helpers-hEpet7x7.cjs");class u{root=null;watchCallback=null;watchers=new Map;watchTimer=null;watchInterval=1e3;scanning=!1;mountingPromise=null;constructor(t,e){a.checkOPFSSupport(),t&&(this.watchCallback=t,e?.watchInterval&&(this.watchInterval=e.watchInterval)),this.mount("/")}async mount(t="/"){return this.mountingPromise&&await this.mountingPromise,this.mountingPromise=new Promise(async(e,i)=>{this.root=null;try{const r=await navigator.storage.getDirectory();t==="/"?this.root=r:this.root=await this.getDirectoryHandle(t,!0,r),e(!0)}catch(r){console.error(r),i(new a.OPFSError("Failed to initialize OPFS","INIT_FAILED"))}finally{this.mountingPromise=null}}),this.mountingPromise}setWatchCallback(t,e){this.watchCallback=t,e?.watchInterval&&(this.watchInterval=e.watchInterval)}async ensureMounted(){if(!this.root){if(this.mountingPromise){await this.mountingPromise;return}throw new a.OPFSError("OPFS not mounted","NOT_MOUNTED")}}async getDirectoryHandle(t,e=!1,i=this.root){if(!i)throw new a.OPFSNotMountedError;const r=Array.isArray(t)?t:a.splitPath(t);let s=i;for(const o of r)s=await s.getDirectoryHandle(o,{create:e});return s}async getFileHandle(t,e=!1,i=this.root){if(!i)throw new a.OPFSNotMountedError;const r=a.splitPath(t);if(r.length===0)throw new a.PathError("Path must not be empty",Array.isArray(t)?t.join("/"):t);const s=r.pop();return(await this.getDirectoryHandle(r,e,i)).getFileHandle(s,{create:e})}async index(t){const e=new Map,i=async r=>{const s=await this.readdir(r,{withFileTypes:!0});for(const o of s){const n=`${r==="/"?"":r}/${o.name}`;try{const c=await this.stat(n,t);e.set(n,c),c.isDirectory&&await i(n)}catch(c){console.warn(`Skipping broken entry: ${n}`,c)}}};return e.set("/",{kind:"directory",size:0,mtime:new Date(0).toISOString(),ctime:new Date(0).toISOString(),isFile:!1,isDirectory:!0}),await i("/"),e}async readFile(t,e="utf-8"){await this.ensureMounted();try{const i=await this.getFileHandle(t,!1),r=await a.readFileData(i);return e==="binary"?r:a.decodeBuffer(r,e)}catch(i){throw console.error(i),new a.FileNotFoundError(t)}}async writeFile(t,e,i){await this.ensureMounted();const r=await this.getFileHandle(t,!0);await a.writeFileData(r,e,i,{truncate:!0})}async appendFile(t,e,i){await this.ensureMounted();const r=await this.getFileHandle(t,!0);await a.writeFileData(r,e,i,{append:!0})}async mkdir(t,e){if(await this.ensureMounted(),!this.root)throw new a.OPFSNotMountedError;const i=e?.recursive??!1,r=a.splitPath(t);let s=this.root;for(let o=0;o<r.length;o++){const n=r[o];try{s=await s.getDirectoryHandle(n,{create:i||o===r.length-1})}catch(c){throw c.name==="NotFoundError"?new a.OPFSError(`Parent directory does not exist: ${a.joinPath(r.slice(0,o+1))}`,"ENOENT"):c.name==="TypeMismatchError"?new a.OPFSError(`Path segment is not a directory: ${n}`,"ENOTDIR"):new a.OPFSError("Failed to create directory","MKDIR_FAILED")}}}async stat(t,e){if(await this.ensureMounted(),t==="/")return{kind:"directory",size:0,mtime:new Date(0).toISOString(),ctime:new Date(0).toISOString(),isFile:!1,isDirectory:!0};const i=a.basename(t),r=await this.getDirectoryHandle(a.dirname(t),!1),s=e?.includeHash??!1,o=e?.hashAlgorithm??"SHA-1";try{const c=await(await r.getFileHandle(i,{create:!1})).getFile(),l={kind:"file",size:c.size,mtime:new Date(c.lastModified).toISOString(),ctime:new Date(c.lastModified).toISOString(),isFile:!0,isDirectory:!1};if(s)try{const h=new Uint8Array(await c.arrayBuffer()),w=await a.calculateFileHash(h,o);l.hash=w}catch(h){console.warn(`Failed to calculate hash for ${t}:`,h)}return l}catch(n){if(n.name!=="TypeMismatchError"&&n.name!=="NotFoundError")throw new a.OPFSError("Failed to stat (file)","STAT_FAILED")}try{return await r.getDirectoryHandle(i,{create:!1}),{kind:"directory",size:0,mtime:new Date(0).toISOString(),ctime:new Date(0).toISOString(),isFile:!1,isDirectory:!0}}catch(n){throw n.name==="NotFoundError"?new a.OPFSError(`No such file or directory: ${t}`,"ENOENT"):new a.OPFSError("Failed to stat (directory)","STAT_FAILED")}}async readdir(t,e){await this.ensureMounted();const i=e?.withFileTypes??!1,r=await this.getDirectoryHandle(t,!1);if(i){const s=[];for await(const[o,n]of r.entries()){const c=n.kind==="file";s.push({name:o,kind:n.kind,isFile:c,isDirectory:!c})}return s}else{const s=[];for await(const[o]of r.entries())s.push(o);return s}}async exists(t){if(await this.ensureMounted(),t==="/")return!0;const e=a.basename(t);let i=null;try{i=await this.getDirectoryHandle(a.dirname(t),!1)}catch(r){throw(r.name==="NotFoundError"||r.name==="TypeMismatchError")&&(i=null),r}if(!i||!e)return!1;try{return await i.getFileHandle(e,{create:!1}),!0}catch(r){if(r.name!=="NotFoundError"&&r.name!=="TypeMismatchError")throw r}try{return await i.getDirectoryHandle(e,{create:!1}),!0}catch(r){if(r.name!=="NotFoundError"&&r.name!=="TypeMismatchError")throw r}return!1}async clear(t="/"){await this.ensureMounted();try{const e=await this.readdir(t,{withFileTypes:!0});for(const i of e){const r=`${t==="/"?"":t}/${i.name}`;await this.remove(r,{recursive:!0})}}catch(e){throw e instanceof a.OPFSError?e:new a.OPFSError(`Failed to clear directory: ${t}`,"CLEAR_FAILED")}}async remove(t,e){await this.ensureMounted();const i=e?.recursive??!1,r=e?.force??!1;if(t==="/")throw new a.OPFSError("Cannot remove root directory","EROOT");const s=a.basename(t);if(!s)throw new a.PathError("Invalid path",t);const o=await this.getDirectoryHandle(a.dirname(t),!1);try{await o.removeEntry(s,{recursive:i})}catch(n){if(n.name==="NotFoundError"){if(!r)throw new a.OPFSError(`No such file or directory: ${t}`,"ENOENT")}else throw n.name==="InvalidModificationError"?new a.OPFSError(`Directory not empty: ${t}. Use recursive option to force removal.`,"ENOTEMPTY"):n.name==="TypeMismatchError"&&!i?new a.OPFSError(`Cannot remove directory without recursive option: ${t}`,"EISDIR"):new a.OPFSError(`Failed to remove path: ${t}`,"RM_FAILED")}}async realpath(t){await this.ensureMounted();try{const e=a.resolvePath(t);if(!await this.exists(e))throw new a.FileNotFoundError(e);return e}catch(e){throw e instanceof a.OPFSError?e:new a.OPFSError(`Failed to resolve path: ${t}`,"REALPATH_FAILED")}}async rename(t,e){await this.ensureMounted();try{if(!await this.exists(t))throw new a.FileNotFoundError(t);await this.copy(t,e,{recursive:!0}),await this.remove(t,{recursive:!0})}catch(i){throw i instanceof a.OPFSError?i:new a.OPFSError(`Failed to rename from ${t} to ${e}`,"RENAME_FAILED")}}async copy(t,e,i){await this.ensureMounted();try{const r=i?.recursive??!1,s=i?.force??!0;if(!await this.exists(t))throw new a.OPFSError(`Source does not exist: ${t}`,"ENOENT");if(await this.exists(e)&&!s)throw new a.OPFSError(`Destination already exists: ${e}`,"EEXIST");if((await this.stat(t)).isFile){const l=await this.readFile(t,"binary");await this.writeFile(e,l)}else{if(!r)throw new a.OPFSError(`Cannot copy directory without recursive option: ${t}`,"EISDIR");await this.mkdir(e,{recursive:!0});const l=await this.readdir(t,{withFileTypes:!0});for(const h of l){const w=`${t}/${h.name}`,f=`${e}/${h.name}`;await this.copy(w,f,{recursive:!0,force:s})}}}catch(r){throw r instanceof a.OPFSError?r:new a.OPFSError(`Failed to copy from ${t} to ${e}`,"CP_FAILED")}}async watch(t){await this.ensureMounted();const e=a.normalizePath(t),i=await this.buildSnapshot(e);this.watchers.set(e,i),this.watchTimer||(this.watchTimer=setInterval(()=>{this.scanWatches()},this.watchInterval))}unwatch(t){const e=a.normalizePath(t);this.watchers.delete(e),this.watchers.size===0&&this.watchTimer&&(clearInterval(this.watchTimer),this.watchTimer=null)}async buildSnapshot(t){const e=new Map,i=async r=>{const s=await this.stat(r);if(e.set(r,s),s.isDirectory){const o=await this.readdir(r,{withFileTypes:!0});for(const n of o){const c=`${r==="/"?"":r}/${n.name}`;await i(c)}}};return await i(t),e}async scanWatches(){if(!this.scanning){this.scanning=!0;try{await Promise.all([...this.watchers.entries()].map(async([t,e])=>{let i;try{i=await this.buildSnapshot(t)}catch{i=new Map}const r=[];for(const[s,o]of i){const n=e.get(s);n?(n.mtime!==o.mtime||n.size!==o.size)&&r.push({path:s,type:"change"}):r.push({path:s,type:"create"})}for(const s of e.keys())i.has(s)||r.push({path:s,type:"delete"});if(r.length&&this.watchCallback)for(const s of r)this.watchCallback(s);this.watchers.set(t,i)}))}finally{this.scanning=!1}}}async sync(t,e){await this.ensureMounted();try{(e?.cleanBefore??!1)&&await this.clear("/");for(const[r,s]of t){const o=a.normalizePath(r);let n;s instanceof Blob?n=await a.convertBlobToUint8Array(s):n=s,await this.writeFile(o,n)}}catch(i){throw i instanceof a.OPFSError?i:new a.OPFSError("Failed to sync file system","SYNC_FAILED")}}}typeof self<"u"&&self.constructor.name==="DedicatedWorkerGlobalScope"&&d.expose(new u);exports.OPFSWorker=u;
|
|
2
2
|
//# sourceMappingURL=raw.cjs.map
|
package/dist/raw.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"raw.cjs","sources":["../src/worker.ts"],"sourcesContent":["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 } 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 /** Watch event callback */\n private watchCallback: ((event: WatchEvent) => void) | 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 /** Polling interval in milliseconds */\n private watchInterval = 1000;\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 /**\n * Creates a new OPFSFileSystem instance\n * \n * @param watchCallback - Optional callback for file change events\n * @param watchOptions - Optional configuration for watching\n * @throws {OPFSError} If OPFS is not supported in the current browser\n */\n constructor(\n watchCallback?: (event: WatchEvent) => void,\n watchOptions?: { watchInterval?: number }\n ) {\n checkOPFSSupport();\n \n if (watchCallback) {\n this.watchCallback = watchCallback;\n if (watchOptions?.watchInterval) {\n this.watchInterval = watchOptions.watchInterval;\n }\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 * Set the watch callback for file change events\n * \n * @param callback - The callback function to invoke when files change\n * @param options - Optional configuration for watching\n */\n setWatchCallback(callback: (event: WatchEvent) => void, options?: { watchInterval?: number }): void {\n this.watchCallback = callback;\n\n if (options?.watchInterval) {\n this.watchInterval = options.watchInterval;\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 * Recursively list all files and directories with their stats\n * \n * Traverses the entire file system starting from the root and returns\n * a Map containing all paths and their corresponding file statistics.\n * \n * @param options - Options for indexing\n * @param options.includeHash - Whether to calculate file hash (default: false)\n * @param options.hashAlgorithm - Hash algorithm to use (default: 'SHA-1', fastest)\n * @returns Promise that resolves to a Map of path => FileStat\n * @throws {OPFSError} If the indexing operation fails\n * \n * @example\n * ```typescript\n * // Basic index without hash\n * const index = await fs.index();\n * \n * // Index with file hash\n * const indexWithHash = await fs.index({ \n * includeHash: true,\n * hashAlgorithm: 'SHA-1'\n * });\n * \n * // Iterate through all files and directories\n * for (const [path, stat] of index) {\n * console.log(`${path}: ${stat.isFile ? 'file' : 'directory'} (${stat.size} bytes)`);\n * if (stat.hash) console.log(` Hash: ${stat.hash}`);\n * }\n * \n * // Get specific file stats\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(options?: { includeHash?: boolean; hashAlgorithm?: 'SHA-1' | 'SHA-256' | 'SHA-384' | 'SHA-512' }): 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, { withFileTypes: true });\n\n for (const item of items) {\n const fullPath = `${ dirPath === '/' ? '' : dirPath }/${ item.name }`;\n\n try {\n const stat = await this.stat(fullPath, options);\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 }\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 }\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 }\n\n /**\n * Get file or directory stats\n * \n * Retrieves metadata about a file or directory, including size, modification time,\n * type information, and optionally file hashes.\n * \n * @param path - The path to the file or directory\n * @param options - Options for stat operation\n * @param options.includeHash - Whether to calculate file hash (default: false, only for files)\n * @param options.hashAlgorithm - Hash algorithm to use (default: 'SHA-1', fastest)\n * @returns Promise that resolves to file/directory statistics\n * @throws {OPFSError} If the file or directory does not exist or cannot be accessed\n * \n * @example\n * ```typescript\n * // Basic stats\n * const stats = await fs.stat('/config/settings.json');\n * console.log(`File size: ${stats.size} bytes`);\n * console.log(`Is file: ${stats.isFile}`);\n * console.log(`Modified: ${stats.mtime}`);\n * \n * // Stats with hash (SHA-1 is fastest)\n * const statsWithHash = await fs.stat('/config/settings.json', { \n * includeHash: true,\n * hashAlgorithm: 'SHA-1'\n * });\n * console.log(`Hash: ${statsWithHash.hash}`);\n * ```\n */\n async stat(path: string, options?: { includeHash?: boolean; hashAlgorithm?: 'SHA-1' | 'SHA-256' | 'SHA-384' | 'SHA-512' }): Promise<FileStat> {\n await this.ensureMounted();\n \n const name = basename(path);\n const parentDir = await this.getDirectoryHandle(dirname(path), false);\n const includeHash = options?.includeHash ?? false;\n const hashAlgorithm = options?.hashAlgorithm ?? 'SHA-1';\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) {\n try {\n const buffer = new Uint8Array(await file.arrayBuffer());\n const hash = await calculateFileHash(buffer, hashAlgorithm);\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 * @param options - Options for the readdir operation\n * @param options.withFileTypes - Whether to return detailed file information (default: false)\n * @returns Promise that resolves to an array of file/directory names or detailed information\n * @throws {OPFSError} If the directory does not exist or cannot be accessed\n * \n * @example\n * ```typescript\n * // Get simple list of names\n * const files = await fs.readdir('/users/john/documents');\n * console.log('Files:', files); // ['readme.txt', 'config.json', 'images']\n * \n * // Get detailed information\n * const detailed = await fs.readdir('/users/john/documents', { withFileTypes: true });\n * detailed.forEach(item => {\n * console.log(`${item.name} - ${item.isFile ? 'file' : 'directory'}`);\n * });\n * ```\n */\n async readdir(path: string): Promise<string[]>;\n async readdir(path: string, options: { withFileTypes: true }): Promise<DirentData[]>;\n async readdir(path: string, options: { withFileTypes: false }): Promise<string[]>;\n async readdir(path: string, options?: { withFileTypes?: boolean }): Promise<string[] | DirentData[]> {\n await this.ensureMounted();\n \n const withTypes = options?.withFileTypes ?? false;\n const dir = await this.getDirectoryHandle(path, false);\n\n if (withTypes) {\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 else {\n const results: string[] = [];\n\n for await (const [name] of (dir as any).entries()) {\n results.push(name);\n }\n\n return results;\n }\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 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, { withFileTypes: true });\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 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 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\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 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, { withFileTypes: true });\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 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 this.watchers.set(normalizedPath, snapshot);\n\n if (!this.watchTimer) {\n this.watchTimer = setInterval(() => {\n void this.scanWatches();\n }, this.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 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, { withFileTypes: true });\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 {\n next = new Map();\n }\n\n const events: WatchEvent[] = [];\n\n for (const [p, stat] of next) {\n const old = prev.get(p);\n if (!old) {\n events.push({ path: p, type: 'create' });\n }\n else if (old.mtime !== stat.mtime || old.size !== stat.size) {\n events.push({ path: p, type: 'change' });\n }\n }\n\n for (const p of prev.keys()) {\n if (!next.has(p)) {\n events.push({ path: p, type: 'delete' });\n }\n }\n\n if (events.length && this.watchCallback) {\n for (const event of events) {\n this.watchCallback(event);\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 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}\n"],"names":["OPFSWorker","watchCallback","watchOptions","checkOPFSSupport","root","resolve","reject","rootDir","error","OPFSError","callback","options","path","create","from","OPFSNotMountedError","segments","splitPath","current","segment","PathError","fileName","result","walk","dirPath","items","item","fullPath","stat","err","encoding","fileHandle","buffer","readFileData","decodeBuffer","FileNotFoundError","data","writeFileData","recursive","i","e","joinPath","name","basename","parentDir","dirname","includeHash","hashAlgorithm","file","baseStat","hash","calculateFileHash","withTypes","dir","results","handle","isFile","itemPath","force","parent","normalizedPath","resolvePath","oldPath","newPath","source","destination","content","sourceItemPath","destItemPath","normalizePath","snapshot","rootPath","entries","entry","child","prev","next","events","p","old","event","fileData","convertBlobToUint8Array","expose"],"mappings":"+IA0CO,MAAMA,CAAW,CAEZ,KAAyC,KAGzC,cAAsD,KAGtD,aAAe,IAGf,WAAoD,KAGpD,cAAgB,IAGhB,SAAW,GAGX,gBAA2C,KASnD,YACIC,EACAC,EACF,CACEC,mBAAA,EAEIF,IACA,KAAK,cAAgBA,EACjBC,GAAc,gBACd,KAAK,cAAgBA,EAAa,gBAIrC,KAAK,MAAM,GAAG,CACvB,CAuBA,MAAM,MAAME,EAAe,IAAuB,CAE9C,OAAI,KAAK,iBACL,MAAM,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,OAAO,IAAInF,CAAY"}
|
|
1
|
+
{"version":3,"file":"raw.cjs","sources":["../src/worker.ts"],"sourcesContent":["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 } 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 /** Watch event callback */\n private watchCallback: ((event: WatchEvent) => void) | 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 /** Polling interval in milliseconds */\n private watchInterval = 1000;\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 /**\n * Creates a new OPFSFileSystem instance\n * \n * @param watchCallback - Optional callback for file change events\n * @param watchOptions - Optional configuration for watching\n * @throws {OPFSError} If OPFS is not supported in the current browser\n */\n constructor(\n watchCallback?: (event: WatchEvent) => void,\n watchOptions?: { watchInterval?: number }\n ) {\n checkOPFSSupport();\n \n if (watchCallback) {\n this.watchCallback = watchCallback;\n if (watchOptions?.watchInterval) {\n this.watchInterval = watchOptions.watchInterval;\n }\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 * Set the watch callback for file change events\n * \n * @param callback - The callback function to invoke when files change\n * @param options - Optional configuration for watching\n */\n setWatchCallback(callback: (event: WatchEvent) => void, options?: { watchInterval?: number }): void {\n this.watchCallback = callback;\n\n if (options?.watchInterval) {\n this.watchInterval = options.watchInterval;\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 * Recursively list all files and directories with their stats\n * \n * Traverses the entire file system starting from the root and returns\n * a Map containing all paths and their corresponding file statistics.\n * \n * @param options - Options for indexing\n * @param options.includeHash - Whether to calculate file hash (default: false)\n * @param options.hashAlgorithm - Hash algorithm to use (default: 'SHA-1', fastest)\n * @returns Promise that resolves to a Map of path => FileStat\n * @throws {OPFSError} If the indexing operation fails\n * \n * @example\n * ```typescript\n * // Basic index without hash\n * const index = await fs.index();\n * \n * // Index with file hash\n * const indexWithHash = await fs.index({ \n * includeHash: true,\n * hashAlgorithm: 'SHA-1'\n * });\n * \n * // Iterate through all files and directories\n * for (const [path, stat] of index) {\n * console.log(`${path}: ${stat.isFile ? 'file' : 'directory'} (${stat.size} bytes)`);\n * if (stat.hash) console.log(` Hash: ${stat.hash}`);\n * }\n * \n * // Get specific file stats\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(options?: { includeHash?: boolean; hashAlgorithm?: 'SHA-1' | 'SHA-256' | 'SHA-384' | 'SHA-512' }): 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, { withFileTypes: true });\n\n for (const item of items) {\n const fullPath = `${ dirPath === '/' ? '' : dirPath }/${ item.name }`;\n\n try {\n const stat = await this.stat(fullPath, options);\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 }\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 }\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 }\n\n /**\n * Get file or directory stats\n * \n * Retrieves metadata about a file or directory, including size, modification time,\n * type information, and optionally file hashes.\n * \n * @param path - The path to the file or directory\n * @param options - Options for stat operation\n * @param options.includeHash - Whether to calculate file hash (default: false, only for files)\n * @param options.hashAlgorithm - Hash algorithm to use (default: 'SHA-1', fastest)\n * @returns Promise that resolves to file/directory statistics\n * @throws {OPFSError} If the file or directory does not exist or cannot be accessed\n * \n * @example\n * ```typescript\n * // Basic stats\n * const stats = await fs.stat('/config/settings.json');\n * console.log(`File size: ${stats.size} bytes`);\n * console.log(`Is file: ${stats.isFile}`);\n * console.log(`Modified: ${stats.mtime}`);\n * \n * // Stats with hash (SHA-1 is fastest)\n * const statsWithHash = await fs.stat('/config/settings.json', { \n * includeHash: true,\n * hashAlgorithm: 'SHA-1'\n * });\n * console.log(`Hash: ${statsWithHash.hash}`);\n * ```\n */\n async stat(path: string, options?: { includeHash?: boolean; hashAlgorithm?: 'SHA-1' | 'SHA-256' | 'SHA-384' | 'SHA-512' }): 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 = options?.includeHash ?? false;\n const hashAlgorithm = options?.hashAlgorithm ?? 'SHA-1';\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) {\n try {\n const buffer = new Uint8Array(await file.arrayBuffer());\n const hash = await calculateFileHash(buffer, hashAlgorithm);\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 * @param options - Options for the readdir operation\n * @param options.withFileTypes - Whether to return detailed file information (default: false)\n * @returns Promise that resolves to an array of file/directory names or detailed information\n * @throws {OPFSError} If the directory does not exist or cannot be accessed\n * \n * @example\n * ```typescript\n * // Get simple list of names\n * const files = await fs.readdir('/users/john/documents');\n * console.log('Files:', files); // ['readme.txt', 'config.json', 'images']\n * \n * // Get detailed information\n * const detailed = await fs.readdir('/users/john/documents', { withFileTypes: true });\n * detailed.forEach(item => {\n * console.log(`${item.name} - ${item.isFile ? 'file' : 'directory'}`);\n * });\n * ```\n */\n async readdir(path: string): Promise<string[]>;\n async readdir(path: string, options: { withFileTypes: true }): Promise<DirentData[]>;\n async readdir(path: string, options: { withFileTypes: false }): Promise<string[]>;\n async readdir(path: string, options?: { withFileTypes?: boolean }): Promise<string[] | DirentData[]> {\n await this.ensureMounted();\n \n const withTypes = options?.withFileTypes ?? false;\n const dir = await this.getDirectoryHandle(path, false);\n\n if (withTypes) {\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 else {\n const results: string[] = [];\n\n for await (const [name] of (dir as any).entries()) {\n results.push(name);\n }\n\n return results;\n }\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, { withFileTypes: true });\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 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\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 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, { withFileTypes: true });\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 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 this.watchers.set(normalizedPath, snapshot);\n\n if (!this.watchTimer) {\n this.watchTimer = setInterval(() => {\n void this.scanWatches();\n }, this.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 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, { withFileTypes: true });\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 {\n next = new Map();\n }\n\n const events: WatchEvent[] = [];\n\n for (const [p, stat] of next) {\n const old = prev.get(p);\n if (!old) {\n events.push({ path: p, type: 'create' });\n }\n else if (old.mtime !== stat.mtime || old.size !== stat.size) {\n events.push({ path: p, type: 'change' });\n }\n }\n\n for (const p of prev.keys()) {\n if (!next.has(p)) {\n events.push({ path: p, type: 'delete' });\n }\n }\n\n if (events.length && this.watchCallback) {\n for (const event of events) {\n this.watchCallback(event);\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 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}\n"],"names":["OPFSWorker","watchCallback","watchOptions","checkOPFSSupport","root","resolve","reject","rootDir","error","OPFSError","callback","options","path","create","from","OPFSNotMountedError","segments","splitPath","current","segment","PathError","fileName","result","walk","dirPath","items","item","fullPath","stat","err","encoding","fileHandle","buffer","readFileData","decodeBuffer","FileNotFoundError","data","writeFileData","recursive","i","e","joinPath","name","basename","parentDir","dirname","includeHash","hashAlgorithm","file","baseStat","hash","calculateFileHash","withTypes","dir","results","handle","isFile","itemPath","force","parent","normalizedPath","resolvePath","oldPath","newPath","source","destination","content","sourceItemPath","destItemPath","normalizePath","snapshot","rootPath","entries","entry","child","prev","next","events","p","old","event","fileData","convertBlobToUint8Array","expose"],"mappings":"+IA0CO,MAAMA,CAAW,CAEZ,KAAyC,KAGzC,cAAsD,KAGtD,aAAe,IAGf,WAAoD,KAGpD,cAAgB,IAGhB,SAAW,GAGX,gBAA2C,KASnD,YACIC,EACAC,EACF,CACEC,mBAAA,EAEIF,IACA,KAAK,cAAgBA,EACjBC,GAAc,gBACd,KAAK,cAAgBA,EAAa,gBAIrC,KAAK,MAAM,GAAG,CACvB,CAuBA,MAAM,MAAME,EAAe,IAAuB,CAE9C,OAAI,KAAK,iBACL,MAAM,KAAK,gBAGf,KAAK,gBAAkB,IAAI,QAAiB,MAAMC,EAASC,IAAW,CAClE,KAAK,KAAO,KAEZ,GAAI,CACA,MAAMC,EAAU,MAAM,UAAU,QAAQ,aA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AiBC,EAAAA,UACXD,EAGJ,IAAIC,EAAAA,UAAU,6BAA8B,aAAa,CACnE,CACJ,CACJ,CAGI,OAAO,KAAS,KAAe,KAAK,YAAY,OAAS,8BAC3D0E,EAAAA,OAAO,IAAInF,CAAY"}
|
package/dist/raw.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { expose as
|
|
2
|
-
import { d as
|
|
1
|
+
import { expose as v } from "comlink";
|
|
2
|
+
import { d as I, O as o, b as f, s as u, P as g, i as p, o as S, F as d, w as E, j as T, e as m, f as y, k as M, r as H, n as F, l as P } from "./helpers-Co-qCBmA.js";
|
|
3
3
|
class $ {
|
|
4
4
|
/** Root directory handle for the file system */
|
|
5
5
|
root = null;
|
|
@@ -23,7 +23,7 @@ class $ {
|
|
|
23
23
|
* @throws {OPFSError} If OPFS is not supported in the current browser
|
|
24
24
|
*/
|
|
25
25
|
constructor(t, e) {
|
|
26
|
-
|
|
26
|
+
I(), t && (this.watchCallback = t, e?.watchInterval && (this.watchInterval = e.watchInterval)), this.mount("/");
|
|
27
27
|
}
|
|
28
28
|
/**
|
|
29
29
|
* Initialize the file system within a given directory
|
|
@@ -137,7 +137,7 @@ class $ {
|
|
|
137
137
|
throw new f();
|
|
138
138
|
const r = u(t);
|
|
139
139
|
if (r.length === 0)
|
|
140
|
-
throw new
|
|
140
|
+
throw new g("Path must not be empty", Array.isArray(t) ? t.join("/") : t);
|
|
141
141
|
const a = r.pop();
|
|
142
142
|
return (await this.getDirectoryHandle(r, e, i)).getFileHandle(a, { create: e });
|
|
143
143
|
}
|
|
@@ -203,7 +203,7 @@ class $ {
|
|
|
203
203
|
async readFile(t, e = "utf-8") {
|
|
204
204
|
await this.ensureMounted();
|
|
205
205
|
try {
|
|
206
|
-
const i = await this.getFileHandle(t, !1), r = await
|
|
206
|
+
const i = await this.getFileHandle(t, !1), r = await p(i);
|
|
207
207
|
return e === "binary" ? r : S(r, e);
|
|
208
208
|
} catch (i) {
|
|
209
209
|
throw console.error(i), new d(t);
|
|
@@ -237,7 +237,7 @@ class $ {
|
|
|
237
237
|
async writeFile(t, e, i) {
|
|
238
238
|
await this.ensureMounted();
|
|
239
239
|
const r = await this.getFileHandle(t, !0);
|
|
240
|
-
await
|
|
240
|
+
await E(r, e, i, { truncate: !0 });
|
|
241
241
|
}
|
|
242
242
|
/**
|
|
243
243
|
* Append data to a file
|
|
@@ -264,7 +264,7 @@ class $ {
|
|
|
264
264
|
async appendFile(t, e, i) {
|
|
265
265
|
await this.ensureMounted();
|
|
266
266
|
const r = await this.getFileHandle(t, !0);
|
|
267
|
-
await
|
|
267
|
+
await E(r, e, i, { append: !0 });
|
|
268
268
|
}
|
|
269
269
|
/**
|
|
270
270
|
* Create a directory
|
|
@@ -334,7 +334,15 @@ class $ {
|
|
|
334
334
|
* ```
|
|
335
335
|
*/
|
|
336
336
|
async stat(t, e) {
|
|
337
|
-
await this.ensureMounted()
|
|
337
|
+
if (await this.ensureMounted(), t === "/")
|
|
338
|
+
return {
|
|
339
|
+
kind: "directory",
|
|
340
|
+
size: 0,
|
|
341
|
+
mtime: (/* @__PURE__ */ new Date(0)).toISOString(),
|
|
342
|
+
ctime: (/* @__PURE__ */ new Date(0)).toISOString(),
|
|
343
|
+
isFile: !1,
|
|
344
|
+
isDirectory: !0
|
|
345
|
+
};
|
|
338
346
|
const i = m(t), r = await this.getDirectoryHandle(y(t), !1), a = e?.includeHash ?? !1, n = e?.hashAlgorithm ?? "SHA-1";
|
|
339
347
|
try {
|
|
340
348
|
const c = await (await r.getFileHandle(i, { create: !1 })).getFile(), l = {
|
|
@@ -407,7 +415,8 @@ class $ {
|
|
|
407
415
|
* ```
|
|
408
416
|
*/
|
|
409
417
|
async exists(t) {
|
|
410
|
-
await this.ensureMounted()
|
|
418
|
+
if (await this.ensureMounted(), t === "/")
|
|
419
|
+
return !0;
|
|
411
420
|
const e = m(t);
|
|
412
421
|
let i = null;
|
|
413
422
|
try {
|
|
@@ -488,9 +497,12 @@ class $ {
|
|
|
488
497
|
*/
|
|
489
498
|
async remove(t, e) {
|
|
490
499
|
await this.ensureMounted();
|
|
491
|
-
const i = e?.recursive ?? !1, r = e?.force ?? !1
|
|
500
|
+
const i = e?.recursive ?? !1, r = e?.force ?? !1;
|
|
501
|
+
if (t === "/")
|
|
502
|
+
throw new o("Cannot remove root directory", "EROOT");
|
|
503
|
+
const a = m(t);
|
|
492
504
|
if (!a)
|
|
493
|
-
throw new
|
|
505
|
+
throw new g("Invalid path", t);
|
|
494
506
|
const n = await this.getDirectoryHandle(y(t), !1);
|
|
495
507
|
try {
|
|
496
508
|
await n.removeEntry(a, { recursive: i });
|
|
@@ -708,7 +720,7 @@ class $ {
|
|
|
708
720
|
}
|
|
709
721
|
}
|
|
710
722
|
}
|
|
711
|
-
typeof self < "u" && self.constructor.name === "DedicatedWorkerGlobalScope" &&
|
|
723
|
+
typeof self < "u" && self.constructor.name === "DedicatedWorkerGlobalScope" && v(new $());
|
|
712
724
|
export {
|
|
713
725
|
$ as OPFSWorker
|
|
714
726
|
};
|