@legit-sdk/core 0.4.4 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/server.js CHANGED
@@ -1,34 +1,18 @@
1
1
  // legit-sdk server bundle (Node.js)
2
2
 
3
- var ze=Object.defineProperty;var Ft=(n,i,e)=>i in n?ze(n,i,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[i]=e;var o=(n,i)=>ze(n,"name",{value:i,configurable:!0});var p=(n,i,e)=>Ft(n,typeof i!="symbol"?i+"":i,e);import*as ge from"path";var he=class he{constructor(i,e){p(this,"entries",[]);p(this,"currentIndex",0);p(this,"closed",!1);p(this,"compositFs");p(this,"dirPath");p(this,"initialized",!1);this.compositFs=i,this.dirPath=e}async initialize(){if(this.initialized)return;let i=new Set;for(let e of[...this.compositFs.subFilesystems].reverse()){let t=await e.readdir(this.dirPath);for(let r of t)i.add(r)}for(let e of Array.from(i)){let t=this.dirPath+"/"+e;await this.compositFs.hiddenFilesFileSystem?.responsible(t)||this.entries.push({name:e,path:t})}this.initialized=!0}async*[Symbol.asyncIterator](){for(await this.initialize();this.currentIndex<this.entries.length&&!this.closed;){let i=this.entries[this.currentIndex++];try{let e=await this.compositFs.stat(i.path);yield{name:i.name,isFile:o(()=>e.isFile(),"isFile"),isDirectory:o(()=>e.isDirectory(),"isDirectory"),isBlockDevice:o(()=>e.isBlockDevice(),"isBlockDevice"),isCharacterDevice:o(()=>e.isCharacterDevice(),"isCharacterDevice"),isSymbolicLink:o(()=>e.isSymbolicLink(),"isSymbolicLink"),isFIFO:o(()=>e.isFIFO(),"isFIFO"),isSocket:o(()=>e.isSocket(),"isSocket")}}catch(e){console.debug(`Failed to stat ${i.path}:`,e)}}}async read(){if(this.closed)throw new Error("Directory handle is closed");if(await this.initialize(),this.currentIndex>=this.entries.length)return null;let i=this.entries[this.currentIndex++];try{let e=await this.compositFs.stat(i.path);return{name:i.name,isFile:o(()=>e.isFile(),"isFile"),isDirectory:o(()=>e.isDirectory(),"isDirectory"),isBlockDevice:o(()=>e.isBlockDevice(),"isBlockDevice"),isCharacterDevice:o(()=>e.isCharacterDevice(),"isCharacterDevice"),isSymbolicLink:o(()=>e.isSymbolicLink(),"isSymbolicLink"),isFIFO:o(()=>e.isFIFO(),"isFIFO"),isSocket:o(()=>e.isSocket(),"isSocket")}}catch{return this.read()}}async close(){this.closed=!0,this.entries=[]}get path(){return this.dirPath}};o(he,"CompositeFsDir");var W=he;var pe=class pe{constructor(i){p(this,"delegate");p(this,"compositeFs");p(this,"_subFsFileDescriptor");p(this,"handleType","file");p(this,"_compositFsFileDescriptor",-1);this.delegate=i.fs,this._subFsFileDescriptor=i.subFsFileDescriptor,this._compositFsFileDescriptor=-1,this.compositeFs=i.compositeFs;let e=this._subFsFileDescriptor}get fsType(){return this.delegate.fileType()}get subFsFileDescriptor(){return this._subFsFileDescriptor}get fd(){return this._compositFsFileDescriptor}realize(i){if(this._compositFsFileDescriptor!==-1)throw new Error("was already realized");this._compositFsFileDescriptor=i}readableWebStream(i){throw new Error("Method not implemented.")}async appendFile(i,e){return await this.compositeFs.logOperationOnFileDescsriptor(this,"appendFile",{data:i,options:e}),await this.delegate.appendFile(this,i,e)}async chmod(i){return await this.compositeFs.logOperationOnFileDescsriptor(this,"chmod",{mode:i}),this.delegate.fchmod(this,i)}async chown(i,e){return await this.compositeFs.logOperationOnFileDescsriptor(this,"chown",{uid:i,gid:e}),this.delegate.fchown(this,i,e)}async close(){return await this.compositeFs.logOperationOnFileDescsriptor(this,"close",{}),this.compositeFs.close(this)}async datasync(){return await this.compositeFs.logOperationOnFileDescsriptor(this,"datasync",{}),this.delegate.dataSync(this)}async read(i,e,t,r){return await this.compositeFs.logOperationOnFileDescsriptor(this,"read",{targetBufferLength:i.length,offset:e,length:t,position:r}),await this.delegate.read(this,i,e,t,r)}async readv(i,e){return await this.compositeFs.logOperationOnFileDescsriptor(this,"readv",{buffers:i,position:e}),this.delegate.readv(this,i,e)}async stat(i){return await this.compositeFs.logOperationOnFileDescsriptor(this,"stat",{options:i}),this.delegate.fstat(this,i)}async truncate(i){return await this.compositeFs.logOperationOnFileDescsriptor(this,"truncate",{len:i}),this.delegate.ftruncate(this,i)}async utimes(i,e){return await this.compositeFs.logOperationOnFileDescsriptor(this,"utimes",{atime:i,mtime:e}),this.delegate.futimes(this,i,e)}async write(i,e,t,r){return await this.compositeFs.logOperationOnFileDescsriptor(this,"write",{buffer:i,offset:e,length:t,position:r}),this.delegate.write(this,i,e,t,r)}async writev(i,e){return await this.compositeFs.logOperationOnFileDescsriptor(this,"writev",{buffers:i,position:e}),this.delegate.writev(this,i,e)}async sync(){return await this.compositeFs.logOperationOnFileDescsriptor(this,"sync",{}),this.delegate.dataSync(this)}};o(pe,"CompositFsFileHandle");var I=pe;import*as je from"path";import{createFsFromVolume as gt,Volume as wt}from"memfs";var ue=class ue{constructor({name:i,parentFs:e,gitRoot:t}){p(this,"compositFs");p(this,"gitRoot");p(this,"name");this.name=i,this.compositFs=e,this.gitRoot=t}toStr(i){return typeof i=="string"?i:Buffer.isBuffer(i)?i.toString():i&&typeof i=="object"&&"fd"in i?`FileHandle(fd=${i.fd})`:String(i)}async open(i,e,t){throw new Error(`open not implemented for: ${this.toStr(i)}`)}async access(i,e){throw new Error(`access not implemented for: ${this.toStr(i)}`)}async stat(i,e){throw new Error(`lstat not implemented for: ${this.toStr(i)}`)}async lstat(i,e){throw new Error(`lstat not implemented for: ${this.toStr(i)}`)}async opendir(i,e){throw new Error(`opendir not implemented for: ${this.toStr(i)}`)}async link(i,e){throw new Error(`link not implemented for: ${this.toStr(i)}`)}async mkdir(i,e){throw new Error(`mkdir not implemented for: ${this.toStr(i)}`)}async readdir(i,e){throw new Error(`readdir not implemented for: ${this.toStr(i)}`)}async readlink(i,...e){throw new Error(`readlink not implemented for: ${this.toStr(i)}`)}async unlink(i){throw new Error(`unlink not implemented for: ${this.toStr(i)}`)}async rename(i,e){throw new Error(`rename not implemented for: ${this.toStr(i)}`)}async rmdir(i,...e){throw new Error(`rmdir not implemented for: ${this.toStr(i)}`)}async symlink(i,e,t){throw new Error(`symlink not implemented for: ${this.toStr(e)}`)}async lookup(i){throw new Error(`lookup not implemented for: ${this.toStr(i)}`)}resolvePath(i){throw new Error(`resolvePath not implemented for fd: ${i}`)}async close(i){this.compositFs.close(i)}async dataSync(i){throw new Error(`dataSync not implemented for: ${i.subFsFileDescriptor}`)}async read(i,e,t,r,s){throw new Error(`read not implemented for: ${i.subFsFileDescriptor}`)}async appendFile(i,e,t){throw new Error(`appendFile not implemented for: ${i.subFsFileDescriptor}`)}async fchmod(i,e){throw new Error(`fchmod not implemented for: ${i.subFsFileDescriptor}`)}async fchown(i,e,t){throw new Error(`fchown not implemented for: ${i.subFsFileDescriptor}`)}async ftruncate(i,e){throw new Error(`ftruncate not implemented for: ${i.subFsFileDescriptor}`)}async fstat(i,e){throw new Error(`fstat not implemented for: ${i.subFsFileDescriptor}`)}async futimes(i,e,t){throw new Error(`futimes not implemented for: ${i.subFsFileDescriptor}`)}async write(i,e,t,r,s){throw new Error(`write not implemented for: ${i.subFsFileDescriptor}`)}async writev(i,e,t){throw new Error(`writev not implemented for: ${i.subFsFileDescriptor}`)}async readv(i,e,t){throw new Error(`readv not implemented for: ${i.subFsFileDescriptor}`)}async readFile(i,e){throw new Error(`readFile not implemented for: ${this.toStr(i)}`)}async writeFile(i,e,t){throw new Error(`writeFile not implemented for: ${this.toStr(i)}`)}};o(ue,"BaseCompositeSubFs");var L=ue;var Fe=class Fe extends L{constructor({name:e,parentFs:t,gitRoot:r,passThroughFs:s}){super({name:e,parentFs:t,gitRoot:r});p(this,"openFh",new Map);p(this,"memFs",gt(new wt));p(this,"targetFs");this.compositFs=t,this.gitRoot=r,this.targetFs=s}async responsible(e){return!0}fileType(){return 4}async open(e,t,r){let s=je.dirname(e),a=await this.targetFs.promises.open(e,t,r);return this.openFh.set(a.fd,a),new I({fs:this,compositeFs:this.compositFs,subFsFileDescriptor:a.fd,parentFsFileDescriptors:[]})}async access(e,t){return await this.targetFs.promises.access(e,t)}async stat(e,...t){return this.targetFs.promises.stat(e,{bigint:!1})}async lstat(e,...t){return this.targetFs.promises.lstat(e,{bigint:!1})}async opendir(e,t){let r=await this.targetFs.promises.opendir(e,t);return new W(this.compositFs,e.toString())}async link(e,t){return await this.targetFs.promises.link(e,t)}async mkdir(e,t){await this.targetFs.promises.mkdir(e,t)}async readdir(e,...t){return this.targetFs.promises.readdir(e,...t)}async readlink(e,...t){throw new Error("not implemented")}async unlink(e){return await this.targetFs.promises.unlink(e)}async rename(e,t){return await this.targetFs.promises.rename(e,t)}async rmdir(e,t){return await this.targetFs.promises.rmdir(e,t)}async symlink(e,t,r){return await this.targetFs.promises.symlink(e,t,r)}async lookup(e){throw new Error(`lookup is not implemented for: ${this.toStr(e)}`)}async close(e){let t=this.openFh.get(e.subFsFileDescriptor);t&&(this.openFh.delete(e.subFsFileDescriptor),await t.close())}async dataSync(e){let t=this.openFh.get(e.subFsFileDescriptor);if(t)return await t.sync()}async read(e,t,r,s,a){let l=this.openFh.get(e.subFsFileDescriptor);if(l)return await l.read(t,r,s,a);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async fchmod(e,t){let r=this.openFh.get(e.subFsFileDescriptor);if(r)return await r.chmod(t)}async fchown(e,t,r){let s=this.openFh.get(e.subFsFileDescriptor);if(s)return await s.chown(t,r)}async write(e,t,r,s,a){let l=this.openFh.get(e.subFsFileDescriptor);if(l)return await l.write(t,r,s,a);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async ftruncate(e,t){let r=this.openFh.get(e.subFsFileDescriptor);if(r)return await r.truncate(t)}resolvePath(e){throw new Error(`resolvePath is not implemented: resolvePath(${e})`)}async fstat(e,t){let r=this.openFh.get(e.subFsFileDescriptor);if(r)return await r.stat(t);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async futimes(e,t,r){let s=this.openFh.get(e.subFsFileDescriptor);if(s)return await s.utimes(t,r)}async writev(e,t,r){let s=this.openFh.get(e.subFsFileDescriptor);if(s)return await s.writev(t,r??void 0);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async readv(e,t,r){let s=this.openFh.get(e.subFsFileDescriptor);if(s)return await s.readv(t,r??void 0);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async readFile(e,t){return this.targetFs.promises.readFile(e,t)}async writeFile(e,t,r){return this.targetFs.promises.writeFile(e,t,r)}};o(Fe,"PassThroughToAsyncFsSubFs");var X=Fe;var we=class we{constructor({name:i,storageFs:e,gitRoot:t,defaultBranch:r="main"}){p(this,"promises");p(this,"gitRoot");p(this,"ephemeralFilesFileSystem");p(this,"hiddenFilesFileSystem");p(this,"passThroughFileSystem");p(this,"subFilesystems",[]);p(this,"parentFs");p(this,"name");p(this,"defaultBranch");p(this,"gitCache");p(this,"pathToFileDescriptors",new Map);p(this,"openFileHandles",new Map);p(this,"logOperation");this.name=i,this.gitRoot=t,this.defaultBranch=r,this.promises={access:this.access.bind(this),opendir:this.opendir.bind(this),mkdir:this.mkdir.bind(this),readdir:this.readdir.bind(this),open:this.open.bind(this),stat:this.stat.bind(this),lstat:this.lstat.bind(this),link:this.link.bind(this),readlink:this.readlink.bind(this),unlink:this.unlink.bind(this),rename:this.rename.bind(this),rmdir:this.rmdir.bind(this),symlink:this.symlink.bind(this),readFile:this.readFile.bind(this),writeFile:this.writeFile.bind(this),getFilehandle:this.getFilehandle.bind(this)},this.passThroughFileSystem=new X({name:i+"-passthrough",passThroughFs:e,gitRoot:t,parentFs:this})}getNextFileDescriptor(){let i=Array.from(this.openFileHandles.keys());return i.length===0?1:Math.max(...i)+1}setLoggger(i){this.logOperation=i}async logOperationOnFileDescsriptor(i,e,t){if(!this.logOperation)return;let r=[];for(let[s,a]of this.pathToFileDescriptors.entries())a.includes(i.fd)&&r.push(s);if(r.length!==0)return this.logOperation?.({fsName:i.delegate.name,fd:i,path:r[0],operation:e,operationArgs:t})}getFilehandle(i){return this.openFileHandles.get(i)}setEphemeralFilesSubFs(i){this.ephemeralFilesFileSystem=i}setHiddenFilesSubFs(i){this.hiddenFilesFileSystem=i}addSubFs(i){this.subFilesystems.push(i)}async getResponsibleFs(i){if(!i.toString().startsWith(this.gitRoot)&&this.gitRoot!=="./")throw new Error("tried to access a file ("+i+") outside of the legit folder: "+this.gitRoot);if(!this.hiddenFilesFileSystem)throw new Error(this.name+" intialize hidden fs first!");if(!this.ephemeralFilesFileSystem)throw new Error(this.name+" intialize ephemeral fs first!");if(await this.hiddenFilesFileSystem.responsible(i.toString()))return this.hiddenFilesFileSystem;if(await this.ephemeralFilesFileSystem.responsible(i.toString()))return this.ephemeralFilesFileSystem;for(let e of this.subFilesystems)if(await e.responsible(i.toString()))return e;return this.passThroughFileSystem}async access(i,e){let t=await this.getResponsibleFs(i);return await this.logOperation?.({fsName:t.name,path:i,operation:"access",operationArgs:{mode:e}}),t.access(i,e)}async opendir(i,e){await this.logOperation?.({fsName:this.name,path:i.toString(),operation:"opendir",operationArgs:{options:e}});let t=i.toString();if(!t.startsWith(this.gitRoot))throw new Error("tried to access a directory ("+t+") outside of the legit folder: "+this.gitRoot);return new W(this,t)}async mkdir(i,e){let t=await this.getResponsibleFs(i);return await this.logOperation?.({fsName:t.name,path:i.toString(),operation:"mkdir",operationArgs:{options:e}}),t.mkdir(i,e)}async readdir(i,e){await this.logOperation?.({fsName:this.name,path:i.toString(),operation:"readdir",operationArgs:{options:e}});let t=new Set;for(let r of[...this.subFilesystems].reverse()){let s=await r.readdir(i,e);for(let a of s)await this.ephemeralFilesFileSystem?.responsible((i=="/"?"":i)+"/"+a)||t.add(a)}try{let r=await this.passThroughFileSystem.readdir(i,e);for(let s of r)await this.ephemeralFilesFileSystem?.responsible((i=="/"?"":i)+"/"+s)||t.add(s)}catch(r){if(r.code!=="ENOENT")throw new Error("error reading ephemeral fs: "+r)}try{let r=await this.ephemeralFilesFileSystem.readdir(i,e);for(let s of r)t.add(s)}catch(r){if(r.code!=="ENOENT")throw new Error("error reading ephemeral fs: "+r)}for(let r of t){let s=(i=="/"?"":i)+"/"+r;await this.hiddenFilesFileSystem.responsible(s)&&t.delete(r)}return Array.from(t)}async open(i,e,t){let r=await this.getResponsibleFs(i);await this.logOperation?.({fsName:r.name,path:i,operation:"open",operationArgs:{flags:e,mode:t}});let s=await r.open(i,e,t),a=this.getNextFileDescriptor();return s.realize(a),this.openFileHandles.set(a,s),this.pathToFileDescriptors.get(i)||this.pathToFileDescriptors.set(i,[]),this.pathToFileDescriptors.get(i).push(a),s}async close(i){try{await i.delegate.close(i)}catch(e){throw e}finally{for(let[e,t]of this.pathToFileDescriptors.entries()){let r=t.indexOf(i.fd);if(r!==-1){t.splice(r,1),t.length===0&&this.pathToFileDescriptors.delete(e);break}}this.openFileHandles.delete(i.fd)}}async stat(i,e){let t=i.toString(),r=await this.getResponsibleFs(i);return await this.logOperation?.({fsName:r.name,path:t,operation:"stat",operationArgs:{opts:e}}),r.stat(i)}async lstat(i,e){let t=await this.getResponsibleFs(i);return await this.logOperation?.({fsName:t.name,path:i.toString(),operation:"lstat",operationArgs:{opts:e}}),t.lstat(i,e)}async link(i,e){throw new Error("not implemented")}async readlink(i,e){throw new Error("not implemented")}async unlink(i){let e=await this.getResponsibleFs(i);return await this.logOperation?.({fsName:e.name,path:i.toString(),operation:"unlink",operationArgs:{}}),e.unlink(i)}async rename(i,e){if(this.hiddenFilesFileSystem){if(await this.hiddenFilesFileSystem.responsible(ge.basename(i.toString())))throw new Error("Renaming of hidden Files is not allowed "+i);if(await this.hiddenFilesFileSystem.responsible(ge.basename(e.toString())))throw new Error("Renaming to hidden Files is not allowed "+e)}let t=await this.getResponsibleFs(i),r=await this.getResponsibleFs(e);if(t===r)return await this.logOperation?.({fsName:t.name,path:i.toString(),operation:"rename",operationArgs:{oldPath:i,newPath:e}}),t.rename(i,e);let s=await t.open(i.toString(),"r");try{let a=await t.fstat(s),l=Buffer.alloc(a.size);await t.read(s,l,0,a.size,0),await t.close(s),await r.writeFile(e.toString(),l,"utf8"),await t.unlink(i)}catch(a){try{await t.close(s)}catch{}throw a}}async rmdir(i,e){let t=await this.getResponsibleFs(i);return await this.logOperation?.({fsName:t.name,path:i.toString(),operation:"rmdir",operationArgs:{dirPath:i,options:e}}),t.rmdir(i,e)}async symlink(i,e,t){throw new Error("not implemented")}async readFile(i,e){await this.logOperation?.({fsName:this.name,path:i.toString(),operation:"readFile",operationArgs:{path:i,options:e}});let t=!0,r;if(typeof i=="number"){t=!1;let s=this.getFilehandle(i);if(!s)throw new Error("Invalid file descriptor");r=s}else if(typeof i=="string")r=await this.open(i,"r");else throw new Error("only filehandle and path are supported atm");try{let a=(await r.stat()).size;if(typeof a=="bigint"){if(a>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("File too large to read into buffer");a=Number(a)}let l=Buffer.alloc(a),{bytesRead:c}=await r.read(l,0,a,0);if(e&&typeof e.encoding=="string")return l.slice(0,c).toString(e.encoding);if(typeof e=="string"){if(e==="utf8"||e==="utf-8")return l.slice(0,c).toString(e);throw new Error("Unsupported encoding: "+e)}return l.slice(0,c)}finally{r&&t&&await r.close()}}async writeFile(i,e,t){await this.logOperation?.({fsName:this.name,path:i.toString(),operation:"writeFile",operationArgs:{data:e,options:t}});let r=typeof i!="number",s,a,l,c="w";if(typeof t=="string"?a=t:t&&typeof t=="object"&&(a=t.encoding,l=t.mode,c=t.flag||"w"),typeof i=="number"){let m=this.getFilehandle(i);if(!m)throw new Error("Invalid file descriptor");s=m}else if(typeof i=="string")s=await this.open(i,c,l);else throw new Error("only filehandle and path are supported atm");try{let m;if(typeof e=="string")m=Buffer.from(e,a||"utf8");else if(e instanceof Buffer)m=e;else if(e instanceof Uint8Array)m=Buffer.from(e);else throw new Error("Invalid data type for writeFile");let d=0;for(;d<m.length;){let{bytesWritten:f}=await s.write(m,d,m.length-d,d);d+=f}}finally{s&&r&&await s.close()}}};o(we,"CompositeFs");var Q=we;import yt from"ignore";var ye=class ye extends L{constructor({name:e,parentFs:t,gitRoot:r,hiddenFiles:s}){super({name:e,parentFs:t,gitRoot:r});p(this,"ig");this.ig=yt(),this.ig.add(s)}async responsible(e){let t=e.replace(/\\/g,"/"),r=t.startsWith("./")?t.slice(2):t;return r=r.startsWith("/")?r.slice(1):r,r===""||r==="."?!1:this.ig.ignores(r)}fileType(){return 255}error(e){return new Error(`Access to hidden file is not allowed: ${this.toStr(e)}`)}async open(e,t,r){throw this.error(e)}async access(e){throw this.error(e)}async stat(e){throw this.error(e)}async lstat(e){throw this.error(e)}async opendir(e){throw this.error(e)}async link(e){throw this.error(e)}async mkdir(e){throw this.error(e)}async readdir(e){throw this.error(e)}async readlink(e){throw this.error(e)}async unlink(e){throw this.error(e)}async rename(e){throw this.error(e)}async rmdir(e){throw this.error(e)}async symlink(e,t){throw this.error(t)}async lookup(e){throw this.error(e)}resolvePath(e){throw new Error(`Access to hidden file is not allowed: resolvePath(${e})`)}async close(e){throw new Error("Access to hidden file is not allowed: close: "+e.subFsFileDescriptor)}async dataSync(e){throw new Error("Access to hidden file is not allowed: dataSync: "+e.subFsFileDescriptor)}async read(e,t,r,s,a){throw new Error("Access to hidden file is not allowed: readFileHandle: "+e.subFsFileDescriptor)}};o(ye,"HiddenFileSubFs");var Y=ye;import*as Z from"path";import{createFsFromVolume as bt,Volume as vt}from"memfs";import Pt from"ignore";var be=class be extends L{constructor({name:e,parentFs:t,gitRoot:r,ephemeralPatterns:s}){super({name:e,parentFs:t,gitRoot:r});p(this,"openFh",new Map);p(this,"memFs",bt(new vt));p(this,"ig");p(this,"patterns");this.compositFs=t,this.gitRoot=r,this.ig=Pt(),this.ig.add(s),this.patterns=s}normalizePath(e){let t=typeof e=="string"?e:e.toString();return t.startsWith("/")?t:"/"+t}async responsible(e){let t=e.replace(/\\/g,"/"),r=t.startsWith("./")?t.slice(2):t;return r=r.startsWith("/")?r.slice(1):r,r===""||r==="."?!1:this.ig.ignores(r)}fileType(){return 5}async open(e,t,r){let s=this.normalizePath(e),a=Z.dirname(s);a&&a!=="/"&&a!=="."&&await this.memFs.promises.mkdir(a,{recursive:!0});let l=await this.memFs.promises.open(s,t,r);return this.openFh.set(l.fd,l),new I({fs:this,compositeFs:this.compositFs,subFsFileDescriptor:l.fd,parentFsFileDescriptors:[l.fd]})}async access(e,t){let r=this.normalizePath(e);return await this.memFs.promises.access(r,t)}async stat(e,t){let r=this.normalizePath(e);return this.memFs.promises.stat(r,{bigint:!1})}async lstat(e,t){let r=this.normalizePath(e);return this.memFs.promises.lstat(r,{bigint:!1})}async opendir(e,t){let r=this.normalizePath(e);return await this.memFs.promises.opendir(r,t)}async link(e,t){let r=this.normalizePath(e),s=this.normalizePath(t);return await this.memFs.promises.link(r,s)}async mkdir(e,t){let r=this.normalizePath(e);if(!(typeof t=="object"&&t&&"recursive"in t&&t.recursive)){let a=Z.dirname(r);if(a&&a!=="/"&&a!==".")try{await this.memFs.promises.stat(a)}catch{await this.memFs.promises.mkdir(a,{recursive:!0})}}await this.memFs.promises.mkdir(r,t)}async readdir(e,...t){let r=this.normalizePath(e),s=await this.memFs.promises.readdir(r,...t);return console.log("EPHEMERAL: READDIR: ",s),s}async readlink(e){throw new Error("readlink is not implemented for EphemeralFileSubFs")}async unlink(e){let t=this.normalizePath(e);return await this.memFs.promises.unlink(t)}async rename(e,t){let r=this.normalizePath(e),s=this.normalizePath(t);return await this.memFs.promises.rename(r,s)}async rmdir(e,t){let r=this.normalizePath(e);return await this.memFs.promises.rmdir(r,t)}async symlink(e,t,r){let s=this.normalizePath(e),a=this.normalizePath(t);return await this.memFs.promises.symlink(s,a,r)}async lookup(e){throw new Error(`lookup is not implemented for: ${this.toStr(e)}`)}async close(e){let t=this.openFh.get(e.subFsFileDescriptor);t&&(await t.close(),this.openFh.delete(e.subFsFileDescriptor))}async dataSync(e){let t=this.openFh.get(e.subFsFileDescriptor);if(t)return await t.datasync()}async read(e,t,r,s,a){let l=this.openFh.get(e.subFsFileDescriptor);if(l)return await l.read(t,r,s,a);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async fchmod(e,t){let r=this.openFh.get(e.subFsFileDescriptor);if(r)return await r.chmod(t)}async fchown(e,t,r){let s=this.openFh.get(e.subFsFileDescriptor);if(s)return await s.chown(t,r)}async write(e,t,r,s,a){let l=this.openFh.get(e.subFsFileDescriptor);if(l)return await l.write(t,r,s,a);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async ftruncate(e,t){let r=this.openFh.get(e.subFsFileDescriptor);if(r)return await r.truncate(t)}resolvePath(e){throw new Error(`resolvePath is not implemented: resolvePath(${e})`)}async fstat(e,t){let r=this.openFh.get(e.subFsFileDescriptor);if(r)return await r.stat(t);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async futimes(e,t,r){let s=this.openFh.get(e.subFsFileDescriptor);if(s)return await s.utimes(t,r)}async writev(e,t,r){let s=this.openFh.get(e.subFsFileDescriptor);if(s)return await s.writev(t,r??void 0);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async readv(e,t,r){let s=this.openFh.get(e.subFsFileDescriptor);if(s)return await s.readv(t,r??void 0);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async readFile(e,t){if(typeof e=="string"||Buffer.isBuffer(e)){let r=this.normalizePath(e);return this.memFs.promises.readFile(r,t)}return super.readFile(e,t)}async writeFile(e,t,r){let s=this.normalizePath(e),a=Z.dirname(s);return a&&a!=="/"&&a!=="."&&await this.memFs.promises.mkdir(a,{recursive:!0}),this.memFs.promises.writeFile(s,t,r)}};o(be,"EphemeralSubFs");var ee=be;import*as We from"path";import{createFsFromVolume as kt,Volume as Dt}from"memfs";var ve=class ve extends L{constructor({name:e,parentFs:t,gitRoot:r}){super({name:e,parentFs:t,gitRoot:r});p(this,"openFh",new Map);p(this,"memFs",kt(new Dt));p(this,"targetFs");if(this.compositFs=t,this.gitRoot=r,this.compositFs.parentFs===void 0)throw new Error("PassThroughSubFs not allowed in root fs");this.targetFs=this.compositFs.parentFs}async responsible(e){return!0}fileType(){return 4}async open(e,t,r){let s=We.dirname(e),a=await this.targetFs.promises.open(e,t,r);return this.openFh.set(a.fd,a),new I({fs:this,compositeFs:this.compositFs,subFsFileDescriptor:a.fd,parentFsFileDescriptors:[a.fd]})}async access(e,t){return await this.targetFs.promises.access(e,t)}async stat(e,t){return this.targetFs.promises.stat(e,{bigint:!1})}async lstat(e,t){return this.targetFs.promises.lstat(e,{bigint:!1})}async opendir(e,t){return await this.targetFs.promises.opendir(e,t)}async link(e,t){return await this.targetFs.promises.link(e,t)}async mkdir(e,t){let r=typeof e=="string"?e:e.toString();return await this.targetFs.promises.mkdir(r,t)}async readdir(e,...t){return this.targetFs.promises.readdir(e,...t)}async readlink(e,...t){throw new Error("not implemented")}async unlink(e){return await this.targetFs.promises.unlink(e)}async rename(e,t){return await this.targetFs.promises.rename(e,t)}async rmdir(e,t){return await this.targetFs.promises.rmdir(e,t)}async symlink(e,t,r){return await this.targetFs.promises.symlink(e,t,r)}async lookup(e){throw new Error(`lookup is not implemented for: ${this.toStr(e)}`)}async close(e){let t=this.openFh.get(e.subFsFileDescriptor);t&&(await t.close(),this.openFh.delete(e.subFsFileDescriptor))}async dataSync(e){let t=this.openFh.get(e.subFsFileDescriptor);if(t)return await t.sync()}async read(e,t,r,s,a){let l=this.openFh.get(e.subFsFileDescriptor);if(l)return await l.read(t,r,s,a);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async fchmod(e,t){let r=this.openFh.get(e.subFsFileDescriptor);if(r)return await r.chmod(t)}async fchown(e,t,r){let s=this.openFh.get(e.subFsFileDescriptor);if(s)return await s.chown(t,r)}async write(e,t,r,s,a){let l=this.openFh.get(e.subFsFileDescriptor);if(l)return await l.write(t,r,s,a);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async ftruncate(e,t){let r=this.openFh.get(e.subFsFileDescriptor);if(r)return await r.truncate(t)}resolvePath(e){throw new Error(`resolvePath is not implemented: resolvePath(${e})`)}async fstat(e,t){let r=this.openFh.get(e.subFsFileDescriptor);if(r)return await r.stat(t);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async futimes(e,t,r){let s=this.openFh.get(e.subFsFileDescriptor);if(s)return await s.utimes(t,r)}async writev(e,t,r){let s=this.openFh.get(e.subFsFileDescriptor);if(s)return await s.writev(t,r??void 0);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async readv(e,t,r){let s=this.openFh.get(e.subFsFileDescriptor);if(s)return await s.readv(t,r??void 0);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async readFile(e,t){return typeof e=="string"||Buffer.isBuffer(e)?this.targetFs.readFile(e.toString(),t):super.readFile(e,t)}async writeFile(e,t,r){let s=typeof r=="object"&&r.flag?r.flag:"w",a=await this.targetFs.open(e,s);try{let l;if(typeof t=="string"){let c=typeof r=="object"&&r.encoding?r.encoding:"utf8";l=Buffer.from(t,c)}else Buffer.isBuffer(t)?l=t:l=Buffer.from(t);await a.write(l,0,l.length,0)}finally{await this.targetFs.close(a)}}};o(ve,"PassThroughSubFs");var _e=ve;import Xe from"@legit-sdk/isomorphic-git";import*as ke from"path";import{createFsFromVolume as Ot,Volume as Bt}from"memfs";var Pe=class Pe{constructor(i){this.routes=i;p(this,"compiledRoutes");let e={},t=o((r,s)=>{if(typeof r.type=="string"){e[s]={handler:r,siblings:[]};let a=r}else{let a=[];for(let[l,c]of Object.entries(r))if(l==="."){if(e[s])throw new Error(`Conflict: multiple handlers for path '${s}', '.' and optional '[[parameter_name]]' defined?`);e[s]={handler:c,siblings:a}}else if(l.startsWith("[[")&&l.endsWith("]]")){if(e[s])throw new Error(`Conflict: multiple handlers for path '${s}', '.' and optional '[[parameter_name]]' defined?`);e[s]={handler:c,siblings:a},l.startsWith("[[...")?e[s?`${s}/${l}`:l]={handler:c,siblings:[]}:t(c,s?`${s}/${l}`:l)}else l.startsWith("[")&&l.endsWith("]")?l.startsWith("[...")?e[s?`${s}/${l}`:l]={handler:c,siblings:[]}:t(c,s?`${s}/${l}`:l):(a.push({segment:l,type:c["."]?"folder":"file"}),t(c,s?`${s}/${l}`:l))}},"walk");t(i,""),this.compiledRoutes=Object.entries(e).map(([r,s])=>{let a=[],l=r.split("/").map(m=>{if(m.startsWith("[[")&&m.endsWith("]]")){let d=m.slice(2,-2).replace(/^\.\.\./,"");return a.push(d),"(.*)"}if(m.startsWith("[")&&m.endsWith("]")){let d=m.slice(1,-1);return a.push(d),"([^/]+)"}return m.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}).join("/");return{regex:new RegExp(`^${l}$`),paramNames:a,staticSiblings:s.siblings,handler:s.handler}})}match(i){i.length>1&&i.endsWith("/")&&(i=i.replace(/\/+$/,""));for(let{regex:e,paramNames:t,handler:r,staticSiblings:s}of this.compiledRoutes){let a=i.match(e);if(!a)continue;let l={};for(let c=0;c<t.length;c++)l[t[c]]=decodeURIComponent(a[c+1]||"");return{handler:r,params:l,staticSiblings:s}}}};o(Pe,"LegitPathRouter");var te=Pe;import $ from"@legit-sdk/isomorphic-git";var St=new Set([" ","~","^",":","?","*","[","\\"]),Et=[/^\/|\/$/,/\/\//,/\.$/,/\.lock$/,/^@$/,/@\{/],Ge="\u2002";function Ue(n){let i=n.codePointAt(0);return!(i>=0&&i<=31||i===127||St.has(n))}o(Ue,"isValidChar");function Je(n){let i="";for(let e of n)e===" "?i+=Ge:Ue(e)?i+=e:i+="%"+e.codePointAt(0);for(let e of Et)if(e.test(i))return Array.from(i).map(t=>Ue(t)?t:"%"+t.codePointAt(0)).join("");return i}o(Je,"encodeName");function Ke(n){return n.replace(/%(\d+)/g,(i,e)=>String.fromCodePoint(parseInt(e,10))).replace(new RegExp(Ge,"g")," ")}o(Ke,"decodeName");function M(n){return n.replace(/\./g,"%2E").replace(/\//g,".")}o(M,"encodeBranchNameForVfs");function B(n){return n.replace(/\./g,"/").replace(/%2E/g,".")}o(B,"decodeBranchNameFromVfs");async function b(n,i,e,t){try{return await $.resolveRef({fs:n,dir:i,ref:`refs/heads/${B(e)}`})}catch{return}}o(b,"tryResolveRef");async function x({dir:n,fs:i,treeOid:e,deletePathParts:t,addPathParts:r,addObj:s,addKeepIfEmpty:a,deleteKeepIfNotEmpty:l,keepFilename:c=".keep",gitCache:m}){let[d,...f]=r??[],[h,...F]=t??[],u=[];if(e){let{tree:v}=await $.readTree({fs:i,dir:n,oid:e,cache:m||{}});u=[...v]}if(d===h){let v=d;if(v===void 0)throw new Error("illegal arguement - called with out a path part");if(f.length===0)throw new Error("can not move into it self");if(F.length===0)throw new Error("can not move from it self");let O=u.findIndex(D=>D.path===v),g=(O!==-1?u[O]:void 0)?.oid,w=await x({dir:n,fs:i,treeOid:g,addPathParts:f,deletePathParts:F,addObj:s,addKeepIfEmpty:a,deleteKeepIfNotEmpty:l});if(w===void 0)throw new Error("on the same path we expect an update - respectivly a newly created subTreeOid");let P=!1;if(w!==g){P=!0;let D={mode:"040000",path:v,oid:w,type:"tree"};O!==-1?u[O]=D:u.push(D)}if(e==null&&!P)throw new Error("Illegal state - if the currentOid is undefined - a new tree should have been created (an update should have happened)");if(P)return await $.writeTree({fs:i,dir:n,tree:u});if(e===void 0)throw new Error("currentOid should be set - since the sub tree didn't exist and ");return e}else{let v=!1,O;if(h){let y=u.findIndex(w=>w.path===h),g=y!==-1?u[y]:void 0;if(g===void 0)throw new Error("Element doesnt exist in tree");if(F.length>0){if(g&&g.type!=="tree")throw new Error("SubPart of the path for the obj to delete is not a tree");let w=await x({dir:n,fs:i,treeOid:g.oid,addPathParts:void 0,deletePathParts:F,addObj:s,addKeepIfEmpty:a,deleteKeepIfNotEmpty:l});if(w===g.oid)throw new Error("in case of a delete we expect a different subtree oid");v=!0,w===void 0?u.splice(y,1):u[y]={mode:"040000",path:h,oid:w,type:"tree"}}else if(v=!0,u.splice(y,1),u.length===0&&a){let w=new Uint8Array(0),P=await $.writeBlob({fs:i,dir:n,blob:w});u.push({mode:"100644",oid:P,path:c,type:"blob"})}O=g}if(d){let y=u.findIndex(w=>w.path===d),g=y!==-1?u[y]:void 0;if(f.length>0){if(g&&g.type!=="tree")throw new Error("SubPart of the path for the obj to add is not a tree");let w=await x({dir:n,fs:i,treeOid:g?.oid,addPathParts:f,deletePathParts:void 0,addObj:s,addKeepIfEmpty:a,deleteKeepIfNotEmpty:l});if(w===void 0)throw new Error("in case we add, we expect an update - respectivly a newly created subTreeOid");if(w!==g?.oid){v=!0;let P={mode:"040000",path:d,oid:w,type:"tree"};if(y!==-1)u[y]=P;else if(u.push(P),l&&u.length>1){let D=u.findIndex(S=>S.path===c);D!==-1&&u.splice(D,1)}}}else{if(v=!0,s){let w={mode:s.type==="tree"?"040000":"100644",path:d,oid:s.oid,type:s.type};if(y!==-1)u[y]=w;else{if(l&&u.length>0){let P=u.findIndex(D=>D.path===c);P!==-1&&u.splice(P,1)}u.push(w)}}if(a&&u.length===0){let w=new Uint8Array(0),P=await $.writeBlob({fs:i,dir:n,blob:w});u.push({mode:"100644",oid:P,path:c,type:"blob"})}}}if(u.length===0)return;if(v)return await $.writeTree({fs:i,dir:n,tree:u});if(e===void 0)throw new Error("currentOid should be set - since the sub tree didn't exist and ");return e}}o(x,"buildUpdatedTree");async function qe(n,i,e,t,r=0,s={}){let{tree:a}=await $.readTree({fs:n,dir:i,oid:e,cache:s});if(t.length===r)return{type:"tree",entries:a.map(m=>T({parent:t.join("/"),name:m.path,isDir:m.type==="tree"})),oid:e};let l=t[r],c=a.find(m=>m.path===l);if(c){if(t.length===r+1){if(c.type==="blob")return{type:"blob",oid:c.oid};if(c.type==="tree"){let m=await $.readTree({fs:n,dir:i,oid:c.oid,cache:s});return{type:"tree",entries:m.tree.map(d=>T({parent:t.join("/"),name:d.path,isDir:d.type==="tree"})),oid:m.oid}}}else if(c.type==="tree")return await qe(n,i,c.oid,t,r+1,s)}}o(qe,"findGitObjectAtPath");async function j({filePath:n,gitRoot:i,nodeFs:e,commitSha:t,pathParams:r,gitCache:s}){let a=s||{};if(!r.filePath){let m=await $.readTree({fs:e,dir:i,oid:t,cache:a});return{type:"tree",entries:m.tree.map(f=>T({parent:n,name:f.path,isDir:f.type==="tree"})),oid:m.oid}}let l=r.filePath?r.filePath.split("/"):[];return await qe(e,i,t,l,0,a)}o(j,"resolveGitObjAtPath");function T(n){return{name:n.name,isFile:o(()=>!n.isDir,"isFile"),isDirectory:o(()=>n.isDir,"isDirectory"),isBlockDevice:o(()=>!0,"isBlockDevice"),isCharacterDevice:o(()=>!1,"isCharacterDevice"),isSymbolicLink:o(()=>!1,"isSymbolicLink"),isFIFO:o(()=>!1,"isFIFO"),isSocket:o(()=>!1,"isSocket"),parentPath:n.parent,path:n.parent}}o(T,"toDirEntry");var J=class J extends L{constructor({name:e,parentFs:t,gitStorageFs:r,gitRoot:s,routerConfig:a}){super({name:e,parentFs:t,gitRoot:s});p(this,"pathRouter");p(this,"memFs");p(this,"openFh",{});p(this,"storageFs");this.pathRouter=new te(a),this.gitRoot=s,this.storageFs=r,this.memFs=Ot(new Bt)}async getAuthor(){let e=await Xe.getConfig({fs:this.storageFs,dir:this.gitRoot,path:"user.name"}),t=await Xe.getConfig({fs:this.storageFs,dir:this.gitRoot,path:"user.email"}),r=Math.floor(Date.now()/1e3),s=new Date().getTimezoneOffset();return{name:e,email:t,date:r,timezoneOffset:s}}async responsible(e){return!0}getRouteHandler(e){let t=e;this.gitRoot&&e.startsWith(this.gitRoot)&&(this.gitRoot==="/"?t=e.slice(this.gitRoot.length):t=e.slice(this.gitRoot.length+1));let r=t.indexOf(`/${J.LEGIT_DIR}`);if(r===-1)return this.pathRouter.match(t);let s=t.slice(r+1);return this.pathRouter.match(t)}async open(e,t,r){let s=this.getRouteHandler(e);if(!s)throw new Error("Not a virtual legit file");if(!(s?.handler.writeFile!==void 0)&&(t.includes("w")||t.includes("a")))throw new Error(`Write operations not allowed for ${s?.handler.type}`);if(t.includes("x")&&s?.handler.type!=="gitBranchFileVirtualFile"&&s?.handler.type!=="claudeVirtualSessionFileVirtualFile")throw new Error(`Exclusive operations not allowed for ${s?.handler.type}`);let l=await this.getAuthor(),c=await s.handler.getFile({cacheFs:this.memFs,filePath:e,userSpaceFs:this.compositFs,gitRoot:this.gitRoot,nodeFs:this.storageFs,pathParams:s.params,author:l}),m=!1;for(let u of Object.values(this.openFh))u.path===e&&(m=!0);if((c||m)&&t.includes("x"))throw Object.assign(new Error(`EEXIST: file already exists, open '${e}'`),{code:"EEXIST",errno:-17,syscall:"open",path:e});if(!c&&!m&&!(t.includes("w")||t.includes("a")))throw Object.assign(new Error(`ENOENT: no such file or directory, open '${e}'`),{code:"ENOENT",errno:-2,syscall:"open",path:e});let d=ke.dirname(e);if(await this.memFs.promises.mkdir(d,{recursive:!0}),c===void 0&&!t.includes("x")||c&&c.type==="file")try{let u=await this.memFs.promises.access(e)}catch{await this.memFs.promises.writeFile(e,"")}let f=await this.memFs.promises.open(e,t,r),h=f.fd,F=new I({fs:this,compositeFs:this.compositFs,subFsFileDescriptor:h,parentFsFileDescriptors:[]});return this.openFh[h]={path:e,mode:t,fh:f,openSha:c?.oid,readSha:void 0,unflushed:[]},(t.includes("x")||t.includes("w"))&&this.openFh[h].unflushed.push({length:0,start:0}),F}async mkdir(e,t){let r=e.toString(),s=this.getRouteHandler(r),a=t?{options:t}:{};try{let l=await this.getAuthor();await s?.handler.mkdir({cacheFs:this.memFs,filePath:e.toString(),userSpaceFs:this.compositFs,nodeFs:this.storageFs,gitRoot:this.gitRoot,pathParams:s.params,...a,author:l});let c=typeof t=="object"?{...t,recursive:!0}:{recursive:!0};await this.memFs.promises.mkdir(e,c);let m=r.split("/"),d="";for(let f=1;f<=m.length;f++){d=m.slice(0,f).join("/");try{if((await this.memFs.promises.stat(d)).isDirectory()){let F=await this.memFs.promises.open(d,"r");this.openFh[F.fd]={path:d,mode:"r",fh:F,openSha:void 0,readSha:void 0,unflushed:[]}}}catch{}}}catch(l){throw l}}async access(e,t){await this.stat(e)}async futimes(e,t,r){let s=this.openFh[e.subFsFileDescriptor];if(!s)throw new Error("Invalid file handle");return await s.fh.utimes(t,r)}async fstat(e,t){let r=this.openFh[e.subFsFileDescriptor];if(!r)throw new Error("Invalid file handle");return this.stat(r.path,t)}async ftruncate(e,t){let r=this.openFh[e.subFsFileDescriptor];if(!r)throw new Error("Invalid file handle");return r.unflushed.push({length:0,start:0}),await r.fh.truncate(t)}async stat(e,t){let r=e.toString(),s=Object.values(this.openFh).find(m=>m.path===r&&m.unflushed.length>0);if(s&&s.unflushed.length>0)return await s.fh.stat(t);let a=this.getRouteHandler(r);if(!a)throw new Error(`ENOENT: no such file or directory, stat '${r}'`);let l=await this.getAuthor();return await a.handler.getStats({cacheFs:this.memFs,filePath:r,userSpaceFs:this.compositFs,gitRoot:this.gitRoot,nodeFs:this.storageFs,pathParams:a.params,author:l})}async lstat(e,t){return this.stat(e,t)}async readdir(e,t){let r=e.toString(),s=this.getRouteHandler(r);if(!s)throw new Error(`ENOENT: no such file or directory, scandir '${r}'`);let a=await this.getAuthor(),l=await s?.handler.getFile({cacheFs:this.memFs,filePath:r,userSpaceFs:this.compositFs,gitRoot:this.gitRoot,nodeFs:this.storageFs,pathParams:s.params,author:a});if(l){if(l.type!=="directory")throw new Error("not a folder");let c=s?.staticSiblings??[],m=Array.from(new Set([...l.content,...c.map(d=>T({name:d.segment,parent:r,isDir:d.type==="folder"}))])).sort((d,f)=>d.name.localeCompare(f.name,void 0,{numeric:!0,sensitivity:"base"}));return t?.withFileTypes?m:m.map(d=>d.name)}return[]}async read(e,t,r,s,a){let l=e.subFsFileDescriptor,c=this.openFh[l];if(!c)throw new Error("Invalid file handle");if(c.unflushed.length===0){let m=this.getRouteHandler(c.path),d=await this.getAuthor(),f=await m.handler.getFile({cacheFs:this.memFs,filePath:c.path,userSpaceFs:this.compositFs,gitRoot:this.gitRoot,nodeFs:this.storageFs,pathParams:m?.params,author:d});if(!f?.content)throw new Error("couldnt access content");if(f.type!=="file")throw new Error("not a file");let h=typeof f.content=="string"?Buffer.from(f.content):f.content,F=typeof a=="number"?a:0,u=Math.min(F+s,h.length),v=Math.max(0,u-F);return h.copy(t,r,F,F+v),{bytesRead:v,buffer:t}}return await c.fh.read(t,r,s,a)}async write(e,t,r,s,a){let l=this.openFh[e.subFsFileDescriptor];if(!l)throw new Error("Invalid file handle");let c=l.mode;if(!c.includes("w")&&!c.includes("a")&&!c.includes("+"))throw Object.assign(new Error("EBADF: bad file descriptor, write"),{code:"EBADF",errno:-9,syscall:"write"});if(l.unflushed.length===0){let h=this.getRouteHandler(l.path),F=await this.getAuthor(),u=await h.handler.getFile({cacheFs:this.memFs,filePath:l.path,userSpaceFs:this.compositFs,gitRoot:this.gitRoot,nodeFs:this.storageFs,pathParams:h.params,author:F});u&&u.oid&&(await this.memFs.promises.writeFile(l.path,u.content),l.readSha=u.oid)}let m=await l.fh.write(t,r,s,a),d=r??0,f=a??0;return l.unflushed.push({start:f,length:s||t.byteLength-d+f}),m}async close(e){let t=e.subFsFileDescriptor,r=this.openFh[t];if(!r)throw new Error("Invalid file handle");try{await this.dataSync(e),await r.fh.close()}finally{delete this.openFh[t]}}async dataSync(e){let t=e.subFsFileDescriptor,r=this.openFh[t];if(!r)throw new Error("Invalid file handle");if(r.unflushed.length>0){let s=this.getRouteHandler(r.path);if(s&&s.handler.writeFile){let a=await this.memFs.promises.readFile(r.path),l=await this.getAuthor();await s.handler.writeFile({cacheFs:this.memFs,filePath:r.path,userSpaceFs:this.compositFs,gitRoot:this.gitRoot,nodeFs:this.storageFs,content:a,pathParams:s.params,author:l})}r.unflushed=[]}}async readFile(e,t){let r=typeof e=="string"?e:Buffer.isBuffer(e)?e.toString():e.fd?`FileHandle(${e.fd})`:e.toString(),s=null;typeof t=="string"?s=t:t&&typeof t=="object"&&t.encoding&&(s=t.encoding);let a=await this.open(r,"r");try{let c=(await this.fstat(a)).size,m=Buffer.alloc(c);return await this.read(a,m,0,c,0),await this.close(a),s?m.toString(s):m}catch(l){try{await this.close(a)}catch{}throw l}}async writeFile(e,t,r){let s="w",a="utf8",l;typeof r=="string"?a=r:r&&typeof r=="object"&&(r.flag&&(s=String(r.flag)),r.encoding&&(a=r.encoding),r.mode&&(l=typeof r.mode=="string"?parseInt(r.mode,8):r.mode));let c=await this.open(e,s,l);try{let m;typeof t=="string"?m=Buffer.from(t,a):Buffer.isBuffer(t)?m=t:t instanceof Uint8Array?m=Buffer.from(t):ArrayBuffer.isView(t)?m=Buffer.from(t.buffer,t.byteOffset,t.byteLength):m=Buffer.from(t),await this.write(c,m,0,m.length,0)}finally{await this.close(c)}}async rename(e,t){let r=e.toString(),s=t.toString(),a=this.getRouteHandler(r),l=this.getRouteHandler(s);if(a?.handler.type==="gitBranchFileVirtualFile"&&l?.handler.type==="gitBranchFileVirtualFile"){let c=!0;try{await this.memFs.promises.access(s)}catch{c=!1}let m=!0;try{await this.stat(s)}catch{m=!1}let d=!0;try{await this.stat(r)}catch{d=!1}let f=!0;try{await this.memFs.promises.access(r)}catch{f=!1}if(f){let v=ke.dirname(s);try{await this.memFs.promises.access(v)}catch{await this.memFs.promises.mkdir(v,{recursive:!0})}await this.memFs.promises.rename(e,t)}let h=this.getRouteHandler(r);if(!h)throw new Error("VF not found");let F=await this.getAuthor(),u=await h.handler.rename({cacheFs:this.memFs,filePath:r,userSpaceFs:this.compositFs,gitRoot:this.gitRoot,nodeFs:this.storageFs,newPath:s,pathParams:h?.params??{},newPathParams:l?.params??{},author:F})}else throw new Error(`Unsupported rename operation from ${a?.handler.type} to ${l?.handler.type}`)}async fchmod(e,t){}async unlink(e){let t=e.toString(),r=this.getRouteHandler(t);if(r?.handler.unlink!==void 0)try{let s=await this.getAuthor();await r.handler.unlink({cacheFs:this.memFs,filePath:t,userSpaceFs:this.compositFs,nodeFs:this.storageFs,gitRoot:this.gitRoot,pathParams:r.params,author:s})}catch(s){let a=!1;for(let[l,c]of Object.entries(this.openFh))c.path===t&&c.unflushed.length>0&&(a=!0);if(!a)throw s}finally{let s=!1;for(let[a,l]of Object.entries(this.openFh))l.path===t&&(s=!0,await l.fh.close(),delete this.openFh[Number(a)]);s&&await this.memFs.promises.unlink(t)}else throw new Error(`Cannot unlink ${r?.handler.type} files`)}async rmdir(e,...t){let r=e.toString(),s=this.getRouteHandler(r);if(s?.handler.rmdir!==void 0){let a=await this.getAuthor();await s.handler.rmdir({cacheFs:this.memFs,filePath:r,userSpaceFs:this.compositFs,nodeFs:this.storageFs,gitRoot:this.gitRoot,pathParams:s.params,author:a});let l=!1;for(let[c,m]of Object.entries(this.openFh))m.path===r&&(l=!0,await m.fh.close(),delete this.openFh[Number(c)]);l&&await this.memFs.promises.rmdir(r,{recursive:!0})}else throw new Error(`Cannot rmdir
4
- ${s?.handler.type} directories`)}fileType(){return 10}};o(J,"GitSubFs"),p(J,"LEGIT_DIR",".legit");var ie=J;import U from"@legit-sdk/isomorphic-git";import Tt from"@legit-sdk/isomorphic-git";var De="-operation";async function C(n,i,e){return(await Tt.listBranches({fs:n,dir:i})).filter(r=>r.endsWith("__"+e+De))[0]}o(C,"resolveOperationBranchName");import Se from"@legit-sdk/isomorphic-git";async function k(n,i){try{let e=await Se.getConfig({fs:i,dir:n,path:"user.legit-current-branch"});if(e)return M(e)}catch{}try{let e=await Se.getConfig({fs:i,dir:n,path:"init.defaultBranch"});return M(e)||"main"}catch{return"main"}}o(k,"getCurrentBranch");async function Qe(n,i,e){await Se.setConfig({fs:i,dir:n,path:"user.legit-current-branch",value:B(e)})}o(Qe,"setCurrentBranch");var re={type:"gitBranchOperationsVirtualFile",rootType:"file",getStats:o(async n=>{let{gitRoot:i,nodeFs:e,pathParams:t}=n;t.branchName===void 0&&(t.branchName=await k(i,e));let r=await C(e,i,t.branchName),s,a=!1;if(r)try{s=await U.resolveRef({fs:e,dir:i,ref:r}),a=!0}catch{try{s=await U.resolveRef({fs:e,dir:i,ref:`refs/heads/${r}`}),a=!0}catch{throw new Error(`Base Branch ${t.branchName} for operations does not exis`)}}else try{s=await U.resolveRef({fs:e,dir:i,ref:`refs/heads/${t.branchName}`})}catch{throw new Error(`Base Branch ${t.branchName} for operations does not exis`)}let l=await U.readCommit({fs:e,dir:i,oid:s}),{commit:c}=l,m=c.committer.timestamp*1e3;try{return{mode:420,size:(a?await re.getFile(n):void 0)?.content?.length??0,atimeMs:m,mtimeMs:m,ctimeMs:m,birthtimeMs:m,atime:new Date(m),mtime:new Date(m),ctime:new Date(m),birthtime:new Date(m),isFile:o(()=>!0,"isFile"),isDirectory:o(()=>!1,"isDirectory"),isSymbolicLink:o(()=>!1,"isSymbolicLink"),isBlockDevice:o(()=>!1,"isBlockDevice"),isCharacterDevice:o(()=>!1,"isCharacterDevice"),isSocket:o(()=>!1,"isSocket"),isFIFO:o(()=>!1,"isFIFO"),isFileSync:o(()=>!0,"isFileSync"),isDirectorySync:o(()=>!1,"isDirectorySync"),dev:0,ino:0,nlink:1,uid:0,gid:0,rdev:0,blksize:4096,blocks:0}}catch{throw new Error("ENOENT: no such file or directory, stat operationHistory")}},"getStats"),getFile:o(async n=>{let{gitRoot:i,nodeFs:e,pathParams:t}=n;t.branchName===void 0&&(t.branchName=await k(i,e));let r=await C(e,i,t.branchName),s=[];if(r){let c=await U.resolveRef({fs:e,dir:i,ref:`refs/heads/${r}`}),m=!1,d=c;for(;d&&!m;){let f=await U.readCommit({fs:e,dir:i,oid:d});s.push({oid:f.oid,parentOids:f.commit.parent,message:f.commit.message,originBranchOid:"unset"}),d=f.commit.parent&&f.commit.parent.length>0?f.commit.parent[0]:null,f.commit.parent.length===2&&f.commit.parent[0]===f.commit.parent[1]&&(m=!0)}}let a;for(let c=s.length-1;c>=0;c--){let m=s[c];if(a===void 0){if(m.parentOids.length!==2&&m.parentOids[0]!==m.parentOids[1])throw new Error(`Operation commit ${m.oid} does not have two parents as expected`);a=m.parentOids[1]}m.parentOids.length===2&&(a=m.parentOids[1]),m.originBranchOid=a}let l=Buffer.from(JSON.stringify(s,null,2),"utf-8");return{type:"file",content:l,mode:420,size:l.length}},"getFile"),rename:o(async function(n){throw new Error("not implemented")},"rename"),mkdir:o(async function(n){throw new Error("not implemented")},"mkdir")};import H from"@legit-sdk/isomorphic-git";import Ee from"@legit-sdk/isomorphic-git/http/node";var z="legit",Ye=o(({fs:n,gitRepoPath:i,serverUrl:e="https://hub.legitcontrol.com",auth:t,anonymousBranch:r,authHeaderPrefix:s="Bearer "})=>{let a=!1;async function l(O){let y=await t.getMaxAccessTokenForBranch(O);if(!y)throw new Error(`No access token for branch ${O}`);await H.fetch({fs:n,http:Ee,dir:i,singleBranch:!0,ref:`${O}`,remote:z,url:e,headers:{Authorization:`${s}${y}`}});let g=await H.resolveRef({fs:n,dir:i,ref:`${z}/${O}`});await H.writeRef({fs:n,dir:i,ref:`refs/heads/${O}`,value:g})}o(l,"loadBranch");let c=[];async function m(){let O=await t.getMaxAccessTokenForBranch("todo");await H.fetch({fs:n,http:Ee,dir:i,remote:z,url:e,headers:{Authorization:`${s}${O}`}});let y=await H.listBranches({fs:n,dir:i});for(let g of y){if(g===r)continue;let w=`${z}/${g}`,P,D;try{P=await H.resolveRef({fs:n,dir:i,ref:g})}catch(S){console.log(`Could not resolve local ref ${g}:`,S)}try{D=await H.resolveRef({fs:n,dir:i,ref:w})}catch{D=void 0}if(P&&D){if(P!==D){let S=await H.findMergeBase({fs:n,dir:i,oids:[P,D]});if(S[0]!==P&&S[0]!==D){let Ve=await H.merge({fs:n,dir:i,ours:P,theirs:D,fastForwardOnly:!1,abortOnConflict:!1,author:{name:"Your Name",email:"your.email@example.com"},mergeDriver:o(async({branches:ce,contents:de,path:fe})=>{let[It,ut,Me]=de;return console.log(`Merging ${ce[0]} with ${ce[1]}...`),console.log("merged:"),console.log(de),{cleanMerge:!0,mergedText:Me===void 0?ut:Me}},"mergeDriver")});await H.writeRef({fs:n,dir:i,ref:`refs/heads/${g}`,value:Ve.oid,force:!0})}S[0]===P?(console.log(`branch ${g} differs - remote ahaed, not behind`),await H.writeRef({fs:n,dir:i,ref:`refs/heads/${g}`,value:D,force:!0})):S[0]===D?(console.log(`branch ${g} differs - local ahead, not behind`),c.push(g)):(console.log(`branch ${g} differs - both changed`),c.push(g))}}else P&&!D&&c.push(g)}}o(m,"pull");async function d(O){if((await t.getUser()).type!=="local")for(let y of O){let g=await t.getMaxAccessTokenForBranch(y);await H.push({fs:n,http:Ee,dir:i,remote:z,url:e,ref:y,headers:{Authorization:`Bearer ${g}`}})}}o(d,"push");let f=Promise.resolve();async function h(O){f=f.then(()=>d(O)),await f}o(h,"sequentialPush");async function F(){await H.getConfig({fs:n,dir:i,path:`remote.${z}.fetch`})||await H.setConfig({fs:n,dir:i,path:`remote.${z}.fetch`,value:`+refs/heads/*:refs/remotes/${z}/*`});try{await m();let y=[...new Set(c)].filter(g=>g.indexOf(r)===-1);await h(y),c=[]}catch(y){console.error("Error monitoring changes:",y)}finally{a&&setTimeout(F,1e3)}}o(F,"pullPushTick");function u(){a=!0,F()}o(u,"startSync");function v(){a=!1}return o(v,"stopSync"),{start:o(()=>{a||(u(),a=!0)},"start"),stop:o(()=>{v()},"stop"),isRunning:o(()=>a,"isRunning"),loadBranch:l,sequentialPush:h}},"createLegitSyncService");import N from"@legit-sdk/isomorphic-git";import{createFsFromVolume as Nt,Volume as Ht}from"memfs";var Ze=o((n,i)=>{let e={type:"local",id:"local",name:"Local User",email:"local@legitcontrol.com"};return{getUser:o(async()=>e,"getUser"),signInAnonymously:o(async()=>{e.type="anonymous",e.id=crypto.randomUUID(),e.email=`anonymous-sha1-${e.id}-@legitcontrol.com`},"signInAnonymously"),addAccessToken:o(async t=>{let r=await n.getUserTokens(e.id);r.accessTokens.push(t),await n.setUserTokens(e.id,r)},"addAccessToken"),getMaxAccessTokenForBranch:o(async t=>{let r=await n.getUserTokens(e.id);if(!(r.accessTokens===void 0||r.accessTokens.length===0))return r.accessTokens[0]},"getMaxAccessTokenForBranch")}},"createSessionManager");import it from"@legit-sdk/isomorphic-git";function et(n){let i=JSON.stringify(n),e=new TextEncoder().encode(i),t="";return typeof btoa=="function"?t=btoa(String.fromCharCode(...e)):t=Buffer.from(e).toString("base64"),t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}o(et,"encodeConfigJson");function tt(n){let i=n.replace(/-/g,"+").replace(/_/g,"/")+"===".slice((n.length+3)%4),e;typeof atob=="function"?e=atob(i):e=Buffer.from(i,"base64").toString("binary");let t=Uint8Array.from(e,s=>s.charCodeAt(0)),r=new TextDecoder().decode(t);return JSON.parse(r)}o(tt,"decodeConfigJson");var rt="user.legit-tokens";function st({storageFs:n,gitRoot:i}){return{getUserTokens:o(async e=>{let t=await it.getConfig({fs:n,dir:i,path:rt});return t?tt(t):{accessTokens:[]}},"getUserTokens"),setUserTokens:o(async(e,t)=>await it.setConfig({fs:n,dir:i,path:rt,value:et(t)}),"setUserTokens")}}o(st,"createGitConfigTokenStore");import E from"@legit-sdk/isomorphic-git";var se=class se extends Error{constructor(e,t){super(e);p(this,"code","ENOENT");p(this,"path");this.name="ENOENTError",this.path=t,Object.setPrototypeOf(this,se.prototype)}};o(se,"ENOENTError");var _=se;function ne(n){return n&&n.gitCache!==void 0?n.gitCache:n&&n.parentFs?ne(n.parentFs):{}}o(ne,"getGitCacheFromFs");var oe={type:"gitBranchFileVirtualFile",rootType:"folder",getStats:o(async({gitRoot:n,nodeFs:i,filePath:e,cacheFs:t,pathParams:r,userSpaceFs:s})=>{r.branchName===void 0&&(r.branchName=await k(n,i));let a=await b(i,n,r.branchName);if(!a)throw new _(`ENOENT: no such file or directory, stat '${e}'`,e);let l=await j({filePath:e,gitRoot:n,nodeFs:i,commitSha:a,pathParams:r,gitCache:ne(s)});if(!l)throw new _(`ENOENT: no such file or directory, stat '${e}'`,e);let c=await E.readCommit({fs:i,dir:n,oid:a}),{commit:m}=c,d=await E.log({fs:i,dir:n,ref:a,filepath:r.filePath,depth:1}),f=m.committer.timestamp*1e3,h=d.length>0?d[0].commit.committer.timestamp*1e3:f;if(l.type==="tree")return{mode:420,size:0,isFile:o(()=>!0,"isFile"),isDirectory:o(()=>!0,"isDirectory"),isSymbolicLink:o(()=>!1,"isSymbolicLink"),isBlockDevice:o(()=>!1,"isBlockDevice"),isCharacterDevice:o(()=>!1,"isCharacterDevice"),isSocket:o(()=>!1,"isSocket"),isFIFO:o(()=>!1,"isFIFO"),isFileSync:o(()=>!0,"isFileSync"),isDirectorySync:o(()=>!1,"isDirectorySync"),dev:0,ino:0,nlink:1,uid:0,gid:0,rdev:0,blksize:4096,blocks:0,atimeMs:h,mtimeMs:h,ctimeMs:h,birthtimeMs:f,atime:new Date(h),mtime:new Date(h),ctime:new Date(h),birthtime:new Date(h)};{let{blob:F}=await E.readBlob({fs:i,dir:n,oid:l.oid});return{mode:420,size:F.length,isFile:o(()=>!0,"isFile"),isDirectory:o(()=>!1,"isDirectory"),isSymbolicLink:o(()=>!1,"isSymbolicLink"),isBlockDevice:o(()=>!1,"isBlockDevice"),isCharacterDevice:o(()=>!1,"isCharacterDevice"),isSocket:o(()=>!1,"isSocket"),isFIFO:o(()=>!1,"isFIFO"),isFileSync:o(()=>!0,"isFileSync"),isDirectorySync:o(()=>!1,"isDirectorySync"),dev:0,ino:0,nlink:1,uid:0,gid:0,rdev:0,blksize:4096,blocks:Math.ceil(F.length/4096),atimeMs:h,mtimeMs:h,ctimeMs:h,birthtimeMs:h,atime:new Date(h),mtime:new Date(h),ctime:new Date(h),birthtime:new Date(h)}}},"getStats"),getFile:o(async({filePath:n,gitRoot:i,nodeFs:e,cacheFs:t,pathParams:r,userSpaceFs:s})=>{r.branchName===void 0&&(r.branchName=await k(i,e));try{let a=await b(e,i,r.branchName);if(!a){let c=await E.resolveRef({fs:e,dir:i,ref:"HEAD"});if(await E.branch({fs:e,dir:i,ref:r.branchName,object:c}),a=await b(e,i,r.branchName),!a)throw new Error("Could not create branch for getFile")}let l=await j({filePath:n,gitRoot:i,nodeFs:e,commitSha:a,pathParams:r,gitCache:ne(s)});if(!l)return;if(l.type==="blob"){let{blob:c}=await E.readBlob({fs:e,dir:i,oid:l.oid});return{type:"file",content:Buffer.from(c),mode:420,size:c.length,oid:l.oid}}else{let c=[];try{let d=await t.promises.stat(n);if(d&&d.isDirectory()){let f=await t.promises.readdir(n,{withFileTypes:!0});c.push(...f)}}catch{}return{type:"directory",content:Array.from(new Set([...c,...l.entries])).map(d=>({...d,name:d.name.toString(),path:`${n}`,parentPath:`${n}`})),mode:493}}}catch{return}},"getFile"),unlink:o(async({filePath:n,gitRoot:i,nodeFs:e,cacheFs:t,pathParams:r,author:s})=>{if(r.branchName===void 0&&(r.branchName=await k(i,e)),!r.filePath)throw new Error("filePath should be in pathParams");let a=await b(e,i,r.branchName);if(!a)throw new Error("Invalid branch file path - branch must exist");let l=await E.readTree({fs:e,dir:i,oid:a}),c=await x({dir:i,fs:e,treeOid:l.oid,deletePathParts:r.filePath.split("/"),addPathParts:void 0,addObj:void 0,deleteKeepIfNotEmpty:!1,addKeepIfEmpty:!0,keepFilename:".keep"});if(c!==l.oid){let m=await E.commit({fs:e,dir:i,message:`Delete ${r.filePath}`,tree:c,noUpdateBranch:!0,parent:[a],author:s});await E.writeRef({fs:e,dir:i,ref:`refs/heads/${B(r.branchName)}`,value:m,force:!0})}},"unlink"),writeFile:o(async({filePath:n,gitRoot:i,nodeFs:e,content:t,cacheFs:r,pathParams:s,author:a})=>{if(s.branchName===void 0&&(s.branchName=await k(i,e)),s.filePath===void 0)throw new Error("filePath should be in pathParams");let l;typeof t=="string"?l=new TextEncoder().encode(t):l=new Uint8Array(t);let c=await E.writeBlob({fs:e,dir:i,blob:l}),m=await b(e,i,s.branchName);if(!m){let h=await E.resolveRef({fs:e,dir:i,ref:"HEAD"});if(await E.branch({fs:e,dir:i,ref:B(s.branchName),object:h}),m=await b(e,i,s.branchName),!m)throw new Error("Could not create branch for writeFile")}let d=await E.readTree({fs:e,dir:i,oid:m}),f=await x({dir:i,fs:e,treeOid:d.oid,deletePathParts:void 0,addPathParts:s.filePath.split("/"),addObj:{type:"blob",oid:c},deleteKeepIfNotEmpty:!0,addKeepIfEmpty:!1,keepFilename:".keep"});if(f!==d.oid){let h=await E.commit({fs:e,dir:i,message:`\u{1F4BE} Change '${s.filePath}'`,tree:f,noUpdateBranch:!0,parent:[m],author:a});await E.writeRef({fs:e,dir:i,ref:`refs/heads/${B(s.branchName)}`,value:h,force:!0});let F=await b(e,i,s.branchName);if(h!==F)throw new Error("Failed to update branch after file deletion")}},"writeFile"),rename:o(async function({filePath:n,newPath:i,gitRoot:e,nodeFs:t,pathParams:r,newPathParams:s,author:a,userSpaceFs:l}){if(r.branchName===void 0&&(r.branchName=await k(e,t)),r.filePath===void 0)throw new Error("filePath should be in pathParams");if(s.branchName===void 0&&(s.branchName=await k(e,t)),s.filePath===void 0)throw new Error("filePath should be in newPathParams");let c=await b(t,e,r.branchName);if(!c)throw new Error("Invalid branch file path - source branch must exist");let m=await b(t,e,s.branchName);if(!m){let F=await E.resolveRef({fs:t,dir:e,ref:"HEAD"});if(await E.branch({fs:t,dir:e,ref:B(s.branchName),object:F}),m=await b(t,e,s.branchName),m===void 0)throw new Error("Could not create branch for rename operation")}if(s.branchName!==r.branchName)throw new Error("cross branch move not implemented yet");let d=await j({gitRoot:e,nodeFs:t,commitSha:c,filePath:n,pathParams:r,gitCache:ne(l)});if(d===void 0)throw new Error("no obj at path exists");let f=await x({dir:e,fs:t,deletePathParts:r.filePath.split("/"),addPathParts:s.filePath.split("/"),addObj:d.type==="blob"?{type:"blob",oid:d.oid}:{type:"tree",oid:d.oid,entries:d.entries.map(F=>F.name.toString())},treeOid:m,addKeepIfEmpty:!0,deleteKeepIfNotEmpty:!0}),h=await E.readTree({fs:t,dir:e,oid:c});if(f!==h.oid){let F=await E.commit({fs:t,dir:e,message:`\u{1F500} Rename '${r.filePath}' to '${s.filePath}'`,tree:f,noUpdateBranch:!0,parent:[m],author:a});await E.writeRef({fs:t,dir:e,ref:`refs/heads/${B(s.branchName)}`,value:F,force:!0})}},"rename"),mkdir:o(async function(n){n.pathParams.branchName===void 0&&(n.pathParams.branchName=await k(n.gitRoot,n.nodeFs));let i=await b(n.nodeFs,n.gitRoot,n.pathParams.branchName);if(n.pathParams.filePath===void 0&&(n.pathParams.filePath="/",i!==void 0))throw new Error("Folder exists");try{throw await oe.getStats(n),new Error("Folder exists")}catch{}if(n.filePath.endsWith("/")&&(n.filePath=n.filePath.replace(/\/+$/,"")),n.pathParams&&typeof n.pathParams.filePath=="string"&&(n.pathParams.filePath=n.pathParams.filePath.replace(/\/+$/,"")),!i){let a=await E.resolveRef({fs:n.nodeFs,dir:n.gitRoot,ref:"HEAD"});if(await E.branch({fs:n.nodeFs,dir:n.gitRoot,ref:B(n.pathParams.branchName),object:a}),i=await b(n.nodeFs,n.gitRoot,n.pathParams.branchName),i===void 0)throw new Error("Could not create branch for mkdir operation")}let e=await E.readTree({fs:n.nodeFs,dir:n.gitRoot,oid:i}),t=new Uint8Array(0),r=await E.writeBlob({fs:n.nodeFs,dir:n.gitRoot,blob:t}),s=await x({dir:n.gitRoot,fs:n.nodeFs,treeOid:e.oid,deletePathParts:void 0,addPathParts:[...n.pathParams.filePath.split("/"),".keep"],addObj:{type:"blob",oid:r},deleteKeepIfNotEmpty:!0,addKeepIfEmpty:!0,keepFilename:".keep"});if(s!==e.oid){let a=await E.commit({fs:n.nodeFs,dir:n.gitRoot,message:`\u{1F4BE} Change '${n.pathParams.filePath}'`,tree:s,noUpdateBranch:!0,parent:[i],author:n.author});await E.writeRef({fs:n.nodeFs,dir:n.gitRoot,ref:`refs/heads/${B(n.pathParams.branchName)}`,value:a,force:!0})}},"mkdir"),rmdir:o(async({filePath:n,gitRoot:i,nodeFs:e,cacheFs:t,pathParams:r,author:s})=>{if(r.branchName===void 0&&(r.branchName=await k(i,e)),!r.filePath)throw new Error("filePath should be in pathParams");let a=await b(e,i,r.branchName);if(!a)throw new Error("Invalid branch file path - branch must exist");let l=await E.readTree({fs:e,dir:i,oid:a}),c=await x({dir:i,fs:e,treeOid:l.oid,deletePathParts:r.filePath.split("/"),addPathParts:void 0,addObj:void 0,deleteKeepIfNotEmpty:!1,addKeepIfEmpty:!0,keepFilename:".keep"});if(c!==l.oid){let m=await E.commit({fs:e,dir:i,message:`Delete ${r.filePath}`,tree:c,noUpdateBranch:!0,parent:[a],author:s});await E.writeRef({fs:e,dir:i,ref:`refs/heads/${B(r.branchName)}`,value:m,force:!0})}},"rmdir")};import nt from"@legit-sdk/isomorphic-git";var ot={type:"gitBranchesListVirtualFile",rootType:"folder",getStats:o(async({gitRoot:n,nodeFs:i})=>{let e=n+"/.git";try{return await i.promises.stat(e)}catch{throw new Error(`ENOENT: no such file or directory, stat '${e}'`)}},"getStats"),getFile:o(async({gitRoot:n,nodeFs:i,filePath:e})=>{try{let t=await nt.listBranches({fs:i,dir:n}),r=await Promise.all(t.map(async s=>{let a=await nt.resolveRef({fs:i,dir:n,ref:s});return T({parent:e,name:M(s),isDir:!0})}));return{type:"directory",content:r,mode:493,size:r}}catch(t){throw t}},"getFile"),rename:o(async n=>{throw new Error("not implemented")},"rename"),mkdir:o(async function(n){throw new Error("not implemented")},"mkdir")};import K from"@legit-sdk/isomorphic-git";function Oe(n){return n&&n.gitCache!==void 0?n.gitCache:n&&n.parentFs?Oe(n.parentFs):{}}o(Oe,"getGitCacheFromFs");var Be={type:"gitBranchHeadVirtualFile",rootType:"file",getStats:o(async({gitRoot:n,nodeFs:i,pathParams:e,userSpaceFs:t})=>{e.branchName===void 0&&(e.branchName=await k(n,i));let r=await b(i,n,e.branchName);if(!r)throw new Error(`Branch ${e.branchName} does not exist in the repository`);let s=await K.readCommit({fs:i,dir:n,oid:r,cache:Oe(t)}),{commit:a}=s,l=a.committer.timestamp*1e3;return{mode:420,size:40,isFile:o(()=>!0,"isFile"),isDirectory:o(()=>!1,"isDirectory"),isSymbolicLink:o(()=>!1,"isSymbolicLink"),isBlockDevice:o(()=>!1,"isBlockDevice"),isCharacterDevice:o(()=>!1,"isCharacterDevice"),isSocket:o(()=>!1,"isSocket"),isFIFO:o(()=>!1,"isFIFO"),isFileSync:o(()=>!0,"isFileSync"),isDirectorySync:o(()=>!1,"isDirectorySync"),dev:0,ino:0,nlink:1,uid:0,gid:0,rdev:0,blksize:4096,blocks:Math.ceil(40/4096),atimeMs:l,mtimeMs:l,ctimeMs:l,birthtimeMs:l,atime:new Date(l),mtime:new Date(l),ctime:new Date(l),birthtime:new Date(l)}},"getStats"),getFile:o(async({gitRoot:n,nodeFs:i,pathParams:e,userSpaceFs:t})=>{e.branchName===void 0&&(e.branchName=await k(n,i));try{let r;try{r=await K.resolveRef({fs:i,dir:n,ref:e.branchName})}catch{r=await K.resolveRef({fs:i,dir:n,ref:`refs/heads/${e.branchName}`})}return{type:"file",content:r+`
5
- `,mode:420,size:r.length}}catch{return}},"getFile"),writeFile:o(async({filePath:n,gitRoot:i,nodeFs:e,content:t,cacheFs:r,pathParams:s,userSpaceFs:a})=>{console.log("gitBranchHeadVirtualFile writeFile called",{pathParams:s,content:t}),s.branchName===void 0&&(s.branchName=await k(i,e));let l=t.toString().trim();try{await K.readCommit({fs:e,dir:i,oid:l,cache:Oe(a)})}catch{throw new Error(`Commit ${l} does not exist in the repository`)}await K.writeRef({fs:e,dir:i,ref:"refs/heads/"+s.branchName,value:l,force:!0})},"writeFile"),rename(n){throw new Error("not implementsd")},mkdir:o(async function(n){throw new Error("not implemented")},"mkdir")};var Te={type:"legitVirtualFile",rootType:"folder",getStats:o(async({gitRoot:n,nodeFs:i})=>{let e=n+"/.git";try{return await i.promises.stat(e)}catch{throw new Error(`ENOENT: no such file or directory, stat '${e}'`)}},"getStats"),getFile:o(async({gitRoot:n,nodeFs:i})=>({type:"directory",content:[],mode:493,size:0}),"getFile"),rename(n){throw new Error("not implemented")},mkdir:o(async function(n){throw new Error("not implemented")},"mkdir")};import Ce from"@legit-sdk/isomorphic-git";function ae(n){return n&&n.gitCache!==void 0?n.gitCache:n&&n.parentFs?ae(n.parentFs):{}}o(ae,"getGitCacheFromFs");var at={type:"gitCommitFileVirtualFile",rootType:"file",getStats:o(async({filePath:n,gitRoot:i,nodeFs:e,pathParams:t,userSpaceFs:r})=>{if(!t.sha_1_1_2)throw new Error("sha_1_1_2 should be in pathParams");if(!t.sha1_3__40)throw new Error("sha1_3__40 should be in pathParams");let s=t.sha_1_1_2+t.sha1_3__40,a=await j({filePath:n,gitRoot:i,nodeFs:e,commitSha:s,pathParams:t,gitCache:ae(r)});if(!a)throw new _(`ENOENT: no such file or directory, stat '${n}'`,n);let l=await Ce.readCommit({fs:e,dir:i,oid:s}),{commit:c}=l,m=c.committer.timestamp*1e3;if(a.type==="tree")return{mode:420,size:0,isFile:o(()=>!0,"isFile"),isDirectory:o(()=>!0,"isDirectory"),isSymbolicLink:o(()=>!1,"isSymbolicLink"),isBlockDevice:o(()=>!1,"isBlockDevice"),isCharacterDevice:o(()=>!1,"isCharacterDevice"),isSocket:o(()=>!1,"isSocket"),isFIFO:o(()=>!1,"isFIFO"),isFileSync:o(()=>!0,"isFileSync"),isDirectorySync:o(()=>!1,"isDirectorySync"),dev:0,ino:0,nlink:1,uid:0,gid:0,rdev:0,blksize:4096,blocks:0,atimeMs:m,mtimeMs:m,ctimeMs:m,birthtimeMs:m,atime:new Date(m),mtime:new Date(m),ctime:new Date(m),birthtime:new Date(m)};{let{blob:d}=await Ce.readBlob({fs:e,dir:i,oid:a.oid});return{mode:420,size:d.length,isFile:o(()=>!0,"isFile"),isDirectory:o(()=>!1,"isDirectory"),isSymbolicLink:o(()=>!1,"isSymbolicLink"),isBlockDevice:o(()=>!1,"isBlockDevice"),isCharacterDevice:o(()=>!1,"isCharacterDevice"),isSocket:o(()=>!1,"isSocket"),isFIFO:o(()=>!1,"isFIFO"),isFileSync:o(()=>!0,"isFileSync"),isDirectorySync:o(()=>!1,"isDirectorySync"),dev:0,ino:0,nlink:1,uid:0,gid:0,rdev:0,blksize:4096,blocks:Math.ceil(d.length/4096),atimeMs:m,mtimeMs:m,ctimeMs:m,birthtimeMs:m,atime:new Date(m),mtime:new Date(m),ctime:new Date(m),birthtime:new Date(m)}}},"getStats"),getFile:o(async({filePath:n,gitRoot:i,nodeFs:e,pathParams:t,userSpaceFs:r})=>{if(!t.sha_1_1_2)throw new Error("sha_1_1_2 should be in pathParams");if(!t.sha1_3__40)throw new Error("sha1_3__40 should be in pathParams");let s=t.sha_1_1_2+t.sha1_3__40;try{let a=await j({filePath:n,gitRoot:i,nodeFs:e,commitSha:s,pathParams:t,gitCache:ae(r)});if(!a)return;if(a.type==="blob"){let{blob:l}=await Ce.readBlob({fs:e,dir:i,oid:a.oid,cache:ae(r)});return{type:"file",content:Buffer.from(l),mode:420,size:l.length,oid:a.oid}}else return{type:"directory",content:Array.from(new Set([...a.entries.filter(c=>c.name!==".keep")])).map(c=>({...c,name:c.name.toString(),path:`${n}`,parentPath:`${n}`})),mode:493}}catch{return}},"getFile"),rename(n){throw new Error("not implementsd")},mkdir:o(async function(n){throw new Error("not implemented")},"mkdir")};import Ne from"@legit-sdk/isomorphic-git";var He={type:"gitCommitVirtualFolder",rootType:"folder",getStats:o(async n=>{let i=n.gitRoot+"/.git";try{return await n.nodeFs.promises.stat(i)}catch{throw new Error(`ENOENT: no such file or directory, stat '${i}'`)}},"getStats"),getFile:o(async({filePath:n,gitRoot:i,nodeFs:e,pathParams:t})=>{let r=await Ne.listBranches({fs:e,dir:i}),s=new Set,a=new Set;for(let m of r){let d=`refs/heads/${m}`;try{let f=await Ne.resolveRef({fs:e,dir:i,ref:d});s.add(f)}catch{}}for(let m of s){let d=await Ne.log({fs:e,dir:i,ref:m});for(let f of d)a.add(f.oid)}if(!t.sha_1_1_2){let m=new Set;for(let f of a)if(m.add(f.slice(0,2)),m.size>=256)break;let d=Array.from(m).sort().map(f=>T({parent:n,name:f,isDir:!0}));return{type:"directory",content:d,mode:493,size:d}}let l=new Set;for(let m of a)m.startsWith(t.sha_1_1_2)&&l.add(m.slice(2,40));let c=Array.from(l).sort().map(m=>T({parent:n,name:m,isDir:!0}));return{type:"directory",content:c,mode:493,size:c.length}},"getFile"),rename(n){throw new Error("not implementsd")},mkdir:o(async function(n){throw new Error("not implemented")},"mkdir")};import A from"@legit-sdk/isomorphic-git";var Le={type:"gitBranchOperationVirtualFile",rootType:"file",getStats:o(async n=>{let{gitRoot:i,nodeFs:e,pathParams:t}=n;t.branchName===void 0&&(t.branchName=await k(i,e));let r=await b(e,i,t.branchName);if(!r)throw new Error(`Base Branch ${t.branchName} for operations does not exis`);let s=await C(e,i,t.branchName),a=!1;if(s)try{r=await A.resolveRef({fs:e,dir:i,ref:s}),a=!0}catch{try{r=await A.resolveRef({fs:e,dir:i,ref:`refs/heads/${s}`}),a=!0}catch{}}let l=await A.readCommit({fs:e,dir:i,oid:r}),{commit:c}=l,m=c.committer.timestamp*1e3;try{return{mode:420,size:40,atimeMs:m,mtimeMs:m,ctimeMs:m,birthtimeMs:m,atime:new Date(m),mtime:new Date(m),ctime:new Date(m),birthtime:new Date(m),isFile:o(()=>!0,"isFile"),isDirectory:o(()=>!1,"isDirectory"),isSymbolicLink:o(()=>!1,"isSymbolicLink"),isBlockDevice:o(()=>!1,"isBlockDevice"),isCharacterDevice:o(()=>!1,"isCharacterDevice"),isSocket:o(()=>!1,"isSocket"),isFIFO:o(()=>!1,"isFIFO"),isFileSync:o(()=>!0,"isFileSync"),isDirectorySync:o(()=>!1,"isDirectorySync"),dev:0,ino:0,nlink:1,uid:0,gid:0,rdev:0,blksize:4096,blocks:0}}catch{throw new Error("ENOENT: no such file or directory, stat operationHistory")}},"getStats"),getFile:o(async n=>{let{gitRoot:i,nodeFs:e,pathParams:t}=n;t.branchName===void 0&&(t.branchName=await k(i,e));let r=await C(e,i,t.branchName),s,a=!1;if(r){if(s=await b(e,i,r),a=!0,!s)throw new Error(`Base Branch ${r} for operations does not exis`)}else if(s=await b(e,i,t.branchName),!s)throw new Error(`Base Branch ${t.branchName} for operations does not exis`);return{type:"file",content:Buffer.from(s),mode:420,size:s.length}},"getFile"),writeFile:o(async({filePath:n,gitRoot:i,nodeFs:e,content:t,cacheFs:r,pathParams:s,author:a})=>{s.branchName===void 0&&(s.branchName=await k(i,e));let l;typeof t=="string"?l=new TextEncoder().encode(t):l=new Uint8Array(t);let c=await A.writeBlob({fs:e,dir:i,blob:l}),m=await b(e,i,s.branchName);if(!m)throw new Error("Invalid branch file path - branch doesn't exist");let d=await C(e,i,s.branchName),f=!1;d||(d="legit/__"+s.branchName+De,await A.branch({fs:e,dir:i,ref:d,object:m}),f=!0);let h=await A.resolveRef({fs:e,dir:i,ref:`refs/heads/${d}`}),F=await A.readTree({fs:e,dir:i,oid:m}),u;t instanceof ArrayBuffer?u=Buffer.from(t).toString("utf-8"):typeof t=="string"?u=t:t instanceof Uint8Array?u=Buffer.from(t).toString("utf-8"):u=String(t);let v=!1;if(!f){let y=await A.findMergeBase({fs:e,dir:i,oids:v?[h]:[h,m]});y.length===1&&y[0]===m&&(v=!0)}let O=await A.commit({fs:e,dir:i,message:u,tree:F.oid,noUpdateBranch:!0,author:a,parent:v?f?[m,m]:[h]:[h,m]});await A.writeRef({fs:e,dir:i,ref:`refs/heads/${d}`,value:O,force:!0})},"writeFile"),rename:o(async function({filePath:n,newPath:i,gitRoot:e,nodeFs:t,pathParams:r,newPathParams:s}){throw new Error("not implemented")},"rename"),mkdir:o(async function(n){throw new Error("not implemented")},"mkdir")};import le from"@legit-sdk/isomorphic-git";var lt={type:"getThreadName",rootType:"file",getStats:o(async n=>{let{gitRoot:i,nodeFs:e,pathParams:t}=n,r=await b(e,i,t.branchName);if(!r)throw new Error(`Base Branch ${t.branchName} for operations does not exis`);let s=await C(e,i,t.branchName),a=!1;if(s)try{r=await le.resolveRef({fs:e,dir:i,ref:s}),a=!0}catch{try{r=await le.resolveRef({fs:e,dir:i,ref:`refs/heads/${s}`}),a=!0}catch{}}let l=await le.readCommit({fs:e,dir:i,oid:r}),{commit:c}=l,m=c.committer.timestamp*1e3;try{return{mode:420,size:40,atimeMs:m,mtimeMs:m,ctimeMs:m,birthtimeMs:m,atime:new Date(m),mtime:new Date(m),ctime:new Date(m),birthtime:new Date(m),isFile:o(()=>!0,"isFile"),isDirectory:o(()=>!1,"isDirectory"),isSymbolicLink:o(()=>!1,"isSymbolicLink"),isBlockDevice:o(()=>!1,"isBlockDevice"),isCharacterDevice:o(()=>!1,"isCharacterDevice"),isSocket:o(()=>!1,"isSocket"),isFIFO:o(()=>!1,"isFIFO"),isFileSync:o(()=>!0,"isFileSync"),isDirectorySync:o(()=>!1,"isDirectorySync"),dev:0,ino:0,nlink:1,uid:0,gid:0,rdev:0,blksize:4096,blocks:0}}catch{throw new Error("ENOENT: no such file or directory, stat operationHistory")}},"getStats"),getFile:o(async n=>{let{gitRoot:i,nodeFs:e,pathParams:t}=n,r=await C(e,i,t.branchName),s;if(r){let a="legit/",l=`__${t.branchName}-operation`;return r.startsWith(a)&&r.endsWith(l)?s=r.slice(a.length,r.length-l.length):s=r,{type:"file",content:Buffer.from(Ke(s)),mode:420,size:s.length}}return{type:"file",content:Buffer.from(""),mode:420,size:0}},"getFile"),writeFile:o(async({filePath:n,gitRoot:i,nodeFs:e,content:t,cacheFs:r,pathParams:s})=>{if(s.branchName===void 0)throw new Error("branchName should be in pathParams");let a=await C(e,i,s.branchName);if(a){let l=`legit/${Je(t.toString())}__${s.branchName}-operation`;await le.renameBranch({fs:e,dir:i,oldref:a,ref:l}),a=l}},"writeFile"),rename:o(async function({filePath:n,newPath:i,gitRoot:e,nodeFs:t,pathParams:r,newPathParams:s}){throw new Error("not implemented")},"rename"),mkdir:o(async function(n){throw new Error("not implemented")},"mkdir")};import mt from"@legit-sdk/isomorphic-git";var Ie={type:"gitBranchHistory",rootType:"file",getStats:o(async({gitRoot:n,nodeFs:i,pathParams:e})=>{e.branchName===void 0&&(e.branchName=await k(n,i));let t=await b(i,n,e.branchName);if(!t)throw new Error(`Branch ${e.branchName} does not exist`);let r=await mt.readCommit({fs:i,dir:n,oid:t}),{commit:s}=r,a=s.committer.timestamp*1e3;return{mode:420,size:1e5,isFile:o(()=>!0,"isFile"),isDirectory:o(()=>!1,"isDirectory"),isSymbolicLink:o(()=>!1,"isSymbolicLink"),isBlockDevice:o(()=>!1,"isBlockDevice"),isCharacterDevice:o(()=>!1,"isCharacterDevice"),isSocket:o(()=>!1,"isSocket"),isFIFO:o(()=>!1,"isFIFO"),isFileSync:o(()=>!0,"isFileSync"),isDirectorySync:o(()=>!1,"isDirectorySync"),dev:0,ino:0,nlink:1,uid:0,gid:0,rdev:0,blksize:4096,blocks:Math.ceil(40/4096),atimeMs:a,mtimeMs:a,ctimeMs:a,birthtimeMs:a,atime:new Date(a),mtime:new Date(a),ctime:new Date(a),birthtime:new Date(a)}},"getStats"),getFile:o(async n=>{let{gitRoot:i,nodeFs:e,pathParams:t}=n,r=t.branchName;r===void 0&&(r=await k(i,e));let s=[];if(r){let l=await b(e,i,r),c=!1,m=l;for(;m&&!c;){let d=await mt.readCommit({fs:e,dir:i,oid:m});s.push({oid:d.oid,...d.commit}),m=d.commit.parent[0]}}let a=Buffer.from(JSON.stringify(s,null,2),"utf-8");return{type:"file",content:a,mode:420,size:a.length}},"getFile"),rename:o(async n=>{throw new Error("not implemented")},"rename"),mkdir:o(async function(n){throw new Error("not implemented")},"mkdir")};import V from"@legit-sdk/isomorphic-git";var Ae={type:"gitBranchOperationHeadVirtualFile",rootType:"file",getStats:o(async({gitRoot:n,nodeFs:i,pathParams:e})=>{e.branchName===void 0&&(e.branchName=await k(n,i));let t=await C(i,n,e.branchName);if(!t){let c=new Date(0);return{mode:420,size:0,isFile:o(()=>!0,"isFile"),isDirectory:o(()=>!1,"isDirectory"),isSymbolicLink:o(()=>!1,"isSymbolicLink"),isBlockDevice:o(()=>!1,"isBlockDevice"),isCharacterDevice:o(()=>!1,"isCharacterDevice"),isSocket:o(()=>!1,"isSocket"),isFIFO:o(()=>!1,"isFIFO"),isFileSync:o(()=>!0,"isFileSync"),isDirectorySync:o(()=>!1,"isDirectorySync"),dev:0,ino:0,nlink:1,uid:0,gid:0,rdev:0,blksize:4096,blocks:Math.ceil(40/4096),atimeMs:c.getTime(),mtimeMs:c.getTime(),ctimeMs:c.getTime(),birthtimeMs:c.getTime(),atime:c,mtime:c,ctime:c,birthtime:c}}let r;try{r=await V.resolveRef({fs:i,dir:n,ref:t})}catch{r=await V.resolveRef({fs:i,dir:n,ref:`refs/heads/${t}`})}let s=await V.readCommit({fs:i,dir:n,oid:r}),{commit:a}=s,l=a.committer.timestamp*1e3;return{mode:420,size:40,isFile:o(()=>!0,"isFile"),isDirectory:o(()=>!1,"isDirectory"),isSymbolicLink:o(()=>!1,"isSymbolicLink"),isBlockDevice:o(()=>!1,"isBlockDevice"),isCharacterDevice:o(()=>!1,"isCharacterDevice"),isSocket:o(()=>!1,"isSocket"),isFIFO:o(()=>!1,"isFIFO"),isFileSync:o(()=>!0,"isFileSync"),isDirectorySync:o(()=>!1,"isDirectorySync"),dev:0,ino:0,nlink:1,uid:0,gid:0,rdev:0,blksize:4096,blocks:Math.ceil(40/4096),atimeMs:l,mtimeMs:l,ctimeMs:l,birthtimeMs:l,atime:new Date(l),mtime:new Date(l),ctime:new Date(l),birthtime:new Date(l)}},"getStats"),getFile:o(async({gitRoot:n,nodeFs:i,pathParams:e})=>{e.branchName===void 0&&(e.branchName=await k(n,i));let t=await C(i,n,e.branchName);if(!t)return{type:"file",content:"",mode:420,size:0};try{let r;try{r=await V.resolveRef({fs:i,dir:n,ref:t})}catch{r=await V.resolveRef({fs:i,dir:n,ref:`refs/heads/${t}`})}return{type:"file",content:r+`
6
- `,mode:420,size:r.length}}catch{return}},"getFile"),writeFile:o(async({filePath:n,gitRoot:i,nodeFs:e,content:t,cacheFs:r,pathParams:s})=>{s.branchName===void 0&&(s.branchName=await k(i,e));let a=await C(e,i,s.branchName),l=await V.resolveRef({fs:e,dir:i,ref:`refs/heads/${a}`});if(!a)throw new Error(`Operation branch name could not be resolved for branch ${s.branchName}`);let c=t.toString().trim(),m,d,f=!1;if(!l)throw new Error(`Operation branch ref could not be resolved for branch ${a}`);let h=l;for(;h&&!f;){let F=await V.readCommit({fs:e,dir:i,oid:h});if(F.oid===c&&(m=F.oid),h=F.commit.parent&&F.commit.parent.length>0?F.commit.parent[0]:null,F.commit.parent.length===2){if(F.commit.parent[0]===F.commit.parent[1])f=!0;else if(m!==void 0){d=F.commit.parent[1];break}}}if(m===void 0)throw new Error(`Cant rollback to ${c} couldn't find newOperationBranchHead ${m}`);if(d===void 0)throw new Error(`Cant rollback to ${c} couldn't find newBranchHead ${d}`);await V.writeRef({fs:e,dir:i,ref:"refs/heads/"+a,value:m,force:!0}),await V.writeRef({fs:e,dir:i,ref:"refs/heads/"+s.branchName,value:d,force:!0})},"writeFile"),rename(n){throw new Error("not implementsd")},mkdir:o(async function(n){throw new Error("not implemented")},"mkdir")};import Ct from"@legit-sdk/isomorphic-git";import Re from"@legit-sdk/isomorphic-git";async function q(n,i){try{let e=await Re.getConfig({fs:i,dir:n,path:"user.legit-target-branch"});if(e)return M(e)}catch{}try{let e=await Re.getConfig({fs:i,dir:n,path:"init.defaultBranch"});return M(e)||"main"}catch{return"main"}}o(q,"getTargetBranch");async function ct(n,i,e){await Re.setConfig({fs:i,dir:n,path:"user.legit-target-branch",value:B(e)})}o(ct,"setTargetBranch");var dt={type:"gitCurrentBranchVirtualFile",rootType:"file",getStats:o(async({gitRoot:n,nodeFs:i})=>{let t=(await k(n,i)).length;return{mode:420,size:t,isFile:o(()=>!0,"isFile"),isDirectory:o(()=>!1,"isDirectory"),isSymbolicLink:o(()=>!1,"isSymbolicLink"),isBlockDevice:o(()=>!1,"isBlockDevice"),isCharacterDevice:o(()=>!1,"isCharacterDevice"),isSocket:o(()=>!1,"isSocket"),isFIFO:o(()=>!1,"isFIFO"),isFileSync:o(()=>!0,"isFileSync"),isDirectorySync:o(()=>!1,"isDirectorySync"),dev:0,ino:0,nlink:1,uid:0,gid:0,rdev:0,blksize:4096,blocks:Math.ceil(t/4096),atimeMs:Date.now(),mtimeMs:Date.now(),ctimeMs:Date.now(),birthtimeMs:Date.now(),atime:new Date,mtime:new Date,ctime:new Date,birthtime:new Date}},"getStats"),getFile:o(async({gitRoot:n,nodeFs:i})=>{let e=await k(n,i);return{type:"file",content:e+`
7
- `,mode:420,size:e.length+1}},"getFile"),writeFile:o(async({gitRoot:n,nodeFs:i,content:e})=>{let t=e.toString().trim();if(!await b(i,n,t)){let s=await q(n,i),a=await b(i,n,s);if(!a)throw new Error(`Ref branch ${s} does not exist in the repository`);await Ct.branch({fs:i,dir:n,ref:B(t),object:a})}await Qe(n,i,t)},"writeFile"),rename(n){throw new Error("not implemented")},mkdir:o(async function(n){throw new Error("not implemented")},"mkdir")};var R="session_data",me=JSON.stringify({env:{CLAUDE_CONFIG_DIR:`.claude/${R}`}},null,2),ft={type:"claudeVirtualSessionFileVirtualFile",rootType:"folder",getStats:o(async({gitRoot:n,nodeFs:i,filePath:e,cacheFs:t,pathParams:r})=>{let s=e.replace(/\\/g,"/");if(s.endsWith(".claude")||s.endsWith(`.claude/${R}`)||s.endsWith(`.claude/${R}/debug`)||s.endsWith(`.claude/${R}/projects`)||new RegExp(`\\.claude\\/${R}\\/projects\\/[^/]+$`).test(s)){let c=new Date(0);return{mode:16877,size:0,isFile:o(()=>!1,"isFile"),isDirectory:o(()=>!0,"isDirectory"),isSymbolicLink:o(()=>!1,"isSymbolicLink"),isBlockDevice:o(()=>!1,"isBlockDevice"),isCharacterDevice:o(()=>!1,"isCharacterDevice"),isSocket:o(()=>!1,"isSocket"),isFIFO:o(()=>!1,"isFIFO"),dev:0,ino:0,nlink:1,uid:0,gid:0,rdev:0,blksize:4096,blocks:0,atimeMs:0,mtimeMs:0,ctimeMs:0,birthtimeMs:0,atime:c,mtime:c,ctime:c,birthtime:c}}let a=new Date(0);return s.endsWith(".claude/settings.json")?{mode:420,size:me.length,isFile:o(()=>!0,"isFile"),isDirectory:o(()=>!1,"isDirectory"),isSymbolicLink:o(()=>!1,"isSymbolicLink"),isBlockDevice:o(()=>!1,"isBlockDevice"),isCharacterDevice:o(()=>!1,"isCharacterDevice"),isSocket:o(()=>!1,"isSocket"),isFIFO:o(()=>!1,"isFIFO"),isFileSync:o(()=>!0,"isFileSync"),isDirectorySync:o(()=>!1,"isDirectorySync"),dev:0,ino:0,nlink:1,uid:0,gid:0,rdev:0,blksize:4096,blocks:Math.ceil(me.length/4096),atimeMs:a,mtimeMs:a,ctimeMs:a,birthtimeMs:a,atime:a,mtime:a,ctime:a,birthtime:a}:await t.promises.stat(e)},"getStats"),getFile:o(async({filePath:n,gitRoot:i,nodeFs:e,cacheFs:t,pathParams:r})=>{let s=n.replace(/\\/g,"/");if((s.endsWith(".claude")||s.endsWith(".claude/session_data")||s.endsWith(".claude/session_data/projects")||s.endsWith(".claude/session_data/debug")||/\.claude\/session_data\/projects\/[^/]+$/.test(s))&&await t.promises.mkdir(n,{recursive:!0}),s.endsWith(".claude/settings.json"))return{type:"file",content:me,mode:420,size:me.length,oid:"unknown"};try{if((await t.promises.stat(n)).isFile()){let l=await t.promises.readFile(n);return{type:"file",content:l,mode:420,size:l.length,oid:"unknown"}}else{let l=await t.promises.readdir(n,{withFileTypes:!0});if(s.endsWith(".claude")){let c=l.find(d=>d.name.toString()==="settings.json");c||l.push(T({name:"settings.json",parent:n,isDir:!1}));let m=l.find(d=>d.name.toString()===R);c||l.push(T({name:R,parent:n,isDir:!0}))}if(s.endsWith(`.claude/${R}`)&&(l.find(m=>m.name.toString()==="projects")||l.push(T({name:"projects",parent:n,isDir:!0}))),s.endsWith(`.claude/${R}/projects`)&&!l.find(m=>m.name.toString()==="projects")){let m=s.replace(`.claude/${R}/projects`,"");l.push(T({name:m.replaceAll("/","-"),parent:n,isDir:!0}))}return{type:"directory",content:l.map(c=>({...c,name:c.name.toString(),path:`${n}`,parentPath:`${n}`})),mode:493}}}catch{return}},"getFile"),unlink:o(async({filePath:n,gitRoot:i,nodeFs:e,cacheFs:t,pathParams:r,author:s})=>{await t.promises.unlink(n)},"unlink"),writeFile:o(async({filePath:n,gitRoot:i,nodeFs:e,content:t,cacheFs:r,userSpaceFs:s,pathParams:a,author:l})=>{let c=n.replace(/\\/g,"/"),m=/\/projects\/([^/]+)\/([^/]+\.jsonl)$/,d=c.match(m);if(d){let f=d[1],h=d[2];console.log({folder:f,file:h}),await r.promises.stat(n).then(()=>!0).catch(()=>!1)||await r.promises.writeFile(n,"");let v=(await r.promises.readFile(n,"utf-8")).split(`
8
- `);if(v.length>1){let O=v[v.length-2]||"",y=JSON.parse(O),g="";if(y.type==="user"){let w=y.message?.content;if(Array.isArray(w)&&w[0]?.type==="tool_result"){let D=w[0],S=typeof D.content=="string"?D.content:JSON.stringify(D.content);g=`\u{1F47E} Tool Result (${y.toolUseResult?.type||"unknown"}): ${S}
9
-
10
- ---
11
-
12
- `}else g=`\u{1F464} ${typeof w=="string"?w:w?.[0]?.content||"User action"}
13
-
14
- ---
15
-
16
- `}else if(y.type==="assistant"){let w=y.message?.content?.[0],P="";w?.type==="text"?P=w.text:w?.type==="tool_use"?P=`Used tool: ${w.name} with input: ${JSON.stringify(w.input)}`:P="Assistant response",g=`\u{1F47E} ${P}
17
-
18
- ---
19
-
20
- `}else y.type==="file-history-snapshot"?g=`System: File history snapshot for message ${y.messageId}
21
-
22
- ---
23
-
24
- `:g=`System: ${y.type||"unknown action"}
25
-
26
- ---
27
-
28
- `;await s.promises.writeFile(i+"/.legit/operation",g+O)}}else console.log("No match"),await r.promises.writeFile(n,t)},"writeFile"),rename:o(async function({filePath:n,newPath:i,gitRoot:e,nodeFs:t,pathParams:r,newPathParams:s,author:a,cacheFs:l}){await l.promises.rename(n,i)},"rename"),mkdir:o(async function(n){await n.cacheFs.promises.mkdir(n.filePath,{recursive:!0})},"mkdir"),rmdir:o(async({filePath:n,gitRoot:i,nodeFs:e,cacheFs:t,pathParams:r,author:s})=>{},"rmdir")};import G from"@legit-sdk/isomorphic-git";function $e(n){return n&&n.gitCache!==void 0?n.gitCache:n&&n.parentFs?$e(n.parentFs):{}}o($e,"getGitCacheFromFs");var ht={type:"gitApplyCurrentChangesToVirtualFile",rootType:"file",getStats:o(async({gitRoot:n,nodeFs:i,pathParams:e,userSpaceFs:t})=>{let r=new Date(0);return{mode:420,size:40,isFile:o(()=>!0,"isFile"),isDirectory:o(()=>!1,"isDirectory"),isSymbolicLink:o(()=>!1,"isSymbolicLink"),isBlockDevice:o(()=>!1,"isBlockDevice"),isCharacterDevice:o(()=>!1,"isCharacterDevice"),isSocket:o(()=>!1,"isSocket"),isFIFO:o(()=>!1,"isFIFO"),isFileSync:o(()=>!0,"isFileSync"),isDirectorySync:o(()=>!1,"isDirectorySync"),dev:0,ino:0,nlink:1,uid:0,gid:0,rdev:0,blksize:4096,blocks:Math.ceil(40/4096),atimeMs:r,mtimeMs:r,ctimeMs:r,birthtimeMs:r,atime:r,mtime:r,ctime:r,birthtime:r}},"getStats"),getFile:o(async({gitRoot:n,nodeFs:i,pathParams:e,userSpaceFs:t})=>{try{return{type:"file",content:`
29
- `,mode:420,size:2}}catch{return}},"getFile"),writeFile:o(async({gitRoot:n,nodeFs:i,content:e,userSpaceFs:t,author:r})=>{let s=await k(n,i),a=e.toString().trim(),l=await b(i,n,s,$e(t));if(!l)throw new Error(`Source branch ${s} does not exist`);let c=await b(i,n,a,$e(t));if(!c)throw new Error(`Target branch ${a} does not exist`);let m=await G.readTree({fs:i,dir:n,oid:l});if(await G.readTree({fs:i,dir:n,oid:c})===m)return;let f=await G.commit({fs:i,dir:n,message:"Changes from "+s+" applied to "+a,tree:m.oid,noUpdateBranch:!0,author:r,parent:[l,c]}),h=await G.commit({fs:i,dir:n,message:"Changes from "+s+" applied to "+a,tree:m.oid,noUpdateBranch:!0,author:r,parent:[l,f]});await G.writeRef({fs:i,dir:n,ref:"refs/heads/"+B(a),value:f,force:!0}),await G.writeRef({fs:i,dir:n,ref:"refs/heads/"+B(s),value:h,force:!0})},"writeFile"),rename(n){throw new Error("not implementsd")},mkdir:o(async function(n){throw new Error("not implemented")},"mkdir")};var pt={type:"gitTargetBranchVirtualFile",rootType:"file",getStats:o(async({gitRoot:n,nodeFs:i})=>{let t=(await q(n,i)).length;return{mode:420,size:t,isFile:o(()=>!0,"isFile"),isDirectory:o(()=>!1,"isDirectory"),isSymbolicLink:o(()=>!1,"isSymbolicLink"),isBlockDevice:o(()=>!1,"isBlockDevice"),isCharacterDevice:o(()=>!1,"isCharacterDevice"),isSocket:o(()=>!1,"isSocket"),isFIFO:o(()=>!1,"isFIFO"),isFileSync:o(()=>!0,"isFileSync"),isDirectorySync:o(()=>!1,"isDirectorySync"),dev:0,ino:0,nlink:1,uid:0,gid:0,rdev:0,blksize:4096,blocks:Math.ceil(t/4096),atimeMs:Date.now(),mtimeMs:Date.now(),ctimeMs:Date.now(),birthtimeMs:Date.now(),atime:new Date,mtime:new Date,ctime:new Date,birthtime:new Date}},"getStats"),getFile:o(async({gitRoot:n,nodeFs:i})=>{let e=await q(n,i);return{type:"file",content:e+`
30
- `,mode:420,size:e.length+1}},"getFile"),writeFile:o(async({gitRoot:n,nodeFs:i,content:e})=>{let t=e.toString().trim();if(!await b(i,n,t))throw new Error(`Branch ${t} does not exist in the repository`);await ct(n,i,t)},"writeFile"),rename(n){throw new Error("not implemented")},mkdir:o(async function(n){throw new Error("not implemented")},"mkdir")};function xe(n){return n&&n.gitCache!==void 0?n.gitCache:n&&n.parentFs?xe(n.parentFs):{}}o(xe,"getGitCache");async function hn(n){let i=new Ht,e=Nt(i);return Lt({...n,storageFs:n?.storageFs?n.storageFs:e,gitRoot:n?.gitRoot||"/"})}o(hn,"openLegitFsWithMemoryFs");async function Lt({storageFs:n,gitRoot:i,anonymousBranch:e="anonymous",showKeepFiles:t=!1,initialAuthor:r={type:"local",id:"local",name:"Local User",email:"local@legitcontrol.com"},serverUrl:s="https://hub.legitcontrol.com",publicKey:a,claudeHandler:l}){await n.promises.readdir(i+"/.git").then(()=>!0).catch(()=>!1)||(await N.init({fs:n,dir:"/",defaultBranch:e}),await n.promises.writeFile(i+"/.gitignore",""),await n.promises.writeFile(i+"/.keep",""),await N.add({fs:n,dir:"/",filepath:".keep",cache:xe(n)}),await N.commit({fs:n,dir:"/",message:"Initial commit",author:{name:"Test",email:"test@example.com"},cache:xe(n)}),await N.setConfig({fs:n,dir:i,path:"init.defaultBranch",value:e})),await N.getConfig({fs:n,dir:i,path:"user.legit_user_id"})||await N.setConfig({fs:n,dir:i,path:"user.legit_user_id",value:r.name}),await N.getConfig({fs:n,dir:i,path:"user.name"})||await N.setConfig({fs:n,dir:i,path:"user.name",value:r.name}),await N.getConfig({fs:n,dir:i,path:"user.email"})||await N.setConfig({fs:n,dir:i,path:"user.email",value:r.email});let h=new Q({name:"git",storageFs:n,gitRoot:i,defaultBranch:e});h.gitCache={};let F={".legit":{".":Te,operation:Le,head:Be,operationHead:Ae,operationHistory:re,history:Ie,currentBranch:dt,"target-branch":pt,"apply-changes":ht,branches:{".":ot,"[branchName]":{".legit":{".":Te,operation:Le,head:Be,operationHead:Ae,operationHistory:re,history:Ie,threadName:lt},"[[...filePath]]":oe}},commits:{".":He,"[sha_1_1_2]":{".":He,"[sha1_3__40]":{"[[...filePath]]":at}}}},".claude":{"[[...filePath]]":ft},"[[...filePath]]":oe};!l&&F[".claude"]&&delete F[".claude"];let u=new ie({name:"git-subfs",parentFs:h,gitRoot:i,gitStorageFs:n,routerConfig:F}),v=t?[".git"]:[".git",".keep"],O=new Y({name:"git-hidden-subfs",parentFs:h,gitRoot:i,hiddenFiles:v}),y=new ee({name:"git-ephemeral-subfs",parentFs:h,gitRoot:i,ephemeralPatterns:["**/._*","**/.DS_Store","**/.AppleDouble/","**/.AppleDB","**/.AppleDesktop","**/.Spotlight-V100","**/.TemporaryItems","**/.Trashes","**/.fseventsd","**/.VolumeIcon.icns","**/.ql_disablethumbnails","**/.~lock.*","**/lu[0-9a-zA-Z]*.tmp","**/.metaentries.json.tmp","**/**.tmp.**","**/**.sb-**"]});h.addSubFs(u),h.setHiddenFilesSubFs(O),h.setEphemeralFilesSubFs(y);let g=st({storageFs:n,gitRoot:i}),w=Ze(g,a),P=Ye({fs:n,gitRepoPath:i,serverUrl:s,auth:w,anonymousBranch:e}),D=Object.assign(h,{auth:w,sync:P,setLogger(S){h.setLoggger(S)},push:o(async S=>{},"push"),shareCurrentBranch:o(async()=>{if((await w.getUser()).type==="local")throw new Error("login first - for example anonymously using legitfs.auth.signInAnonymously()");let S=await D.getCurrentBranch();return S===e&&(S=(await w.getUser()).id,await N.renameBranch({fs:n,dir:i,oldref:e,ref:S})),await P.sequentialPush([S]),D.setCurrentBranch(S),S},"shareCurrentBranch"),setCurrentBranch:o(async S=>{(await N.listBranches({fs:n,dir:i})).includes(S)||await P?.loadBranch(S);let fe=(await N.listBranches({fs:n,dir:i})).includes(S);if(console.log("branchExistsAfter",fe),!fe)throw new Error(`Branch ${S} does not exist`);await N.setConfig({fs:n,dir:i,path:"init.defaultBranch",value:S})},"setCurrentBranch"),getCurrentBranch:o(async()=>{let S=await N.getConfig({fs:n,dir:i,path:"init.defaultBranch"});if(!S)throw new Error("No current branch set");return S},"getCurrentBranch")});return D}o(Lt,"openLegitFs");var Fn=o(n=>async i=>{if(!i.path.includes(".legit/branches/")||(i.path.match(/\.legit/g)||[]).length>1)return;let[e,t]=i.path.split(".legit/branches/"),[r,...s]=t.split("/"),a=s.join("/"),l=e+".legit/branches/"+r+"/.legit/operation",c=JSON.stringify(i.operationArgs,(m,d)=>Buffer.isBuffer(d)?{__buffer__:d.toString("base64")}:d);console.log(l,`[${i.fsName}].${i.operation}(${i.fd?i.fd.fd+" - ":""}${i.path})
31
-
32
- ${c}
33
-
34
- `)},"createFsOperationFileLogger");export{Q as CompositeFs,ee as EphemeralSubFs,ie as GitSubFs,Y as HiddenFileSubFs,_e as PassThroughSubFs,Fn as createFsOperationFileLogger,Ye as createLegitSyncService,re as gitBranchOperationsVirtualFile,Lt as openLegitFs,hn as openLegitFsWithMemoryFs};
3
+ var Qi=Object.defineProperty;var oa=(t,i,e)=>i in t?Qi(t,i,{enumerable:!0,configurable:!0,writable:!0,value:e}):t[i]=e;var c=(t,i)=>Qi(t,"name",{value:i,configurable:!0});var g=(t,i,e)=>oa(t,typeof i!="symbol"?i+"":i,e);var Xt=class Xt{constructor(i,e){g(this,"entries",[]);g(this,"currentIndex",0);g(this,"closed",!1);g(this,"compositFs");g(this,"dirPath");g(this,"initialized",!1);this.compositFs=i,this.dirPath=e}async initialize(){if(this.initialized)return;let i=new Set;for(let e of[...this.compositFs.filterLayers].reverse())if(e.readDirFiltering)i=new Set(await e.readDirFiltering(this.dirPath,Array.from(i)));else{let r=await e.readdir(this.dirPath);for(let n of r)i.add(n)}this.initialized=!0}async*[Symbol.asyncIterator](){for(await this.initialize();this.currentIndex<this.entries.length&&!this.closed;){let i=this.entries[this.currentIndex++];try{let e=await this.compositFs.stat(i.path);yield{name:i.name,isFile:c(()=>e.isFile(),"isFile"),isDirectory:c(()=>e.isDirectory(),"isDirectory"),isBlockDevice:c(()=>e.isBlockDevice(),"isBlockDevice"),isCharacterDevice:c(()=>e.isCharacterDevice(),"isCharacterDevice"),isSymbolicLink:c(()=>e.isSymbolicLink(),"isSymbolicLink"),isFIFO:c(()=>e.isFIFO(),"isFIFO"),isSocket:c(()=>e.isSocket(),"isSocket")}}catch(e){console.debug(`Failed to stat ${i.path}:`,e)}}}async read(){if(this.closed)throw new Error("Directory handle is closed");if(await this.initialize(),this.currentIndex>=this.entries.length)return null;let i=this.entries[this.currentIndex++];try{let e=await this.compositFs.stat(i.path);return{name:i.name,isFile:c(()=>e.isFile(),"isFile"),isDirectory:c(()=>e.isDirectory(),"isDirectory"),isBlockDevice:c(()=>e.isBlockDevice(),"isBlockDevice"),isCharacterDevice:c(()=>e.isCharacterDevice(),"isCharacterDevice"),isSymbolicLink:c(()=>e.isSymbolicLink(),"isSymbolicLink"),isFIFO:c(()=>e.isFIFO(),"isFIFO"),isSocket:c(()=>e.isSocket(),"isSocket")}}catch{return this.read()}}async close(){this.closed=!0,this.entries=[]}get path(){return this.dirPath}};c(Xt,"CompositeFsDir");var Fe=Xt;function la(t){let i=t.split("/").filter(Boolean),e=[],r=[],n=!1,a;for(let s of i)if(s.startsWith("[[")&&s.endsWith("]]")){let o=s.slice(2,-2).replace(/^\.\.\./,"");if(e.push(o),s.startsWith("[[..."))n=!0,r.push("(/.*)*"),a=o;else throw new Error("Optional single-segment parameters [[param]] are not supported. Use [[...param]] for catch-all or [param] for required single segment.")}else if(s.startsWith("[")&&s.endsWith("]")){if(s.startsWith("[..."))throw new Error("Required catch-all parameters [...param] are not supported. Use [[...param]] instead.");{let o=s.slice(1,-1);e.push(o),r.push("/([^\\/]+)")}}else s==="."?n=!0:r.push("/"+s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"));return{regexStr:r.join("")+"$",paramNames:e,folderRoute:n,pathParameter:a}}c(la,"compilePattern");function Yt(t){if(t===".")return 1;let i=t.split("/").filter(Boolean),e=Math.pow(2,i.length);for(let r=0;r<i.length;r++){let n=i[r],a;n.startsWith("[[...")?a=10:n.startsWith("[[")?a=50:n.startsWith("[")?a=100:a=1e3+n.length;let s=Math.pow(.9,r);e+=a*s}return e}c(Yt,"calculatePriority");function ca(t){if(typeof t.name!="string")return"folder";let i=t;return i.fsType==="folder"?"folder":i.fsType==="file"?"file":"readdir"in i&&typeof i.readdir=="function"?"folder":"file"}c(ca,"getNodeType");function da(t){let i=[];function e(r,n){if(typeof r.name=="string"){i.push({pattern:n||".",handler:r,priority:Yt(n||"."),staticBaseChildren:[]});return}let a=r,s=[],o=Object.keys(a).filter(d=>d.startsWith("[[")||d===".");if(o.length>1)throw new Error(`Expected exactly one folder handler for ${n||"/"} expected but multuple found: ${o.join(", ")}`);if(o.length===0)throw new Error(`No folder handler for ${n||"/"} founds`);for(let[d,l]of Object.entries(a)){let h=n?`${n}/${d}`:d;if(d==="."){if(typeof l.name!="string")throw new Error(`Folder root '.' at path '${n}' must be a handler, not a folder`);if(l.fsType!=="folder"&&l.fsType!=="fs")throw new Error(`Folder root handler '.' at path '${n}' must be of type 'folder' or 'fs'`);i.push({pattern:n+"/.",handler:l,priority:Yt(n),staticBaseChildren:s})}else if(d.startsWith("[["))if(d.startsWith("[[..."))if(typeof l.name=="string"){if(i.push({pattern:h,handler:l,priority:Yt(h),staticBaseChildren:s}),l.fsType!=="folder"&&l.fsType!=="fs")throw new Error(`Folder root handler '.' at path '${n}' must be of type 'folder' or 'fs'`)}else e(l,h);else e(l,h);else if(d.startsWith("[")){if(d.startsWith("[..."))throw new Error(`Required catch-all '${d}' is not supported. Use '[[...${d.slice(5,-1)}]]' instead`);e(l,h)}else s.push({segment:d,type:ca(l)}),e(l,h)}}return c(e,"walk"),e(t,""),i}c(da,"flattenRoutes");var Jt=class Jt{constructor(i,e){this.routes=i;this.rootPath=e;g(this,"compiledRoutes");let r=da(i);this.compiledRoutes=r.map(n=>{let{regexStr:a,paramNames:s,folderRoute:o,pathParameter:d}=la(n.pattern);return{regex:new RegExp(a),paramNames:s,staticBaseChildren:n.staticBaseChildren,handler:n.handler,priority:n.priority,pattern:n.pattern,folderRoute:o,pathParameter:d}})}match(i){let e=i;e.startsWith(this.rootPath+"/")?e=e.slice(this.rootPath.length+1):e.startsWith(this.rootPath)&&(e=e.slice(this.rootPath.length)),e.startsWith("/")||(e="/"+e),e.length>1&&e.endsWith("/")&&(e=e.slice(0,-1));let r,n={},a=-1,s=this.compiledRoutes,o=[];for(let l of s){let h=e.match(l.regex);if(h)o.push(l);else continue;if(!(!h||l.priority<=a)){n={};for(let m=0;m<l.paramNames.length;m++){let f=h[m+1]||"";f.startsWith("/")&&(f=f.slice(1)),n[l.paramNames[m]]=decodeURIComponent(f)}a=l.priority,r=l}}if(!r||r.handler===void 0)return;let d=[];return r.folderRoute&&(r.pathParameter?n[r.pathParameter]===""&&(d=r.staticBaseChildren.map(l=>({segment:l.segment,type:l.type}))):d=r.staticBaseChildren.map(l=>({segment:l.segment,type:l.type}))),{handler:r.handler,matchingPattern:r.pattern,params:n,staticSiblings:d}}};c(Jt,"PathRouter");var Dt=Jt;function z(t){return typeof t=="string"?t:Buffer.isBuffer(t)?t.toString():String(t)}c(z,"pathToString");var qt=class qt{constructor({name:i,rootPath:e}){g(this,"compositeFs");g(this,"context");g(this,"newContext");g(this,"fsType","fs");g(this,"rootInstanceId");g(this,"name");g(this,"rootPath");this.name=i,this.rootPath=e,this.rootInstanceId=`${i}-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}attach(i){this.compositeFs=i}withContext(i){let e=Object.create(Object.getPrototypeOf(this));return Object.assign(e,this),e.context=i,e}async open(i,e,r){throw new Error(`open not implemented for: ${z(i)}`)}async access(i,e){throw new Error(`access not implemented for: ${z(i)}`)}async stat(i,e){throw new Error(`lstat not implemented for: ${z(i)}`)}async lstat(i,e){throw new Error(`lstat not implemented for: ${z(i)}`)}async opendir(i,e){throw new Error(`opendir not implemented for: ${z(i)}`)}async link(i,e){throw new Error(`link not implemented for: ${z(i)}`)}async mkdir(i,e){throw new Error(`mkdir not implemented for: ${z(i)}`)}async readdir(i,e){throw new Error(`readdir not implemented for: ${z(i)}`)}async readlink(i,...e){throw new Error(`readlink not implemented for: ${z(i)}`)}async unlink(i){throw new Error(`unlink not implemented for: ${z(i)}`)}async rename(i,e){throw new Error(`rename not implemented for: ${z(i)}`)}async rmdir(i,...e){throw new Error(`rmdir not implemented for: ${z(i)}`)}async symlink(i,e,r){throw new Error(`symlink not implemented for: ${z(e)}`)}async lookup(i){throw new Error(`lookup not implemented for: ${z(i)}`)}resolvePath(i){throw new Error(`resolvePath not implemented for fd: ${i}`)}async close(i){this.compositeFs.close(i)}async dataSync(i){throw new Error(`dataSync not implemented for: ${i.subFsFileDescriptor}`)}async read(i,e,r,n,a){throw new Error(`read not implemented for: ${i.subFsFileDescriptor}`)}async appendFile(i,e,r){throw new Error(`appendFile not implemented for: ${i.subFsFileDescriptor}`)}async fchmod(i,e){throw new Error(`fchmod not implemented for: ${i.subFsFileDescriptor}`)}async fchown(i,e,r){throw new Error(`fchown not implemented for: ${i.subFsFileDescriptor}`)}async ftruncate(i,e){throw new Error(`ftruncate not implemented for: ${i.subFsFileDescriptor}`)}async fstat(i,e){throw new Error(`fstat not implemented for: ${i.subFsFileDescriptor}`)}async futimes(i,e,r){throw new Error(`futimes not implemented for: ${i.subFsFileDescriptor}`)}async write(i,e,r,n,a){throw new Error(`write not implemented for: ${i.subFsFileDescriptor}`)}async writev(i,e,r){throw new Error(`writev not implemented for: ${i.subFsFileDescriptor}`)}async readv(i,e,r){throw new Error(`readv not implemented for: ${i.subFsFileDescriptor}`)}async readFile(i,e){throw new Error(`readFile not implemented for: ${i}`)}async writeFile(i,e,r){throw new Error(`writeFile not implemented for: ${i}`)}};c(qt,"BaseCompositeSubFs");var j=qt;var Qt=class Qt{constructor({name:i,filterLayers:e,routes:r,rootPath:n}){g(this,"promises");g(this,"filterLayers",[]);g(this,"router");g(this,"parentFs");g(this,"name");g(this,"rootPath");g(this,"pathToFileDescriptors",new Map);g(this,"openFileHandles",new Map);g(this,"logOperation");this.name=i,this.rootPath=n;for(let a of e)this.filterLayers.push(a),a.attach(this);this.router=new Dt(r,this.rootPath),this.promises={access:this.access.bind(this),opendir:this.opendir.bind(this),mkdir:this.mkdir.bind(this),readdir:this.readdir.bind(this),open:this.open.bind(this),stat:this.stat.bind(this),lstat:this.lstat.bind(this),link:this.link.bind(this),readlink:this.readlink.bind(this),unlink:this.unlink.bind(this),rename:this.rename.bind(this),rmdir:this.rmdir.bind(this),symlink:this.symlink.bind(this),readFile:this.readFile.bind(this),writeFile:this.writeFile.bind(this),getFilehandle:this.getFilehandle.bind(this)}}getNextFileDescriptor(){let i=Array.from(this.openFileHandles.keys());return i.length===0?1:Math.max(...i)+1}setLoggger(i){this.logOperation=i}async logOperationOnFileDescsriptor(i,e,r){if(!this.logOperation)return;let n=[];for(let[a,s]of this.pathToFileDescriptors.entries())s.includes(i.fd)&&n.push(a);if(n.length!==0)return this.logOperation?.({fsName:i.delegate.name,fd:i,path:n[0],operation:e,operationArgs:r})}getFilehandle(i){return this.openFileHandles.get(i)}async getResponsibleFs(i){let e=i.toString();for(let a of this.filterLayers)if(await a.responsible(e)){if(a.withContext!==void 0)return a.withContext({fullPath:e,params:{},staticSiblings:[]});throw new Error(`Filter layer filesystem ${a.name} is not a BaseCompositeSubFs`)}let r=this.router.match(e);if(!r)throw new Error(`No route match for: ${e}`);let n=r.handler;return n.attach(this),n.withContext({fullPath:e,params:r.params,staticSiblings:r.staticSiblings})}async access(i,e){let r=await this.getResponsibleFs(i);return await this.logOperation?.({fsName:r.name,path:i,operation:"access",operationArgs:{mode:e}}),r.access(i,e)}async stat(i,e){let r=i.toString(),n=await this.getResponsibleFs(i);return await this.logOperation?.({fsName:n.name,path:r,operation:"stat",operationArgs:{opts:e}}),n.stat(i)}async lstat(i,e){let r=await this.getResponsibleFs(i);return await this.logOperation?.({fsName:r.name,path:i.toString(),operation:"lstat",operationArgs:{opts:e}}),r.lstat(i,e)}async unlink(i){let e=await this.getResponsibleFs(i);return await this.logOperation?.({fsName:e.name,path:i.toString(),operation:"unlink",operationArgs:{}}),e.unlink(i)}async mkdir(i,e){let r=await this.getResponsibleFs(i);return await this.logOperation?.({fsName:r.name,path:i.toString(),operation:"mkdir",operationArgs:{options:e}}),r.mkdir(i,e)}async rmdir(i,e){let r=await this.getResponsibleFs(i);return await this.logOperation?.({fsName:r.name,path:i.toString(),operation:"rmdir",operationArgs:{dirPath:i,options:e}}),r.rmdir(i,e)}async opendir(i,e){await this.logOperation?.({fsName:this.name,path:i.toString(),operation:"opendir",operationArgs:{options:e}});let r=i.toString();return new Fe(this,r)}async readdir(i,e){await this.logOperation?.({fsName:this.name,path:i.toString(),operation:"readdir",operationArgs:{options:e}});let r=new Set,n=this.router.match(i.toString());if(n?.handler instanceof j){let a=n?.handler.withContext({fullPath:i.toString(),params:n.params,staticSiblings:n.staticSiblings});a.attach(this),r=new Set(await a.readdir(i,e))}for(let a of[...this.filterLayers].reverse())if(a.readDirFiltering)r=new Set(await a.readDirFiltering(i,Array.from(r)));else{let s=await a.readdir(i,e);for(let o of s)r.add(o)}return Array.from(r)}async open(i,e,r){let n=await this.getResponsibleFs(i);await this.logOperation?.({fsName:n.name,path:i,operation:"open",operationArgs:{flags:e,mode:r}});let a=await n.open(i,e,r),s=this.getNextFileDescriptor();return a.realize(s),this.openFileHandles.set(s,a),this.pathToFileDescriptors.get(i)||this.pathToFileDescriptors.set(i,[]),this.pathToFileDescriptors.get(i).push(s),a}async close(i){try{await i.delegate.close(i)}catch(e){throw e}finally{for(let[e,r]of this.pathToFileDescriptors.entries()){let n=r.indexOf(i.fd);if(n!==-1){r.splice(n,1),r.length===0&&this.pathToFileDescriptors.delete(e);break}}this.openFileHandles.delete(i.fd)}}async link(i,e){throw new Error("not implemented")}async readlink(i,e){throw new Error("not implemented")}async rename(i,e){let r=await this.getResponsibleFs(i),n=await this.getResponsibleFs(e);if(r.rootInstanceId===n.rootInstanceId)return await this.logOperation?.({fsName:r.name,path:i.toString(),operation:"rename",operationArgs:{oldPath:i,newPath:e}}),r.newContext=n.context,r.rename(i,e);let a=await r.open(i.toString(),"r");try{let s=await r.fstat(a),o=Buffer.alloc(s.size);await r.read(a,o,0,s.size,0),await r.close(a),await n.writeFile(e.toString(),o,"utf8"),await r.unlink(i)}catch(s){try{await r.close(a)}catch{}throw s}}async symlink(i,e,r){throw new Error("not implemented")}async readFile(i,e){await this.logOperation?.({fsName:this.name,path:i.toString(),operation:"readFile",operationArgs:{path:i,options:e}});let r=!0,n;if(typeof i=="number"){r=!1;let a=this.getFilehandle(i);if(!a)throw new Error("Invalid file descriptor");n=a}else if(typeof i=="string")n=await this.open(i,"r");else throw new Error("only filehandle and path are supported atm");try{let s=(await n.stat()).size;if(typeof s=="bigint"){if(s>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("File too large to read into buffer");s=Number(s)}let o=Buffer.alloc(s),{bytesRead:d}=await n.read(o,0,s,0);if(e&&typeof e.encoding=="string")return o.slice(0,d).toString(e.encoding);if(typeof e=="string"){if(e==="utf8"||e==="utf-8")return o.slice(0,d).toString(e);throw new Error("Unsupported encoding: "+e)}return o.slice(0,d)}finally{n&&r&&await n.close()}}async writeFile(i,e,r){await this.logOperation?.({fsName:this.name,path:i.toString(),operation:"writeFile",operationArgs:{data:e,options:r}});let n=typeof i!="number",a,s,o,d="w";if(typeof r=="string"?s=r:r&&typeof r=="object"&&(s=r.encoding,o=r.mode,d=r.flag||"w"),typeof i=="number"){let l=this.getFilehandle(i);if(!l)throw new Error("Invalid file descriptor");a=l}else if(typeof i=="string")a=await this.open(i,d,o);else throw new Error("only filehandle and path are supported atm");try{let l;if(typeof e=="string")l=Buffer.from(e,s||"utf8");else if(e instanceof Buffer)l=e;else if(e instanceof Uint8Array)l=Buffer.from(e);else throw new Error("Invalid data type for writeFile");let h=0;for(;h<l.length;){let{bytesWritten:m}=await a.write(l,h,l.length-h,h);h+=m}}finally{a&&n&&await a.close()}}};c(Qt,"CompositeFs");var rt=Qt;import ha from"ignore";var ei=class ei extends j{constructor({name:e,hiddenFiles:r,rootPath:n}){super({name:e,rootPath:n});g(this,"ig");this.ig=ha(),this.ig.add(r)}async responsible(e){let r=e.replace(/\\/g,"/"),n=r;if(this.rootPath){let a=this.rootPath;r.startsWith(a+"/")?n=r.slice(a.length+1):r.startsWith(a)&&(n=r.slice(a.length))}return n=n.startsWith("./")?n.slice(2):n,n=n.startsWith("/")?n.slice(1):n,n===""||n==="."?!1:this.ig.ignores(n)}fileType(){return 255}error(e){return new Error(`Access to hidden file is not allowed: ${z(e)}`)}async open(e,r,n){throw this.error(e)}async access(e){throw this.error(e)}async stat(e){throw this.error(e)}async lstat(e){throw this.error(e)}async opendir(e){throw this.error(e)}async link(e){throw this.error(e)}async mkdir(e){throw this.error(e)}async readDirFiltering(e,r){let n=[];for(let a of r){let s=z(e)!=="/"?z(e)+"/"+a:"/"+a;await this.responsible(s)||n.push(a)}return n}async readdir(e){throw this.error(e)}async readlink(e){throw this.error(e)}async unlink(e){throw this.error(e)}async rename(e){throw this.error(e)}async rmdir(e){throw this.error(e)}async symlink(e,r){throw this.error(r)}async lookup(e){throw this.error(e)}resolvePath(e){throw new Error(`Access to hidden file is not allowed: resolvePath(${e})`)}async close(e){throw new Error("Access to hidden file is not allowed: close: "+e.subFsFileDescriptor)}async dataSync(e){throw new Error("Access to hidden file is not allowed: dataSync: "+e.subFsFileDescriptor)}async read(e,r,n,a,s){throw new Error("Access to hidden file is not allowed: readFileHandle: "+e.subFsFileDescriptor)}};c(ei,"HiddenFileSubFs");var St=ei;var ti=class ti{constructor(i){g(this,"delegate");g(this,"compositeFs");g(this,"_subFsFileDescriptor");g(this,"handleType","file");g(this,"_compositFsFileDescriptor",-1);this.delegate=i.fs,this._subFsFileDescriptor=i.subFsFileDescriptor,this._compositFsFileDescriptor=-1,this.compositeFs=i.compositeFs;let e=this._subFsFileDescriptor}get fsType(){return this.delegate.fileType()}get subFsFileDescriptor(){return this._subFsFileDescriptor}get fd(){return this._compositFsFileDescriptor}realize(i){if(this._compositFsFileDescriptor!==-1)throw new Error("was already realized");this._compositFsFileDescriptor=i}readableWebStream(i){throw new Error("Method not implemented.")}async appendFile(i,e){return await this.compositeFs.logOperationOnFileDescsriptor(this,"appendFile",{data:i,options:e}),await this.delegate.appendFile(this,i,e)}async chmod(i){return await this.compositeFs.logOperationOnFileDescsriptor(this,"chmod",{mode:i}),this.delegate.fchmod(this,i)}async chown(i,e){return await this.compositeFs.logOperationOnFileDescsriptor(this,"chown",{uid:i,gid:e}),this.delegate.fchown(this,i,e)}async close(){return await this.compositeFs.logOperationOnFileDescsriptor(this,"close",{}),this.compositeFs.close(this)}async datasync(){return await this.compositeFs.logOperationOnFileDescsriptor(this,"datasync",{}),this.delegate.dataSync(this)}async read(i,e,r,n){return await this.compositeFs.logOperationOnFileDescsriptor(this,"read",{targetBufferLength:i.length,offset:e,length:r,position:n}),await this.delegate.read(this,i,e,r,n)}async readv(i,e){return await this.compositeFs.logOperationOnFileDescsriptor(this,"readv",{buffers:i,position:e}),this.delegate.readv(this,i,e)}async stat(i){return await this.compositeFs.logOperationOnFileDescsriptor(this,"stat",{options:i}),this.delegate.fstat(this,i)}async truncate(i){return await this.compositeFs.logOperationOnFileDescsriptor(this,"truncate",{len:i}),this.delegate.ftruncate(this,i)}async utimes(i,e){return await this.compositeFs.logOperationOnFileDescsriptor(this,"utimes",{atime:i,mtime:e}),this.delegate.futimes(this,i,e)}async write(i,e,r,n){return await this.compositeFs.logOperationOnFileDescsriptor(this,"write",{buffer:i,offset:e,length:r,position:n}),this.delegate.write(this,i,e,r,n)}async writev(i,e){return await this.compositeFs.logOperationOnFileDescsriptor(this,"writev",{buffers:i,position:e}),this.delegate.writev(this,i,e)}async sync(){return await this.compositeFs.logOperationOnFileDescsriptor(this,"sync",{}),this.delegate.dataSync(this)}};c(ti,"CompositFsFileHandle");var W=ti;import*as Tt from"path";import{createFsFromVolume as fa,Volume as ma}from"memfs";import pa from"ignore";var ii=class ii extends j{constructor({name:e,rootPath:r,ephemeralPatterns:n}){super({name:e,rootPath:r});g(this,"openFh",new Map);g(this,"memFs",fa(new ma));g(this,"ig");g(this,"patterns");this.ig=pa(),this.ig.add(n),this.patterns=n}normalizePath(e){let r=typeof e=="string"?e:e.toString();return r.startsWith("/")?r:"/"+r}async responsible(e){let r=e.replace(/\\/g,"/"),n=r;return this.rootPath&&(r.startsWith(this.rootPath+"/")?n=r.slice(this.rootPath.length+1):r.startsWith(this.rootPath)&&(n=r.slice(this.rootPath.length))),n=n.startsWith("./")?n.slice(2):n,n=n.startsWith("/")?n.slice(1):n,n===""||n==="."?!1:this.ig.ignores(n)}fileType(){return 5}async open(e,r,n){let a=this.normalizePath(e),s=Tt.dirname(a);s&&s!=="/"&&s!=="."&&await this.memFs.promises.mkdir(s,{recursive:!0});let o=await this.memFs.promises.open(a,r,n);return this.openFh.set(o.fd,o),new W({fs:this,compositeFs:this.compositeFs,subFsFileDescriptor:o.fd,parentFsFileDescriptors:[o.fd]})}async access(e,r){let n=this.normalizePath(e);return await this.memFs.promises.access(n,r)}async stat(e,r){let n=this.normalizePath(e);return this.memFs.promises.stat(n,{bigint:!1})}async lstat(e,r){let n=this.normalizePath(e);return this.memFs.promises.lstat(n,{bigint:!1})}async opendir(e,r){let n=this.normalizePath(e);return await this.memFs.promises.opendir(n,r)}async link(e,r){let n=this.normalizePath(e),a=this.normalizePath(r);return await this.memFs.promises.link(n,a)}async mkdir(e,r){let n=this.normalizePath(e);if(!(typeof r=="object"&&r&&"recursive"in r&&r.recursive)){let s=Tt.dirname(n);if(s&&s!=="/"&&s!==".")try{await this.memFs.promises.stat(s)}catch{await this.memFs.promises.mkdir(s,{recursive:!0})}}await this.memFs.promises.mkdir(n,r)}async readdir(e,...r){let n=this.normalizePath(e),a=await this.memFs.promises.readdir(n,...r);return console.log("EPHEMERAL: READDIR: ",a),a}async readlink(e){throw new Error("readlink is not implemented for EphemeralFileSubFs")}async unlink(e){let r=this.normalizePath(e);return await this.memFs.promises.unlink(r)}async rename(e,r){let n=this.normalizePath(e),a=this.normalizePath(r);return await this.memFs.promises.rename(n,a)}async rmdir(e,r){let n=this.normalizePath(e);return await this.memFs.promises.rmdir(n,r)}async symlink(e,r,n){let a=this.normalizePath(e),s=this.normalizePath(r);return await this.memFs.promises.symlink(a,s,n)}async lookup(e){throw new Error(`lookup is not implemented for: ${z(e)}`)}async close(e){let r=this.openFh.get(e.subFsFileDescriptor);r&&(await r.close(),this.openFh.delete(e.subFsFileDescriptor))}async dataSync(e){let r=this.openFh.get(e.subFsFileDescriptor);if(r)return await r.datasync()}async read(e,r,n,a,s){let o=this.openFh.get(e.subFsFileDescriptor);if(o)return await o.read(r,n,a,s);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async fchmod(e,r){let n=this.openFh.get(e.subFsFileDescriptor);if(n)return await n.chmod(r)}async fchown(e,r,n){let a=this.openFh.get(e.subFsFileDescriptor);if(a)return await a.chown(r,n)}async write(e,r,n,a,s){let o=this.openFh.get(e.subFsFileDescriptor);if(o)return await o.write(r,n,a,s);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async ftruncate(e,r){let n=this.openFh.get(e.subFsFileDescriptor);if(n)return await n.truncate(r)}resolvePath(e){throw new Error(`resolvePath is not implemented: resolvePath(${e})`)}async fstat(e,r){let n=this.openFh.get(e.subFsFileDescriptor);if(n)return await n.stat(r);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async futimes(e,r,n){let a=this.openFh.get(e.subFsFileDescriptor);if(a)return await a.utimes(r,n)}async writev(e,r,n){let a=this.openFh.get(e.subFsFileDescriptor);if(a)return await a.writev(r,n??void 0);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async readv(e,r,n){let a=this.openFh.get(e.subFsFileDescriptor);if(a)return await a.readv(r,n??void 0);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async readFile(e,r){if(typeof e=="string"||Buffer.isBuffer(e)){let n=this.normalizePath(e);return this.memFs.promises.readFile(n,r)}return super.readFile(e,r)}async writeFile(e,r,n){let a=this.normalizePath(e),s=Tt.dirname(a);return s&&s!=="/"&&s!=="."&&await this.memFs.promises.mkdir(s,{recursive:!0}),this.memFs.promises.writeFile(a,r,n)}};c(ii,"EphemeralSubFs");var er=ii;import*as Se from"path";import ua from"ignore";var ri=class ri extends j{constructor({name:e,sourceFs:r,copyToFs:n,copyToRootPath:a,rootPath:s,patterns:o}){super({rootPath:s,name:e});g(this,"openFh",new Map);g(this,"sourceFs");g(this,"copyToFs");g(this,"copyPath");g(this,"ig");g(this,"patterns");this.sourceFs=r,this.copyToFs=n,this.copyPath=a,this.patterns=o,this.ig=ua(),this.ig.add(o)}normalizeCopyPath(e){let r=typeof e=="string"?e:e.toString(),n=r.startsWith("/")?r:"/"+r;return Se.join(this.copyPath,n)}normalizePath(e){let r=typeof e=="string"?e:e.toString();return r.startsWith("/")?r:"/"+r}async responsible(e){let r=e.replace(/\\/g,"/"),n=r;if(this.compositeFs.rootPath){let a=this.compositeFs.rootPath;r.startsWith(a+"/")?n=r.slice(a.length+1):r.startsWith(a)&&(n=r.slice(a.length))}return n=n.startsWith("./")?n.slice(2):n,n=n.startsWith("/")?n.slice(1):n,n===""||n==="."?!1:this.ig.ignores(n)}fileType(){return 6}async isCopied(e){let r=this.normalizeCopyPath(e);try{return await this.copyToFs.promises.access(r),!0}catch{return!1}}async copyFromSource(e){let r=this.normalizeCopyPath(e),n=this.normalizePath(e),a=Se.dirname(r);a&&a!=="/"&&a!=="."&&await this.copyToFs.promises.mkdir(a,{recursive:!0});try{let s=await this.sourceFs.promises.readFile(n);await this.copyToFs.promises.writeFile(r,s)}catch(s){if(s.code!=="ENOENT")throw s}}async open(e,r,n){let a=this.normalizePath(e),s=this.normalizeCopyPath(e);if(r.includes("w")||r.includes("a")||r.includes("+")){let d=Se.dirname(s);if(d&&d!=="/"&&d!=="."&&await this.copyToFs.promises.mkdir(d,{recursive:!0}),!await this.isCopied(e))try{await this.sourceFs.promises.access(a),await this.copyFromSource(e)}catch{}let h=await this.copyToFs.promises.open(s,r,n);return this.openFh.set(h.fd,h),new W({fs:this,compositeFs:this.compositeFs,subFsFileDescriptor:h.fd,parentFsFileDescriptors:[h.fd]})}else{let d=await this.isCopied(e),l=d?this.copyToFs:this.sourceFs,h=d?s:a,m=await l.promises.open(h,r,n);return this.openFh.set(m.fd,m),new W({fs:this,compositeFs:this.compositeFs,subFsFileDescriptor:m.fd,parentFsFileDescriptors:[m.fd]})}}async access(e,r){let n=this.normalizePath(e),a=this.normalizeCopyPath(e);try{await this.copyToFs.promises.access(a,r);return}catch{return await this.sourceFs.promises.access(n,r)}}async stat(e,r){let n=this.normalizePath(e),a=this.normalizeCopyPath(e);try{return await this.copyToFs.promises.stat(a,{bigint:r?.bigint??!1})}catch{return this.sourceFs.promises.stat(n,{bigint:r?.bigint??!1})}}async lstat(e,r){let n=this.normalizePath(e),a=this.normalizeCopyPath(e);try{return await this.copyToFs.promises.lstat(a,{bigint:r?.bigint??!1})}catch{return this.sourceFs.promises.lstat(n,{bigint:r?.bigint??!1})}}async opendir(e,r){let n=this.normalizePath(e);return new Fe(this.compositeFs,n)}async link(e,r){let n=this.normalizeCopyPath(e),a=this.normalizeCopyPath(r);return await this.copyToFs.promises.link(n,a)}async mkdir(e,r){let n=this.normalizeCopyPath(e);if(!(typeof r=="object"&&r&&"recursive"in r&&r.recursive)){let s=Se.dirname(n);if(s&&s!=="/"&&s!==".")try{await this.copyToFs.promises.stat(s)}catch{await this.copyToFs.promises.mkdir(s,{recursive:!0})}}await this.copyToFs.promises.mkdir(n,r)}async readdir(e,...r){let n=this.normalizePath(e),a=this.normalizeCopyPath(e),s=new Set,o=new Set;try{let l=await this.sourceFs.promises.readdir(n,...r);Array.isArray(l)&&l.forEach(h=>s.add(typeof h=="string"?h:h.name))}catch(l){if(l.code!=="ENOENT")throw l}try{let l=await this.copyToFs.promises.readdir(a,...r);Array.isArray(l)&&l.forEach(h=>o.add(typeof h=="string"?h:h.name))}catch(l){if(l.code!=="ENOENT")throw l}return Array.from(new Set([...s,...o]))}async readlink(e){throw new Error("readlink is not implemented for CopyOnWriteSubFs")}async unlink(e){let r=this.normalizeCopyPath(e);return await this.copyToFs.promises.unlink(r)}async rename(e,r){let n=this.normalizeCopyPath(e),a=this.normalizeCopyPath(r);return await this.copyToFs.promises.rename(n,a)}async rmdir(e,r){let n=this.normalizeCopyPath(e);return await this.copyToFs.promises.rmdir(n,r)}async symlink(e,r,n){let a=this.normalizeCopyPath(e),s=this.normalizeCopyPath(r);return await this.copyToFs.promises.symlink(a,s,n)}async lookup(e){throw new Error(`lookup is not implemented for: ${z(e)}`)}resolvePath(e){throw new Error(`resolvePath is not implemented: resolvePath(${e})`)}async close(e){let r=this.openFh.get(e.subFsFileDescriptor);r&&(await r.close(),this.openFh.delete(e.subFsFileDescriptor))}async dataSync(e){let r=this.openFh.get(e.subFsFileDescriptor);if(r)return await r.datasync()}async read(e,r,n,a,s){let o=this.openFh.get(e.subFsFileDescriptor);if(o)return await o.read(r,n,a,s);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async fchmod(e,r){let n=this.openFh.get(e.subFsFileDescriptor);if(n)return await n.chmod(r)}async fchown(e,r,n){let a=this.openFh.get(e.subFsFileDescriptor);if(a)return await a.chown(r,n)}async write(e,r,n,a,s){let o=this.openFh.get(e.subFsFileDescriptor);if(o)return await o.write(r,n,a,s);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async ftruncate(e,r){let n=this.openFh.get(e.subFsFileDescriptor);if(n)return await n.truncate(r)}async fstat(e,r){let n=this.openFh.get(e.subFsFileDescriptor);if(n)return await n.stat(r);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async futimes(e,r,n){let a=this.openFh.get(e.subFsFileDescriptor);if(a)return await a.utimes(r,n)}async writev(e,r,n){let a=this.openFh.get(e.subFsFileDescriptor);if(a)return await a.writev(r,n??void 0);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async readv(e,r,n){let a=this.openFh.get(e.subFsFileDescriptor);if(a)return await a.readv(r,n??void 0);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async readFile(e,r){if(typeof e!="string"&&!Buffer.isBuffer(e))return super.readFile(e,r);let n=this.normalizePath(e),a=this.normalizeCopyPath(e);try{return await this.copyToFs.promises.readFile(a,r)}catch{return this.sourceFs.promises.readFile(n,r)}}async writeFile(e,r,n){let a=this.normalizeCopyPath(e);await this.isCopied(e)||await this.copyFromSource(e);let o=Se.dirname(a);o&&o!=="/"&&o!=="."&&await this.copyToFs.promises.mkdir(o,{recursive:!0}),await this.copyToFs.promises.writeFile(a,r,n)}};c(ri,"CopyOnWriteSubFs");var nt=ri;import tr from"@legit-sdk/isomorphic-git";import*as ni from"path";import{createFsFromVolume as wa,Volume as ya}from"memfs";function V(t){return{name:t.name,isFile:c(()=>!t.isDir,"isFile"),isDirectory:c(()=>t.isDir,"isDirectory"),isBlockDevice:c(()=>!0,"isBlockDevice"),isCharacterDevice:c(()=>!1,"isCharacterDevice"),isSymbolicLink:c(()=>!1,"isSymbolicLink"),isFIFO:c(()=>!1,"isFIFO"),isSocket:c(()=>!1,"isSocket"),parentPath:t.parent,path:t.parent}}c(V,"toDirEntry");var ai=class ai extends j{constructor({name:e,gitStorageFs:r,gitRoot:n,handler:a,rootPath:s}){super({name:e,rootPath:s});g(this,"memFs");g(this,"openFh",{});g(this,"storageFs");g(this,"gitRoot");g(this,"handler");this.handler=a,this.gitRoot=n,this.storageFs=r,this.memFs=wa(new ya)}async getAuthor(){let e=await tr.getConfig({fs:this.storageFs,dir:this.gitRoot,path:"user.name"}),r=await tr.getConfig({fs:this.storageFs,dir:this.gitRoot,path:"user.email"}),n=Math.floor(Date.now()/1e3),a=new Date().getTimezoneOffset();return{name:e,email:r,date:n,timezoneOffset:a}}async responsible(e){return!0}getRouteParams(){return this.context?.params||{}}getStaticSiblings(){return this.context?.staticSiblings||[]}async open(e,r,n){if(!(this.handler.writeFile!==void 0)&&(r.includes("w")||r.includes("a")))throw new Error(`Write operations not allowed for ${this.handler.type}`);if(r.includes("x")&&this.handler.type!=="gitBranchFileVirtualFile"&&this.handler.type!=="claudeVirtualSessionFileVirtualFile")throw new Error(`Exclusive operations not allowed for ${this.handler.type}`);let s=await this.getAuthor(),o=this.getRouteParams(),d=await this.handler.getFile({cacheFs:this.memFs,filePath:e,userSpaceFs:this.compositeFs,pathParams:o,author:s}),l=!1;for(let u of Object.values(this.openFh))u.path===e&&(l=!0);if((d||l)&&r.includes("x"))throw Object.assign(new Error(`EEXIST: file already exists, open '${e}'`),{code:"EEXIST",errno:-17,syscall:"open",path:e});if(!d&&!l&&!(r.includes("w")||r.includes("a")))throw Object.assign(new Error(`ENOENT: no such file or directory, open '${e}'`),{code:"ENOENT",errno:-2,syscall:"open",path:e});let h=ni.dirname(e);if(await this.memFs.promises.mkdir(h,{recursive:!0}),d===void 0&&!r.includes("x")||d&&d.type==="file")try{let u=await this.memFs.promises.access(e)}catch{await this.memFs.promises.writeFile(e,"")}let m=await this.memFs.promises.open(e,r,n),f=m.fd,p=new W({fs:this,compositeFs:this.compositeFs,subFsFileDescriptor:f,parentFsFileDescriptors:[]});return this.openFh[f]={path:e,mode:r,fh:m,openSha:d?.oid,readSha:void 0,unflushed:[]},(r.includes("x")||r.includes("w"))&&this.openFh[f].unflushed.push({length:0,start:0}),p}async mkdir(e,r){let n=e.toString(),a=this.getRouteParams(),s=r?{options:r}:{};try{let o=await this.getAuthor();await this.handler.mkdir({cacheFs:this.memFs,filePath:e.toString(),userSpaceFs:this.compositeFs,pathParams:a,...s,author:o});let d=typeof r=="object"?{...r,recursive:!0}:{recursive:!0};await this.memFs.promises.mkdir(e,d);let l=n.split("/"),h="";for(let m=1;m<=l.length;m++){h=l.slice(0,m).join("/");try{if((await this.memFs.promises.stat(h)).isDirectory()){let p=await this.memFs.promises.open(h,"r");this.openFh[p.fd]={path:h,mode:"r",fh:p,openSha:void 0,readSha:void 0,unflushed:[]}}}catch{}}}catch(o){throw o}}async access(e,r){await this.stat(e)}async futimes(e,r,n){let a=this.openFh[e.subFsFileDescriptor];if(!a)throw new Error("Invalid file handle");return await a.fh.utimes(r,n)}async fstat(e,r){let n=this.openFh[e.subFsFileDescriptor];if(!n)throw new Error("Invalid file handle");return this.stat(n.path,r)}async ftruncate(e,r){let n=this.openFh[e.subFsFileDescriptor];if(!n)throw new Error("Invalid file handle");return n.unflushed.push({length:0,start:0}),await n.fh.truncate(r)}async stat(e,r){let n=e.toString(),a=Object.values(this.openFh).find(l=>l.path===n&&l.unflushed.length>0);if(a&&a.unflushed.length>0)return await a.fh.stat(r);let s=this.getRouteParams(),o=await this.getAuthor();return await this.handler.getStats({cacheFs:this.memFs,filePath:n,userSpaceFs:this.compositeFs,pathParams:s,author:o})}async lstat(e,r){return this.stat(e,r)}async readdir(e,r){let n=e.toString(),a=this.getRouteParams(),s=this.getStaticSiblings(),o=await this.getAuthor(),d=await this.handler.getFile({cacheFs:this.memFs,filePath:n,userSpaceFs:this.compositeFs,pathParams:a,author:o});if(d){if(d.type!=="directory")throw new Error("not a folder");let l=Array.from(new Set([...d.content,...s.map(h=>V({name:h.segment,parent:n,isDir:h.type==="folder"}))])).sort((h,m)=>h.name.localeCompare(m.name,void 0,{numeric:!0,sensitivity:"base"}));return r?.withFileTypes?l:l.map(h=>h.name)}return[]}async read(e,r,n,a,s){let o=e.subFsFileDescriptor,d=this.openFh[o];if(!d)throw new Error("Invalid file handle");if(d.unflushed.length===0){let l=this.getRouteParams(),h=await this.getAuthor(),m=await this.handler.getFile({cacheFs:this.memFs,filePath:d.path,userSpaceFs:this.compositeFs,pathParams:l,author:h});if(!m?.content)throw new Error("couldnt access content");if(m.type!=="file")throw new Error("not a file");let f=typeof m.content=="string"?Buffer.from(m.content):m.content,p=typeof s=="number"?s:0,u=Math.min(p+a,f.length),v=Math.max(0,u-p);return f.copy(r,n,p,p+v),{bytesRead:v,buffer:r}}return await d.fh.read(r,n,a,s)}async write(e,r,n,a,s){let o=this.openFh[e.subFsFileDescriptor];if(!o)throw new Error("Invalid file handle");let d=o.mode;if(!d.includes("w")&&!d.includes("a")&&!d.includes("+"))throw Object.assign(new Error("EBADF: bad file descriptor, write"),{code:"EBADF",errno:-9,syscall:"write"});if(o.unflushed.length===0){let f=this.getRouteParams(),p=await this.getAuthor(),u=await this.handler.getFile({cacheFs:this.memFs,filePath:o.path,userSpaceFs:this.compositeFs,pathParams:f,author:p});u&&u.oid&&(await this.memFs.promises.writeFile(o.path,u.content),o.readSha=u.oid)}let l=await o.fh.write(r,n,a,s),h=n??0,m=s??0;return o.unflushed.push({start:m,length:a||r.byteLength-h+m}),l}async close(e){let r=e.subFsFileDescriptor,n=this.openFh[r];if(!n)throw new Error("Invalid file handle");try{await this.dataSync(e),await n.fh.close()}finally{delete this.openFh[r]}}async dataSync(e){let r=e.subFsFileDescriptor,n=this.openFh[r];if(!n)throw new Error("Invalid file handle");if(n.unflushed.length>0){if(this.handler.writeFile){let a=await this.memFs.promises.readFile(n.path),s=this.getRouteParams(),o=await this.getAuthor();await this.handler.writeFile({cacheFs:this.memFs,filePath:n.path,userSpaceFs:this.compositeFs,content:a,pathParams:s,author:o})}n.unflushed=[]}}async readFile(e,r){let n=typeof e=="string"?e:Buffer.isBuffer(e)?e.toString():e.fd?`FileHandle(${e.fd})`:e.toString(),a=null;typeof r=="string"?a=r:r&&typeof r=="object"&&r.encoding&&(a=r.encoding);let s=await this.open(n,"r");try{let d=(await this.fstat(s)).size,l=Buffer.alloc(d);return await this.read(s,l,0,d,0),await this.close(s),a?l.toString(a):l}catch(o){try{await this.close(s)}catch{}throw o}}async writeFile(e,r,n){let a="w",s="utf8",o;typeof n=="string"?s=n:n&&typeof n=="object"&&(n.flag&&(a=String(n.flag)),n.encoding&&(s=n.encoding),n.mode&&(o=typeof n.mode=="string"?parseInt(n.mode,8):n.mode));let d=await this.open(e,a,o);try{let l;typeof r=="string"?l=Buffer.from(r,s):Buffer.isBuffer(r)?l=r:r instanceof Uint8Array?l=Buffer.from(r):ArrayBuffer.isView(r)?l=Buffer.from(r.buffer,r.byteOffset,r.byteLength):l=Buffer.from(r),await this.write(d,l,0,l.length,0)}finally{await this.close(d)}}async rename(e,r){let n=e.toString(),a=r.toString();if(!this.handler.rename)throw new Error(`Rename not supported for ${this.handler.type} files`);let s=await this.memFs.promises.access(a).then(()=>!0).catch(()=>!1),o=await this.stat(a).then(()=>!0).catch(()=>!1),d=await this.stat(n).then(()=>!0).catch(()=>!1);if(await this.memFs.promises.access(n).then(()=>!0).catch(()=>!1)){let f=ni.dirname(a);try{await this.memFs.promises.access(f)}catch{await this.memFs.promises.mkdir(f,{recursive:!0})}await this.memFs.promises.rename(e,r)}let h=this.getRouteParams(),m=await this.getAuthor();await this.handler.rename({cacheFs:this.memFs,filePath:n,userSpaceFs:this.compositeFs,newPath:a,pathParams:h,newPathParams:this.newContext?.params||{},author:m})}async fchmod(e,r){}async unlink(e){let r=e.toString();if(!this.handler.unlink)throw new Error(`Cannot unlink ${this.handler.type} files`);try{let n=this.getRouteParams(),a=await this.getAuthor();await this.handler.unlink({cacheFs:this.memFs,filePath:r,userSpaceFs:this.compositeFs,pathParams:n,author:a})}catch(n){let a=!1;for(let[s,o]of Object.entries(this.openFh))o.path===r&&o.unflushed.length>0&&(a=!0);if(!a)throw n}finally{let n=!1;for(let[a,s]of Object.entries(this.openFh))s.path===r&&(n=!0,await s.fh.close(),delete this.openFh[Number(a)]);n&&await this.memFs.promises.unlink(r)}}async rmdir(e,...r){let n=e.toString();if(!this.handler.rmdir)throw new Error(`Cannot rmdir ${this.handler.type} directories`);let a=this.getRouteParams(),s=await this.getAuthor();await this.handler.rmdir({cacheFs:this.memFs,filePath:n,userSpaceFs:this.compositeFs,pathParams:a,author:s});let o=!1;for(let[d,l]of Object.entries(this.openFh))l.path===n&&(o=!0,await l.fh.close(),delete this.openFh[Number(d)]);o&&await this.memFs.promises.rmdir(n,{recursive:!0})}fileType(){return 10}};c(ai,"CompositeSubFsAdapter");var N=ai;function ir({gitStorageFs:t,gitRoot:i,rootPath:e}){return new N({name:"legit-virtual-file",gitStorageFs:t,gitRoot:i,rootPath:e||i,handler:{type:"legitVirtualFile",rootType:"folder",getStats:c(async n=>{let a=i+"/.git";try{return await t.promises.stat(a)}catch{throw new Error(`ENOENT: no such file or directory, stat '${a}'`)}},"getStats"),getFile:c(async n=>({type:"directory",content:[],mode:493,size:0}),"getFile"),rename(n){throw new Error("not implemented")},mkdir:c(async function(n){throw new Error("not implemented")},"mkdir")}})}c(ir,"createLegitVirtualFileAdapter");import Ue from"@legit-sdk/isomorphic-git";import Fa from"@legit-sdk/isomorphic-git";function re(t){return t.replace(/\./g,"%2E").replace(/\//g,".")}c(re,"encodeBranchNameForVfs");function H(t){return t.replace(/\./g,"/").replace(/%2E/g,".")}c(H,"decodeBranchNameFromVfs");var si="-operation";async function te(t,i,e){let n=(await Fa.listBranches({fs:t,dir:i})).filter(a=>a.endsWith(H(e)+si))[0];return n?re(n):void 0}c(te,"resolveOperationBranchName");import oi from"@legit-sdk/isomorphic-git";async function O(t,i){try{let e=await oi.getConfig({fs:i,dir:t,path:"user.legit-current-branch"});if(e)return re(e)}catch{}try{let e=await oi.getConfig({fs:i,dir:t,path:"init.defaultBranch"});return re(e)||"main"}catch{return"main"}}c(O,"getCurrentBranch");async function rr(t,i,e){await oi.setConfig({fs:i,dir:t,path:"user.legit-current-branch",value:H(e)})}c(rr,"setCurrentBranch");function nr({gitStorageFs:t,gitRoot:i,rootPath:e}){let r={type:"gitBranchOperationsVirtualFile",rootType:"file",getStats:c(async a=>{let{pathParams:s}=a;s.branchName===void 0&&(s.branchName=await O(i,t));let o=await te(t,i,s.branchName),d,l=!1;if(o)try{d=await Ue.resolveRef({fs:t,dir:i,ref:o}),l=!0}catch{try{d=await Ue.resolveRef({fs:t,dir:i,ref:`refs/heads/${o}`}),l=!0}catch{throw new Error(`Base Branch ${s.branchName} for operations does not exis`)}}else try{d=await Ue.resolveRef({fs:t,dir:i,ref:`refs/heads/${s.branchName}`})}catch{throw new Error(`Base Branch ${s.branchName} for operations does not exis`)}let h=await Ue.readCommit({fs:t,dir:i,oid:d}),{commit:m}=h,f=m.committer.timestamp*1e3;try{return{mode:420,size:(l?await n.handler.getFile(a):void 0)?.content?.length??0,atimeMs:f,mtimeMs:f,ctimeMs:f,birthtimeMs:f,atime:new Date(f),mtime:new Date(f),ctime:new Date(f),birthtime:new Date(f),isFile:c(()=>!0,"isFile"),isDirectory:c(()=>!1,"isDirectory"),isSymbolicLink:c(()=>!1,"isSymbolicLink"),isBlockDevice:c(()=>!1,"isBlockDevice"),isCharacterDevice:c(()=>!1,"isCharacterDevice"),isSocket:c(()=>!1,"isSocket"),isFIFO:c(()=>!1,"isFIFO"),isFileSync:c(()=>!0,"isFileSync"),isDirectorySync:c(()=>!1,"isDirectorySync"),dev:0,ino:0,nlink:1,uid:0,gid:0,rdev:0,blksize:4096,blocks:0}}catch{throw new Error("ENOENT: no such file or directory, stat operationHistory")}},"getStats"),getFile:c(async a=>{let{pathParams:s}=a;s.branchName===void 0&&(s.branchName=await O(i,t));let o=await te(t,i,s.branchName),d=[];if(o){let m=await Ue.resolveRef({fs:t,dir:i,ref:`refs/heads/${o}`}),f=!1,p=m;for(;p&&!f;){let u=await Ue.readCommit({fs:t,dir:i,oid:p});d.push({oid:u.oid,parentOids:u.commit.parent,message:u.commit.message,originBranchOid:"unset"}),p=u.commit.parent&&u.commit.parent.length>0?u.commit.parent[0]:null,u.commit.parent.length===2&&u.commit.parent[0]===u.commit.parent[1]&&(f=!0)}}let l;for(let m=d.length-1;m>=0;m--){let f=d[m];if(l===void 0){if(f.parentOids.length!==2&&f.parentOids[0]!==f.parentOids[1])throw new Error(`Operation commit ${f.oid} does not have two parents as expected`);l=f.parentOids[1]}f.parentOids.length===2&&(l=f.parentOids[1]),f.originBranchOid=l}let h=Buffer.from(JSON.stringify(d,null,2),"utf-8");return{type:"file",content:h,mode:420,size:h.length}},"getFile"),rename:c(async function(a){throw new Error("not implemented")},"rename"),mkdir:c(async function(a){throw new Error("not implemented")},"mkdir")},n=new N({name:"branch-operations",gitStorageFs:t,gitRoot:i,rootPath:e||i,handler:r});return n}c(nr,"createBranchOperationsAdapter");import G from"@legit-sdk/isomorphic-git";import li from"@legit-sdk/isomorphic-git/http/node";var be="legit",ar=c(({fs:t,gitRepoPath:i,serverUrl:e="https://hub.legitcontrol.com",auth:r,anonymousBranch:n,authHeaderPrefix:a="Bearer "})=>{let s=!1;async function o(b){let F=await r.getMaxAccessTokenForBranch(b);if(!F)throw new Error(`No access token for branch ${b}`);await G.fetch({fs:t,http:li,dir:i,singleBranch:!0,ref:`${b}`,remote:be,url:e,headers:{Authorization:`${a}${F}`}});let y=await G.resolveRef({fs:t,dir:i,ref:`${be}/${b}`});await G.writeRef({fs:t,dir:i,ref:`refs/heads/${b}`,value:y})}c(o,"loadBranch");let d=[];async function l(){let b=await r.getMaxAccessTokenForBranch("todo");await G.fetch({fs:t,http:li,dir:i,remote:be,url:e,headers:{Authorization:`${a}${b}`}});let F=await G.listBranches({fs:t,dir:i});for(let y of F){if(y===n)continue;let _=`${be}/${y}`,w,P;try{w=await G.resolveRef({fs:t,dir:i,ref:y})}catch(A){console.log(`Could not resolve local ref ${y}:`,A)}try{P=await G.resolveRef({fs:t,dir:i,ref:_})}catch{P=void 0}if(w&&P){if(w!==P){let A=await G.findMergeBase({fs:t,dir:i,oids:[w,P]});if(A[0]!==w&&A[0]!==P){let k=await G.merge({fs:t,dir:i,ours:w,theirs:P,fastForwardOnly:!1,abortOnConflict:!1,author:{name:"Your Name",email:"your.email@example.com"},mergeDriver:c(async({branches:C,contents:E,path:x})=>{let[D,ee,we]=E;return console.log(`Merging ${C[0]} with ${C[1]}...`),console.log("merged:"),console.log(E),{cleanMerge:!0,mergedText:we===void 0?ee:we}},"mergeDriver")});await G.writeRef({fs:t,dir:i,ref:`refs/heads/${y}`,value:k.oid,force:!0})}A[0]===w?(console.log(`branch ${y} differs - remote ahaed, not behind`),await G.writeRef({fs:t,dir:i,ref:`refs/heads/${y}`,value:P,force:!0})):A[0]===P?(console.log(`branch ${y} differs - local ahead, not behind`),d.push(y)):(console.log(`branch ${y} differs - both changed`),d.push(y))}}else w&&!P&&d.push(y)}}c(l,"pull");async function h(b){if((await r.getUser()).type!=="local")for(let F of b){let y=await r.getMaxAccessTokenForBranch(F);await G.push({fs:t,http:li,dir:i,remote:be,url:e,ref:F,headers:{Authorization:`Bearer ${y}`}})}}c(h,"push");let m=Promise.resolve();async function f(b){m=m.then(()=>h(b)),await m}c(f,"sequentialPush");async function p(){await G.getConfig({fs:t,dir:i,path:`remote.${be}.fetch`})||await G.setConfig({fs:t,dir:i,path:`remote.${be}.fetch`,value:`+refs/heads/*:refs/remotes/${be}/*`});try{await l();let F=[...new Set(d)].filter(y=>y.indexOf(n)===-1);await f(F),d=[]}catch(F){console.error("Error monitoring changes:",F)}finally{s&&setTimeout(p,1e3)}}c(p,"pullPushTick");function u(){s=!0,p()}c(u,"startSync");function v(){s=!1}return c(v,"stopSync"),{start:c(()=>{s||(u(),s=!0)},"start"),stop:c(()=>{v()},"stop"),isRunning:c(()=>s,"isRunning"),loadBranch:o,sequentialPush:f}},"createLegitSyncService");import R from"@legit-sdk/isomorphic-git";function Ke(t){let i=t.length;for(;--i>=0;)t[i]=0}c(Ke,"zero$1");var ba=0,Vr=1,ga=2,_a=3,va=258,Ai=29,bt=256,ht=bt+1+Ai,Ze=30,Bi=19,Zr=2*ht+1,Te=15,ci=16,Pa=7,Ii=256,Wr=16,Gr=17,Kr=18,Pi=new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]),Nt=new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]),ka=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),Xr=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),xa=512,fe=new Array((ht+2)*2);Ke(fe);var lt=new Array(Ze*2);Ke(lt);var ft=new Array(xa);Ke(ft);var mt=new Array(va-_a+1);Ke(mt);var Ni=new Array(Ai);Ke(Ni);var Lt=new Array(Ze);Ke(Lt);function di(t,i,e,r,n){this.static_tree=t,this.extra_bits=i,this.extra_base=e,this.elems=r,this.max_length=n,this.has_stree=t&&t.length}c(di,"StaticTreeDesc");var Yr,Jr,qr;function hi(t,i){this.dyn_tree=t,this.max_code=0,this.stat_desc=i}c(hi,"TreeDesc");var Qr=c(t=>t<256?ft[t]:ft[256+(t>>>7)],"d_code"),pt=c((t,i)=>{t.pending_buf[t.pending++]=i&255,t.pending_buf[t.pending++]=i>>>8&255},"put_short"),K=c((t,i,e)=>{t.bi_valid>ci-e?(t.bi_buf|=i<<t.bi_valid&65535,pt(t,t.bi_buf),t.bi_buf=i>>ci-t.bi_valid,t.bi_valid+=e-ci):(t.bi_buf|=i<<t.bi_valid&65535,t.bi_valid+=e)},"send_bits"),ae=c((t,i,e)=>{K(t,e[i*2],e[i*2+1])},"send_code"),en=c((t,i)=>{let e=0;do e|=t&1,t>>>=1,e<<=1;while(--i>0);return e>>>1},"bi_reverse"),Ea=c(t=>{t.bi_valid===16?(pt(t,t.bi_buf),t.bi_buf=0,t.bi_valid=0):t.bi_valid>=8&&(t.pending_buf[t.pending++]=t.bi_buf&255,t.bi_buf>>=8,t.bi_valid-=8)},"bi_flush"),Da=c((t,i)=>{let e=i.dyn_tree,r=i.max_code,n=i.stat_desc.static_tree,a=i.stat_desc.has_stree,s=i.stat_desc.extra_bits,o=i.stat_desc.extra_base,d=i.stat_desc.max_length,l,h,m,f,p,u,v=0;for(f=0;f<=Te;f++)t.bl_count[f]=0;for(e[t.heap[t.heap_max]*2+1]=0,l=t.heap_max+1;l<Zr;l++)h=t.heap[l],f=e[e[h*2+1]*2+1]+1,f>d&&(f=d,v++),e[h*2+1]=f,!(h>r)&&(t.bl_count[f]++,p=0,h>=o&&(p=s[h-o]),u=e[h*2],t.opt_len+=u*(f+p),a&&(t.static_len+=u*(n[h*2+1]+p)));if(v!==0){do{for(f=d-1;t.bl_count[f]===0;)f--;t.bl_count[f]--,t.bl_count[f+1]+=2,t.bl_count[d]--,v-=2}while(v>0);for(f=d;f!==0;f--)for(h=t.bl_count[f];h!==0;)m=t.heap[--l],!(m>r)&&(e[m*2+1]!==f&&(t.opt_len+=(f-e[m*2+1])*e[m*2],e[m*2+1]=f),h--)}},"gen_bitlen"),tn=c((t,i,e)=>{let r=new Array(Te+1),n=0,a,s;for(a=1;a<=Te;a++)n=n+e[a-1]<<1,r[a]=n;for(s=0;s<=i;s++){let o=t[s*2+1];o!==0&&(t[s*2]=en(r[o]++,o))}},"gen_codes"),Sa=c(()=>{let t,i,e,r,n,a=new Array(Te+1);for(e=0,r=0;r<Ai-1;r++)for(Ni[r]=e,t=0;t<1<<Pi[r];t++)mt[e++]=r;for(mt[e-1]=r,n=0,r=0;r<16;r++)for(Lt[r]=n,t=0;t<1<<Nt[r];t++)ft[n++]=r;for(n>>=7;r<Ze;r++)for(Lt[r]=n<<7,t=0;t<1<<Nt[r]-7;t++)ft[256+n++]=r;for(i=0;i<=Te;i++)a[i]=0;for(t=0;t<=143;)fe[t*2+1]=8,t++,a[8]++;for(;t<=255;)fe[t*2+1]=9,t++,a[9]++;for(;t<=279;)fe[t*2+1]=7,t++,a[7]++;for(;t<=287;)fe[t*2+1]=8,t++,a[8]++;for(tn(fe,ht+1,a),t=0;t<Ze;t++)lt[t*2+1]=5,lt[t*2]=en(t,5);Yr=new di(fe,Pi,bt+1,ht,Te),Jr=new di(lt,Nt,0,Ze,Te),qr=new di(new Array(0),ka,0,Bi,Pa)},"tr_static_init"),rn=c(t=>{let i;for(i=0;i<ht;i++)t.dyn_ltree[i*2]=0;for(i=0;i<Ze;i++)t.dyn_dtree[i*2]=0;for(i=0;i<Bi;i++)t.bl_tree[i*2]=0;t.dyn_ltree[Ii*2]=1,t.opt_len=t.static_len=0,t.sym_next=t.matches=0},"init_block"),nn=c(t=>{t.bi_valid>8?pt(t,t.bi_buf):t.bi_valid>0&&(t.pending_buf[t.pending++]=t.bi_buf),t.bi_buf=0,t.bi_valid=0},"bi_windup"),sr=c((t,i,e,r)=>{let n=i*2,a=e*2;return t[n]<t[a]||t[n]===t[a]&&r[i]<=r[e]},"smaller"),fi=c((t,i,e)=>{let r=t.heap[e],n=e<<1;for(;n<=t.heap_len&&(n<t.heap_len&&sr(i,t.heap[n+1],t.heap[n],t.depth)&&n++,!sr(i,r,t.heap[n],t.depth));)t.heap[e]=t.heap[n],e=n,n<<=1;t.heap[e]=r},"pqdownheap"),or=c((t,i,e)=>{let r,n,a=0,s,o;if(t.sym_next!==0)do r=t.pending_buf[t.sym_buf+a++]&255,r+=(t.pending_buf[t.sym_buf+a++]&255)<<8,n=t.pending_buf[t.sym_buf+a++],r===0?ae(t,n,i):(s=mt[n],ae(t,s+bt+1,i),o=Pi[s],o!==0&&(n-=Ni[s],K(t,n,o)),r--,s=Qr(r),ae(t,s,e),o=Nt[s],o!==0&&(r-=Lt[s],K(t,r,o)));while(a<t.sym_next);ae(t,Ii,i)},"compress_block"),ki=c((t,i)=>{let e=i.dyn_tree,r=i.stat_desc.static_tree,n=i.stat_desc.has_stree,a=i.stat_desc.elems,s,o,d=-1,l;for(t.heap_len=0,t.heap_max=Zr,s=0;s<a;s++)e[s*2]!==0?(t.heap[++t.heap_len]=d=s,t.depth[s]=0):e[s*2+1]=0;for(;t.heap_len<2;)l=t.heap[++t.heap_len]=d<2?++d:0,e[l*2]=1,t.depth[l]=0,t.opt_len--,n&&(t.static_len-=r[l*2+1]);for(i.max_code=d,s=t.heap_len>>1;s>=1;s--)fi(t,e,s);l=a;do s=t.heap[1],t.heap[1]=t.heap[t.heap_len--],fi(t,e,1),o=t.heap[1],t.heap[--t.heap_max]=s,t.heap[--t.heap_max]=o,e[l*2]=e[s*2]+e[o*2],t.depth[l]=(t.depth[s]>=t.depth[o]?t.depth[s]:t.depth[o])+1,e[s*2+1]=e[o*2+1]=l,t.heap[1]=l++,fi(t,e,1);while(t.heap_len>=2);t.heap[--t.heap_max]=t.heap[1],Da(t,i),tn(e,d,t.bl_count)},"build_tree"),lr=c((t,i,e)=>{let r,n=-1,a,s=i[0*2+1],o=0,d=7,l=4;for(s===0&&(d=138,l=3),i[(e+1)*2+1]=65535,r=0;r<=e;r++)a=s,s=i[(r+1)*2+1],!(++o<d&&a===s)&&(o<l?t.bl_tree[a*2]+=o:a!==0?(a!==n&&t.bl_tree[a*2]++,t.bl_tree[Wr*2]++):o<=10?t.bl_tree[Gr*2]++:t.bl_tree[Kr*2]++,o=0,n=a,s===0?(d=138,l=3):a===s?(d=6,l=3):(d=7,l=4))},"scan_tree"),cr=c((t,i,e)=>{let r,n=-1,a,s=i[0*2+1],o=0,d=7,l=4;for(s===0&&(d=138,l=3),r=0;r<=e;r++)if(a=s,s=i[(r+1)*2+1],!(++o<d&&a===s)){if(o<l)do ae(t,a,t.bl_tree);while(--o!==0);else a!==0?(a!==n&&(ae(t,a,t.bl_tree),o--),ae(t,Wr,t.bl_tree),K(t,o-3,2)):o<=10?(ae(t,Gr,t.bl_tree),K(t,o-3,3)):(ae(t,Kr,t.bl_tree),K(t,o-11,7));o=0,n=a,s===0?(d=138,l=3):a===s?(d=6,l=3):(d=7,l=4)}},"send_tree"),Ta=c(t=>{let i;for(lr(t,t.dyn_ltree,t.l_desc.max_code),lr(t,t.dyn_dtree,t.d_desc.max_code),ki(t,t.bl_desc),i=Bi-1;i>=3&&t.bl_tree[Xr[i]*2+1]===0;i--);return t.opt_len+=3*(i+1)+5+5+4,i},"build_bl_tree"),Ca=c((t,i,e,r)=>{let n;for(K(t,i-257,5),K(t,e-1,5),K(t,r-4,4),n=0;n<r;n++)K(t,t.bl_tree[Xr[n]*2+1],3);cr(t,t.dyn_ltree,i-1),cr(t,t.dyn_dtree,e-1)},"send_all_trees"),Oa=c(t=>{let i=4093624447,e;for(e=0;e<=31;e++,i>>>=1)if(i&1&&t.dyn_ltree[e*2]!==0)return 0;if(t.dyn_ltree[9*2]!==0||t.dyn_ltree[10*2]!==0||t.dyn_ltree[13*2]!==0)return 1;for(e=32;e<bt;e++)if(t.dyn_ltree[e*2]!==0)return 1;return 0},"detect_data_type"),dr=!1,Aa=c(t=>{dr||(Sa(),dr=!0),t.l_desc=new hi(t.dyn_ltree,Yr),t.d_desc=new hi(t.dyn_dtree,Jr),t.bl_desc=new hi(t.bl_tree,qr),t.bi_buf=0,t.bi_valid=0,rn(t)},"_tr_init$1"),an=c((t,i,e,r)=>{K(t,(ba<<1)+(r?1:0),3),nn(t),pt(t,e),pt(t,~e),e&&t.pending_buf.set(t.window.subarray(i,i+e),t.pending),t.pending+=e},"_tr_stored_block$1"),Ba=c(t=>{K(t,Vr<<1,3),ae(t,Ii,fe),Ea(t)},"_tr_align$1"),Ia=c((t,i,e,r)=>{let n,a,s=0;t.level>0?(t.strm.data_type===2&&(t.strm.data_type=Oa(t)),ki(t,t.l_desc),ki(t,t.d_desc),s=Ta(t),n=t.opt_len+3+7>>>3,a=t.static_len+3+7>>>3,a<=n&&(n=a)):n=a=e+5,e+4<=n&&i!==-1?an(t,i,e,r):t.strategy===4||a===n?(K(t,(Vr<<1)+(r?1:0),3),or(t,fe,lt)):(K(t,(ga<<1)+(r?1:0),3),Ca(t,t.l_desc.max_code+1,t.d_desc.max_code+1,s+1),or(t,t.dyn_ltree,t.dyn_dtree)),rn(t),r&&nn(t)},"_tr_flush_block$1"),Na=c((t,i,e)=>(t.pending_buf[t.sym_buf+t.sym_next++]=i,t.pending_buf[t.sym_buf+t.sym_next++]=i>>8,t.pending_buf[t.sym_buf+t.sym_next++]=e,i===0?t.dyn_ltree[e*2]++:(t.matches++,i--,t.dyn_ltree[(mt[e]+bt+1)*2]++,t.dyn_dtree[Qr(i)*2]++),t.sym_next===t.sym_end),"_tr_tally$1"),La=Aa,za=an,Ha=Ia,$a=Na,Ma=Ba,Ra={_tr_init:La,_tr_stored_block:za,_tr_flush_block:Ha,_tr_tally:$a,_tr_align:Ma},Ua=c((t,i,e,r)=>{let n=t&65535|0,a=t>>>16&65535|0,s=0;for(;e!==0;){s=e>2e3?2e3:e,e-=s;do n=n+i[r++]|0,a=a+n|0;while(--s);n%=65521,a%=65521}return n|a<<16|0},"adler32"),ut=Ua,ja=c(()=>{let t,i=[];for(var e=0;e<256;e++){t=e;for(var r=0;r<8;r++)t=t&1?3988292384^t>>>1:t>>>1;i[e]=t}return i},"makeTable"),Va=new Uint32Array(ja()),Za=c((t,i,e,r)=>{let n=Va,a=r+e;t^=-1;for(let s=r;s<a;s++)t=t>>>8^n[(t^i[s])&255];return t^-1},"crc32"),M=Za,Ae={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"},Xe={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8},{_tr_init:Wa,_tr_stored_block:xi,_tr_flush_block:Ga,_tr_tally:ve,_tr_align:Ka}=Ra,{Z_NO_FLUSH:Pe,Z_PARTIAL_FLUSH:Xa,Z_FULL_FLUSH:Ya,Z_FINISH:q,Z_BLOCK:hr,Z_OK:U,Z_STREAM_END:fr,Z_STREAM_ERROR:se,Z_DATA_ERROR:Ja,Z_BUF_ERROR:mi,Z_DEFAULT_COMPRESSION:qa,Z_FILTERED:Qa,Z_HUFFMAN_ONLY:Ct,Z_RLE:es,Z_FIXED:ts,Z_DEFAULT_STRATEGY:is,Z_UNKNOWN:rs,Z_DEFLATED:$t}=Xe,ns=9,as=15,ss=8,os=29,ls=256,Ei=ls+1+os,cs=30,ds=19,hs=2*Ei+1,fs=15,S=3,_e=258,oe=_e+S+1,ms=32,We=42,Li=57,Di=69,Si=73,Ti=91,Ci=103,Ce=113,st=666,Z=1,Ye=2,Be=3,Je=4,ps=3,Oe=c((t,i)=>(t.msg=Ae[i],i),"err"),mr=c(t=>t*2-(t>4?9:0),"rank"),ge=c(t=>{let i=t.length;for(;--i>=0;)t[i]=0},"zero"),us=c(t=>{let i,e,r,n=t.w_size;i=t.hash_size,r=i;do e=t.head[--r],t.head[r]=e>=n?e-n:0;while(--i);i=n,r=i;do e=t.prev[--r],t.prev[r]=e>=n?e-n:0;while(--i)},"slide_hash"),ws=c((t,i,e)=>(i<<t.hash_shift^e)&t.hash_mask,"HASH_ZLIB"),ke=ws,X=c(t=>{let i=t.state,e=i.pending;e>t.avail_out&&(e=t.avail_out),e!==0&&(t.output.set(i.pending_buf.subarray(i.pending_out,i.pending_out+e),t.next_out),t.next_out+=e,i.pending_out+=e,t.total_out+=e,t.avail_out-=e,i.pending-=e,i.pending===0&&(i.pending_out=0))},"flush_pending"),Y=c((t,i)=>{Ga(t,t.block_start>=0?t.block_start:-1,t.strstart-t.block_start,i),t.block_start=t.strstart,X(t.strm)},"flush_block_only"),B=c((t,i)=>{t.pending_buf[t.pending++]=i},"put_byte"),at=c((t,i)=>{t.pending_buf[t.pending++]=i>>>8&255,t.pending_buf[t.pending++]=i&255},"putShortMSB"),Oi=c((t,i,e,r)=>{let n=t.avail_in;return n>r&&(n=r),n===0?0:(t.avail_in-=n,i.set(t.input.subarray(t.next_in,t.next_in+n),e),t.state.wrap===1?t.adler=ut(t.adler,i,n,e):t.state.wrap===2&&(t.adler=M(t.adler,i,n,e)),t.next_in+=n,t.total_in+=n,n)},"read_buf"),sn=c((t,i)=>{let e=t.max_chain_length,r=t.strstart,n,a,s=t.prev_length,o=t.nice_match,d=t.strstart>t.w_size-oe?t.strstart-(t.w_size-oe):0,l=t.window,h=t.w_mask,m=t.prev,f=t.strstart+_e,p=l[r+s-1],u=l[r+s];t.prev_length>=t.good_match&&(e>>=2),o>t.lookahead&&(o=t.lookahead);do if(n=i,!(l[n+s]!==u||l[n+s-1]!==p||l[n]!==l[r]||l[++n]!==l[r+1])){r+=2,n++;do;while(l[++r]===l[++n]&&l[++r]===l[++n]&&l[++r]===l[++n]&&l[++r]===l[++n]&&l[++r]===l[++n]&&l[++r]===l[++n]&&l[++r]===l[++n]&&l[++r]===l[++n]&&r<f);if(a=_e-(f-r),r=f-_e,a>s){if(t.match_start=i,s=a,a>=o)break;p=l[r+s-1],u=l[r+s]}}while((i=m[i&h])>d&&--e!==0);return s<=t.lookahead?s:t.lookahead},"longest_match"),Ge=c(t=>{let i=t.w_size,e,r,n;do{if(r=t.window_size-t.lookahead-t.strstart,t.strstart>=i+(i-oe)&&(t.window.set(t.window.subarray(i,i+i-r),0),t.match_start-=i,t.strstart-=i,t.block_start-=i,t.insert>t.strstart&&(t.insert=t.strstart),us(t),r+=i),t.strm.avail_in===0)break;if(e=Oi(t.strm,t.window,t.strstart+t.lookahead,r),t.lookahead+=e,t.lookahead+t.insert>=S)for(n=t.strstart-t.insert,t.ins_h=t.window[n],t.ins_h=ke(t,t.ins_h,t.window[n+1]);t.insert&&(t.ins_h=ke(t,t.ins_h,t.window[n+S-1]),t.prev[n&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=n,n++,t.insert--,!(t.lookahead+t.insert<S)););}while(t.lookahead<oe&&t.strm.avail_in!==0)},"fill_window"),on=c((t,i)=>{let e=t.pending_buf_size-5>t.w_size?t.w_size:t.pending_buf_size-5,r,n,a,s=0,o=t.strm.avail_in;do{if(r=65535,a=t.bi_valid+42>>3,t.strm.avail_out<a||(a=t.strm.avail_out-a,n=t.strstart-t.block_start,r>n+t.strm.avail_in&&(r=n+t.strm.avail_in),r>a&&(r=a),r<e&&(r===0&&i!==q||i===Pe||r!==n+t.strm.avail_in)))break;s=i===q&&r===n+t.strm.avail_in?1:0,xi(t,0,0,s),t.pending_buf[t.pending-4]=r,t.pending_buf[t.pending-3]=r>>8,t.pending_buf[t.pending-2]=~r,t.pending_buf[t.pending-1]=~r>>8,X(t.strm),n&&(n>r&&(n=r),t.strm.output.set(t.window.subarray(t.block_start,t.block_start+n),t.strm.next_out),t.strm.next_out+=n,t.strm.avail_out-=n,t.strm.total_out+=n,t.block_start+=n,r-=n),r&&(Oi(t.strm,t.strm.output,t.strm.next_out,r),t.strm.next_out+=r,t.strm.avail_out-=r,t.strm.total_out+=r)}while(s===0);return o-=t.strm.avail_in,o&&(o>=t.w_size?(t.matches=2,t.window.set(t.strm.input.subarray(t.strm.next_in-t.w_size,t.strm.next_in),0),t.strstart=t.w_size,t.insert=t.strstart):(t.window_size-t.strstart<=o&&(t.strstart-=t.w_size,t.window.set(t.window.subarray(t.w_size,t.w_size+t.strstart),0),t.matches<2&&t.matches++,t.insert>t.strstart&&(t.insert=t.strstart)),t.window.set(t.strm.input.subarray(t.strm.next_in-o,t.strm.next_in),t.strstart),t.strstart+=o,t.insert+=o>t.w_size-t.insert?t.w_size-t.insert:o),t.block_start=t.strstart),t.high_water<t.strstart&&(t.high_water=t.strstart),s?Je:i!==Pe&&i!==q&&t.strm.avail_in===0&&t.strstart===t.block_start?Ye:(a=t.window_size-t.strstart,t.strm.avail_in>a&&t.block_start>=t.w_size&&(t.block_start-=t.w_size,t.strstart-=t.w_size,t.window.set(t.window.subarray(t.w_size,t.w_size+t.strstart),0),t.matches<2&&t.matches++,a+=t.w_size,t.insert>t.strstart&&(t.insert=t.strstart)),a>t.strm.avail_in&&(a=t.strm.avail_in),a&&(Oi(t.strm,t.window,t.strstart,a),t.strstart+=a,t.insert+=a>t.w_size-t.insert?t.w_size-t.insert:a),t.high_water<t.strstart&&(t.high_water=t.strstart),a=t.bi_valid+42>>3,a=t.pending_buf_size-a>65535?65535:t.pending_buf_size-a,e=a>t.w_size?t.w_size:a,n=t.strstart-t.block_start,(n>=e||(n||i===q)&&i!==Pe&&t.strm.avail_in===0&&n<=a)&&(r=n>a?a:n,s=i===q&&t.strm.avail_in===0&&r===n?1:0,xi(t,t.block_start,r,s),t.block_start+=r,X(t.strm)),s?Be:Z)},"deflate_stored"),pi=c((t,i)=>{let e,r;for(;;){if(t.lookahead<oe){if(Ge(t),t.lookahead<oe&&i===Pe)return Z;if(t.lookahead===0)break}if(e=0,t.lookahead>=S&&(t.ins_h=ke(t,t.ins_h,t.window[t.strstart+S-1]),e=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),e!==0&&t.strstart-e<=t.w_size-oe&&(t.match_length=sn(t,e)),t.match_length>=S)if(r=ve(t,t.strstart-t.match_start,t.match_length-S),t.lookahead-=t.match_length,t.match_length<=t.max_lazy_match&&t.lookahead>=S){t.match_length--;do t.strstart++,t.ins_h=ke(t,t.ins_h,t.window[t.strstart+S-1]),e=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart;while(--t.match_length!==0);t.strstart++}else t.strstart+=t.match_length,t.match_length=0,t.ins_h=t.window[t.strstart],t.ins_h=ke(t,t.ins_h,t.window[t.strstart+1]);else r=ve(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++;if(r&&(Y(t,!1),t.strm.avail_out===0))return Z}return t.insert=t.strstart<S-1?t.strstart:S-1,i===q?(Y(t,!0),t.strm.avail_out===0?Be:Je):t.sym_next&&(Y(t,!1),t.strm.avail_out===0)?Z:Ye},"deflate_fast"),je=c((t,i)=>{let e,r,n;for(;;){if(t.lookahead<oe){if(Ge(t),t.lookahead<oe&&i===Pe)return Z;if(t.lookahead===0)break}if(e=0,t.lookahead>=S&&(t.ins_h=ke(t,t.ins_h,t.window[t.strstart+S-1]),e=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),t.prev_length=t.match_length,t.prev_match=t.match_start,t.match_length=S-1,e!==0&&t.prev_length<t.max_lazy_match&&t.strstart-e<=t.w_size-oe&&(t.match_length=sn(t,e),t.match_length<=5&&(t.strategy===Qa||t.match_length===S&&t.strstart-t.match_start>4096)&&(t.match_length=S-1)),t.prev_length>=S&&t.match_length<=t.prev_length){n=t.strstart+t.lookahead-S,r=ve(t,t.strstart-1-t.prev_match,t.prev_length-S),t.lookahead-=t.prev_length-1,t.prev_length-=2;do++t.strstart<=n&&(t.ins_h=ke(t,t.ins_h,t.window[t.strstart+S-1]),e=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart);while(--t.prev_length!==0);if(t.match_available=0,t.match_length=S-1,t.strstart++,r&&(Y(t,!1),t.strm.avail_out===0))return Z}else if(t.match_available){if(r=ve(t,0,t.window[t.strstart-1]),r&&Y(t,!1),t.strstart++,t.lookahead--,t.strm.avail_out===0)return Z}else t.match_available=1,t.strstart++,t.lookahead--}return t.match_available&&(r=ve(t,0,t.window[t.strstart-1]),t.match_available=0),t.insert=t.strstart<S-1?t.strstart:S-1,i===q?(Y(t,!0),t.strm.avail_out===0?Be:Je):t.sym_next&&(Y(t,!1),t.strm.avail_out===0)?Z:Ye},"deflate_slow"),ys=c((t,i)=>{let e,r,n,a,s=t.window;for(;;){if(t.lookahead<=_e){if(Ge(t),t.lookahead<=_e&&i===Pe)return Z;if(t.lookahead===0)break}if(t.match_length=0,t.lookahead>=S&&t.strstart>0&&(n=t.strstart-1,r=s[n],r===s[++n]&&r===s[++n]&&r===s[++n])){a=t.strstart+_e;do;while(r===s[++n]&&r===s[++n]&&r===s[++n]&&r===s[++n]&&r===s[++n]&&r===s[++n]&&r===s[++n]&&r===s[++n]&&n<a);t.match_length=_e-(a-n),t.match_length>t.lookahead&&(t.match_length=t.lookahead)}if(t.match_length>=S?(e=ve(t,1,t.match_length-S),t.lookahead-=t.match_length,t.strstart+=t.match_length,t.match_length=0):(e=ve(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++),e&&(Y(t,!1),t.strm.avail_out===0))return Z}return t.insert=0,i===q?(Y(t,!0),t.strm.avail_out===0?Be:Je):t.sym_next&&(Y(t,!1),t.strm.avail_out===0)?Z:Ye},"deflate_rle"),Fs=c((t,i)=>{let e;for(;;){if(t.lookahead===0&&(Ge(t),t.lookahead===0)){if(i===Pe)return Z;break}if(t.match_length=0,e=ve(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++,e&&(Y(t,!1),t.strm.avail_out===0))return Z}return t.insert=0,i===q?(Y(t,!0),t.strm.avail_out===0?Be:Je):t.sym_next&&(Y(t,!1),t.strm.avail_out===0)?Z:Ye},"deflate_huff");function ne(t,i,e,r,n){this.good_length=t,this.max_lazy=i,this.nice_length=e,this.max_chain=r,this.func=n}c(ne,"Config");var ot=[new ne(0,0,0,0,on),new ne(4,4,8,4,pi),new ne(4,5,16,8,pi),new ne(4,6,32,32,pi),new ne(4,4,16,16,je),new ne(8,16,32,32,je),new ne(8,16,128,128,je),new ne(8,32,128,256,je),new ne(32,128,258,1024,je),new ne(32,258,258,4096,je)],bs=c(t=>{t.window_size=2*t.w_size,ge(t.head),t.max_lazy_match=ot[t.level].max_lazy,t.good_match=ot[t.level].good_length,t.nice_match=ot[t.level].nice_length,t.max_chain_length=ot[t.level].max_chain,t.strstart=0,t.block_start=0,t.lookahead=0,t.insert=0,t.match_length=t.prev_length=S-1,t.match_available=0,t.ins_h=0},"lm_init");function gs(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=$t,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Uint16Array(hs*2),this.dyn_dtree=new Uint16Array((2*cs+1)*2),this.bl_tree=new Uint16Array((2*ds+1)*2),ge(this.dyn_ltree),ge(this.dyn_dtree),ge(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(fs+1),this.heap=new Uint16Array(2*Ei+1),ge(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(2*Ei+1),ge(this.depth),this.sym_buf=0,this.lit_bufsize=0,this.sym_next=0,this.sym_end=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}c(gs,"DeflateState");var gt=c(t=>{if(!t)return 1;let i=t.state;return!i||i.strm!==t||i.status!==We&&i.status!==Li&&i.status!==Di&&i.status!==Si&&i.status!==Ti&&i.status!==Ci&&i.status!==Ce&&i.status!==st?1:0},"deflateStateCheck"),ln=c(t=>{if(gt(t))return Oe(t,se);t.total_in=t.total_out=0,t.data_type=rs;let i=t.state;return i.pending=0,i.pending_out=0,i.wrap<0&&(i.wrap=-i.wrap),i.status=i.wrap===2?Li:i.wrap?We:Ce,t.adler=i.wrap===2?0:1,i.last_flush=-2,Wa(i),U},"deflateResetKeep"),cn=c(t=>{let i=ln(t);return i===U&&bs(t.state),i},"deflateReset"),_s=c((t,i)=>gt(t)||t.state.wrap!==2?se:(t.state.gzhead=i,U),"deflateSetHeader"),dn=c((t,i,e,r,n,a)=>{if(!t)return se;let s=1;if(i===qa&&(i=6),r<0?(s=0,r=-r):r>15&&(s=2,r-=16),n<1||n>ns||e!==$t||r<8||r>15||i<0||i>9||a<0||a>ts||r===8&&s!==1)return Oe(t,se);r===8&&(r=9);let o=new gs;return t.state=o,o.strm=t,o.status=We,o.wrap=s,o.gzhead=null,o.w_bits=r,o.w_size=1<<o.w_bits,o.w_mask=o.w_size-1,o.hash_bits=n+7,o.hash_size=1<<o.hash_bits,o.hash_mask=o.hash_size-1,o.hash_shift=~~((o.hash_bits+S-1)/S),o.window=new Uint8Array(o.w_size*2),o.head=new Uint16Array(o.hash_size),o.prev=new Uint16Array(o.w_size),o.lit_bufsize=1<<n+6,o.pending_buf_size=o.lit_bufsize*4,o.pending_buf=new Uint8Array(o.pending_buf_size),o.sym_buf=o.lit_bufsize,o.sym_end=(o.lit_bufsize-1)*3,o.level=i,o.strategy=a,o.method=e,cn(t)},"deflateInit2"),vs=c((t,i)=>dn(t,i,$t,as,ss,is),"deflateInit"),Ps=c((t,i)=>{if(gt(t)||i>hr||i<0)return t?Oe(t,se):se;let e=t.state;if(!t.output||t.avail_in!==0&&!t.input||e.status===st&&i!==q)return Oe(t,t.avail_out===0?mi:se);let r=e.last_flush;if(e.last_flush=i,e.pending!==0){if(X(t),t.avail_out===0)return e.last_flush=-1,U}else if(t.avail_in===0&&mr(i)<=mr(r)&&i!==q)return Oe(t,mi);if(e.status===st&&t.avail_in!==0)return Oe(t,mi);if(e.status===We&&e.wrap===0&&(e.status=Ce),e.status===We){let n=$t+(e.w_bits-8<<4)<<8,a=-1;if(e.strategy>=Ct||e.level<2?a=0:e.level<6?a=1:e.level===6?a=2:a=3,n|=a<<6,e.strstart!==0&&(n|=ms),n+=31-n%31,at(e,n),e.strstart!==0&&(at(e,t.adler>>>16),at(e,t.adler&65535)),t.adler=1,e.status=Ce,X(t),e.pending!==0)return e.last_flush=-1,U}if(e.status===Li){if(t.adler=0,B(e,31),B(e,139),B(e,8),e.gzhead)B(e,(e.gzhead.text?1:0)+(e.gzhead.hcrc?2:0)+(e.gzhead.extra?4:0)+(e.gzhead.name?8:0)+(e.gzhead.comment?16:0)),B(e,e.gzhead.time&255),B(e,e.gzhead.time>>8&255),B(e,e.gzhead.time>>16&255),B(e,e.gzhead.time>>24&255),B(e,e.level===9?2:e.strategy>=Ct||e.level<2?4:0),B(e,e.gzhead.os&255),e.gzhead.extra&&e.gzhead.extra.length&&(B(e,e.gzhead.extra.length&255),B(e,e.gzhead.extra.length>>8&255)),e.gzhead.hcrc&&(t.adler=M(t.adler,e.pending_buf,e.pending,0)),e.gzindex=0,e.status=Di;else if(B(e,0),B(e,0),B(e,0),B(e,0),B(e,0),B(e,e.level===9?2:e.strategy>=Ct||e.level<2?4:0),B(e,ps),e.status=Ce,X(t),e.pending!==0)return e.last_flush=-1,U}if(e.status===Di){if(e.gzhead.extra){let n=e.pending,a=(e.gzhead.extra.length&65535)-e.gzindex;for(;e.pending+a>e.pending_buf_size;){let o=e.pending_buf_size-e.pending;if(e.pending_buf.set(e.gzhead.extra.subarray(e.gzindex,e.gzindex+o),e.pending),e.pending=e.pending_buf_size,e.gzhead.hcrc&&e.pending>n&&(t.adler=M(t.adler,e.pending_buf,e.pending-n,n)),e.gzindex+=o,X(t),e.pending!==0)return e.last_flush=-1,U;n=0,a-=o}let s=new Uint8Array(e.gzhead.extra);e.pending_buf.set(s.subarray(e.gzindex,e.gzindex+a),e.pending),e.pending+=a,e.gzhead.hcrc&&e.pending>n&&(t.adler=M(t.adler,e.pending_buf,e.pending-n,n)),e.gzindex=0}e.status=Si}if(e.status===Si){if(e.gzhead.name){let n=e.pending,a;do{if(e.pending===e.pending_buf_size){if(e.gzhead.hcrc&&e.pending>n&&(t.adler=M(t.adler,e.pending_buf,e.pending-n,n)),X(t),e.pending!==0)return e.last_flush=-1,U;n=0}e.gzindex<e.gzhead.name.length?a=e.gzhead.name.charCodeAt(e.gzindex++)&255:a=0,B(e,a)}while(a!==0);e.gzhead.hcrc&&e.pending>n&&(t.adler=M(t.adler,e.pending_buf,e.pending-n,n)),e.gzindex=0}e.status=Ti}if(e.status===Ti){if(e.gzhead.comment){let n=e.pending,a;do{if(e.pending===e.pending_buf_size){if(e.gzhead.hcrc&&e.pending>n&&(t.adler=M(t.adler,e.pending_buf,e.pending-n,n)),X(t),e.pending!==0)return e.last_flush=-1,U;n=0}e.gzindex<e.gzhead.comment.length?a=e.gzhead.comment.charCodeAt(e.gzindex++)&255:a=0,B(e,a)}while(a!==0);e.gzhead.hcrc&&e.pending>n&&(t.adler=M(t.adler,e.pending_buf,e.pending-n,n))}e.status=Ci}if(e.status===Ci){if(e.gzhead.hcrc){if(e.pending+2>e.pending_buf_size&&(X(t),e.pending!==0))return e.last_flush=-1,U;B(e,t.adler&255),B(e,t.adler>>8&255),t.adler=0}if(e.status=Ce,X(t),e.pending!==0)return e.last_flush=-1,U}if(t.avail_in!==0||e.lookahead!==0||i!==Pe&&e.status!==st){let n=e.level===0?on(e,i):e.strategy===Ct?Fs(e,i):e.strategy===es?ys(e,i):ot[e.level].func(e,i);if((n===Be||n===Je)&&(e.status=st),n===Z||n===Be)return t.avail_out===0&&(e.last_flush=-1),U;if(n===Ye&&(i===Xa?Ka(e):i!==hr&&(xi(e,0,0,!1),i===Ya&&(ge(e.head),e.lookahead===0&&(e.strstart=0,e.block_start=0,e.insert=0))),X(t),t.avail_out===0))return e.last_flush=-1,U}return i!==q?U:e.wrap<=0?fr:(e.wrap===2?(B(e,t.adler&255),B(e,t.adler>>8&255),B(e,t.adler>>16&255),B(e,t.adler>>24&255),B(e,t.total_in&255),B(e,t.total_in>>8&255),B(e,t.total_in>>16&255),B(e,t.total_in>>24&255)):(at(e,t.adler>>>16),at(e,t.adler&65535)),X(t),e.wrap>0&&(e.wrap=-e.wrap),e.pending!==0?U:fr)},"deflate$2"),ks=c(t=>{if(gt(t))return se;let i=t.state.status;return t.state=null,i===Ce?Oe(t,Ja):U},"deflateEnd"),xs=c((t,i)=>{let e=i.length;if(gt(t))return se;let r=t.state,n=r.wrap;if(n===2||n===1&&r.status!==We||r.lookahead)return se;if(n===1&&(t.adler=ut(t.adler,i,e,0)),r.wrap=0,e>=r.w_size){n===0&&(ge(r.head),r.strstart=0,r.block_start=0,r.insert=0);let d=new Uint8Array(r.w_size);d.set(i.subarray(e-r.w_size,e),0),i=d,e=r.w_size}let a=t.avail_in,s=t.next_in,o=t.input;for(t.avail_in=e,t.next_in=0,t.input=i,Ge(r);r.lookahead>=S;){let d=r.strstart,l=r.lookahead-(S-1);do r.ins_h=ke(r,r.ins_h,r.window[d+S-1]),r.prev[d&r.w_mask]=r.head[r.ins_h],r.head[r.ins_h]=d,d++;while(--l);r.strstart=d,r.lookahead=S-1,Ge(r)}return r.strstart+=r.lookahead,r.block_start=r.strstart,r.insert=r.lookahead,r.lookahead=0,r.match_length=r.prev_length=S-1,r.match_available=0,t.next_in=s,t.input=o,t.avail_in=a,r.wrap=n,U},"deflateSetDictionary"),Es=vs,Ds=dn,Ss=cn,Ts=ln,Cs=_s,Os=Ps,As=ks,Bs=xs,Is="pako deflate (from Nodeca project)",ct={deflateInit:Es,deflateInit2:Ds,deflateReset:Ss,deflateResetKeep:Ts,deflateSetHeader:Cs,deflate:Os,deflateEnd:As,deflateSetDictionary:Bs,deflateInfo:Is},Ns=c((t,i)=>Object.prototype.hasOwnProperty.call(t,i),"_has"),Ls=c(function(t){let i=Array.prototype.slice.call(arguments,1);for(;i.length;){let e=i.shift();if(e){if(typeof e!="object")throw new TypeError(e+"must be non-object");for(let r in e)Ns(e,r)&&(t[r]=e[r])}}return t},"assign"),zs=c(t=>{let i=0;for(let r=0,n=t.length;r<n;r++)i+=t[r].length;let e=new Uint8Array(i);for(let r=0,n=0,a=t.length;r<a;r++){let s=t[r];e.set(s,n),n+=s.length}return e},"flattenChunks"),Mt={assign:Ls,flattenChunks:zs},hn=!0;try{String.fromCharCode.apply(null,new Uint8Array(1))}catch{hn=!1}var wt=new Uint8Array(256);for(let t=0;t<256;t++)wt[t]=t>=252?6:t>=248?5:t>=240?4:t>=224?3:t>=192?2:1;wt[254]=wt[254]=1;var Hs=c(t=>{if(typeof TextEncoder=="function"&&TextEncoder.prototype.encode)return new TextEncoder().encode(t);let i,e,r,n,a,s=t.length,o=0;for(n=0;n<s;n++)e=t.charCodeAt(n),(e&64512)===55296&&n+1<s&&(r=t.charCodeAt(n+1),(r&64512)===56320&&(e=65536+(e-55296<<10)+(r-56320),n++)),o+=e<128?1:e<2048?2:e<65536?3:4;for(i=new Uint8Array(o),a=0,n=0;a<o;n++)e=t.charCodeAt(n),(e&64512)===55296&&n+1<s&&(r=t.charCodeAt(n+1),(r&64512)===56320&&(e=65536+(e-55296<<10)+(r-56320),n++)),e<128?i[a++]=e:e<2048?(i[a++]=192|e>>>6,i[a++]=128|e&63):e<65536?(i[a++]=224|e>>>12,i[a++]=128|e>>>6&63,i[a++]=128|e&63):(i[a++]=240|e>>>18,i[a++]=128|e>>>12&63,i[a++]=128|e>>>6&63,i[a++]=128|e&63);return i},"string2buf"),$s=c((t,i)=>{if(i<65534&&t.subarray&&hn)return String.fromCharCode.apply(null,t.length===i?t:t.subarray(0,i));let e="";for(let r=0;r<i;r++)e+=String.fromCharCode(t[r]);return e},"buf2binstring"),Ms=c((t,i)=>{let e=i||t.length;if(typeof TextDecoder=="function"&&TextDecoder.prototype.decode)return new TextDecoder().decode(t.subarray(0,i));let r,n,a=new Array(e*2);for(n=0,r=0;r<e;){let s=t[r++];if(s<128){a[n++]=s;continue}let o=wt[s];if(o>4){a[n++]=65533,r+=o-1;continue}for(s&=o===2?31:o===3?15:7;o>1&&r<e;)s=s<<6|t[r++]&63,o--;if(o>1){a[n++]=65533;continue}s<65536?a[n++]=s:(s-=65536,a[n++]=55296|s>>10&1023,a[n++]=56320|s&1023)}return $s(a,n)},"buf2string"),Rs=c((t,i)=>{i=i||t.length,i>t.length&&(i=t.length);let e=i-1;for(;e>=0&&(t[e]&192)===128;)e--;return e<0||e===0?i:e+wt[t[e]]>i?e:i},"utf8border"),yt={string2buf:Hs,buf2string:Ms,utf8border:Rs};function Us(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}c(Us,"ZStream");var fn=Us,mn=Object.prototype.toString,{Z_NO_FLUSH:js,Z_SYNC_FLUSH:Vs,Z_FULL_FLUSH:Zs,Z_FINISH:Ws,Z_OK:zt,Z_STREAM_END:Gs,Z_DEFAULT_COMPRESSION:Ks,Z_DEFAULT_STRATEGY:Xs,Z_DEFLATED:Ys}=Xe;function _t(t){this.options=Mt.assign({level:Ks,method:Ys,chunkSize:16384,windowBits:15,memLevel:8,strategy:Xs},t||{});let i=this.options;i.raw&&i.windowBits>0?i.windowBits=-i.windowBits:i.gzip&&i.windowBits>0&&i.windowBits<16&&(i.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new fn,this.strm.avail_out=0;let e=ct.deflateInit2(this.strm,i.level,i.method,i.windowBits,i.memLevel,i.strategy);if(e!==zt)throw new Error(Ae[e]);if(i.header&&ct.deflateSetHeader(this.strm,i.header),i.dictionary){let r;if(typeof i.dictionary=="string"?r=yt.string2buf(i.dictionary):mn.call(i.dictionary)==="[object ArrayBuffer]"?r=new Uint8Array(i.dictionary):r=i.dictionary,e=ct.deflateSetDictionary(this.strm,r),e!==zt)throw new Error(Ae[e]);this._dict_set=!0}}c(_t,"Deflate$1");_t.prototype.push=function(t,i){let e=this.strm,r=this.options.chunkSize,n,a;if(this.ended)return!1;for(i===~~i?a=i:a=i===!0?Ws:js,typeof t=="string"?e.input=yt.string2buf(t):mn.call(t)==="[object ArrayBuffer]"?e.input=new Uint8Array(t):e.input=t,e.next_in=0,e.avail_in=e.input.length;;){if(e.avail_out===0&&(e.output=new Uint8Array(r),e.next_out=0,e.avail_out=r),(a===Vs||a===Zs)&&e.avail_out<=6){this.onData(e.output.subarray(0,e.next_out)),e.avail_out=0;continue}if(n=ct.deflate(e,a),n===Gs)return e.next_out>0&&this.onData(e.output.subarray(0,e.next_out)),n=ct.deflateEnd(this.strm),this.onEnd(n),this.ended=!0,n===zt;if(e.avail_out===0){this.onData(e.output);continue}if(a>0&&e.next_out>0){this.onData(e.output.subarray(0,e.next_out)),e.avail_out=0;continue}if(e.avail_in===0)break}return!0};_t.prototype.onData=function(t){this.chunks.push(t)};_t.prototype.onEnd=function(t){t===zt&&(this.result=Mt.flattenChunks(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg};function zi(t,i){let e=new _t(i);if(e.push(t,!0),e.err)throw e.msg||Ae[e.err];return e.result}c(zi,"deflate$1");function Js(t,i){return i=i||{},i.raw=!0,zi(t,i)}c(Js,"deflateRaw$1");function qs(t,i){return i=i||{},i.gzip=!0,zi(t,i)}c(qs,"gzip$1");var Qs=_t,eo=zi,to=Js,io=qs,ro=Xe,no={Deflate:Qs,deflate:eo,deflateRaw:to,gzip:io,constants:ro},Ot=16209,ao=16191,so=c(function(i,e){let r,n,a,s,o,d,l,h,m,f,p,u,v,b,F,y,_,w,P,A,k,C,E,x,D=i.state;r=i.next_in,E=i.input,n=r+(i.avail_in-5),a=i.next_out,x=i.output,s=a-(e-i.avail_out),o=a+(i.avail_out-257),d=D.dmax,l=D.wsize,h=D.whave,m=D.wnext,f=D.window,p=D.hold,u=D.bits,v=D.lencode,b=D.distcode,F=(1<<D.lenbits)-1,y=(1<<D.distbits)-1;e:do{u<15&&(p+=E[r++]<<u,u+=8,p+=E[r++]<<u,u+=8),_=v[p&F];t:for(;;){if(w=_>>>24,p>>>=w,u-=w,w=_>>>16&255,w===0)x[a++]=_&65535;else if(w&16){P=_&65535,w&=15,w&&(u<w&&(p+=E[r++]<<u,u+=8),P+=p&(1<<w)-1,p>>>=w,u-=w),u<15&&(p+=E[r++]<<u,u+=8,p+=E[r++]<<u,u+=8),_=b[p&y];i:for(;;){if(w=_>>>24,p>>>=w,u-=w,w=_>>>16&255,w&16){if(A=_&65535,w&=15,u<w&&(p+=E[r++]<<u,u+=8,u<w&&(p+=E[r++]<<u,u+=8)),A+=p&(1<<w)-1,A>d){i.msg="invalid distance too far back",D.mode=Ot;break e}if(p>>>=w,u-=w,w=a-s,A>w){if(w=A-w,w>h&&D.sane){i.msg="invalid distance too far back",D.mode=Ot;break e}if(k=0,C=f,m===0){if(k+=l-w,w<P){P-=w;do x[a++]=f[k++];while(--w);k=a-A,C=x}}else if(m<w){if(k+=l+m-w,w-=m,w<P){P-=w;do x[a++]=f[k++];while(--w);if(k=0,m<P){w=m,P-=w;do x[a++]=f[k++];while(--w);k=a-A,C=x}}}else if(k+=m-w,w<P){P-=w;do x[a++]=f[k++];while(--w);k=a-A,C=x}for(;P>2;)x[a++]=C[k++],x[a++]=C[k++],x[a++]=C[k++],P-=3;P&&(x[a++]=C[k++],P>1&&(x[a++]=C[k++]))}else{k=a-A;do x[a++]=x[k++],x[a++]=x[k++],x[a++]=x[k++],P-=3;while(P>2);P&&(x[a++]=x[k++],P>1&&(x[a++]=x[k++]))}}else if(w&64){i.msg="invalid distance code",D.mode=Ot;break e}else{_=b[(_&65535)+(p&(1<<w)-1)];continue i}break}}else if(w&64)if(w&32){D.mode=ao;break e}else{i.msg="invalid literal/length code",D.mode=Ot;break e}else{_=v[(_&65535)+(p&(1<<w)-1)];continue t}break}}while(r<n&&a<o);P=u>>3,r-=P,u-=P<<3,p&=(1<<u)-1,i.next_in=r,i.next_out=a,i.avail_in=r<n?5+(n-r):5-(r-n),i.avail_out=a<o?257+(o-a):257-(a-o),D.hold=p,D.bits=u},"inflate_fast"),Ve=15,pr=852,ur=592,wr=0,ui=1,yr=2,oo=new Uint16Array([3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0]),lo=new Uint8Array([16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78]),co=new Uint16Array([1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0]),ho=new Uint8Array([16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64]),fo=c((t,i,e,r,n,a,s,o)=>{let d=o.bits,l=0,h=0,m=0,f=0,p=0,u=0,v=0,b=0,F=0,y=0,_,w,P,A,k,C=null,E,x=new Uint16Array(Ve+1),D=new Uint16Array(Ve+1),ee=null,we,Ee,$e;for(l=0;l<=Ve;l++)x[l]=0;for(h=0;h<r;h++)x[i[e+h]]++;for(p=d,f=Ve;f>=1&&x[f]===0;f--);if(p>f&&(p=f),f===0)return n[a++]=1<<24|64<<16|0,n[a++]=1<<24|64<<16|0,o.bits=1,0;for(m=1;m<f&&x[m]===0;m++);for(p<m&&(p=m),b=1,l=1;l<=Ve;l++)if(b<<=1,b-=x[l],b<0)return-1;if(b>0&&(t===wr||f!==1))return-1;for(D[1]=0,l=1;l<Ve;l++)D[l+1]=D[l]+x[l];for(h=0;h<r;h++)i[e+h]!==0&&(s[D[i[e+h]]++]=h);if(t===wr?(C=ee=s,E=20):t===ui?(C=oo,ee=lo,E=257):(C=co,ee=ho,E=0),y=0,h=0,l=m,k=a,u=p,v=0,P=-1,F=1<<p,A=F-1,t===ui&&F>pr||t===yr&&F>ur)return 1;for(;;){we=l-v,s[h]+1<E?(Ee=0,$e=s[h]):s[h]>=E?(Ee=ee[s[h]-E],$e=C[s[h]-E]):(Ee=96,$e=0),_=1<<l-v,w=1<<u,m=w;do w-=_,n[k+(y>>v)+w]=we<<24|Ee<<16|$e|0;while(w!==0);for(_=1<<l-1;y&_;)_>>=1;if(_!==0?(y&=_-1,y+=_):y=0,h++,--x[l]===0){if(l===f)break;l=i[e+s[h]]}if(l>p&&(y&A)!==P){for(v===0&&(v=p),k+=m,u=l-v,b=1<<u;u+v<f&&(b-=x[u+v],!(b<=0));)u++,b<<=1;if(F+=1<<u,t===ui&&F>pr||t===yr&&F>ur)return 1;P=y&A,n[P]=p<<24|u<<16|k-a|0}}return y!==0&&(n[k+y]=l-v<<24|64<<16|0),o.bits=p,0},"inflate_table"),dt=fo,mo=0,pn=1,un=2,{Z_FINISH:Fr,Z_BLOCK:po,Z_TREES:At,Z_OK:Ie,Z_STREAM_END:uo,Z_NEED_DICT:wo,Z_STREAM_ERROR:Q,Z_DATA_ERROR:wn,Z_MEM_ERROR:yn,Z_BUF_ERROR:yo,Z_DEFLATED:br}=Xe,Rt=16180,gr=16181,_r=16182,vr=16183,Pr=16184,kr=16185,xr=16186,Er=16187,Dr=16188,Sr=16189,Ht=16190,he=16191,wi=16192,Tr=16193,yi=16194,Cr=16195,Or=16196,Ar=16197,Br=16198,Bt=16199,It=16200,Ir=16201,Nr=16202,Lr=16203,zr=16204,Hr=16205,Fi=16206,$r=16207,Mr=16208,$=16209,Fn=16210,bn=16211,Fo=852,bo=592,go=15,_o=go,Rr=c(t=>(t>>>24&255)+(t>>>8&65280)+((t&65280)<<8)+((t&255)<<24),"zswap32");function vo(){this.strm=null,this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}c(vo,"InflateState");var Ne=c(t=>{if(!t)return 1;let i=t.state;return!i||i.strm!==t||i.mode<Rt||i.mode>bn?1:0},"inflateStateCheck"),gn=c(t=>{if(Ne(t))return Q;let i=t.state;return t.total_in=t.total_out=i.total=0,t.msg="",i.wrap&&(t.adler=i.wrap&1),i.mode=Rt,i.last=0,i.havedict=0,i.flags=-1,i.dmax=32768,i.head=null,i.hold=0,i.bits=0,i.lencode=i.lendyn=new Int32Array(Fo),i.distcode=i.distdyn=new Int32Array(bo),i.sane=1,i.back=-1,Ie},"inflateResetKeep"),_n=c(t=>{if(Ne(t))return Q;let i=t.state;return i.wsize=0,i.whave=0,i.wnext=0,gn(t)},"inflateReset"),vn=c((t,i)=>{let e;if(Ne(t))return Q;let r=t.state;return i<0?(e=0,i=-i):(e=(i>>4)+5,i<48&&(i&=15)),i&&(i<8||i>15)?Q:(r.window!==null&&r.wbits!==i&&(r.window=null),r.wrap=e,r.wbits=i,_n(t))},"inflateReset2"),Pn=c((t,i)=>{if(!t)return Q;let e=new vo;t.state=e,e.strm=t,e.window=null,e.mode=Rt;let r=vn(t,i);return r!==Ie&&(t.state=null),r},"inflateInit2"),Po=c(t=>Pn(t,_o),"inflateInit"),Ur=!0,bi,gi,ko=c(t=>{if(Ur){bi=new Int32Array(512),gi=new Int32Array(32);let i=0;for(;i<144;)t.lens[i++]=8;for(;i<256;)t.lens[i++]=9;for(;i<280;)t.lens[i++]=7;for(;i<288;)t.lens[i++]=8;for(dt(pn,t.lens,0,288,bi,0,t.work,{bits:9}),i=0;i<32;)t.lens[i++]=5;dt(un,t.lens,0,32,gi,0,t.work,{bits:5}),Ur=!1}t.lencode=bi,t.lenbits=9,t.distcode=gi,t.distbits=5},"fixedtables"),kn=c((t,i,e,r)=>{let n,a=t.state;return a.window===null&&(a.wsize=1<<a.wbits,a.wnext=0,a.whave=0,a.window=new Uint8Array(a.wsize)),r>=a.wsize?(a.window.set(i.subarray(e-a.wsize,e),0),a.wnext=0,a.whave=a.wsize):(n=a.wsize-a.wnext,n>r&&(n=r),a.window.set(i.subarray(e-r,e-r+n),a.wnext),r-=n,r?(a.window.set(i.subarray(e-r,e),0),a.wnext=r,a.whave=a.wsize):(a.wnext+=n,a.wnext===a.wsize&&(a.wnext=0),a.whave<a.wsize&&(a.whave+=n))),0},"updatewindow"),xo=c((t,i)=>{let e,r,n,a,s,o,d,l,h,m,f,p,u,v,b=0,F,y,_,w,P,A,k,C,E=new Uint8Array(4),x,D,ee=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(Ne(t)||!t.output||!t.input&&t.avail_in!==0)return Q;e=t.state,e.mode===he&&(e.mode=wi),s=t.next_out,n=t.output,d=t.avail_out,a=t.next_in,r=t.input,o=t.avail_in,l=e.hold,h=e.bits,m=o,f=d,C=Ie;e:for(;;)switch(e.mode){case Rt:if(e.wrap===0){e.mode=wi;break}for(;h<16;){if(o===0)break e;o--,l+=r[a++]<<h,h+=8}if(e.wrap&2&&l===35615){e.wbits===0&&(e.wbits=15),e.check=0,E[0]=l&255,E[1]=l>>>8&255,e.check=M(e.check,E,2,0),l=0,h=0,e.mode=gr;break}if(e.head&&(e.head.done=!1),!(e.wrap&1)||(((l&255)<<8)+(l>>8))%31){t.msg="incorrect header check",e.mode=$;break}if((l&15)!==br){t.msg="unknown compression method",e.mode=$;break}if(l>>>=4,h-=4,k=(l&15)+8,e.wbits===0&&(e.wbits=k),k>15||k>e.wbits){t.msg="invalid window size",e.mode=$;break}e.dmax=1<<e.wbits,e.flags=0,t.adler=e.check=1,e.mode=l&512?Sr:he,l=0,h=0;break;case gr:for(;h<16;){if(o===0)break e;o--,l+=r[a++]<<h,h+=8}if(e.flags=l,(e.flags&255)!==br){t.msg="unknown compression method",e.mode=$;break}if(e.flags&57344){t.msg="unknown header flags set",e.mode=$;break}e.head&&(e.head.text=l>>8&1),e.flags&512&&e.wrap&4&&(E[0]=l&255,E[1]=l>>>8&255,e.check=M(e.check,E,2,0)),l=0,h=0,e.mode=_r;case _r:for(;h<32;){if(o===0)break e;o--,l+=r[a++]<<h,h+=8}e.head&&(e.head.time=l),e.flags&512&&e.wrap&4&&(E[0]=l&255,E[1]=l>>>8&255,E[2]=l>>>16&255,E[3]=l>>>24&255,e.check=M(e.check,E,4,0)),l=0,h=0,e.mode=vr;case vr:for(;h<16;){if(o===0)break e;o--,l+=r[a++]<<h,h+=8}e.head&&(e.head.xflags=l&255,e.head.os=l>>8),e.flags&512&&e.wrap&4&&(E[0]=l&255,E[1]=l>>>8&255,e.check=M(e.check,E,2,0)),l=0,h=0,e.mode=Pr;case Pr:if(e.flags&1024){for(;h<16;){if(o===0)break e;o--,l+=r[a++]<<h,h+=8}e.length=l,e.head&&(e.head.extra_len=l),e.flags&512&&e.wrap&4&&(E[0]=l&255,E[1]=l>>>8&255,e.check=M(e.check,E,2,0)),l=0,h=0}else e.head&&(e.head.extra=null);e.mode=kr;case kr:if(e.flags&1024&&(p=e.length,p>o&&(p=o),p&&(e.head&&(k=e.head.extra_len-e.length,e.head.extra||(e.head.extra=new Uint8Array(e.head.extra_len)),e.head.extra.set(r.subarray(a,a+p),k)),e.flags&512&&e.wrap&4&&(e.check=M(e.check,r,p,a)),o-=p,a+=p,e.length-=p),e.length))break e;e.length=0,e.mode=xr;case xr:if(e.flags&2048){if(o===0)break e;p=0;do k=r[a+p++],e.head&&k&&e.length<65536&&(e.head.name+=String.fromCharCode(k));while(k&&p<o);if(e.flags&512&&e.wrap&4&&(e.check=M(e.check,r,p,a)),o-=p,a+=p,k)break e}else e.head&&(e.head.name=null);e.length=0,e.mode=Er;case Er:if(e.flags&4096){if(o===0)break e;p=0;do k=r[a+p++],e.head&&k&&e.length<65536&&(e.head.comment+=String.fromCharCode(k));while(k&&p<o);if(e.flags&512&&e.wrap&4&&(e.check=M(e.check,r,p,a)),o-=p,a+=p,k)break e}else e.head&&(e.head.comment=null);e.mode=Dr;case Dr:if(e.flags&512){for(;h<16;){if(o===0)break e;o--,l+=r[a++]<<h,h+=8}if(e.wrap&4&&l!==(e.check&65535)){t.msg="header crc mismatch",e.mode=$;break}l=0,h=0}e.head&&(e.head.hcrc=e.flags>>9&1,e.head.done=!0),t.adler=e.check=0,e.mode=he;break;case Sr:for(;h<32;){if(o===0)break e;o--,l+=r[a++]<<h,h+=8}t.adler=e.check=Rr(l),l=0,h=0,e.mode=Ht;case Ht:if(e.havedict===0)return t.next_out=s,t.avail_out=d,t.next_in=a,t.avail_in=o,e.hold=l,e.bits=h,wo;t.adler=e.check=1,e.mode=he;case he:if(i===po||i===At)break e;case wi:if(e.last){l>>>=h&7,h-=h&7,e.mode=Fi;break}for(;h<3;){if(o===0)break e;o--,l+=r[a++]<<h,h+=8}switch(e.last=l&1,l>>>=1,h-=1,l&3){case 0:e.mode=Tr;break;case 1:if(ko(e),e.mode=Bt,i===At){l>>>=2,h-=2;break e}break;case 2:e.mode=Or;break;case 3:t.msg="invalid block type",e.mode=$}l>>>=2,h-=2;break;case Tr:for(l>>>=h&7,h-=h&7;h<32;){if(o===0)break e;o--,l+=r[a++]<<h,h+=8}if((l&65535)!==(l>>>16^65535)){t.msg="invalid stored block lengths",e.mode=$;break}if(e.length=l&65535,l=0,h=0,e.mode=yi,i===At)break e;case yi:e.mode=Cr;case Cr:if(p=e.length,p){if(p>o&&(p=o),p>d&&(p=d),p===0)break e;n.set(r.subarray(a,a+p),s),o-=p,a+=p,d-=p,s+=p,e.length-=p;break}e.mode=he;break;case Or:for(;h<14;){if(o===0)break e;o--,l+=r[a++]<<h,h+=8}if(e.nlen=(l&31)+257,l>>>=5,h-=5,e.ndist=(l&31)+1,l>>>=5,h-=5,e.ncode=(l&15)+4,l>>>=4,h-=4,e.nlen>286||e.ndist>30){t.msg="too many length or distance symbols",e.mode=$;break}e.have=0,e.mode=Ar;case Ar:for(;e.have<e.ncode;){for(;h<3;){if(o===0)break e;o--,l+=r[a++]<<h,h+=8}e.lens[ee[e.have++]]=l&7,l>>>=3,h-=3}for(;e.have<19;)e.lens[ee[e.have++]]=0;if(e.lencode=e.lendyn,e.lenbits=7,x={bits:e.lenbits},C=dt(mo,e.lens,0,19,e.lencode,0,e.work,x),e.lenbits=x.bits,C){t.msg="invalid code lengths set",e.mode=$;break}e.have=0,e.mode=Br;case Br:for(;e.have<e.nlen+e.ndist;){for(;b=e.lencode[l&(1<<e.lenbits)-1],F=b>>>24,y=b>>>16&255,_=b&65535,!(F<=h);){if(o===0)break e;o--,l+=r[a++]<<h,h+=8}if(_<16)l>>>=F,h-=F,e.lens[e.have++]=_;else{if(_===16){for(D=F+2;h<D;){if(o===0)break e;o--,l+=r[a++]<<h,h+=8}if(l>>>=F,h-=F,e.have===0){t.msg="invalid bit length repeat",e.mode=$;break}k=e.lens[e.have-1],p=3+(l&3),l>>>=2,h-=2}else if(_===17){for(D=F+3;h<D;){if(o===0)break e;o--,l+=r[a++]<<h,h+=8}l>>>=F,h-=F,k=0,p=3+(l&7),l>>>=3,h-=3}else{for(D=F+7;h<D;){if(o===0)break e;o--,l+=r[a++]<<h,h+=8}l>>>=F,h-=F,k=0,p=11+(l&127),l>>>=7,h-=7}if(e.have+p>e.nlen+e.ndist){t.msg="invalid bit length repeat",e.mode=$;break}for(;p--;)e.lens[e.have++]=k}}if(e.mode===$)break;if(e.lens[256]===0){t.msg="invalid code -- missing end-of-block",e.mode=$;break}if(e.lenbits=9,x={bits:e.lenbits},C=dt(pn,e.lens,0,e.nlen,e.lencode,0,e.work,x),e.lenbits=x.bits,C){t.msg="invalid literal/lengths set",e.mode=$;break}if(e.distbits=6,e.distcode=e.distdyn,x={bits:e.distbits},C=dt(un,e.lens,e.nlen,e.ndist,e.distcode,0,e.work,x),e.distbits=x.bits,C){t.msg="invalid distances set",e.mode=$;break}if(e.mode=Bt,i===At)break e;case Bt:e.mode=It;case It:if(o>=6&&d>=258){t.next_out=s,t.avail_out=d,t.next_in=a,t.avail_in=o,e.hold=l,e.bits=h,so(t,f),s=t.next_out,n=t.output,d=t.avail_out,a=t.next_in,r=t.input,o=t.avail_in,l=e.hold,h=e.bits,e.mode===he&&(e.back=-1);break}for(e.back=0;b=e.lencode[l&(1<<e.lenbits)-1],F=b>>>24,y=b>>>16&255,_=b&65535,!(F<=h);){if(o===0)break e;o--,l+=r[a++]<<h,h+=8}if(y&&!(y&240)){for(w=F,P=y,A=_;b=e.lencode[A+((l&(1<<w+P)-1)>>w)],F=b>>>24,y=b>>>16&255,_=b&65535,!(w+F<=h);){if(o===0)break e;o--,l+=r[a++]<<h,h+=8}l>>>=w,h-=w,e.back+=w}if(l>>>=F,h-=F,e.back+=F,e.length=_,y===0){e.mode=Hr;break}if(y&32){e.back=-1,e.mode=he;break}if(y&64){t.msg="invalid literal/length code",e.mode=$;break}e.extra=y&15,e.mode=Ir;case Ir:if(e.extra){for(D=e.extra;h<D;){if(o===0)break e;o--,l+=r[a++]<<h,h+=8}e.length+=l&(1<<e.extra)-1,l>>>=e.extra,h-=e.extra,e.back+=e.extra}e.was=e.length,e.mode=Nr;case Nr:for(;b=e.distcode[l&(1<<e.distbits)-1],F=b>>>24,y=b>>>16&255,_=b&65535,!(F<=h);){if(o===0)break e;o--,l+=r[a++]<<h,h+=8}if(!(y&240)){for(w=F,P=y,A=_;b=e.distcode[A+((l&(1<<w+P)-1)>>w)],F=b>>>24,y=b>>>16&255,_=b&65535,!(w+F<=h);){if(o===0)break e;o--,l+=r[a++]<<h,h+=8}l>>>=w,h-=w,e.back+=w}if(l>>>=F,h-=F,e.back+=F,y&64){t.msg="invalid distance code",e.mode=$;break}e.offset=_,e.extra=y&15,e.mode=Lr;case Lr:if(e.extra){for(D=e.extra;h<D;){if(o===0)break e;o--,l+=r[a++]<<h,h+=8}e.offset+=l&(1<<e.extra)-1,l>>>=e.extra,h-=e.extra,e.back+=e.extra}if(e.offset>e.dmax){t.msg="invalid distance too far back",e.mode=$;break}e.mode=zr;case zr:if(d===0)break e;if(p=f-d,e.offset>p){if(p=e.offset-p,p>e.whave&&e.sane){t.msg="invalid distance too far back",e.mode=$;break}p>e.wnext?(p-=e.wnext,u=e.wsize-p):u=e.wnext-p,p>e.length&&(p=e.length),v=e.window}else v=n,u=s-e.offset,p=e.length;p>d&&(p=d),d-=p,e.length-=p;do n[s++]=v[u++];while(--p);e.length===0&&(e.mode=It);break;case Hr:if(d===0)break e;n[s++]=e.length,d--,e.mode=It;break;case Fi:if(e.wrap){for(;h<32;){if(o===0)break e;o--,l|=r[a++]<<h,h+=8}if(f-=d,t.total_out+=f,e.total+=f,e.wrap&4&&f&&(t.adler=e.check=e.flags?M(e.check,n,f,s-f):ut(e.check,n,f,s-f)),f=d,e.wrap&4&&(e.flags?l:Rr(l))!==e.check){t.msg="incorrect data check",e.mode=$;break}l=0,h=0}e.mode=$r;case $r:if(e.wrap&&e.flags){for(;h<32;){if(o===0)break e;o--,l+=r[a++]<<h,h+=8}if(e.wrap&4&&l!==(e.total&4294967295)){t.msg="incorrect length check",e.mode=$;break}l=0,h=0}e.mode=Mr;case Mr:C=uo;break e;case $:C=wn;break e;case Fn:return yn;case bn:default:return Q}return t.next_out=s,t.avail_out=d,t.next_in=a,t.avail_in=o,e.hold=l,e.bits=h,(e.wsize||f!==t.avail_out&&e.mode<$&&(e.mode<Fi||i!==Fr))&&kn(t,t.output,t.next_out,f-t.avail_out),m-=t.avail_in,f-=t.avail_out,t.total_in+=m,t.total_out+=f,e.total+=f,e.wrap&4&&f&&(t.adler=e.check=e.flags?M(e.check,n,f,t.next_out-f):ut(e.check,n,f,t.next_out-f)),t.data_type=e.bits+(e.last?64:0)+(e.mode===he?128:0)+(e.mode===Bt||e.mode===yi?256:0),(m===0&&f===0||i===Fr)&&C===Ie&&(C=yo),C},"inflate$2"),Eo=c(t=>{if(Ne(t))return Q;let i=t.state;return i.window&&(i.window=null),t.state=null,Ie},"inflateEnd"),Do=c((t,i)=>{if(Ne(t))return Q;let e=t.state;return e.wrap&2?(e.head=i,i.done=!1,Ie):Q},"inflateGetHeader"),So=c((t,i)=>{let e=i.length,r,n,a;return Ne(t)||(r=t.state,r.wrap!==0&&r.mode!==Ht)?Q:r.mode===Ht&&(n=1,n=ut(n,i,e,0),n!==r.check)?wn:(a=kn(t,i,e,e),a?(r.mode=Fn,yn):(r.havedict=1,Ie))},"inflateSetDictionary"),To=_n,Co=vn,Oo=gn,Ao=Po,Bo=Pn,Io=xo,No=Eo,Lo=Do,zo=So,Ho="pako inflate (from Nodeca project)",me={inflateReset:To,inflateReset2:Co,inflateResetKeep:Oo,inflateInit:Ao,inflateInit2:Bo,inflate:Io,inflateEnd:No,inflateGetHeader:Lo,inflateSetDictionary:zo,inflateInfo:Ho};function $o(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}c($o,"GZheader");var Mo=$o,xn=Object.prototype.toString,{Z_NO_FLUSH:Ro,Z_FINISH:Uo,Z_OK:Ft,Z_STREAM_END:_i,Z_NEED_DICT:vi,Z_STREAM_ERROR:jo,Z_DATA_ERROR:jr,Z_MEM_ERROR:Vo}=Xe;function vt(t){this.options=Mt.assign({chunkSize:1024*64,windowBits:15,to:""},t||{});let i=this.options;i.raw&&i.windowBits>=0&&i.windowBits<16&&(i.windowBits=-i.windowBits,i.windowBits===0&&(i.windowBits=-15)),i.windowBits>=0&&i.windowBits<16&&!(t&&t.windowBits)&&(i.windowBits+=32),i.windowBits>15&&i.windowBits<48&&(i.windowBits&15||(i.windowBits|=15)),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new fn,this.strm.avail_out=0;let e=me.inflateInit2(this.strm,i.windowBits);if(e!==Ft)throw new Error(Ae[e]);if(this.header=new Mo,me.inflateGetHeader(this.strm,this.header),i.dictionary&&(typeof i.dictionary=="string"?i.dictionary=yt.string2buf(i.dictionary):xn.call(i.dictionary)==="[object ArrayBuffer]"&&(i.dictionary=new Uint8Array(i.dictionary)),i.raw&&(e=me.inflateSetDictionary(this.strm,i.dictionary),e!==Ft)))throw new Error(Ae[e])}c(vt,"Inflate$1");vt.prototype.push=function(t,i){let e=this.strm,r=this.options.chunkSize,n=this.options.dictionary,a,s,o;if(this.ended)return!1;for(i===~~i?s=i:s=i===!0?Uo:Ro,xn.call(t)==="[object ArrayBuffer]"?e.input=new Uint8Array(t):e.input=t,e.next_in=0,e.avail_in=e.input.length;;){for(e.avail_out===0&&(e.output=new Uint8Array(r),e.next_out=0,e.avail_out=r),a=me.inflate(e,s),a===vi&&n&&(a=me.inflateSetDictionary(e,n),a===Ft?a=me.inflate(e,s):a===jr&&(a=vi));e.avail_in>0&&a===_i&&e.state.wrap>0&&t[e.next_in]!==0;)me.inflateReset(e),a=me.inflate(e,s);switch(a){case jo:case jr:case vi:case Vo:return this.onEnd(a),this.ended=!0,!1}if(o=e.avail_out,e.next_out&&(e.avail_out===0||a===_i))if(this.options.to==="string"){let d=yt.utf8border(e.output,e.next_out),l=e.next_out-d,h=yt.buf2string(e.output,d);e.next_out=l,e.avail_out=r-l,l&&e.output.set(e.output.subarray(d,d+l),0),this.onData(h)}else this.onData(e.output.length===e.next_out?e.output:e.output.subarray(0,e.next_out));if(!(a===Ft&&o===0)){if(a===_i)return a=me.inflateEnd(this.strm),this.onEnd(a),this.ended=!0,!0;if(e.avail_in===0)break}}return!0};vt.prototype.onData=function(t){this.chunks.push(t)};vt.prototype.onEnd=function(t){t===Ft&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=Mt.flattenChunks(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg};function Hi(t,i){let e=new vt(i);if(e.push(t),e.err)throw e.msg||Ae[e.err];return e.result}c(Hi,"inflate$1");function Zo(t,i){return i=i||{},i.raw=!0,Hi(t,i)}c(Zo,"inflateRaw$1");var Wo=vt,Go=Hi,Ko=Zo,Xo=Hi,Yo=Xe,Jo={Inflate:Wo,inflate:Go,inflateRaw:Ko,ungzip:Xo,constants:Yo},{Deflate:Pc,deflate:qo,deflateRaw:kc,gzip:xc}=no,{Inflate:Ec,inflate:Qo,inflateRaw:Dc,ungzip:Sc}=Jo;var En=qo;var Dn=Qo;import{createFsFromVolume as Vi,Volume as Zi}from"memfs";var Sn=c((t,i)=>{let e={type:"local",id:"local",name:"Local User",email:"local@legitcontrol.com"};return{getUser:c(async()=>e,"getUser"),signInAnonymously:c(async()=>{e.type="anonymous",e.id=crypto.randomUUID(),e.email=`anonymous-sha1-${e.id}-@legitcontrol.com`},"signInAnonymously"),addAccessToken:c(async r=>{let n=await t.getUserTokens(e.id);n.accessTokens.push(r),await t.setUserTokens(e.id,n)},"addAccessToken"),getMaxAccessTokenForBranch:c(async r=>{let n=await t.getUserTokens(e.id);if(!(n.accessTokens===void 0||n.accessTokens.length===0))return n.accessTokens[0]},"getMaxAccessTokenForBranch")}},"createSessionManager");import On from"@legit-sdk/isomorphic-git";function Tn(t){let i=JSON.stringify(t),e=new TextEncoder().encode(i),r="";return typeof btoa=="function"?r=btoa(String.fromCharCode(...e)):r=Buffer.from(e).toString("base64"),r.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}c(Tn,"encodeConfigJson");function Cn(t){let i=t.replace(/-/g,"+").replace(/_/g,"/")+"===".slice((t.length+3)%4),e;typeof atob=="function"?e=atob(i):e=Buffer.from(i,"base64").toString("binary");let r=Uint8Array.from(e,a=>a.charCodeAt(0)),n=new TextDecoder().decode(r);return JSON.parse(n)}c(Cn,"decodeConfigJson");var An="user.legit-tokens";function Bn({storageFs:t,gitRoot:i}){return{getUserTokens:c(async e=>{let r=await On.getConfig({fs:t,dir:i,path:An});return r?Cn(r):{accessTokens:[]}},"getUserTokens"),setUserTokens:c(async(e,r)=>await On.setConfig({fs:t,dir:i,path:An,value:Tn(r)}),"setUserTokens")}}c(Bn,"createGitConfigTokenStore");import I from"@legit-sdk/isomorphic-git";import pe from"@legit-sdk/isomorphic-git";async function T(t,i,e){try{return await pe.resolveRef({fs:t,dir:i,ref:`refs/heads/${H(e)}`})}catch{return}}c(T,"tryResolveRef");async function ue({dir:t,fs:i,treeOid:e,deletePathParts:r,addPathParts:n,addObj:a,addKeepIfEmpty:s,deleteKeepIfNotEmpty:o,keepFilename:d=".keep",gitCache:l}){let[h,...m]=n??[],[f,...p]=r??[],u=[];if(e){let{tree:v}=await pe.readTree({fs:i,dir:t,oid:e,cache:l||{}});u=[...v]}if(h===f){let v=h;if(v===void 0)throw new Error("illegal arguement - called with out a path part");if(m.length===0)throw new Error("can not move into it self");if(p.length===0)throw new Error("can not move from it self");let b=u.findIndex(P=>P.path===v),y=(b!==-1?u[b]:void 0)?.oid,_=await ue({dir:t,fs:i,treeOid:y,addPathParts:m,deletePathParts:p,addObj:a,addKeepIfEmpty:s,deleteKeepIfNotEmpty:o});if(_===void 0)throw new Error("on the same path we expect an update - respectivly a newly created subTreeOid");let w=!1;if(_!==y){w=!0;let P={mode:"040000",path:v,oid:_,type:"tree"};b!==-1?u[b]=P:u.push(P)}if(e==null&&!w)throw new Error("Illegal state - if the currentOid is undefined - a new tree should have been created (an update should have happened)");if(w)return await pe.writeTree({fs:i,dir:t,tree:u});if(e===void 0)throw new Error("currentOid should be set - since the sub tree didn't exist and ");return e}else{let v=!1,b;if(f){let F=u.findIndex(_=>_.path===f),y=F!==-1?u[F]:void 0;if(y===void 0)throw new Error("Element doesnt exist in tree");if(p.length>0){if(y&&y.type!=="tree")throw new Error("SubPart of the path for the obj to delete is not a tree");let _=await ue({dir:t,fs:i,treeOid:y.oid,addPathParts:void 0,deletePathParts:p,addObj:a,addKeepIfEmpty:s,deleteKeepIfNotEmpty:o});if(_===y.oid)throw new Error("in case of a delete we expect a different subtree oid");v=!0,_===void 0?u.splice(F,1):u[F]={mode:"040000",path:f,oid:_,type:"tree"}}else if(v=!0,u.splice(F,1),u.length===0&&s){let _=new Uint8Array(0),w=await pe.writeBlob({fs:i,dir:t,blob:_});u.push({mode:"100644",oid:w,path:d,type:"blob"})}b=y}if(h){let F=u.findIndex(_=>_.path===h),y=F!==-1?u[F]:void 0;if(m.length>0){if(y&&y.type!=="tree")throw new Error("SubPart of the path for the obj to add is not a tree");let _=await ue({dir:t,fs:i,treeOid:y?.oid,addPathParts:m,deletePathParts:void 0,addObj:a,addKeepIfEmpty:s,deleteKeepIfNotEmpty:o});if(_===void 0)throw new Error("in case we add, we expect an update - respectivly a newly created subTreeOid");if(_!==y?.oid){v=!0;let w={mode:"040000",path:h,oid:_,type:"tree"};if(F!==-1)u[F]=w;else if(u.push(w),o&&u.length>1){let P=u.findIndex(A=>A.path===d);P!==-1&&u.splice(P,1)}}}else{if(v=!0,a){let _={mode:a.type==="tree"?"040000":"100644",path:h,oid:a.oid,type:a.type};if(F!==-1)u[F]=_;else{if(o&&u.length>0){let w=u.findIndex(P=>P.path===d);w!==-1&&u.splice(w,1)}u.push(_)}}if(s&&u.length===0){let _=new Uint8Array(0),w=await pe.writeBlob({fs:i,dir:t,blob:_});u.push({mode:"100644",oid:w,path:d,type:"blob"})}}}if(u.length===0)return;if(v)return await pe.writeTree({fs:i,dir:t,tree:u});if(e===void 0)throw new Error("currentOid should be set - since the sub tree didn't exist and ");return e}}c(ue,"buildUpdatedTree");async function In(t,i,e,r,n=0,a={}){let{tree:s}=await pe.readTree({fs:t,dir:i,oid:e,cache:a});if(r.length===n)return{type:"tree",entries:s.map(l=>V({parent:r.join("/"),name:l.path,isDir:l.type==="tree"})),oid:e};let o=r[n],d=s.find(l=>l.path===o);if(d){if(r.length===n+1){if(d.type==="blob")return{type:"blob",oid:d.oid};if(d.type==="tree"){let l=await pe.readTree({fs:t,dir:i,oid:d.oid,cache:a});return{type:"tree",entries:l.tree.map(h=>V({parent:r.join("/"),name:h.path,isDir:h.type==="tree"})),oid:l.oid}}}else if(d.type==="tree")return await In(t,i,d.oid,r,n+1,a)}}c(In,"findGitObjectAtPath");async function Le({filePath:t,gitRoot:i,nodeFs:e,commitSha:r,pathParams:n,gitCache:a}){let s=a||{};if(!n.filePath){let l=await pe.readTree({fs:e,dir:i,oid:r,cache:s});return{type:"tree",entries:l.tree.map(m=>V({parent:t,name:m.path,isDir:m.type==="tree"})),oid:l.oid}}let o=n.filePath?n.filePath.split("/"):[];return await In(e,i,r,o,0,s)}c(Le,"resolveGitObjAtPath");var Ut=class Ut extends Error{constructor(e,r){super(e);g(this,"code","ENOENT");g(this,"path");this.name="ENOENTError",this.path=r,Object.setPrototypeOf(this,Ut.prototype)}};c(Ut,"ENOENTError");var ze=Ut;function jt(t){return t&&t.gitCache!==void 0?t.gitCache:t&&t.parentFs?jt(t.parentFs):{}}c(jt,"getGitCacheFromFs");function Nn({gitStorageFs:t,gitRoot:i,rootPath:e}){return new N({name:"branch-file",gitStorageFs:t,gitRoot:i,rootPath:e||i,handler:{type:"gitBranchFileVirtualFile",rootType:"folder",getStats:c(async n=>{let{filePath:a,pathParams:s,userSpaceFs:o}=n;s.branchName===void 0&&(s.branchName=await O(i,t));let d=await T(t,i,s.branchName);if(!d)throw new ze(`ENOENT: no such file or directory, stat '${a}'`,a);let l=await Le({filePath:a,gitRoot:i,nodeFs:t,commitSha:d,pathParams:s,gitCache:jt(o)});if(!l)throw new ze(`ENOENT: no such file or directory, stat '${a}'`,a);let h=await I.readCommit({fs:t,dir:i,oid:d}),{commit:m}=h,f=await I.log({fs:t,dir:i,ref:d,filepath:s.filePath,depth:1}),p=m.committer.timestamp*1e3,u=f.length>0?f[0].commit.committer.timestamp*1e3:p;if(l.type==="tree")return{mode:420,size:0,isFile:c(()=>!0,"isFile"),isDirectory:c(()=>!0,"isDirectory"),isSymbolicLink:c(()=>!1,"isSymbolicLink"),isBlockDevice:c(()=>!1,"isBlockDevice"),isCharacterDevice:c(()=>!1,"isCharacterDevice"),isSocket:c(()=>!1,"isSocket"),isFIFO:c(()=>!1,"isFIFO"),isFileSync:c(()=>!0,"isFileSync"),isDirectorySync:c(()=>!1,"isDirectorySync"),dev:0,ino:0,nlink:1,uid:0,gid:0,rdev:0,blksize:4096,blocks:0,atimeMs:u,mtimeMs:u,ctimeMs:u,birthtimeMs:p,atime:new Date(u),mtime:new Date(u),ctime:new Date(u),birthtime:new Date(u)};{let{blob:v}=await I.readBlob({fs:t,dir:i,oid:l.oid});return{mode:420,size:v.length,isFile:c(()=>!0,"isFile"),isDirectory:c(()=>!1,"isDirectory"),isSymbolicLink:c(()=>!1,"isSymbolicLink"),isBlockDevice:c(()=>!1,"isBlockDevice"),isCharacterDevice:c(()=>!1,"isCharacterDevice"),isSocket:c(()=>!1,"isSocket"),isFIFO:c(()=>!1,"isFIFO"),isFileSync:c(()=>!0,"isFileSync"),isDirectorySync:c(()=>!1,"isDirectorySync"),dev:0,ino:0,nlink:1,uid:0,gid:0,rdev:0,blksize:4096,blocks:Math.ceil(v.length/4096),atimeMs:u,mtimeMs:u,ctimeMs:u,birthtimeMs:u,atime:new Date(u),mtime:new Date(u),ctime:new Date(u),birthtime:new Date(u)}}},"getStats"),getFile:c(async n=>{let{filePath:a,cacheFs:s,pathParams:o,userSpaceFs:d}=n;o.branchName===void 0&&(o.branchName=await O(i,t));try{let l=await T(t,i,o.branchName);if(!l){let m=await I.resolveRef({fs:t,dir:i,ref:"HEAD"});if(await I.branch({fs:t,dir:i,ref:o.branchName,object:m}),l=await T(t,i,o.branchName),!l)throw new Error("Could not create branch for getFile")}let h=await Le({filePath:a,gitRoot:i,nodeFs:t,commitSha:l,pathParams:o,gitCache:jt(d)});if(!h)return;if(h.type==="blob"){let{blob:m}=await I.readBlob({fs:t,dir:i,oid:h.oid});return{type:"file",content:Buffer.from(m),mode:420,size:m.length,oid:h.oid}}else{let m=[];try{let p=await s.promises.stat(a);if(p&&p.isDirectory()){let u=await s.promises.readdir(a,{withFileTypes:!0});m.push(...u)}}catch{}return{type:"directory",content:Array.from(new Set([...m,...h.entries])).map(p=>({...p,name:p.name.toString(),path:`${a}`,parentPath:`${a}`})),mode:493}}}catch{return}},"getFile"),unlink:c(async n=>{let{pathParams:a,author:s}=n;if(a.branchName===void 0&&(a.branchName=await O(i,t)),!a.filePath)throw new Error("filePath should be in pathParams");let o=await T(t,i,a.branchName);if(!o)throw new Error("Invalid branch file path - branch must exist");let d=await I.readTree({fs:t,dir:i,oid:o}),l=await ue({dir:i,fs:t,treeOid:d.oid,deletePathParts:a.filePath.split("/"),addPathParts:void 0,addObj:void 0,deleteKeepIfNotEmpty:!1,addKeepIfEmpty:!0,keepFilename:".keep"});if(l!==d.oid){let h=await I.commit({fs:t,dir:i,message:`Delete ${a.filePath}`,tree:l,noUpdateBranch:!0,parent:[o],author:s});await I.writeRef({fs:t,dir:i,ref:`refs/heads/${H(a.branchName)}`,value:h,force:!0})}},"unlink"),writeFile:c(async n=>{let{filePath:a,content:s,cacheFs:o,pathParams:d,author:l}=n;if(d.branchName===void 0&&(d.branchName=await O(i,t)),d.filePath===void 0)throw new Error("filePath should be in pathParams");let h;typeof s=="string"?h=new TextEncoder().encode(s):h=new Uint8Array(s);let m=await I.writeBlob({fs:t,dir:i,blob:h}),f=await T(t,i,d.branchName);if(!f){let v=await I.resolveRef({fs:t,dir:i,ref:"HEAD"});if(await I.branch({fs:t,dir:i,ref:H(d.branchName),object:v}),f=await T(t,i,d.branchName),!f)throw new Error("Could not create branch for writeFile")}let p=await I.readTree({fs:t,dir:i,oid:f}),u=await ue({dir:i,fs:t,treeOid:p.oid,deletePathParts:void 0,addPathParts:d.filePath.split("/"),addObj:{type:"blob",oid:m},deleteKeepIfNotEmpty:!0,addKeepIfEmpty:!1,keepFilename:".keep"});if(u!==p.oid){let v=await I.commit({fs:t,dir:i,message:`\u{1F4BE} Change '${d.filePath}'`,tree:u,noUpdateBranch:!0,parent:[f],author:l});await I.writeRef({fs:t,dir:i,ref:`refs/heads/${H(d.branchName)}`,value:v,force:!0});let b=await T(t,i,d.branchName);if(v!==b)throw new Error("Failed to update branch after file deletion")}},"writeFile"),rename:c(async function(n){let{filePath:a,newPath:s,pathParams:o,newPathParams:d,author:l,userSpaceFs:h}=n;if(o.branchName===void 0&&(o.branchName=await O(i,t)),o.filePath===void 0)throw new Error("filePath should be in pathParams");if(d.branchName===void 0&&(d.branchName=await O(i,t)),d.filePath===void 0)throw new Error("filePath should be in newPathParams");let m=await T(t,i,o.branchName);if(!m)throw new Error("Invalid branch file path - source branch must exist");let f=await T(t,i,d.branchName);if(!f){let b=await I.resolveRef({fs:t,dir:i,ref:"HEAD"});if(await I.branch({fs:t,dir:i,ref:H(d.branchName),object:b}),f=await T(t,i,d.branchName),f===void 0)throw new Error("Could not create branch for rename operation")}if(d.branchName!==o.branchName)throw new Error("cross branch move not implemented yet");let p=await Le({gitRoot:i,nodeFs:t,commitSha:m,filePath:a,pathParams:o,gitCache:jt(h)});if(p===void 0)throw new Error("no obj at path exists");let u=await ue({dir:i,fs:t,deletePathParts:o.filePath.split("/"),addPathParts:d.filePath.split("/"),addObj:p.type==="blob"?{type:"blob",oid:p.oid}:{type:"tree",oid:p.oid,entries:p.entries.map(b=>b.name.toString())},treeOid:f,addKeepIfEmpty:!0,deleteKeepIfNotEmpty:!0}),v=await I.readTree({fs:t,dir:i,oid:m});if(u!==v.oid){let b=await I.commit({fs:t,dir:i,message:`\u{1F500} Rename '${o.filePath}' to '${d.filePath}'`,tree:u,noUpdateBranch:!0,parent:[f],author:l});await I.writeRef({fs:t,dir:i,ref:`refs/heads/${H(d.branchName)}`,value:b,force:!0})}},"rename"),mkdir:c(async function(n){n.pathParams.branchName===void 0&&(n.pathParams.branchName=await O(i,t));let a=await T(t,i,n.pathParams.branchName);if(n.pathParams.filePath===""&&(n.pathParams.filePath="/",a!==void 0))throw new Error("Folder exists");try{throw await this.getStats(n),new Error("Folder exists")}catch{}if(n.filePath.endsWith("/")&&(n.filePath=n.filePath.replace(/\/+$/,"")),n.pathParams&&typeof n.pathParams.filePath=="string"&&(n.pathParams.filePath=n.pathParams.filePath.replace(/\/+$/,"")),!a){let h=await I.resolveRef({fs:t,dir:i,ref:"HEAD"});if(await I.branch({fs:t,dir:i,ref:H(n.pathParams.branchName),object:h}),a=await T(t,i,n.pathParams.branchName),a===void 0)throw new Error("Could not create branch for mkdir operation")}let s=await I.readTree({fs:t,dir:i,oid:a}),o=new Uint8Array(0),d=await I.writeBlob({fs:t,dir:i,blob:o}),l=await ue({dir:i,fs:t,treeOid:s.oid,deletePathParts:void 0,addPathParts:[...n.pathParams.filePath.split("/"),".keep"],addObj:{type:"blob",oid:d},deleteKeepIfNotEmpty:!0,addKeepIfEmpty:!0,keepFilename:".keep"});if(l!==s.oid){let h=await I.commit({fs:t,dir:i,message:`\u{1F4BE} Change '${n.pathParams.filePath}'`,tree:l,noUpdateBranch:!0,parent:[a],author:n.author});await I.writeRef({fs:t,dir:i,ref:`refs/heads/${H(n.pathParams.branchName)}`,value:h,force:!0})}},"mkdir"),rmdir:c(async n=>{let{pathParams:a,author:s}=n;if(a.branchName===void 0&&(a.branchName=await O(i,t)),!a.filePath)throw new Error("filePath should be in pathParams");let o=await T(t,i,a.branchName);if(!o)throw new Error("Invalid branch file path - branch must exist");let d=await I.readTree({fs:t,dir:i,oid:o}),l=await ue({dir:i,fs:t,treeOid:d.oid,deletePathParts:a.filePath.split("/"),addPathParts:void 0,addObj:void 0,deleteKeepIfNotEmpty:!1,addKeepIfEmpty:!0,keepFilename:".keep"});if(l!==d.oid){let h=await I.commit({fs:t,dir:i,message:`Delete ${a.filePath}`,tree:l,noUpdateBranch:!0,parent:[o],author:s});await I.writeRef({fs:t,dir:i,ref:`refs/heads/${H(a.branchName)}`,value:h,force:!0})}},"rmdir")}})}c(Nn,"createBranchFileAdapter");import Ln from"@legit-sdk/isomorphic-git";function zn({gitStorageFs:t,gitRoot:i,rootPath:e}){return new N({name:"branches-list",gitStorageFs:t,gitRoot:i,rootPath:e||i,handler:{type:"gitBranchesListVirtualFile",rootType:"folder",getStats:c(async()=>{let n=i+"/.git";try{return await t.promises.stat(n)}catch{throw new Error(`ENOENT: no such file or directory, stat '${n}'`)}},"getStats"),getFile:c(async({filePath:n})=>{try{let a=await Ln.listBranches({fs:t,dir:i}),s=await Promise.all(a.map(async o=>{let d=await Ln.resolveRef({fs:t,dir:i,ref:o});return V({parent:n,name:re(o),isDir:!0})}));return{type:"directory",content:s,mode:493,size:s}}catch(a){throw a}},"getFile"),rename:c(async n=>{throw new Error("not implemented")},"rename"),mkdir:c(async function(n){throw new Error("not implemented")},"mkdir")}})}c(zn,"createBranchesListAdapter");import Pt from"@legit-sdk/isomorphic-git";function $i(t){return t&&t.gitCache!==void 0?t.gitCache:t&&t.parentFs?$i(t.parentFs):{}}c($i,"getGitCacheFromFs");function Hn({gitStorageFs:t,gitRoot:i,rootPath:e}){return new N({name:"branch-head",gitStorageFs:t,gitRoot:i,rootPath:e||i,handler:{type:"gitBranchHeadVirtualFile",rootType:"file",getStats:c(async({pathParams:n,userSpaceFs:a})=>{n.branchName===void 0&&(n.branchName=await O(i,t));let s=await T(t,i,n.branchName);if(!s)throw new Error(`Branch ${n.branchName} does not exist in the repository`);let o=await Pt.readCommit({fs:t,dir:i,oid:s,cache:$i(a)}),{commit:d}=o,l=d.committer.timestamp*1e3;return{mode:420,size:40,isFile:c(()=>!0,"isFile"),isDirectory:c(()=>!1,"isDirectory"),isSymbolicLink:c(()=>!1,"isSymbolicLink"),isBlockDevice:c(()=>!1,"isBlockDevice"),isCharacterDevice:c(()=>!1,"isCharacterDevice"),isSocket:c(()=>!1,"isSocket"),isFIFO:c(()=>!1,"isFIFO"),isFileSync:c(()=>!0,"isFileSync"),isDirectorySync:c(()=>!1,"isDirectorySync"),dev:0,ino:0,nlink:1,uid:0,gid:0,rdev:0,blksize:4096,blocks:Math.ceil(.009765625),atimeMs:l,mtimeMs:l,ctimeMs:l,birthtimeMs:l,atime:new Date(l),mtime:new Date(l),ctime:new Date(l),birthtime:new Date(l)}},"getStats"),getFile:c(async({pathParams:n,userSpaceFs:a})=>{n.branchName===void 0&&(n.branchName=await O(i,t));try{let s;try{s=await Pt.resolveRef({fs:t,dir:i,ref:n.branchName})}catch{s=await Pt.resolveRef({fs:t,dir:i,ref:`refs/heads/${n.branchName}`})}return{type:"file",content:s+`
4
+ `,mode:420,size:s.length}}catch{return}},"getFile"),writeFile:c(async({content:n,pathParams:a,userSpaceFs:s})=>{a.branchName===void 0&&(a.branchName=await O(i,t));let o=n.toString().trim();try{await Pt.readCommit({fs:t,dir:i,oid:o,cache:$i(s)})}catch{throw new Error(`Commit ${o} does not exist in the repository`)}await Pt.writeRef({fs:t,dir:i,ref:"refs/heads/"+a.branchName,value:o,force:!0})},"writeFile"),rename(n){throw new Error("not implementsd")},mkdir:c(async function(n){throw new Error("not implemented")},"mkdir")}})}c(Hn,"createBranchHeadAdapter");import Mi from"@legit-sdk/isomorphic-git";import*as $n from"node:fs";function Vt(t){return t&&t.gitCache!==void 0?t.gitCache:t&&t.parentFs?Vt(t.parentFs):{}}c(Vt,"getGitCacheFromFs");function Mn({gitStorageFs:t,gitRoot:i,rootPath:e}){return new N({name:"commit-file",gitStorageFs:t,gitRoot:i,rootPath:e||i,handler:{type:"gitCommitFileVirtualFile",rootType:"file",getStats:c(async({filePath:n,pathParams:a,userSpaceFs:s})=>{if(!a.sha_1_1_2)throw new Error("sha_1_1_2 should be in pathParams");if(!a.sha1_3__40)throw new Error("sha1_3__40 should be in pathParams");let o=a.sha_1_1_2+a.sha1_3__40,d=await Le({filePath:n,gitRoot:i,nodeFs:t,commitSha:o,pathParams:a,gitCache:Vt(s)});if(!d)throw new ze(`ENOENT: no such file or directory, stat '${n}'`,n);let l=await Mi.readCommit({fs:$n,dir:i,oid:o}),{commit:h}=l,m=h.committer.timestamp*1e3;if(d.type==="tree")return{mode:420,size:0,isFile:c(()=>!0,"isFile"),isDirectory:c(()=>!0,"isDirectory"),isSymbolicLink:c(()=>!1,"isSymbolicLink"),isBlockDevice:c(()=>!1,"isBlockDevice"),isCharacterDevice:c(()=>!1,"isCharacterDevice"),isSocket:c(()=>!1,"isSocket"),isFIFO:c(()=>!1,"isFIFO"),isFileSync:c(()=>!0,"isFileSync"),isDirectorySync:c(()=>!1,"isDirectorySync"),dev:0,ino:0,nlink:1,uid:0,gid:0,rdev:0,blksize:4096,blocks:0,atimeMs:m,mtimeMs:m,ctimeMs:m,birthtimeMs:m,atime:new Date(m),mtime:new Date(m),ctime:new Date(m),birthtime:new Date(m)};{let{blob:f}=await Mi.readBlob({fs:$n,dir:i,oid:d.oid});return{mode:420,size:f.length,isFile:c(()=>!0,"isFile"),isDirectory:c(()=>!1,"isDirectory"),isSymbolicLink:c(()=>!1,"isSymbolicLink"),isBlockDevice:c(()=>!1,"isBlockDevice"),isCharacterDevice:c(()=>!1,"isCharacterDevice"),isSocket:c(()=>!1,"isSocket"),isFIFO:c(()=>!1,"isFIFO"),isFileSync:c(()=>!0,"isFileSync"),isDirectorySync:c(()=>!1,"isDirectorySync"),dev:0,ino:0,nlink:1,uid:0,gid:0,rdev:0,blksize:4096,blocks:Math.ceil(f.length/4096),atimeMs:m,mtimeMs:m,ctimeMs:m,birthtimeMs:m,atime:new Date(m),mtime:new Date(m),ctime:new Date(m),birthtime:new Date(m)}}},"getStats"),getFile:c(async({filePath:n,pathParams:a,userSpaceFs:s})=>{if(!a.sha_1_1_2)throw new Error("sha_1_1_2 should be in pathParams");if(!a.sha1_3__40)throw new Error("sha1_3__40 should be in pathParams");let o=a.sha_1_1_2+a.sha1_3__40;try{let d=await Le({filePath:n,gitRoot:i,nodeFs:t,commitSha:o,pathParams:a,gitCache:Vt(s)});if(!d)return;if(d.type==="blob"){let{blob:l}=await Mi.readBlob({fs:t,dir:i,oid:d.oid,cache:Vt(s)});return{type:"file",content:Buffer.from(l),mode:420,size:l.length,oid:d.oid}}else return{type:"directory",content:Array.from(new Set([...d.entries.filter(h=>h.name!==".keep")])).map(h=>({...h,name:h.name.toString(),path:`${n}`,parentPath:`${n}`})),mode:493}}catch{return}},"getFile"),rename(n){throw new Error("not implementsd")},mkdir:c(async function(n){throw new Error("not implemented")},"mkdir")}})}c(Mn,"createCommitFileAdapter");import Ri from"@legit-sdk/isomorphic-git";function Rn({gitStorageFs:t,gitRoot:i,rootPath:e}){return new N({name:"commit-folder",gitStorageFs:t,gitRoot:i,rootPath:e||i,handler:{type:"gitCommitVirtualFolder",rootType:"folder",getStats:c(async n=>{let a=i+"/.git";try{return await t.promises.stat(a)}catch{throw new Error(`ENOENT: no such file or directory, stat '${a}'`)}},"getStats"),getFile:c(async n=>{let{filePath:a,pathParams:s}=n,o=await Ri.listBranches({fs:t,dir:i}),d=new Set,l=new Set;for(let f of o){let p=`refs/heads/${f}`;try{let u=await Ri.resolveRef({fs:t,dir:i,ref:p});d.add(u)}catch{}}for(let f of d){let p=await Ri.log({fs:t,dir:i,ref:f});for(let u of p)l.add(u.oid)}if(!s.sha_1_1_2){let f=new Set;for(let u of l)if(f.add(u.slice(0,2)),f.size>=256)break;let p=Array.from(f).sort().map(u=>V({parent:a,name:u,isDir:!0}));return{type:"directory",content:p,mode:493,size:p}}let h=new Set;for(let f of l)f.startsWith(s.sha_1_1_2)&&h.add(f.slice(2,40));let m=Array.from(h).sort().map(f=>V({parent:a,name:f,isDir:!0}));return{type:"directory",content:m,mode:493,size:m.length}},"getFile"),rename(n){throw new Error("not implementsd")},mkdir:c(async function(n){throw new Error("not implemented")},"mkdir")}})}c(Rn,"createCommitFolderAdapter");import le from"@legit-sdk/isomorphic-git";function Un({gitStorageFs:t,gitRoot:i,rootPath:e}){return new N({name:"branch-operation",gitStorageFs:t,gitRoot:i,rootPath:e||i,handler:{type:"gitBranchOperationVirtualFile",rootType:"file",getStats:c(async n=>{let{pathParams:a}=n;a.branchName===void 0&&(a.branchName=await O(i,t));let s=await T(t,i,a.branchName);if(!s)throw new Error(`Base Branch ${a.branchName} for operations does not exis`);let o=await te(t,i,a.branchName),d=!1;if(o)try{s=await le.resolveRef({fs:t,dir:i,ref:o}),d=!0}catch{try{s=await le.resolveRef({fs:t,dir:i,ref:`refs/heads/${o}`}),d=!0}catch{}}let l=await le.readCommit({fs:t,dir:i,oid:s}),{commit:h}=l,m=h.committer.timestamp*1e3;try{return{mode:420,size:40,atimeMs:m,mtimeMs:m,ctimeMs:m,birthtimeMs:m,atime:new Date(m),mtime:new Date(m),ctime:new Date(m),birthtime:new Date(m),isFile:c(()=>!0,"isFile"),isDirectory:c(()=>!1,"isDirectory"),isSymbolicLink:c(()=>!1,"isSymbolicLink"),isBlockDevice:c(()=>!1,"isBlockDevice"),isCharacterDevice:c(()=>!1,"isCharacterDevice"),isSocket:c(()=>!1,"isSocket"),isFIFO:c(()=>!1,"isFIFO"),isFileSync:c(()=>!0,"isFileSync"),isDirectorySync:c(()=>!1,"isDirectorySync"),dev:0,ino:0,nlink:1,uid:0,gid:0,rdev:0,blksize:4096,blocks:0}}catch{throw new Error("ENOENT: no such file or directory, stat operationHistory")}},"getStats"),getFile:c(async n=>{let{pathParams:a}=n;a.branchName===void 0&&(a.branchName=await O(i,t));let s=await te(t,i,a.branchName),o,d=!1;if(s){if(o=await T(t,i,s),d=!0,!o)throw new Error(`Base Branch ${s} for operations does not exis`)}else if(o=await T(t,i,a.branchName),!o)throw new Error(`Base Branch ${a.branchName} for operations does not exis`);return{type:"file",content:Buffer.from(o),mode:420,size:o.length}},"getFile"),writeFile:c(async n=>{let{content:a,pathParams:s,author:o}=n;s.branchName===void 0&&(s.branchName=await O(i,t));let d;typeof a=="string"?d=new TextEncoder().encode(a):d=new Uint8Array(a);let l=await le.writeBlob({fs:t,dir:i,blob:d}),h=await T(t,i,s.branchName);if(!h)throw new Error("Invalid branch file path - branch doesn't exist");let m=await te(t,i,s.branchName),f=!1;if(!m){m=s.branchName+si,await le.branch({fs:t,dir:i,ref:H(m),object:h});let y=await le.listBranches({fs:t,dir:i});f=!0}let p=await T(t,i,m),u=await le.readTree({fs:t,dir:i,oid:h}),v;a instanceof ArrayBuffer?v=Buffer.from(a).toString("utf-8"):typeof a=="string"?v=a:a instanceof Uint8Array?v=Buffer.from(a).toString("utf-8"):v=String(a);let b=!1;if(!f){let y=await le.findMergeBase({fs:t,dir:i,oids:b?[p]:[p,h]});y.length===1&&y[0]===h&&(b=!0)}let F=await le.commit({fs:t,dir:i,message:v,tree:u.oid,noUpdateBranch:!0,author:o,parent:b?f?[h,h]:[p]:[p,h]});await le.writeRef({fs:t,dir:i,ref:`refs/heads/${H(m)}`,value:F,force:!0})},"writeFile"),rename:c(async function(n){throw new Error("not implemented")},"rename"),mkdir:c(async function(n){throw new Error("not implemented")},"mkdir")}})}c(Un,"createBranchOperationAdapter");import jn from"@legit-sdk/isomorphic-git";function Vn({gitStorageFs:t,gitRoot:i,rootPath:e}){return new N({name:"branch-history",gitStorageFs:t,gitRoot:i,rootPath:e||i,handler:{type:"gitBranchHistory",rootType:"file",getStats:c(async({pathParams:n})=>{n.branchName===void 0&&(n.branchName=await O(i,t));let a=await T(t,i,n.branchName);if(!a)throw new Error(`Branch ${n.branchName} does not exist`);let s=await jn.readCommit({fs:t,dir:i,oid:a}),{commit:o}=s,d=o.committer.timestamp*1e3;return{mode:420,size:1e5,isFile:c(()=>!0,"isFile"),isDirectory:c(()=>!1,"isDirectory"),isSymbolicLink:c(()=>!1,"isSymbolicLink"),isBlockDevice:c(()=>!1,"isBlockDevice"),isCharacterDevice:c(()=>!1,"isCharacterDevice"),isSocket:c(()=>!1,"isSocket"),isFIFO:c(()=>!1,"isFIFO"),isFileSync:c(()=>!0,"isFileSync"),isDirectorySync:c(()=>!1,"isDirectorySync"),dev:0,ino:0,nlink:1,uid:0,gid:0,rdev:0,blksize:4096,blocks:Math.ceil(.009765625),atimeMs:d,mtimeMs:d,ctimeMs:d,birthtimeMs:d,atime:new Date(d),mtime:new Date(d),ctime:new Date(d),birthtime:new Date(d)}},"getStats"),getFile:c(async n=>{let{pathParams:a}=n,s=a.branchName;s===void 0&&(s=await O(i,t));let o=[];if(s){let l=await T(t,i,s),h=!1,m=l;for(;m&&!h;){let f=await jn.readCommit({fs:t,dir:i,oid:m});o.push({oid:f.oid,...f.commit}),m=f.commit.parent[0]}}let d=Buffer.from(JSON.stringify(o,null,2),"utf-8");return{type:"file",content:d,mode:420,size:d.length}},"getFile"),rename:c(async n=>{throw new Error("not implemented")},"rename"),mkdir:c(async function(n){throw new Error("not implemented")},"mkdir")}})}c(Vn,"createBranchHistoryAdapter");import xe from"@legit-sdk/isomorphic-git";function Zn({gitStorageFs:t,gitRoot:i,rootPath:e}){return new N({name:"branch-operation-head",gitStorageFs:t,gitRoot:i,rootPath:e||i,handler:{type:"gitBranchOperationHeadVirtualFile",rootType:"file",getStats:c(async n=>{let{pathParams:a}=n;a.branchName===void 0&&(a.branchName=await O(i,t));let s=await te(t,i,a.branchName);if(!s){let m=new Date(0);return{mode:420,size:0,isFile:c(()=>!0,"isFile"),isDirectory:c(()=>!1,"isDirectory"),isSymbolicLink:c(()=>!1,"isSymbolicLink"),isBlockDevice:c(()=>!1,"isBlockDevice"),isCharacterDevice:c(()=>!1,"isCharacterDevice"),isSocket:c(()=>!1,"isSocket"),isFIFO:c(()=>!1,"isFIFO"),isFileSync:c(()=>!0,"isFileSync"),isDirectorySync:c(()=>!1,"isDirectorySync"),dev:0,ino:0,nlink:1,uid:0,gid:0,rdev:0,blksize:4096,blocks:Math.ceil(.009765625),atimeMs:m.getTime(),mtimeMs:m.getTime(),ctimeMs:m.getTime(),birthtimeMs:m.getTime(),atime:m,mtime:m,ctime:m,birthtime:m}}let o;try{o=await xe.resolveRef({fs:t,dir:i,ref:s})}catch{o=await xe.resolveRef({fs:t,dir:i,ref:`refs/heads/${s}`})}let d=await xe.readCommit({fs:t,dir:i,oid:o}),{commit:l}=d,h=l.committer.timestamp*1e3;return{mode:420,size:40,isFile:c(()=>!0,"isFile"),isDirectory:c(()=>!1,"isDirectory"),isSymbolicLink:c(()=>!1,"isSymbolicLink"),isBlockDevice:c(()=>!1,"isBlockDevice"),isCharacterDevice:c(()=>!1,"isCharacterDevice"),isSocket:c(()=>!1,"isSocket"),isFIFO:c(()=>!1,"isFIFO"),isFileSync:c(()=>!0,"isFileSync"),isDirectorySync:c(()=>!1,"isDirectorySync"),dev:0,ino:0,nlink:1,uid:0,gid:0,rdev:0,blksize:4096,blocks:Math.ceil(.009765625),atimeMs:h,mtimeMs:h,ctimeMs:h,birthtimeMs:h,atime:new Date(h),mtime:new Date(h),ctime:new Date(h),birthtime:new Date(h)}},"getStats"),getFile:c(async n=>{let{pathParams:a}=n;a.branchName===void 0&&(a.branchName=await O(i,t));let s=await te(t,i,a.branchName);if(!s)return{type:"file",content:"",mode:420,size:0};try{let o;try{o=await xe.resolveRef({fs:t,dir:i,ref:s})}catch{o=await xe.resolveRef({fs:t,dir:i,ref:`refs/heads/${s}`})}return{type:"file",content:o+`
5
+ `,mode:420,size:o.length}}catch{return}},"getFile"),writeFile:c(async n=>{let{content:a,pathParams:s}=n;s.branchName===void 0&&(s.branchName=await O(i,t));let o=await te(t,i,s.branchName);if(!o)throw new Error(`Operation branch name could not be resolved for branch ${s.branchName}`);let d=await T(t,i,o),l=a.toString().trim(),h,m,f=!1;if(!d)throw new Error(`Operation branch ref could not be resolved for branch ${o}`);let p=d;for(;p&&!f;){let u=await xe.readCommit({fs:t,dir:i,oid:p});if(u.oid===l&&(h=u.oid),p=u.commit.parent&&u.commit.parent.length>0?u.commit.parent[0]:null,u.commit.parent.length===2){if(u.commit.parent[0]===u.commit.parent[1])f=!0;else if(h!==void 0){m=u.commit.parent[1];break}}}if(h===void 0)throw new Error(`Cant rollback to ${l} couldn't find newOperationBranchHead ${h}`);if(m===void 0)throw new Error(`Cant rollback to ${l} couldn't find newBranchHead ${m}`);await xe.writeRef({fs:t,dir:i,ref:"refs/heads/"+o,value:h,force:!0}),await xe.writeRef({fs:t,dir:i,ref:"refs/heads/"+s.branchName,value:m,force:!0})},"writeFile"),rename(n){throw new Error("not implementsd")},mkdir:c(async function(n){throw new Error("not implemented")},"mkdir")}})}c(Zn,"createBranchOperationHeadAdapter");import tl from"@legit-sdk/isomorphic-git";import Ui from"@legit-sdk/isomorphic-git";async function He(t,i){try{let e=await Ui.getConfig({fs:i,dir:t,path:"user.legit-reference-branch"});if(e)return re(e)}catch{}try{let e=await Ui.getConfig({fs:i,dir:t,path:"init.defaultBranch"});return re(e)||"main"}catch{return"main"}}c(He,"getReferenceBranch");async function Wn(t,i,e){await Ui.setConfig({fs:i,dir:t,path:"user.legit-reference-branch",value:H(e)})}c(Wn,"setReferenceBranch");function Gn({gitStorageFs:t,gitRoot:i,rootPath:e}){return new N({name:"current-branch",gitStorageFs:t,gitRoot:i,rootPath:e||i,handler:{type:"gitCurrentBranchVirtualFile",rootType:"file",getStats:c(async n=>{let s=(await O(i,t)).length;return{mode:420,size:s,isFile:c(()=>!0,"isFile"),isDirectory:c(()=>!1,"isDirectory"),isSymbolicLink:c(()=>!1,"isSymbolicLink"),isBlockDevice:c(()=>!1,"isBlockDevice"),isCharacterDevice:c(()=>!1,"isCharacterDevice"),isSocket:c(()=>!1,"isSocket"),isFIFO:c(()=>!1,"isFIFO"),isFileSync:c(()=>!0,"isFileSync"),isDirectorySync:c(()=>!1,"isDirectorySync"),dev:0,ino:0,nlink:1,uid:0,gid:0,rdev:0,blksize:4096,blocks:Math.ceil(s/4096),atimeMs:Date.now(),mtimeMs:Date.now(),ctimeMs:Date.now(),birthtimeMs:Date.now(),atime:new Date,mtime:new Date,ctime:new Date,birthtime:new Date}},"getStats"),getFile:c(async n=>{let a=await O(i,t);return{type:"file",content:a+`
6
+ `,mode:420,size:a.length+1}},"getFile"),writeFile:c(async n=>{let{content:a}=n,s=a.toString().trim();if(!await T(t,i,s)){let d=await He(i,t),l=await T(t,i,d);if(!l)throw new Error(`Ref branch ${d} does not exist in the repository`);await tl.branch({fs:t,dir:i,ref:H(s),object:l})}await rr(i,t,s)},"writeFile"),rename(n){throw new Error("not implemented")},mkdir:c(async function(n){throw new Error("not implemented")},"mkdir")}})}c(Gn,"createCurrentBranchAdapter");import qe from"@legit-sdk/isomorphic-git";function Kn({gitStorageFs:t,gitRoot:i,rootPath:e}){return new N({name:"apply-changes",gitStorageFs:t,gitRoot:i,rootPath:e||i,handler:{type:"gitApplyCurrentChangesToVirtualFile",rootType:"file",getStats:c(async({pathParams:n,userSpaceFs:a})=>{let s=new Date(0);return{mode:420,size:40,isFile:c(()=>!0,"isFile"),isDirectory:c(()=>!1,"isDirectory"),isSymbolicLink:c(()=>!1,"isSymbolicLink"),isBlockDevice:c(()=>!1,"isBlockDevice"),isCharacterDevice:c(()=>!1,"isCharacterDevice"),isSocket:c(()=>!1,"isSocket"),isFIFO:c(()=>!1,"isFIFO"),isFileSync:c(()=>!0,"isFileSync"),isDirectorySync:c(()=>!1,"isDirectorySync"),dev:0,ino:0,nlink:1,uid:0,gid:0,rdev:0,blksize:4096,blocks:Math.ceil(.009765625),atimeMs:s,mtimeMs:s,ctimeMs:s,birthtimeMs:s,atime:s,mtime:s,ctime:s,birthtime:s}},"getStats"),getFile:c(async({pathParams:n,userSpaceFs:a})=>{try{return{type:"file",content:`
7
+ `,mode:420,size:2}}catch{return}},"getFile"),writeFile:c(async n=>{let{content:a,userSpaceFs:s}=n,o=await O(i,t),d=await He(i,t),l=a.toString().trim(),h=await T(t,i,o);if(!h)throw new Error(`Source branch ${o} does not exist`);let m=await T(t,i,d);if(!m)throw new Error(`Target branch ${d} does not exist`);let f=await qe.readTree({fs:t,dir:i,oid:h});if(await qe.readTree({fs:t,dir:i,oid:m})===f)return;let u=Math.floor(Date.now()/1e3),v=await qe.commit({fs:t,dir:i,message:l,tree:f.oid,noUpdateBranch:!0,author:{...n.author,timestamp:u},parent:[m]}),b=await qe.commit({fs:t,dir:i,message:"Changes from "+o+" applied to "+d,tree:f.oid,noUpdateBranch:!0,author:{...n.author,timestamp:u-3},parent:[h,v]});await qe.writeRef({fs:t,dir:i,ref:"refs/heads/"+H(d),value:v,force:!0}),await qe.writeRef({fs:t,dir:i,ref:"refs/heads/"+H(o),value:b,force:!0})},"writeFile"),rename(n){throw new Error("not implementsd")},mkdir:c(async function(n){throw new Error("not implemented")},"mkdir")}})}c(Kn,"createApplyChangesAdapter");function Xn({gitStorageFs:t,gitRoot:i,rootPath:e}){return new N({name:"reference-branch",gitStorageFs:t,gitRoot:i,rootPath:e||i,handler:{type:"gitReferenceBranchVirtualFile",rootType:"file",getStats:c(async n=>{let s=(await He(i,t)).length;return{mode:420,size:s,isFile:c(()=>!0,"isFile"),isDirectory:c(()=>!1,"isDirectory"),isSymbolicLink:c(()=>!1,"isSymbolicLink"),isBlockDevice:c(()=>!1,"isBlockDevice"),isCharacterDevice:c(()=>!1,"isCharacterDevice"),isSocket:c(()=>!1,"isSocket"),isFIFO:c(()=>!1,"isFIFO"),isFileSync:c(()=>!0,"isFileSync"),isDirectorySync:c(()=>!1,"isDirectorySync"),dev:0,ino:0,nlink:1,uid:0,gid:0,rdev:0,blksize:4096,blocks:Math.ceil(s/4096),atimeMs:Date.now(),mtimeMs:Date.now(),ctimeMs:Date.now(),birthtimeMs:Date.now(),atime:new Date,mtime:new Date,ctime:new Date,birthtime:new Date}},"getStats"),getFile:c(async n=>{let a=await He(i,t);return{type:"file",content:a+`
8
+ `,mode:420,size:a.length+1}},"getFile"),writeFile:c(async n=>{let{content:a}=n,s=a.toString().trim();if(!await T(t,i,s))throw new Error(`Branch ${s} does not exist in the repository`);await Wn(i,t,s)},"writeFile"),rename(n){throw new Error("not implemented")},mkdir:c(async function(n){throw new Error("not implemented")},"mkdir")}})}c(Xn,"createReferenceBranchAdapter");import*as Yn from"path";var ji=class ji extends j{constructor({name:e,rootPath:r,passThroughFs:n}){super({name:e,rootPath:r});g(this,"openFh",new Map);g(this,"targetFs");this.targetFs=n}async responsible(e){return!0}fileType(){return 4}async open(e,r,n){let a=Yn.dirname(e),s=await this.targetFs.promises.open(e,r,n);return this.openFh.set(s.fd,s),new W({fs:this,compositeFs:this.compositeFs,subFsFileDescriptor:s.fd,parentFsFileDescriptors:[]})}async access(e,r){return await this.targetFs.promises.access(e,r)}async stat(e,...r){return this.targetFs.promises.stat(e,{bigint:!1})}async lstat(e,...r){return this.targetFs.promises.lstat(e,{bigint:!1})}async opendir(e,r){let n=await this.targetFs.promises.opendir(e,r);return new Fe(this.compositeFs,e.toString())}async link(e,r){return await this.targetFs.promises.link(e,r)}async mkdir(e,r){await this.targetFs.promises.mkdir(e,r)}async readdir(e,...r){return this.targetFs.promises.readdir(e,...r)}async readlink(e,...r){throw new Error("not implemented")}async unlink(e){return await this.targetFs.promises.unlink(e)}async rename(e,r){return await this.targetFs.promises.rename(e,r)}async rmdir(e,r){return await this.targetFs.promises.rmdir(e,r)}async symlink(e,r,n){return await this.targetFs.promises.symlink(e,r,n)}async lookup(e){throw new Error(`lookup is not implemented for: ${z(e)}`)}async close(e){let r=this.openFh.get(e.subFsFileDescriptor);r&&(this.openFh.delete(e.subFsFileDescriptor),await r.close())}async dataSync(e){let r=this.openFh.get(e.subFsFileDescriptor);if(r)return await r.sync()}async read(e,r,n,a,s){let o=this.openFh.get(e.subFsFileDescriptor);if(o)return await o.read(r,n,a,s);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async fchmod(e,r){let n=this.openFh.get(e.subFsFileDescriptor);if(n)return await n.chmod(r)}async fchown(e,r,n){let a=this.openFh.get(e.subFsFileDescriptor);if(a)return await a.chown(r,n)}async write(e,r,n,a,s){let o=this.openFh.get(e.subFsFileDescriptor);if(o)return await o.write(r,n,a,s);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async ftruncate(e,r){let n=this.openFh.get(e.subFsFileDescriptor);if(n)return await n.truncate(r)}resolvePath(e){throw new Error(`resolvePath is not implemented: resolvePath(${e})`)}async fstat(e,r){let n=this.openFh.get(e.subFsFileDescriptor);if(n)return await n.stat(r);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async futimes(e,r,n){let a=this.openFh.get(e.subFsFileDescriptor);if(a)return await a.utimes(r,n)}async writev(e,r,n){let a=this.openFh.get(e.subFsFileDescriptor);if(a)return await a.writev(r,n??void 0);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async readv(e,r,n){let a=this.openFh.get(e.subFsFileDescriptor);if(a)return await a.readv(r,n??void 0);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async readFile(e,r){return this.targetFs.promises.readFile(e,r)}async writeFile(e,r,n){return this.targetFs.promises.writeFile(e,r,n)}};c(ji,"PassThroughToAsyncFsSubFs");var Zt=ji;function Jn(t){return typeof t=="object"&&t!==null&&t!==void 0&&!Array.isArray(t)}c(Jn,"isLegitRouteFolder");function qn(t,i){let e={...t};for(let r of Object.keys(i)){let n=t[r],a=i[r];n!==void 0&&Jn(n)&&Jn(a)?e[r]=qn(n,a):e[r]=a}return e}c(qn,"mergeLegitRouteFolders");function Wi(t){return t&&t.gitCache!==void 0?t.gitCache:t&&t.parentFs?Wi(t.parentFs):{}}c(Wi,"getGitCache");async function Jh(t){let i=new Zi,e=Vi(i);return il({...t,storageFs:t?.storageFs?t.storageFs:e,gitRoot:t?.gitRoot||"/"})}c(Jh,"openLegitFsWithMemoryFs");async function il({storageFs:t,gitRoot:i,anonymousBranch:e="anonymous",showKeepFiles:r=!1,initialAuthor:n={type:"local",id:"local",name:"Local User",email:"local@legitcontrol.com"},serverUrl:a="https://hub.legitcontrol.com",publicKey:s,ephemaralGitConfig:o=!1,additionalFilterLayers:d,routeOverrides:l}){await t.promises.readdir(i+"/.git").then(()=>!0).catch(()=>!1)||(await R.init({fs:t,dir:"/",defaultBranch:e}),await t.promises.writeFile(i+"/.gitignore",""),await t.promises.writeFile(i+"/.keep",""),await R.add({fs:t,dir:"/",filepath:".keep",cache:Wi(t)}),await R.commit({fs:t,dir:"/",message:"Initial commit",author:{name:"Test",email:"test@example.com"},cache:Wi(t)}),await R.setConfig({fs:t,dir:i,path:"init.defaultBranch",value:e})),await R.getConfig({fs:t,dir:i,path:"user.legit_user_id"})||await R.setConfig({fs:t,dir:i,path:"user.legit_user_id",value:n.name}),await R.getConfig({fs:t,dir:i,path:"user.name"})||await R.setConfig({fs:t,dir:i,path:"user.name",value:n.name}),await R.getConfig({fs:t,dir:i,path:"user.email"})||await R.setConfig({fs:t,dir:i,path:"user.email",value:n.email});let u=Vi(new Zi),v=new nt({name:"root-copy-on-write",sourceFs:t,copyToFs:u,copyToRootPath:"/copies",rootPath:i,patterns:o?["**/.git/config"]:[]}),b=new Zt({name:"root-passthrough",passThroughFs:t,rootPath:i}),F=new rt({name:"root",filterLayers:[v],rootPath:i,routes:{"[[...relativePath]]":b}}),y={gitStorageFs:F,gitRoot:i,rootPath:i},_=ir(y),w=Un(y),P=Hn(y),A=Zn(y),k=nr(y),C=Vn(y),E=Gn(y),x=Xn(y),D=Kn(y),ee=zn(y),we=Nn(y),Ee=Rn(y),$e=Mn(y),ea=r?[".git"]:[".git",".keep"],ta=new St({name:"git-hidden-subfs",hiddenFiles:ea,rootPath:i}),Yi=[];try{let L=i+"/.gitignore";Yi=(await F.readFile(L,"utf8")).split(`
9
+ `).filter(ce=>ce.trim()!==""&&!ce.trim().startsWith("#")).map(ce=>ce.trim())}catch{}let ia=["**/._*","**/.DS_Store","**/.AppleDouble/","**/.AppleDB","**/.AppleDesktop","**/.Spotlight-V100","**/.TemporaryItems","**/.Trashes","**/.fseventsd","**/.VolumeIcon.icns","**/.ql_disablethumbnails","**/.~lock.*","**/lu[0-9a-zA-Z]*.tmp","**/.metaentries.json.tmp","**/**.tmp.**","**/**.sb-**",...Yi],ra=Vi(new Zi),na=new nt({name:"git-copy-on-write-subfs",sourceFs:F,copyToFs:ra,copyToRootPath:"/user-copies",rootPath:i,patterns:ia}),Ji={".legit":{".":_,operation:w,head:P,operationHead:A,operationHistory:k,history:C,currentBranch:E,"reference-branch":x,"apply-changes":D,branches:{".":ee,"[branchName]":{".legit":{".":_,operation:w,head:P,operationHead:A,operationHistory:k,history:C},"[[...filePath]]":we}},commits:{".":Ee,"[sha_1_1_2]":{".":Ee,"[sha1_3__40]":{"[[...filePath]]":$e}}}},"[[...filePath]]":{".":we}},aa=l?qn(Ji,l):Ji,qi=new rt({name:"git",rootPath:i,filterLayers:[ta,na,...d||[]],routes:aa}),sa=Bn({storageFs:F,gitRoot:i}),kt=Sn(sa,s),Gt=ar({fs:t,gitRepoPath:i,serverUrl:a,auth:kt,anonymousBranch:e}),Kt=Object.assign(qi,{auth:kt,sync:Gt,_storageFs:F,setLogger(L){qi.setLoggger(L)},push:c(async L=>{},"push"),shareCurrentBranch:c(async()=>{if((await kt.getUser()).type==="local")throw new Error("login first - for example anonymously using legitfs.auth.signInAnonymously()");let L=await Kt.getCurrentBranch();return L===e&&(L=(await kt.getUser()).id,await R.renameBranch({fs:t,dir:i,oldref:e,ref:L})),await Gt.sequentialPush([L]),Kt.setCurrentBranch(L),L},"shareCurrentBranch"),setCurrentBranch:c(async L=>{(await R.listBranches({fs:t,dir:i})).includes(L)||await Gt?.loadBranch(L);let De=(await R.listBranches({fs:t,dir:i})).includes(L);if(console.log("branchExistsAfter",De),!De)throw new Error(`Branch ${L} does not exist`);await R.setConfig({fs:t,dir:i,path:"init.defaultBranch",value:L})},"setCurrentBranch"),getCurrentBranch:c(async()=>{let L=await R.getConfig({fs:t,dir:i,path:"init.defaultBranch"});if(!L)throw new Error("No current branch set");return L},"getCurrentBranch"),loadArchive:c(async L=>{let Me=Dn(L),ce=new TextDecoder().decode(Me),xt=JSON.parse(ce),De=new Map;try{let ie=await R.listBranches({fs:t,dir:i});for(let Qe of ie){let J=await R.resolveRef({fs:t,dir:i,ref:Qe});De.set(Qe,J)}}catch{}for(let[ie,Qe]of Object.entries(xt.files)){let J=`${i}/.git/${ie}`;if(ie==="config")continue;let de=Buffer.from(Qe,"base64");if(ie.startsWith("refs/heads/")||ie.startsWith("refs/tags/")){let Re=ie.replace(/^refs\/(heads|tags)\//,"");if(!De.has(Re))await t.promises.mkdir(J.split("/").slice(0,-1).join("/"),{recursive:!0}),await t.promises.writeFile(J,de);else{let ye=De.get(Re),et=de.toString("utf-8").trim();try{if(await R.isDescendent({fs:t,dir:i,oid:et,ancestor:ye})||ye===et)await t.promises.writeFile(J,de);else{let tt=`${Re}-conflict-${crypto.randomUUID()}`,it=`${i}/.git/refs/heads/${tt}`;await t.promises.mkdir(it.split("/").slice(0,-1).join("/"),{recursive:!0}),await t.promises.writeFile(it,de)}}catch{let tt=`${Re}-conflict-${crypto.randomUUID()}`,it=`${i}/.git/refs/heads/${tt}`;await t.promises.mkdir(it.split("/").slice(0,-1).join("/"),{recursive:!0}),await t.promises.writeFile(it,de)}}}else await t.promises.mkdir(J.split("/").slice(0,-1).join("/"),{recursive:!0}),await t.promises.writeFile(J,de)}},"loadArchive"),saveArchive:c(async()=>{let L={version:1,files:{}};async function Me(J,de=""){let Re=await t.promises.readdir(J,{withFileTypes:!0});for(let ye of Re){let et=`${J}/${ye.name}`,Et=de?`${de}/${ye.name}`:ye.name;if(ye.isDirectory())await Me(et,Et);else if(ye.isFile()){let tt=await t.promises.readFile(et);L.files[Et]=Buffer.from(tt).toString("base64")}}}c(Me,"readDirectoryRecursive");let ce=`${i}/.git`;try{await Me(ce)}catch(J){console.warn("Failed to read .git folder:",J)}let xt=JSON.stringify(L),ie=new TextEncoder().encode(xt);return En(ie)},"saveArchive")});return Kt}c(il,"openLegitFs");var ef=c(t=>async i=>{if(!i.path.includes(".legit/branches/")||(i.path.match(/\.legit/g)||[]).length>1)return;let[e,r]=i.path.split(".legit/branches/"),[n,...a]=r.split("/"),s=a.join("/"),o=e+".legit/branches/"+n+"/.legit/operation",d=JSON.stringify(i.operationArgs,(l,h)=>Buffer.isBuffer(h)?{__buffer__:h.toString("base64")}:h);console.log(o,`[${i.fsName}].${i.operation}(${i.fd?i.fd.fd+" - ":""}${i.path})
10
+
11
+ ${d}
12
+
13
+ `)},"createFsOperationFileLogger");import{Stats as al}from"node:fs";import*as Gi from"path";import{createFsFromVolume as rl,Volume as nl}from"memfs";var Ki=class Ki extends j{constructor({name:e,rootPath:r}){super({name:e,rootPath:r});g(this,"memFs");g(this,"openFh",{});this.memFs=rl(new nl)}isWriteSupported(){return!0}async responsible(e){return!0}getRouteParams(){return this.context?.params||{}}getStaticSiblings(){return this.context?.staticSiblings||[]}async open(e,r,n){if(!this.isWriteSupported()&&(r.includes("w")||r.includes("a")))throw new Error("Write operations not allowed");r.includes("x");let s=!1;try{await this.getStats({path:e,context:this.context}),s=!0}catch{s=!1}let o=!1;for(let f of Object.values(this.openFh))f.path===e&&(o=!0);if((s||o)&&r.includes("x"))throw Object.assign(new Error(`EEXIST: file already exists, open '${e}'`),{code:"EEXIST",errno:-17,syscall:"open",path:e});if(!s&&!o&&!(r.includes("w")||r.includes("a")))throw Object.assign(new Error(`ENOENT: no such file or directory, open '${e}'`),{code:"ENOENT",errno:-2,syscall:"open",path:e});let d=Gi.dirname(e);if(await this.memFs.promises.mkdir(d,{recursive:!0}),s)try{await this.memFs.promises.access(e)}catch{await this.memFs.promises.writeFile(e,"")}let l=await this.memFs.promises.open(e,r,n),h=l.fd,m=new W({fs:this,compositeFs:this.compositeFs,subFsFileDescriptor:h,parentFsFileDescriptors:[]});return this.openFh[h]={path:e,mode:r,fh:l,unflushed:[]},(r.includes("x")||r.includes("w"))&&this.openFh[h].unflushed.push({length:0,start:0}),m}async mkdir(e,r){let n=e.toString();try{await this.createDirectory({path:n,recursive:!0,context:this.context});let a=typeof r=="object"?{...r,recursive:!0}:{recursive:!0};await this.memFs.promises.mkdir(e,a);let s=n.split("/"),o="";for(let d=1;d<=s.length;d++){o=s.slice(0,d).join("/");try{if((await this.memFs.promises.stat(o)).isDirectory()){let h=await this.memFs.promises.open(o,"r");this.openFh[h.fd]={path:o,mode:"r",fh:h,unflushed:[]}}}catch{}}}catch(a){throw a}}async access(e,r){await this.stat(e)}async futimes(e,r,n){let a=this.openFh[e.subFsFileDescriptor];if(!a)throw new Error("Invalid file handle");return await a.fh.utimes(r,n)}async fstat(e,r){let n=this.openFh[e.subFsFileDescriptor];if(!n)throw new Error("Invalid file handle");return this.stat(n.path,r)}async ftruncate(e,r){let n=this.openFh[e.subFsFileDescriptor];if(!n)throw new Error("Invalid file handle");return n.unflushed.push({length:0,start:0}),await n.fh.truncate(r)}async stat(e,r){let n=e.toString(),a=Object.values(this.openFh).find(s=>s.path===n&&s.unflushed.length>0);return a&&a.unflushed.length>0?await a.fh.stat(r):this.getStats({path:n,context:this.context})}async lstat(e,r){return this.stat(e,r)}async readdir(e,r){let n=e.toString(),a=this.getStaticSiblings(),s=await this.readDirectory({path:n,context:this.context}),o=Array.from(new Set([...s,...a.map(d=>V({name:d.segment,parent:n,isDir:d.type==="folder"}))])).sort((d,l)=>d.name.localeCompare(l.name,void 0,{numeric:!0,sensitivity:"base"}));return r?.withFileTypes?o:o.map(d=>d.name)}async read(e,r,n,a,s){let o=e.subFsFileDescriptor,d=this.openFh[o];if(!d)throw new Error("Invalid file handle");if(d.unflushed.length===0){let l=await this.readFileContent({path:d.path,context:this.context});if(!l?.content)throw new Error("couldnt access content");let h=typeof l.content=="string"?Buffer.from(l.content):l.content,m=typeof s=="number"?s:0,f=Math.min(m+a,h.length),p=Math.max(0,f-m);return h.copy(r,n,m,m+p),{bytesRead:p,buffer:r}}return await d.fh.read(r,n,a,s)}async write(e,r,n,a,s){let o=this.openFh[e.subFsFileDescriptor];if(!o)throw new Error("Invalid file handle");let d=o.mode;if(!d.includes("w")&&!d.includes("a")&&!d.includes("+"))throw Object.assign(new Error("EBADF: bad file descriptor, write"),{code:"EBADF",errno:-9,syscall:"write"});if(o.unflushed.length===0){let f=await this.readFileContent({path:o.path,context:this.context});f&&f.content&&await this.memFs.promises.writeFile(o.path,f.content)}let l=await o.fh.write(r,n,a,s),h=n??0,m=s??0;return o.unflushed.push({start:m,length:a||r.byteLength-h+m}),l}async close(e){let r=e.subFsFileDescriptor,n=this.openFh[r];if(!n)throw new Error("Invalid file handle");try{await this.dataSync(e),await n.fh.close()}finally{delete this.openFh[r]}}async dataSync(e){let r=e.subFsFileDescriptor,n=this.openFh[r];if(!n)throw new Error("Invalid file handle");if(n.unflushed.length>0){let a=await this.memFs.promises.readFile(n.path);await this.writeFileContent({path:n.path,content:a,context:this.context}),n.unflushed=[]}}async readFile(e,r){let n=typeof e=="string"?e:Buffer.isBuffer(e)?e.toString():e.fd?`FileHandle(${e.fd})`:e.toString(),a=null;typeof r=="string"?a=r:r&&typeof r=="object"&&r.encoding&&(a=r.encoding);let s=await this.open(n,"r");try{let d=(await this.fstat(s)).size,l=Buffer.alloc(d);return await this.read(s,l,0,d,0),await this.close(s),a?l.toString(a):l}catch(o){try{await this.close(s)}catch{}throw o}}async writeFile(e,r,n){let a="w",s="utf8",o;typeof n=="string"?s=n:n&&typeof n=="object"&&(n.flag&&(a=String(n.flag)),n.encoding&&(s=n.encoding),n.mode&&(o=typeof n.mode=="string"?parseInt(n.mode,8):n.mode));let d=await this.open(e,a,o);try{let l;typeof r=="string"?l=Buffer.from(r,s):Buffer.isBuffer(r)?l=r:r instanceof Uint8Array?l=Buffer.from(r):ArrayBuffer.isView(r)?l=Buffer.from(r.buffer,r.byteOffset,r.byteLength):l=Buffer.from(r),await this.write(d,l,0,l.length,0)}finally{await this.close(d)}}async rename(e,r){let n=e.toString(),a=r.toString();if(await this.memFs.promises.access(n).then(()=>!0).catch(()=>!1)){let o=Gi.dirname(a);try{await this.memFs.promises.access(o)}catch{await this.memFs.promises.mkdir(o,{recursive:!0})}await this.memFs.promises.rename(e,r)}await this.renamePath({oldPath:n,newPath:a,oldContext:this.context,newContext:this.newContext||this.context})}async fchmod(e,r){}async unlink(e){let r=e.toString();try{await this.deleteFile({path:r,context:this.context})}catch(n){let a=!1;for(let[s,o]of Object.entries(this.openFh))o.path===r&&o.unflushed.length>0&&(a=!0);if(!a)throw n}finally{let n=!1;for(let[a,s]of Object.entries(this.openFh))s.path===r&&(n=!0,await s.fh.close(),delete this.openFh[Number(a)]);n&&await this.memFs.promises.unlink(r)}}async rmdir(e,...r){let n=e.toString();await this.removeDirectory({path:n,context:this.context});let a=!1;for(let[s,o]of Object.entries(this.openFh))o.path===n&&(a=!0,await o.fh.close(),delete this.openFh[Number(s)]);a&&await this.memFs.promises.rmdir(n,{recursive:!0})}fileType(){return 10}};c(Ki,"ASimpleCompositeSubfs");var Wt=Ki;var Xi=class Xi extends Wt{constructor({name:e,rootPath:r,initialData:n}){super({name:e,rootPath:r});g(this,"storage",new Map);g(this,"nextFileType",1);this.storage.set("/",{type:"directory",entries:new Set,mode:493,createdAt:new Date,modifiedAt:new Date}),n&&this.populateFromInitialData(n,"/")}_debugGetStorage(){return this.storage}populateFromInitialData(e,r){if(typeof e=="string"){this.storage.set(r,{type:"file",content:Buffer.from(e,"utf8"),mode:420,createdAt:new Date,modifiedAt:new Date});let n=this.getParentPath(r);if(n){let a=this.storage.get(n);a&&a.type==="directory"&&a.entries.add(this.getBaseName(r))}}else{let n=this.storage.get(r);if(n&&n.type==="directory")for(let[a,s]of Object.entries(e)){let o=r==="/"?`/${a}`:`${r}/${a}`;n.entries.add(a),this.populateFromInitialData(s,o)}else{let a=new Date;this.storage.set(r,{type:"directory",entries:new Set,mode:493,createdAt:a,modifiedAt:a});let s=this.getParentPath(r);if(s){let d=this.storage.get(s);d&&d.type==="directory"&&d.entries.add(this.getBaseName(r))}let o=this.storage.get(r);if(o&&o.type==="directory")for(let[d,l]of Object.entries(e)){let h=r==="/"?`/${d}`:`${r}/${d}`;o.entries.add(d),this.populateFromInitialData(l,h)}}}}fileType(){return this.nextFileType}async createDirectory(e){let{path:r,recursive:n=!1}=e,a=this.normalizePath(r);if(this.storage.has(a)){if(this.storage.get(a)?.type==="directory")return;throw Object.assign(new Error(`EEXIST: file already exists, mkdir '${r}'`),{code:"EEXIST",errno:-17,syscall:"mkdir",path:a})}if(n){let d=this.getParentPath(a);d&&d!==a&&!this.storage.has(d)&&await this.createDirectory({path:d,recursive:!0,context:e.context})}let s=new Date;this.storage.set(a,{type:"directory",entries:new Set,mode:493,createdAt:s,modifiedAt:s});let o=this.getParentPath(a);if(o){let d=this.storage.get(o);d&&d.type==="directory"&&(d.entries.add(this.getBaseName(a)),d.modifiedAt=s)}}async getStats(e){let r=this.normalizePath(e.path),n=this.storage.get(r);if(!n)throw Object.assign(new Error(`ENOENT: no such file or directory, stat '${e.path}'`),{code:"ENOENT",errno:-2,syscall:"stat",path:r});let a=new al,s=n.type==="directory"?16877:33188;return a.mode=s,a.size=n.type==="file"?n.content.length:4096,a.mtimeMs=n.modifiedAt.getTime(),a.birthtimeMs=n.createdAt.getTime(),a.ctimeMs=n.modifiedAt.getTime(),a}async readFileContent(e){let r=this.normalizePath(e.path),n=this.storage.get(r);if(!(!n||n.type!=="file"))return{content:n.content}}async writeFileContent(e){let r=this.normalizePath(e.path),n=new Date,a=typeof e.content=="string"?Buffer.from(e.content,"utf8"):e.content,s=this.storage.get(r);if(s){if(s.type==="directory")throw Object.assign(new Error(`EISDIR: illegal operation on a directory, write '${e.path}'`),{code:"EISDIR",errno:-21,syscall:"write",path:r});s.content=a,s.modifiedAt=n}else{this.storage.set(r,{type:"file",content:a,mode:420,createdAt:n,modifiedAt:n});let o=this.getParentPath(r);if(o){let d=this.storage.get(o);d||(await this.createDirectory({path:o,recursive:!0,context:e.context}),d=this.storage.get(o)),d&&d.type==="directory"&&(d.entries.add(this.getBaseName(r)),d.modifiedAt=n)}}}async readDirectory(e){let r=this.normalizePath(e.path),n=this.storage.get(r);if(!n)throw Object.assign(new Error(`ENOENT: no such file or directory, scandir '${e.path}'`),{code:"ENOENT",errno:-2,syscall:"scandir",path:r});if(n.type!=="directory")throw Object.assign(new Error(`ENOTDIR: not a directory, scandir '${e.path}'`),{code:"ENOTDIR",errno:-20,syscall:"scandir",path:r});let a=[];for(let s of n.entries){let o;r==="/"?o="/"+s:o=r+"/"+s;let d=this.storage.get(o);d&&a.push(V({name:s,parent:r,isDir:d.type==="directory"}))}return a}async renamePath(e){let r=this.normalizePath(e.oldPath),n=this.normalizePath(e.newPath),a=this.storage.get(r);if(!a)throw Object.assign(new Error(`ENOENT: no such file or directory, rename '${e.oldPath}'`),{code:"ENOENT",errno:-2,syscall:"rename",path:r});let s=this.getParentPath(r);if(s){let d=this.storage.get(s);d&&d.type==="directory"&&d.entries.delete(this.getBaseName(r))}this.storage.delete(r),this.storage.set(n,a),a.modifiedAt=new Date;let o=this.getParentPath(n);if(o){let d=this.storage.get(o);d&&d.type==="directory"&&(d.entries.add(this.getBaseName(n)),d.modifiedAt=new Date)}if(a.type==="directory"){let d=Array.from(a.entries);for(let l of d){let h=this.joinPath(r,l),m=this.joinPath(n,l);await this.renamePath({oldPath:h,newPath:m,oldContext:e.oldContext,newContext:e.newContext})}}}async deleteFile(e){let r=this.normalizePath(e.path),n=this.storage.get(r);if(!n)throw Object.assign(new Error(`ENOENT: no such file or directory, unlink '${e.path}'`),{code:"ENOENT",errno:-2,syscall:"unlink",path:r});if(n.type==="directory")throw Object.assign(new Error(`EISDIR: illegal operation on a directory, unlink '${e.path}'`),{code:"EISDIR",errno:-21,syscall:"unlink",path:r});let a=this.getParentPath(r);if(a){let s=this.storage.get(a);s&&s.type==="directory"&&(s.entries.delete(this.getBaseName(r)),s.modifiedAt=new Date)}this.storage.delete(r)}async removeDirectory(e){let r=this.normalizePath(e.path),n=this.storage.get(r);if(!n)throw Object.assign(new Error(`ENOENT: no such file or directory, rmdir '${e.path}'`),{code:"ENOENT",errno:-2,syscall:"rmdir",path:r});if(n.type!=="directory")throw Object.assign(new Error(`ENOTDIR: not a directory, rmdir '${e.path}'`),{code:"ENOTDIR",errno:-20,syscall:"rmdir",path:r});let a=Array.from(n.entries);for(let o of a){let d=this.joinPath(r,o),l=this.storage.get(d);l&&(l.type==="directory"?await this.removeDirectory({path:d,context:e.context}):await this.deleteFile({path:d,context:e.context}))}let s=this.getParentPath(r);if(s){let o=this.storage.get(s);o&&o.type==="directory"&&(o.entries.delete(this.getBaseName(r)),o.modifiedAt=new Date)}this.storage.delete(r)}normalizePath(e){if(!e||e===".")return"/";let r=e.startsWith("/")?e:"/"+e;r!=="/"&&r.endsWith("/")&&(r=r.slice(0,-1));let n=r.split("/").filter(Boolean),a=[];for(let s of n)s!=="."&&(s===".."?a.pop():a.push(s));return"/"+a.join("/")}getParentPath(e){let r=this.normalizePath(e);if(r==="/")return null;let n=r.lastIndexOf("/");return n===0?"/":r.substring(0,n)||"/"}getBaseName(e){let r=this.normalizePath(e);if(r==="/")return"";let n=r.lastIndexOf("/");return r.substring(n+1)}joinPath(...e){return"/"+e.filter(Boolean).map(n=>n.startsWith("/")?n.slice(1):n).filter(n=>n!==".").join("/")}};c(Xi,"SimpleMemorySubFs");var Qn=Xi;export{Wt as ASimpleCompositeSubfs,rt as CompositeFs,N as CompositeSubFsAdapter,nt as CopyOnWriteSubFs,er as EphemeralSubFs,St as HiddenFileSubFs,Qn as SimpleMemorySubFs,nr as createBranchOperationsAdapter,ef as createFsOperationFileLogger,ar as createLegitSyncService,ir as createLegitVirtualFileAdapter,qn as mergeLegitRouteFolders,il as openLegitFs,Jh as openLegitFsWithMemoryFs,V as toDirEntry};
14
+ /*! Bundled license information:
15
+
16
+ pako/dist/pako.esm.mjs:
17
+ (*! pako 2.1.0 https://github.com/nodeca/pako @license (MIT AND Zlib) *)
18
+ */