@legit-sdk/react 0.2.7 → 0.2.9

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.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import * as react_jsx_runtime from 'react/jsx-runtime';
2
2
  import { ReactNode } from 'react';
3
- import { openLegitFsWithMemoryFs, HistoryItem, openLegitFs } from '@legit-sdk/core/server';
3
+ import { openLegitFsWithMemoryFs, HistoryItem, openLegitFs } from '@legit-sdk/core';
4
4
 
5
5
  interface LegitContextValue {
6
6
  legitFs: Awaited<ReturnType<typeof openLegitFsWithMemoryFs>> | null;
package/dist/server.js CHANGED
@@ -1,11 +1,12 @@
1
1
  // legit-sdk server bundle (Node.js)
2
2
 
3
- var lt=Object.defineProperty;var g=(a,e)=>lt(a,"name",{value:e,configurable:!0});import{createContext as Mt,useContext as _t,useEffect as it,useState as ae,useRef as Ht}from"react";import*as fe from"path";import*as Ie from"path";import{createFsFromVolume as ct,Volume as dt}from"memfs";import*as xe from"path";import{createFsFromVolume as ft,Volume as pt}from"memfs";import ut from"ignore";import*as re from"path";import{createFsFromVolume as Ft,Volume as gt}from"memfs";import yt from"ignore";import ke from"isomorphic-git";import*as pe from"path";import{createFsFromVolume as bt,Volume as vt}from"memfs";import le from"isomorphic-git";import b from"isomorphic-git";import O from"isomorphic-git";import x from"isomorphic-git";import Et from"isomorphic-git";import he from"isomorphic-git";import ce from"isomorphic-git";import de from"isomorphic-git";import N from"isomorphic-git";import Rt from"isomorphic-git";import M from"isomorphic-git";import X from"isomorphic-git";import Y from"isomorphic-git";import C from"isomorphic-git";import R from"isomorphic-git";import me from"isomorphic-git/http/node";import P from"isomorphic-git";import{createFsFromVolume as At,Volume as xt}from"memfs";import Ne from"isomorphic-git";var Oe=Object.defineProperty,ht=g((a,e,t)=>e in a?Oe(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,"Ze"),n=g((a,e)=>Oe(a,"name",{value:e,configurable:!0}),"n"),u=g((a,e,t)=>ht(a,typeof e!="symbol"?e+"":e,t),"p"),H,Be=(H=class{constructor(e,t){u(this,"entries",[]),u(this,"currentIndex",0),u(this,"closed",!1),u(this,"compositFs"),u(this,"dirPath"),u(this,"initialized",!1),this.compositFs=e,this.dirPath=t}async initialize(){if(this.initialized)return;let e=new Set;for(let t of[...this.compositFs.subFilesystems].reverse()){let r=await t.readdir(this.dirPath);for(let i of r)e.add(i)}for(let t of Array.from(e)){let r=this.dirPath+"/"+t;await this.compositFs.hiddenFilesFileSystem?.responsible(r)||this.entries.push({name:t,path:r})}this.initialized=!0}async*[Symbol.asyncIterator](){for(await this.initialize();this.currentIndex<this.entries.length&&!this.closed;){let e=this.entries[this.currentIndex++];try{let t=await this.compositFs.stat(e.path);yield{name:e.name,isFile:n(()=>t.isFile(),"isFile"),isDirectory:n(()=>t.isDirectory(),"isDirectory"),isBlockDevice:n(()=>t.isBlockDevice(),"isBlockDevice"),isCharacterDevice:n(()=>t.isCharacterDevice(),"isCharacterDevice"),isSymbolicLink:n(()=>t.isSymbolicLink(),"isSymbolicLink"),isFIFO:n(()=>t.isFIFO(),"isFIFO"),isSocket:n(()=>t.isSocket(),"isSocket")}}catch(t){console.debug(`Failed to stat ${e.path}:`,t)}}}async read(){if(this.closed)throw new Error("Directory handle is closed");if(await this.initialize(),this.currentIndex>=this.entries.length)return null;let e=this.entries[this.currentIndex++];try{let t=await this.compositFs.stat(e.path);return{name:e.name,isFile:n(()=>t.isFile(),"isFile"),isDirectory:n(()=>t.isDirectory(),"isDirectory"),isBlockDevice:n(()=>t.isBlockDevice(),"isBlockDevice"),isCharacterDevice:n(()=>t.isCharacterDevice(),"isCharacterDevice"),isSymbolicLink:n(()=>t.isSymbolicLink(),"isSymbolicLink"),isFIFO:n(()=>t.isFIFO(),"isFIFO"),isSocket:n(()=>t.isSocket(),"isSocket")}}catch{return this.read()}}async close(){this.closed=!0,this.entries=[]}get path(){return this.dirPath}},g(H,"de"),H);n(Be,"CompositeFsDir");var Ce=Be,U,Te=(U=class{constructor(e){u(this,"delegate"),u(this,"compositeFs"),u(this,"_subFsFileDescriptor"),u(this,"handleType","file"),u(this,"_compositFsFileDescriptor",-1),this.delegate=e.fs,this._subFsFileDescriptor=e.subFsFileDescriptor,this._compositFsFileDescriptor=-1,this.compositeFs=e.compositeFs;let t=this._subFsFileDescriptor}get fsType(){return this.delegate.fileType()}get subFsFileDescriptor(){return this._subFsFileDescriptor}get fd(){return this._compositFsFileDescriptor}realize(e){if(this._compositFsFileDescriptor!==-1)throw new Error("was already realized");this._compositFsFileDescriptor=e}readableWebStream(e){throw new Error("Method not implemented.")}async appendFile(e,t){return await this.compositeFs.logOperationOnFileDescsriptor(this,"appendFile",{data:e,options:t}),await this.delegate.appendFile(this,e,t)}async chmod(e){return await this.compositeFs.logOperationOnFileDescsriptor(this,"chmod",{mode:e}),this.delegate.fchmod(this,e)}async chown(e,t){return await this.compositeFs.logOperationOnFileDescsriptor(this,"chown",{uid:e,gid:t}),this.delegate.fchown(this,e,t)}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(e,t,r,i){return await this.compositeFs.logOperationOnFileDescsriptor(this,"read",{targetBufferLength:e.length,offset:t,length:r,position:i}),await this.delegate.read(this,e,t,r,i)}async readv(e,t){return await this.compositeFs.logOperationOnFileDescsriptor(this,"readv",{buffers:e,position:t}),this.delegate.readv(this,e,t)}async stat(e){return await this.compositeFs.logOperationOnFileDescsriptor(this,"stat",{options:e}),this.delegate.fstat(this,e)}async truncate(e){return await this.compositeFs.logOperationOnFileDescsriptor(this,"truncate",{len:e}),this.delegate.ftruncate(this,e)}async utimes(e,t){return await this.compositeFs.logOperationOnFileDescsriptor(this,"utimes",{atime:e,mtime:t}),this.delegate.futimes(this,e,t)}async write(e,t,r,i){return await this.compositeFs.logOperationOnFileDescsriptor(this,"write",{buffer:e,offset:t,length:r,position:i}),this.delegate.write(this,e,t,r,i)}async writev(e,t){return await this.compositeFs.logOperationOnFileDescsriptor(this,"writev",{buffers:e,position:t}),this.delegate.writev(this,e,t)}async sync(){return await this.compositeFs.logOperationOnFileDescsriptor(this,"sync",{}),this.delegate.dataSync(this)}},g(U,"me"),U);n(Te,"CompositFsFileHandle");var se=Te,j,Le=(j=class{constructor({name:e,parentFs:t,gitRoot:r}){u(this,"compositFs"),u(this,"gitRoot"),u(this,"name"),this.name=e,this.compositFs=t,this.gitRoot=r}toStr(e){return typeof e=="string"?e:Buffer.isBuffer(e)?e.toString():e&&typeof e=="object"&&"fd"in e?`FileHandle(fd=${e.fd})`:String(e)}async open(e,t,r){throw new Error(`open not implemented for: ${this.toStr(e)}`)}async access(e,t){throw new Error(`access not implemented for: ${this.toStr(e)}`)}async stat(e,t){throw new Error(`lstat not implemented for: ${this.toStr(e)}`)}async lstat(e,t){throw new Error(`lstat not implemented for: ${this.toStr(e)}`)}async opendir(e,t){throw new Error(`opendir not implemented for: ${this.toStr(e)}`)}async link(e,t){throw new Error(`link not implemented for: ${this.toStr(e)}`)}async mkdir(e,t){throw new Error(`mkdir not implemented for: ${this.toStr(e)}`)}async readdir(e,t){throw new Error(`readdir not implemented for: ${this.toStr(e)}`)}async readlink(e,...t){throw new Error(`readlink not implemented for: ${this.toStr(e)}`)}async unlink(e){throw new Error(`unlink not implemented for: ${this.toStr(e)}`)}async rename(e,t){throw new Error(`rename not implemented for: ${this.toStr(e)}`)}async rmdir(e,...t){throw new Error(`rmdir not implemented for: ${this.toStr(e)}`)}async symlink(e,t,r){throw new Error(`symlink not implemented for: ${this.toStr(t)}`)}async lookup(e){throw new Error(`lookup not implemented for: ${this.toStr(e)}`)}resolvePath(e){throw new Error(`resolvePath not implemented for fd: ${e}`)}async close(e){this.compositFs.close(e)}async dataSync(e){throw new Error(`dataSync not implemented for: ${e.subFsFileDescriptor}`)}async read(e,t,r,i,s){throw new Error(`read not implemented for: ${e.subFsFileDescriptor}`)}async appendFile(e,t,r){throw new Error(`appendFile not implemented for: ${e.subFsFileDescriptor}`)}async fchmod(e,t){throw new Error(`fchmod not implemented for: ${e.subFsFileDescriptor}`)}async fchown(e,t,r){throw new Error(`fchown not implemented for: ${e.subFsFileDescriptor}`)}async ftruncate(e,t){throw new Error(`ftruncate not implemented for: ${e.subFsFileDescriptor}`)}async fstat(e,t){throw new Error(`fstat not implemented for: ${e.subFsFileDescriptor}`)}async futimes(e,t,r){throw new Error(`futimes not implemented for: ${e.subFsFileDescriptor}`)}async write(e,t,r,i,s){throw new Error(`write not implemented for: ${e.subFsFileDescriptor}`)}async writev(e,t,r){throw new Error(`writev not implemented for: ${e.subFsFileDescriptor}`)}async readv(e,t,r){throw new Error(`readv not implemented for: ${e.subFsFileDescriptor}`)}async readFile(e,t){throw new Error(`readFile not implemented for: ${this.toStr(e)}`)}async writeFile(e,t,r){throw new Error(`writeFile not implemented for: ${this.toStr(e)}`)}},g(j,"ce"),j);n(Le,"BaseCompositeSubFs");var Q=Le,V,Ae=(V=class extends Q{constructor({name:e,parentFs:t,gitRoot:r}){if(super({name:e,parentFs:t,gitRoot:r}),u(this,"openFh",new Map),u(this,"memFs",ct(new dt)),u(this,"targetFs"),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 i=Ie.dirname(e),s=await this.targetFs.promises.open(e,t,r);return this.openFh.set(s.fd,s),new se({fs:this,compositeFs:this.compositFs,subFsFileDescriptor:s.fd,parentFsFileDescriptors:[s.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,i,s){let o=this.openFh.get(e.subFsFileDescriptor);if(o)return await o.read(t,r,i,s);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 i=this.openFh.get(e.subFsFileDescriptor);if(i)return await i.chown(t,r)}async write(e,t,r,i,s){let o=this.openFh.get(e.subFsFileDescriptor);if(o)return await o.write(t,r,i,s);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 i=this.openFh.get(e.subFsFileDescriptor);if(i)return await i.utimes(t,r)}async writev(e,t,r){let i=this.openFh.get(e.subFsFileDescriptor);if(i)return await i.writev(t,r??void 0);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async readv(e,t,r){let i=this.openFh.get(e.subFsFileDescriptor);if(i)return await i.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 i=typeof r=="object"&&r.flag?r.flag:"w",s=await this.targetFs.open(e,i);try{let o;if(typeof t=="string"){let l=typeof r=="object"&&r.encoding?r.encoding:"utf8";o=Buffer.from(t,l)}else Buffer.isBuffer(t)?o=t:o=Buffer.from(t);await s.write(o,0,o.length,0)}finally{await this.targetFs.close(s)}}},g(V,"he"),V);n(Ae,"PassThroughSubFs");var mt=Ae,W,ze=(W=class extends Q{constructor({name:e,parentFs:t,gitRoot:r,passThroughFs:i}){super({name:e,parentFs:t,gitRoot:r}),u(this,"openFh",new Map),u(this,"memFs",ft(new pt)),u(this,"targetFs"),this.compositFs=t,this.gitRoot=r,this.targetFs=i}async responsible(e){return!0}fileType(){return 4}async open(e,t,r){let i=xe.dirname(e),s=await this.targetFs.promises.open(e,t,r);return this.openFh.set(s.fd,s),new se({fs:this,compositeFs:this.compositFs,subFsFileDescriptor:s.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 Ce(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,i,s){let o=this.openFh.get(e.subFsFileDescriptor);if(o)return await o.read(t,r,i,s);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 i=this.openFh.get(e.subFsFileDescriptor);if(i)return await i.chown(t,r)}async write(e,t,r,i,s){let o=this.openFh.get(e.subFsFileDescriptor);if(o)return await o.write(t,r,i,s);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 i=this.openFh.get(e.subFsFileDescriptor);if(i)return await i.utimes(t,r)}async writev(e,t,r){let i=this.openFh.get(e.subFsFileDescriptor);if(i)return await i.writev(t,r??void 0);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async readv(e,t,r){let i=this.openFh.get(e.subFsFileDescriptor);if(i)return await i.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)}},g(W,"fe"),W);n(ze,"PassThroughToAsyncFsSubFs");var wt=ze,K,Me=(K=class{constructor({name:e,parentFs:t,storageFs:r,gitRoot:i,defaultBranch:s="main"}){if(u(this,"promises"),u(this,"gitRoot"),u(this,"ephemeralFilesFileSystem"),u(this,"hiddenFilesFileSystem"),u(this,"passThroughFileSystem"),u(this,"subFilesystems",[]),u(this,"parentFs"),u(this,"name"),u(this,"defaultBranch"),u(this,"pathToFileDescriptors",new Map),u(this,"openFileHandles",new Map),u(this,"logOperation"),this.name=e,this.parentFs=t,this.gitRoot=i,this.defaultBranch=s,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)},!t&&r){this.passThroughFileSystem=new wt({name:e+"-passthrough",passThroughFs:r,gitRoot:i,parentFs:this});return}if(!r&&t){this.passThroughFileSystem=new mt({name:e+"-passthrough",parentFs:this,gitRoot:i});return}throw new Error("invalid configuration")}getNextFileDescriptor(){let e=Array.from(this.openFileHandles.keys());return e.length===0?1:Math.max(...e)+1}setLoggger(e){this.logOperation=e}async logOperationOnFileDescsriptor(e,t,r){if(!this.logOperation)return;let i=[];for(let[s,o]of this.pathToFileDescriptors.entries())o.includes(e.fd)&&i.push(s);if(i.length!==0)return this.logOperation?.({fsName:e.delegate.name,fd:e,path:i[0],operation:t,operationArgs:r})}getFilehandle(e){return this.openFileHandles.get(e)}setEphemeralFilesSubFs(e){this.ephemeralFilesFileSystem=e}setHiddenFilesSubFs(e){this.hiddenFilesFileSystem=e}addSubFs(e){this.subFilesystems.push(e)}async getResponsibleFs(e){if(!e.toString().startsWith(this.gitRoot)&&this.gitRoot!=="./")throw new Error("tried to access a file ("+e+") 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(e.toString()))return this.hiddenFilesFileSystem;if(await this.ephemeralFilesFileSystem.responsible(e.toString()))return this.ephemeralFilesFileSystem;for(let t of this.subFilesystems)if(await t.responsible(e.toString()))return t;return this.passThroughFileSystem}async access(e,t){let r=await this.getResponsibleFs(e);return await this.logOperation?.({fsName:r.name,path:e,operation:"access",operationArgs:{mode:t}}),r.access(e,t)}async opendir(e,t){await this.logOperation?.({fsName:this.name,path:e.toString(),operation:"opendir",operationArgs:{options:t}});let r=e.toString();if(!r.startsWith(this.gitRoot))throw new Error("tried to access a directory ("+r+") outside of the legit folder: "+this.gitRoot);return new Ce(this,r)}async mkdir(e,t){let r=await this.getResponsibleFs(e);return await this.logOperation?.({fsName:r.name,path:e.toString(),operation:"mkdir",operationArgs:{options:t}}),r.mkdir(e,t)}async readdir(e,t){await this.logOperation?.({fsName:this.name,path:e.toString(),operation:"readdir",operationArgs:{options:t}});let r=new Set;for(let i of[...this.subFilesystems].reverse()){let s=await i.readdir(e,t);for(let o of s)await this.ephemeralFilesFileSystem?.responsible((e=="/"?"":e)+"/"+o)||r.add(o)}try{let i=await this.passThroughFileSystem.readdir(e,t);for(let s of i)await this.ephemeralFilesFileSystem?.responsible((e=="/"?"":e)+"/"+s)||r.add(s)}catch(i){if(i.code!=="ENOENT")throw new Error("error reading ephemeral fs: "+i)}try{let i=await this.ephemeralFilesFileSystem.readdir(e,t);for(let s of i)r.add(s)}catch(i){if(i.code!=="ENOENT")throw new Error("error reading ephemeral fs: "+i)}for(let i of r){let s=(e=="/"?"":e)+"/"+i;await this.hiddenFilesFileSystem.responsible(s)&&r.delete(i)}return Array.from(r)}async open(e,t,r){let i=await this.getResponsibleFs(e);await this.logOperation?.({fsName:i.name,path:e,operation:"open",operationArgs:{flags:t,mode:r}});let s=await i.open(e,t,r),o=this.getNextFileDescriptor();return s.realize(o),this.openFileHandles.set(o,s),this.pathToFileDescriptors.get(e)||this.pathToFileDescriptors.set(e,[]),this.pathToFileDescriptors.get(e).push(o),s}async close(e){try{await e.delegate.close(e)}catch(t){throw t}finally{for(let[t,r]of this.pathToFileDescriptors.entries()){let i=r.indexOf(e.fd);if(i!==-1){r.splice(i,1),r.length===0&&this.pathToFileDescriptors.delete(t);break}}this.openFileHandles.delete(e.fd)}}async stat(e,t){let r=e.toString(),i=await this.getResponsibleFs(e);return await this.logOperation?.({fsName:i.name,path:r,operation:"stat",operationArgs:{opts:t}}),i.stat(e)}async lstat(e,t){let r=await this.getResponsibleFs(e);return await this.logOperation?.({fsName:r.name,path:e.toString(),operation:"lstat",operationArgs:{opts:t}}),r.lstat(e,t)}async link(e,t){throw new Error("not implemented")}async readlink(e,t){throw new Error("not implemented")}async unlink(e){return(await this.getResponsibleFs(e)).unlink(e)}async rename(e,t){if(this.hiddenFilesFileSystem){if(await this.hiddenFilesFileSystem.responsible(fe.basename(e.toString())))throw new Error("Renaming of hidden Files is not allowed "+e);if(await this.hiddenFilesFileSystem.responsible(fe.basename(t.toString())))throw new Error("Renaming to hidden Files is not allowed "+t)}let r=await this.getResponsibleFs(e),i=await this.getResponsibleFs(t);if(r===i)return await this.logOperation?.({fsName:r.name,path:e.toString(),operation:"rename",operationArgs:{oldPath:e,newPath:t}}),r.rename(e,t);let s=await r.open(e.toString(),"r");try{let o=await r.fstat(s),l=Buffer.alloc(o.size);await r.read(s,l,0,o.size,0),await r.close(s),await i.writeFile(t.toString(),l,"utf8"),await r.unlink(e)}catch(o){try{await r.close(s)}catch{}throw o}}async rmdir(e,t){let r=await this.getResponsibleFs(e);return await this.logOperation?.({fsName:r.name,path:e.toString(),operation:"rmdir",operationArgs:{dirPath:e,options:t}}),r.rmdir(e,t)}async symlink(e,t,r){throw new Error("not implemented")}async readFile(e,t){await this.logOperation?.({fsName:this.name,path:e.toString(),operation:"readFile",operationArgs:{path:e,options:t}});let r=!0,i;if(typeof e=="number"){r=!1;let s=this.getFilehandle(e);if(!s)throw new Error("Invalid file descriptor");i=s}else if(typeof e=="string")i=await this.open(e,"r");else throw new Error("only filehandle and path are supported atm");try{let s=(await i.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:l}=await i.read(o,0,s,0);if(t&&typeof t.encoding=="string")return o.slice(0,l).toString(t.encoding);if(typeof t=="string"){if(t==="utf8"||t==="utf-8")return o.slice(0,l).toString(t);throw new Error("Unsupported encoding: "+t)}return o.slice(0,l)}finally{i&&r&&await i.close()}}async writeFile(e,t,r){await this.logOperation?.({fsName:this.name,path:e.toString(),operation:"writeFile",operationArgs:{data:t,options:r}});let i=typeof e!="number",s,o,l,h="w";if(typeof r=="string"?o=r:r&&typeof r=="object"&&(o=r.encoding,l=r.mode,h=r.flag||"w"),typeof e=="number"){let c=this.getFilehandle(e);if(!c)throw new Error("Invalid file descriptor");s=c}else if(typeof e=="string")s=await this.open(e,h,l);else throw new Error("only filehandle and path are supported atm");try{let c;if(typeof t=="string")c=Buffer.from(t,o||"utf8");else if(t instanceof Buffer)c=t;else if(t instanceof Uint8Array)c=Buffer.from(t);else throw new Error("Invalid data type for writeFile");let d=0;for(;d<c.length;){let{bytesWritten:m}=await s.write(c,d,c.length-d,d);d+=m}}finally{s&&i&&await s.close()}}},g(K,"ue"),K);n(Me,"CompositeFs");var Se=Me,J,_e=(J=class extends Q{constructor({name:e,parentFs:t,gitRoot:r,hiddenFiles:i}){super({name:e,parentFs:t,gitRoot:r}),u(this,"ig"),this.ig=ut(),this.ig.add(i)}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,i,s){throw new Error("Access to hidden file is not allowed: readFileHandle: "+e.subFsFileDescriptor)}},g(J,"Fe"),J);n(_e,"HiddenFileSubFs");var De=_e,G,He=(G=class extends Q{constructor({name:e,parentFs:t,gitRoot:r,ephemeralPatterns:i}){super({name:e,parentFs:t,gitRoot:r}),u(this,"openFh",new Map),u(this,"memFs",Ft(new gt)),u(this,"ig"),u(this,"patterns"),this.compositFs=t,this.gitRoot=r,this.ig=yt(),this.ig.add(i),this.patterns=i}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 i=this.normalizePath(e),s=re.dirname(i);s&&s!=="/"&&s!=="."&&await this.memFs.promises.mkdir(s,{recursive:!0});let o=await this.memFs.promises.open(i,t,r);return this.openFh.set(o.fd,o),new se({fs:this,compositeFs:this.compositFs,subFsFileDescriptor:o.fd,parentFsFileDescriptors:[o.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),i=this.normalizePath(t);return await this.memFs.promises.link(r,i)}async mkdir(e,t){let r=this.normalizePath(e);if(!(typeof t=="object"&&t&&"recursive"in t&&t.recursive)){let i=re.dirname(r);if(i&&i!=="/"&&i!==".")try{await this.memFs.promises.stat(i)}catch{await this.memFs.promises.mkdir(i,{recursive:!0})}}await this.memFs.promises.mkdir(r,t)}async readdir(e,...t){let r=this.normalizePath(e),i=await this.memFs.promises.readdir(r,...t);return console.log("EPHEMERAL: READDIR: ",i),i}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),i=this.normalizePath(t);return await this.memFs.promises.rename(r,i)}async rmdir(e,t){let r=this.normalizePath(e);return await this.memFs.promises.rmdir(r,t)}async symlink(e,t,r){let i=this.normalizePath(e),s=this.normalizePath(t);return await this.memFs.promises.symlink(i,s,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,i,s){let o=this.openFh.get(e.subFsFileDescriptor);if(o)return await o.read(t,r,i,s);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 i=this.openFh.get(e.subFsFileDescriptor);if(i)return await i.chown(t,r)}async write(e,t,r,i,s){let o=this.openFh.get(e.subFsFileDescriptor);if(o)return await o.write(t,r,i,s);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 i=this.openFh.get(e.subFsFileDescriptor);if(i)return await i.utimes(t,r)}async writev(e,t,r){let i=this.openFh.get(e.subFsFileDescriptor);if(i)return await i.writev(t,r??void 0);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async readv(e,t,r){let i=this.openFh.get(e.subFsFileDescriptor);if(i)return await i.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 i=this.normalizePath(e),s=re.dirname(i);return s&&s!=="/"&&s!=="."&&await this.memFs.promises.mkdir(s,{recursive:!0}),this.memFs.promises.writeFile(i,t,r)}},g(G,"ge"),G);n(He,"EphemeralSubFs");var Pe=He,Ue={type:"gitBranchesListVirtualFile",getStats:n(async({gitRoot:a,nodeFs:e})=>{let t=a+"/.git";try{return await e.stat(t)}catch{throw new Error(`ENOENT: no such file or directory, stat '${t}'`)}},"getStats"),getFile:n(async({gitRoot:a,nodeFs:e})=>{try{let t=(await le.listBranches({fs:e,dir:a})).filter(s=>s.indexOf("/")===-1),r=await le.currentBranch({fs:e,dir:a}),i=await Promise.all(t.map(async s=>{let o=await le.resolveRef({fs:e,dir:a,ref:s});return s}));return{type:"directory",content:i,mode:493,size:i}}catch(t){throw t}},"getFile"),rename:n(async a=>{throw new Error("not implemented")},"rename"),mkdir:n(async function(a){throw new Error("not implemented")},"mkdir")};async function A(a,e,t){try{return await O.resolveRef({fs:a,dir:e,ref:`refs/heads/${t}`})}catch{return}}g(A,"R");n(A,"tryResolveRef");async function T({dir:a,fs:e,treeOid:t,deletePathParts:r,addPathParts:i,addObj:s,addKeepIfEmpty:o,deleteKeepIfNotEmpty:l,keepFilename:h=".keep"}){let[c,...d]=i??[],[m,...w]=r??[],f=[];if(t){let{tree:E}=await O.readTree({fs:e,dir:a,oid:t});f=[...E]}if(c===m){let E=c;if(E===void 0)throw new Error("illegal arguement - called with out a path part");if(d.length===0)throw new Error("can not move into it self");if(w.length===0)throw new Error("can not move from it self");let D=f.findIndex(F=>F.path===E),y=(D!==-1?f[D]:void 0)?.oid,v=await T({dir:a,fs:e,treeOid:y,addPathParts:d,deletePathParts:w,addObj:s,addKeepIfEmpty:o,deleteKeepIfNotEmpty:l});if(v===void 0)throw new Error("on the same path we expect an update - respectivly a newly created subTreeOid");let p=!1;if(v!==y){p=!0;let F={mode:"040000",path:E,oid:v,type:"tree"};D!==-1?f[D]=F:f.push(F)}if(t==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 O.writeTree({fs:e,dir:a,tree:f});if(t===void 0)throw new Error("currentOid should be set - since the sub tree didn't exist and ");return t}else{let E=!1,D;if(m){let y=f.findIndex(p=>p.path===m),v=y!==-1?f[y]:void 0;if(v===void 0)throw new Error("Element doesnt exist in tree");if(w.length>0){if(v&&v.type!=="tree")throw new Error("SubPart of the path for the obj to delete is not a tree");let p=await T({dir:a,fs:e,treeOid:v.oid,addPathParts:void 0,deletePathParts:w,addObj:s,addKeepIfEmpty:o,deleteKeepIfNotEmpty:l});if(p===v.oid)throw new Error("in case of a delete we expect a different subtree oid");E=!0,p===void 0?f.splice(y,1):f[y]={mode:"040000",path:m,oid:p,type:"tree"}}else if(E=!0,f.splice(y,1),f.length===0&&o){let p=new Uint8Array(0),F=await O.writeBlob({fs:e,dir:a,blob:p});f.push({mode:"100644",oid:F,path:h,type:"blob"})}D=v}if(c){let y=f.findIndex(p=>p.path===c),v=y!==-1?f[y]:void 0;if(d.length>0){if(v&&v.type!=="tree")throw new Error("SubPart of the path for the obj to add is not a tree");let p=await T({dir:a,fs:e,treeOid:v?.oid,addPathParts:d,deletePathParts:void 0,addObj:s,addKeepIfEmpty:o,deleteKeepIfNotEmpty:l});if(p===void 0)throw new Error("in case we add, we expect an update - respectivly a newly created subTreeOid");if(p!==v?.oid){E=!0;let F={mode:"040000",path:c,oid:p,type:"tree"};if(y!==-1)f[y]=F;else if(f.push(F),l&&f.length>1){let S=f.findIndex(k=>k.path===h);S!==-1&&f.splice(S,1)}}}else{if(E=!0,s){let p={mode:s.type==="tree"?"040000":"100644",path:c,oid:s.oid,type:s.type};if(y!==-1)f[y]=p;else{if(l&&f.length>0){let F=f.findIndex(S=>S.path===h);F!==-1&&f.splice(F,1)}f.push(p)}}if(o&&f.length===0){let p=new Uint8Array(0),F=await O.writeBlob({fs:e,dir:a,blob:p});f.push({mode:"100644",oid:F,path:h,type:"blob"})}}}if(f.length===0)return;if(E)return await O.writeTree({fs:e,dir:a,tree:f});if(t===void 0)throw new Error("currentOid should be set - since the sub tree didn't exist and ");return t}}g(T,"I");n(T,"buildUpdatedTree");async function _({filePath:a,gitRoot:e,nodeFs:t,commitSha:r,pathParams:i}){if(!i.filePath){let s=await O.readTree({fs:t,dir:e,oid:r});return{type:"tree",entries:s.tree.map(o=>o.path),oid:s.oid}}return(await O.walk({fs:t,dir:e,trees:[O.TREE({ref:r})],map:n(async(s,[o])=>{if(s===i.filePath&&o){let l=await o.type();if(l==="blob")return{type:"blob",oid:await o.oid()};if(l=="tree"){let h=await O.readTree({fs:t,dir:e,oid:await o.oid()});return{type:"tree",entries:h.tree.map(c=>c.path),oid:h.oid}}}},"map")})).find(s=>s!==void 0)}g(_,"V");n(_,"resolveGitObjAtPath");var z,je=(z=class extends Error{constructor(e,t){super(e),u(this,"code","ENOENT"),u(this,"path"),this.name="ENOENTError",this.path=t,Object.setPrototypeOf(this,z.prototype)}},g(z,"te"),z);n(je,"ENOENTError");var we=je,ge={type:"gitBranchFileVirtualFile",getStats:n(async({gitRoot:a,nodeFs:e,filePath:t,cacheFs:r,pathParams:i})=>{if(i.branchName===void 0)throw new Error("branchName should be in pathParams");let s=await A(e,a,i.branchName);if(!s)throw new we(`ENOENT: no such file or directory, stat '${t}'`,t);let o=await _({filePath:t,gitRoot:a,nodeFs:e,commitSha:s,pathParams:i});if(!o)throw new we(`ENOENT: no such file or directory, stat '${t}'`,t);let l=await b.readCommit({fs:e,dir:a,oid:s}),{commit:h}=l,c=await b.log({fs:e,dir:a,ref:s,filepath:i.filePath,depth:1}),d=h.committer.timestamp*1e3,m=c.length>0?c[0].commit.committer.timestamp*1e3:d;if(o.type==="tree")return{mode:420,size:0,isFile:n(()=>!0,"isFile"),isDirectory:n(()=>!0,"isDirectory"),isSymbolicLink:n(()=>!1,"isSymbolicLink"),isBlockDevice:n(()=>!1,"isBlockDevice"),isCharacterDevice:n(()=>!1,"isCharacterDevice"),isSocket:n(()=>!1,"isSocket"),isFIFO:n(()=>!1,"isFIFO"),isFileSync:n(()=>!0,"isFileSync"),isDirectorySync:n(()=>!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:d,atime:new Date(m),mtime:new Date(m),ctime:new Date(m),birthtime:new Date(m)};{let{blob:w}=await b.readBlob({fs:e,dir:a,oid:o.oid});return{mode:420,size:w.length,isFile:n(()=>!0,"isFile"),isDirectory:n(()=>!1,"isDirectory"),isSymbolicLink:n(()=>!1,"isSymbolicLink"),isBlockDevice:n(()=>!1,"isBlockDevice"),isCharacterDevice:n(()=>!1,"isCharacterDevice"),isSocket:n(()=>!1,"isSocket"),isFIFO:n(()=>!1,"isFIFO"),isFileSync:n(()=>!0,"isFileSync"),isDirectorySync:n(()=>!1,"isDirectorySync"),dev:0,ino:0,nlink:1,uid:0,gid:0,rdev:0,blksize:4096,blocks:Math.ceil(w.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:n(async({filePath:a,gitRoot:e,nodeFs:t,cacheFs:r,pathParams:i})=>{if(i.branchName===void 0)throw new Error("branchName should be in pathParams");let s=[];try{let o=await A(t,e,i.branchName);if(!o){let h=await b.resolveRef({fs:t,dir:e,ref:"HEAD"});await b.branch({fs:t,dir:e,ref:i.branchName,object:h}),o=await b.resolveRef({fs:t,ref:`refs/heads/${i.branchName}`,dir:e})}let l=await _({filePath:a,gitRoot:e,nodeFs:t,commitSha:o,pathParams:i});if(!l)return;if(l.type==="blob"){let{blob:h}=await b.readBlob({fs:t,dir:e,oid:l.oid});return{type:"file",content:Buffer.from(h),mode:420,size:h.length,oid:l.oid}}else{let h=[];try{let c=await r.promises.stat(a);if(c&&c.isDirectory()){let d=await r.promises.readdir(a,{withFileTypes:!1,encoding:"utf-8"});h.push(...d)}}catch{}return{type:"directory",content:Array.from(new Set([...h,...l.entries])),mode:493}}}catch{return}},"getFile"),unlink:n(async({filePath:a,gitRoot:e,nodeFs:t,cacheFs:r,pathParams:i,author:s})=>{if(!i.branchName)throw new Error("branchName should be in pathParams");if(!i.filePath)throw new Error("filePath should be in pathParams");let o=await b.resolveRef({fs:t,dir:e,ref:i.branchName}),l=await b.readTree({fs:t,dir:e,oid:o}),h=await T({dir:e,fs:t,treeOid:l.oid,deletePathParts:i.filePath.split("/"),addPathParts:void 0,addObj:void 0,deleteKeepIfNotEmpty:!1,addKeepIfEmpty:!0,keepFilename:".keep"});if(h!==l.oid){let c=await b.commit({fs:t,dir:e,message:`Delete ${i.filePath}`,tree:h,noUpdateBranch:!0,parent:[o],author:s});await b.writeRef({fs:t,dir:e,ref:`refs/heads/${i.branchName}`,value:c,force:!0})}},"unlink"),writeFile:n(async({filePath:a,gitRoot:e,nodeFs:t,content:r,cacheFs:i,pathParams:s,author:o})=>{if(s.branchName===void 0)throw new Error("branchName should be in pathParams");if(s.filePath===void 0)throw new Error("filePath should be in pathParams");let l;typeof r=="string"?l=new TextEncoder().encode(r):l=new Uint8Array(r);let h=await b.writeBlob({fs:t,dir:e,blob:l}),c=await A(t,e,s.branchName);if(!c){let w=await b.resolveRef({fs:t,dir:e,ref:"HEAD"});await b.branch({fs:t,dir:e,ref:s.branchName,object:w}),c=await b.resolveRef({fs:t,dir:e,ref:`refs/heads/${s.branchName}`})}let d=await b.readTree({fs:t,dir:e,oid:c}),m=await T({dir:e,fs:t,treeOid:d.oid,deletePathParts:void 0,addPathParts:s.filePath.split("/"),addObj:{type:"blob",oid:h},deleteKeepIfNotEmpty:!0,addKeepIfEmpty:!1,keepFilename:".keep"});if(m!==d.oid){let w=await b.commit({fs:t,dir:e,message:`\u{1F4BE} Change '${s.filePath}'`,tree:m,noUpdateBranch:!0,parent:[c],author:o});await b.writeRef({fs:t,dir:e,ref:`refs/heads/${s.branchName}`,value:w,force:!0})}},"writeFile"),rename:n(async function({filePath:a,newPath:e,gitRoot:t,nodeFs:r,pathParams:i,newPathParams:s,author:o}){if(i.branchName===void 0)throw new Error("branchName should be in pathParams");if(i.filePath===void 0)throw new Error("filePath should be in pathParams");if(s.branchName===void 0)throw new Error("branchName should be in newPathParams");if(s.filePath===void 0)throw new Error("filePath should be in newPathParams");let l=await A(r,t,i.branchName);if(!l)throw new Error("Invalid branch file path - source branch must exist");let h=await A(r,t,s.branchName);if(!h){let w=await b.resolveRef({fs:r,dir:t,ref:"HEAD"});await b.branch({fs:r,dir:t,ref:s.branchName,object:w}),h=await b.resolveRef({fs:r,dir:t,ref:`refs/heads/${s.branchName}`})}if(s.branchName!==i.branchName)throw new Error("cross branch move not implemented yet");let c=await _({gitRoot:t,nodeFs:r,commitSha:l,filePath:a,pathParams:i});if(c===void 0)throw new Error("no obj at path exists");let d=await T({dir:t,fs:r,deletePathParts:i.filePath.split("/"),addPathParts:s.filePath.split("/"),addObj:c,treeOid:h,addKeepIfEmpty:!0,deleteKeepIfNotEmpty:!0}),m=await b.readTree({fs:r,dir:t,oid:l});if(d!==m.oid){let w=await b.commit({fs:r,dir:t,message:`\u{1F500} Rename '${i.filePath}' to '${s.filePath}'`,tree:d,noUpdateBranch:!0,parent:[h],author:o});await b.writeRef({fs:r,dir:t,ref:`refs/heads/${s.branchName}`,value:w,force:!0})}},"rename"),mkdir:n(async function(a){if(a.pathParams.branchName===void 0)throw new Error("branchName should be in pathParams");if(a.pathParams.filePath===void 0)throw new Error("filePath should be in pathParams");try{throw await ge.getStats(a),new Error("Folder exists")}catch{}a.filePath.endsWith("/")&&(a.filePath=a.filePath.replace(/\/+$/,"")),a.pathParams&&typeof a.pathParams.filePath=="string"&&(a.pathParams.filePath=a.pathParams.filePath.replace(/\/+$/,""));let e=await A(a.nodeFs,a.gitRoot,a.pathParams.branchName);if(!e){let o=await b.resolveRef({fs:a.nodeFs,dir:a.gitRoot,ref:"HEAD"});await b.branch({fs:a.nodeFs,dir:a.gitRoot,ref:a.pathParams.branchName,object:o}),e=await b.resolveRef({fs:a.nodeFs,dir:a.gitRoot,ref:`refs/heads/${a.pathParams.branchName}`})}let t=await b.readTree({fs:a.nodeFs,dir:a.gitRoot,oid:e}),r=new Uint8Array(0),i=await b.writeBlob({fs:a.nodeFs,dir:a.gitRoot,blob:r}),s=await T({dir:a.gitRoot,fs:a.nodeFs,treeOid:t.oid,deletePathParts:void 0,addPathParts:[...a.pathParams.filePath.split("/"),".keep"],addObj:{type:"blob",oid:i},deleteKeepIfNotEmpty:!0,addKeepIfEmpty:!0,keepFilename:".keep"});if(s!==t.oid){let o=await b.commit({fs:a.nodeFs,dir:a.gitRoot,message:`\u{1F4BE} Change '${a.pathParams.filePath}'`,tree:s,noUpdateBranch:!0,parent:[e],author:a.author});await b.writeRef({fs:a.nodeFs,dir:a.gitRoot,ref:`refs/heads/${a.pathParams.branchName}`,value:o,force:!0})}},"mkdir"),rmdir:n(async({filePath:a,gitRoot:e,nodeFs:t,cacheFs:r,pathParams:i,author:s})=>{if(!i.branchName)throw new Error("branchName should be in pathParams");if(!i.filePath)throw new Error("filePath should be in pathParams");let o=await b.resolveRef({fs:t,dir:e,ref:i.branchName}),l=await b.readTree({fs:t,dir:e,oid:o}),h=await T({dir:e,fs:t,treeOid:l.oid,deletePathParts:i.filePath.split("/"),addPathParts:void 0,addObj:void 0,deleteKeepIfNotEmpty:!1,addKeepIfEmpty:!0,keepFilename:".keep"});if(h!==l.oid){let c=await b.commit({fs:t,dir:e,message:`Delete ${i.filePath}`,tree:h,noUpdateBranch:!0,parent:[o],author:s});await b.writeRef({fs:t,dir:e,ref:`refs/heads/${i.branchName}`,value:c,force:!0})}},"rmdir")},Ve={type:"gitBranchHeadVirtualFile",getStats:n(async({gitRoot:a,nodeFs:e,pathParams:t})=>{if(t.branchName===void 0)throw new Error("branchName should be in pathParams");let r;try{r=await x.resolveRef({fs:e,dir:a,ref:t.branchName})}catch{r=await x.resolveRef({fs:e,dir:a,ref:`refs/heads/${t.branchName}`})}let i=await x.readCommit({fs:e,dir:a,oid:r}),{commit:s}=i,o=s.committer.timestamp*1e3;return{mode:420,size:40,isFile:n(()=>!0,"isFile"),isDirectory:n(()=>!1,"isDirectory"),isSymbolicLink:n(()=>!1,"isSymbolicLink"),isBlockDevice:n(()=>!1,"isBlockDevice"),isCharacterDevice:n(()=>!1,"isCharacterDevice"),isSocket:n(()=>!1,"isSocket"),isFIFO:n(()=>!1,"isFIFO"),isFileSync:n(()=>!0,"isFileSync"),isDirectorySync:n(()=>!1,"isDirectorySync"),dev:0,ino:0,nlink:1,uid:0,gid:0,rdev:0,blksize:4096,blocks:Math.ceil(40/4096),atimeMs:o,mtimeMs:o,ctimeMs:o,birthtimeMs:o,atime:new Date(o),mtime:new Date(o),ctime:new Date(o),birthtime:new Date(o)}},"getStats"),getFile:n(async({gitRoot:a,nodeFs:e,pathParams:t})=>{if(t.branchName===void 0)throw new Error("branchName should be in pathParams");try{let r;try{r=await x.resolveRef({fs:e,dir:a,ref:t.branchName})}catch{r=await x.resolveRef({fs:e,dir:a,ref:`refs/heads/${t.branchName}`})}return{type:"file",content:r+`
4
- `,mode:420,size:r.length}}catch{return}},"getFile"),writeFile:n(async({filePath:a,gitRoot:e,nodeFs:t,content:r,cacheFs:i,pathParams:s})=>{if(console.log("gitBranchHeadVirtualFile writeFile called",{pathParams:s,content:r}),s.branchName===void 0)throw new Error("branchName should be in pathParams");let o=r.toString().trim();try{await x.readCommit({fs:t,dir:e,oid:o})}catch{throw new Error(`Commit ${o} does not exist in the repository`)}await x.writeRef({fs:t,dir:e,ref:"refs/heads/"+s.branchName,value:o,force:!0})},"writeFile"),rename(a){throw new Error("not implementsd")},mkdir:n(async function(a){throw new Error("not implemented")},"mkdir")},St={type:"gitBranchTipVirtualFile",getStats:n(async a=>{let e=a.gitRoot+"/.git";try{return await a.nodeFs.stat(e)}catch{throw new Error(`ENOENT: no such file or directory, stat '${e}'`)}},"getStats"),getFile:n(async({filePath:a,gitRoot:e,nodeFs:t,pathParams:r})=>{if(!r.branchName)throw new Error("branchName should be in pathParams");try{let i=await Et.resolveRef({fs:t,dir:e,ref:`refs/heads/${r.branchName}`});return{type:"file",content:i+`
5
- `,mode:420,size:i.length+1}}catch{return}},"getFile"),rename(a){throw new Error("not implementsd")},mkdir:n(async function(a){throw new Error("not implemented")},"mkdir")},We={type:"gitCommitFileVirtualFile",getStats:n(async({filePath:a,gitRoot:e,nodeFs:t,pathParams:r})=>{if(!r.sha_1_1_2)throw new Error("sha_1_1_2 should be in pathParams");if(!r.sha1_3__40)throw new Error("sha1_3__40 should be in pathParams");let i=r.sha_1_1_2+r.sha1_3__40,s=await _({filePath:a,gitRoot:e,nodeFs:t,commitSha:i,pathParams:r});if(!s)throw new we(`ENOENT: no such file or directory, stat '${a}'`,a);let o=await he.readCommit({fs:t,dir:e,oid:i}),{commit:l}=o,h=l.committer.timestamp*1e3;if(s.type==="tree")return{mode:420,size:0,isFile:n(()=>!0,"isFile"),isDirectory:n(()=>!0,"isDirectory"),isSymbolicLink:n(()=>!1,"isSymbolicLink"),isBlockDevice:n(()=>!1,"isBlockDevice"),isCharacterDevice:n(()=>!1,"isCharacterDevice"),isSocket:n(()=>!1,"isSocket"),isFIFO:n(()=>!1,"isFIFO"),isFileSync:n(()=>!0,"isFileSync"),isDirectorySync:n(()=>!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:h,atime:new Date(h),mtime:new Date(h),ctime:new Date(h),birthtime:new Date(h)};{let{blob:c}=await he.readBlob({fs:t,dir:e,oid:s.oid});return{mode:420,size:c.length,isFile:n(()=>!0,"isFile"),isDirectory:n(()=>!1,"isDirectory"),isSymbolicLink:n(()=>!1,"isSymbolicLink"),isBlockDevice:n(()=>!1,"isBlockDevice"),isCharacterDevice:n(()=>!1,"isCharacterDevice"),isSocket:n(()=>!1,"isSocket"),isFIFO:n(()=>!1,"isFIFO"),isFileSync:n(()=>!0,"isFileSync"),isDirectorySync:n(()=>!1,"isDirectorySync"),dev:0,ino:0,nlink:1,uid:0,gid:0,rdev:0,blksize:4096,blocks:Math.ceil(c.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:n(async({filePath:a,gitRoot:e,nodeFs:t,pathParams:r})=>{if(!r.sha_1_1_2)throw new Error("sha_1_1_2 should be in pathParams");if(!r.sha1_3__40)throw new Error("sha1_3__40 should be in pathParams");let i=r.sha_1_1_2+r.sha1_3__40;try{let s=await _({filePath:a,gitRoot:e,nodeFs:t,commitSha:i,pathParams:r});if(!s)return;if(s.type==="blob"){let{blob:o}=await he.readBlob({fs:t,dir:e,oid:s.oid});return{type:"file",content:Buffer.from(o),mode:420,size:o.length,oid:s.oid}}else return{type:"directory",content:Array.from(new Set([...s.entries.filter(o=>o!==".keep")])),mode:493}}catch{return}},"getFile"),rename(a){throw new Error("not implementsd")},mkdir:n(async function(a){throw new Error("not implemented")},"mkdir")};function Ke(a,e,t){return a===0&&e===2&&t===0?"untracked":a===1&&e===0&&t===0?"deleted":a===1&&e===2&&t!==0?"modified":a===0&&e===2&&t===2?"added":"unknown"}g(Ke,"dt");n(Ke,"getFileStatus");var Dt={type:"gitStatusVirtualFile",getStats:n(async a=>{let e=a.gitRoot+"/.git";try{return await a.nodeFs.stat(e)}catch{throw new Error(`ENOENT: no such file or directory, stat '${e}'`)}},"getStats"),getFile:n(async({gitRoot:a,nodeFs:e})=>{try{let t=await ce.currentBranch({fs:e,dir:a})||"HEAD",r=await ce.resolveRef({fs:e,dir:a,ref:"HEAD"}),i=(await ce.statusMatrix({fs:e,dir:a})).filter(([,o,l,h])=>o!==l||l!==h).map(([o,l,h,c])=>({path:o,status:Ke(l,h,c)})),s=JSON.stringify({branch:t,commit:r,clean:i.length===0,files:i},null,2);return{type:"file",content:s,mode:33188,size:Buffer.byteLength(s)}}catch(t){throw console.error(t),t}},"getFile"),rename(a){throw new Error("not implementsd")},mkdir:n(async function(a){throw new Error("not implemented")},"mkdir")},ue={type:"legitVirtualFile",getStats:n(async({gitRoot:a,nodeFs:e})=>{let t=a+"/.git";try{return await e.stat(t)}catch{throw new Error(`ENOENT: no such file or directory, stat '${t}'`)}},"getStats"),getFile:n(async({gitRoot:a,nodeFs:e})=>({type:"directory",content:[],mode:493,size:0}),"getFile"),rename(a){throw new Error("not implementsd")},mkdir:n(async function(a){throw new Error("not implemented")},"mkdir")},Pt=[ue,Dt,We,Ue,ge,Ve,St],q,Je=(q=class{constructor(e){this.routes=e,u(this,"compiledRoutes");let t={},r=n((i,s)=>{if(typeof i.type=="string"){t[s]={handler:i,siblings:[]};let o=i}else{let o=[];for(let[l,h]of Object.entries(i))if(l==="."){if(t[s])throw new Error(`Conflict: multiple handlers for path '${s}', '.' and optional '[[parameter_name]]' defined?`);t[s]={handler:h,siblings:o}}else if(l.startsWith("[[")&&l.endsWith("]]")){if(t[s])throw new Error(`Conflict: multiple handlers for path '${s}', '.' and optional '[[parameter_name]]' defined?`);t[s]={handler:h,siblings:o},l.startsWith("[[...")?t[s?`${s}/${l}`:l]={handler:h,siblings:[]}:r(h,s?`${s}/${l}`:l)}else l.startsWith("[")&&l.endsWith("]")?l.startsWith("[...")?t[s?`${s}/${l}`:l]={handler:h,siblings:[]}:r(h,s?`${s}/${l}`:l):(o.push(l),r(h,s?`${s}/${l}`:l))}},"walk");for(let[i,s]of Object.entries(e))r(s,i);this.compiledRoutes=Object.entries(t).map(([i,s])=>{let o=[],l=i.split("/").map(h=>{if(h.startsWith("[[")&&h.endsWith("]]")){let c=h.slice(2,-2).replace(/^\.\.\./,"");return o.push(c),"(.*)"}if(h.startsWith("[")&&h.endsWith("]")){let c=h.slice(1,-1);return o.push(c),"([^/]+)"}return h.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}).join("/");return{regex:new RegExp(`^${l}$`),paramNames:o,staticSiblings:s.siblings,handler:s.handler}})}match(e){e.length>1&&e.endsWith("/")&&(e=e.replace(/\/+$/,""));for(let{regex:t,paramNames:r,handler:i,staticSiblings:s}of this.compiledRoutes){let o=e.match(t);if(!o)continue;let l={};for(let h=0;h<r.length;h++)l[r[h]]=decodeURIComponent(o[h+1]||"");return{handler:i,params:l,staticSiblings:s}}}},g(q,"Pe"),q);n(Je,"LegitPathRouter");var kt=Je,Re={type:"gitCommitVirtualFolder",getStats:n(async a=>{let e=a.gitRoot+"/.git";try{return await a.nodeFs.stat(e)}catch{throw new Error(`ENOENT: no such file or directory, stat '${e}'`)}},"getStats"),getFile:n(async({filePath:a,gitRoot:e,nodeFs:t,pathParams:r})=>{let i=await de.listBranches({fs:t,dir:e}),s=new Set,o=new Set;for(let c of i){let d=`refs/heads/${c}`;try{let m=await de.resolveRef({fs:t,dir:e,ref:d});s.add(m)}catch{}}for(let c of s){let d=await de.log({fs:t,dir:e,ref:c});for(let m of d)o.add(m.oid)}if(!r.sha_1_1_2){let c=new Set;for(let m of o)if(c.add(m.slice(0,2)),c.size>=256)break;let d=Array.from(c).sort();return{type:"directory",content:d,mode:493,size:d}}let l=new Set;for(let c of o)c.startsWith(r.sha_1_1_2)&&l.add(c.slice(2,40));let h=Array.from(l).sort();return{type:"directory",content:h,mode:493,size:h.length}},"getFile"),rename(a){throw new Error("not implementsd")},mkdir:n(async function(a){throw new Error("not implemented")},"mkdir")},Ge="-operation";async function $(a,e,t){return(await Rt.listBranches({fs:a,dir:e})).filter(r=>r.endsWith("__"+t+Ge))[0]}g($,"D");n($,"resolveOperationBranchName");var Nt={type:"gitBranchOperationVirtualFile",getStats:n(async a=>{let{gitRoot:e,nodeFs:t,pathParams:r}=a,i;try{i=await N.resolveRef({fs:t,dir:e,ref:`refs/heads/${r.branchName}`})}catch{throw new Error(`Base Branch ${r.branchName} for operations does not exis`)}let s=await $(t,e,r.branchName),o=!1;if(s)try{i=await N.resolveRef({fs:t,dir:e,ref:s}),o=!0}catch{try{i=await N.resolveRef({fs:t,dir:e,ref:`refs/heads/${s}`}),o=!0}catch{}}let l=await N.readCommit({fs:t,dir:e,oid:i}),{commit:h}=l,c=h.committer.timestamp*1e3;try{return{mode:420,size:40,atimeMs:c,mtimeMs:c,ctimeMs:c,birthtimeMs:c,atime:new Date(c),mtime:new Date(c),ctime:new Date(c),birthtime:new Date(c),isFile:n(()=>!0,"isFile"),isDirectory:n(()=>!1,"isDirectory"),isSymbolicLink:n(()=>!1,"isSymbolicLink"),isBlockDevice:n(()=>!1,"isBlockDevice"),isCharacterDevice:n(()=>!1,"isCharacterDevice"),isSocket:n(()=>!1,"isSocket"),isFIFO:n(()=>!1,"isFIFO"),isFileSync:n(()=>!0,"isFileSync"),isDirectorySync:n(()=>!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:n(async a=>{let{gitRoot:e,nodeFs:t,pathParams:r}=a,i=await $(t,e,r.branchName),s,o=!1;return i?(s=await N.resolveRef({fs:t,dir:e,ref:`refs/heads/${i}`}),o=!0):s=await N.resolveRef({fs:t,dir:e,ref:`refs/heads/${r.branchName}`}),{type:"file",content:Buffer.from(s),mode:420,size:s.length}},"getFile"),writeFile:n(async({filePath:a,gitRoot:e,nodeFs:t,content:r,cacheFs:i,pathParams:s,author:o})=>{if(s.branchName===void 0)throw new Error("branchName should be in pathParams");let l;typeof r=="string"?l=new TextEncoder().encode(r):l=new Uint8Array(r);let h=await N.writeBlob({fs:t,dir:e,blob:l}),c=await A(t,e,s.branchName);if(!c)throw new Error("Invalid branch file path - branch doesn't exist");let d=await $(t,e,s.branchName),m=!1;d||(d="legit/__"+s.branchName+Ge,await N.branch({fs:t,dir:e,ref:d,object:c}),m=!0);let w=await N.resolveRef({fs:t,dir:e,ref:`refs/heads/${d}`}),f=await N.readTree({fs:t,dir:e,oid:c}),E;r instanceof ArrayBuffer?E=Buffer.from(r).toString("utf-8"):typeof r=="string"?E=r:r instanceof Uint8Array?E=Buffer.from(r).toString("utf-8"):E=String(r);let D=!1;if(!m){let v=await N.findMergeBase({fs:t,dir:e,oids:D?[w]:[w,c]});v.length===1&&v[0]===c&&(D=!0)}let y=await N.commit({fs:t,dir:e,message:E,tree:f.oid,noUpdateBranch:!0,author:o,parent:D?m?[c,c]:[w]:[w,c]});await N.writeRef({fs:t,dir:e,ref:`refs/heads/${d}`,value:y,force:!0})},"writeFile"),rename:n(async function({filePath:a,newPath:e,gitRoot:t,nodeFs:r,pathParams:i,newPathParams:s}){throw new Error("not implemented")},"rename"),mkdir:n(async function(a){throw new Error("not implemented")},"mkdir")},qe={type:"gitBranchOperationsVirtualFile",getStats:n(async a=>{let{gitRoot:e,nodeFs:t,pathParams:r}=a;if(r.branchName===void 0)throw new Error("branchName should be in pathParams");let i=await $(t,e,r.branchName),s,o=!1;if(i)try{s=await M.resolveRef({fs:t,dir:e,ref:i}),o=!0}catch{try{s=await M.resolveRef({fs:t,dir:e,ref:`refs/heads/${i}`}),o=!0}catch{throw new Error(`Base Branch ${r.branchName} for operations does not exis`)}}else try{s=await M.resolveRef({fs:t,dir:e,ref:`refs/heads/${r.branchName}`})}catch{throw new Error(`Base Branch ${r.branchName} for operations does not exis`)}let l=await M.readCommit({fs:t,dir:e,oid:s}),{commit:h}=l,c=h.committer.timestamp*1e3;try{return{mode:420,size:(o?await qe.getFile(a):void 0)?.content?.length??0,atimeMs:c,mtimeMs:c,ctimeMs:c,birthtimeMs:c,atime:new Date(c),mtime:new Date(c),ctime:new Date(c),birthtime:new Date(c),isFile:n(()=>!0,"isFile"),isDirectory:n(()=>!1,"isDirectory"),isSymbolicLink:n(()=>!1,"isSymbolicLink"),isBlockDevice:n(()=>!1,"isBlockDevice"),isCharacterDevice:n(()=>!1,"isCharacterDevice"),isSocket:n(()=>!1,"isSocket"),isFIFO:n(()=>!1,"isFIFO"),isFileSync:n(()=>!0,"isFileSync"),isDirectorySync:n(()=>!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:n(async a=>{let{gitRoot:e,nodeFs:t,pathParams:r}=a,i=await $(t,e,r.branchName),s=[];if(i){let h=await M.resolveRef({fs:t,dir:e,ref:`refs/heads/${i}`}),c=!1,d=h;for(;d&&!c;){let m=await M.readCommit({fs:t,dir:e,oid:d});s.push({oid:m.oid,parentOids:m.commit.parent,message:m.commit.message,originBranchOid:"unset"}),d=m.commit.parent&&m.commit.parent.length>0?m.commit.parent[0]:null,m.commit.parent.length===2&&m.commit.parent[0]===m.commit.parent[1]&&(c=!0)}}let o;for(let h=s.length-1;h>=0;h--){let c=s[h];if(o===void 0){if(c.parentOids.length!==2&&c.parentOids[0]!==c.parentOids[1])throw new Error(`Operation commit ${c.oid} does not have two parents as expected`);o=c.parentOids[1]}c.parentOids.length===2&&(o=c.parentOids[1]),c.originBranchOid=o}let l=Buffer.from(JSON.stringify(s,null,2),"utf-8");return{type:"file",content:l,mode:420,size:l.length}},"getFile"),rename:n(async function(a){throw new Error("not implemented")},"rename"),mkdir:n(async function(a){throw new Error("not implemented")},"mkdir")},$t=new Set([" ","~","^",":","?","*","[","\\"]),Ot=[/^\/|\/$/,/\/\//,/\.$/,/\.lock$/,/^@$/,/@\{/],Ze="\u2002";function Fe(a){let e=a.codePointAt(0);return!(e>=0&&e<=31||e===127||$t.has(a))}g(Fe,"Ae");n(Fe,"isValidChar");function Xe(a){let e="";for(let t of a)t===" "?e+=Ze:Fe(t)?e+=t:e+="%"+t.codePointAt(0);for(let t of Ot)if(t.test(e))return Array.from(e).map(r=>Fe(r)?r:"%"+r.codePointAt(0)).join("");return e}g(Xe,"xe");n(Xe,"encodeName");function Ye(a){return a.replace(/%(\d+)/g,(e,t)=>String.fromCodePoint(parseInt(t,10))).replace(new RegExp(Ze,"g")," ")}g(Ye,"Ve");n(Ye,"decodeName");var Bt={type:"getThreadName",getStats:n(async a=>{let{gitRoot:e,nodeFs:t,pathParams:r}=a,i;try{i=await X.resolveRef({fs:t,dir:e,ref:`refs/heads/${r.branchName}`})}catch{throw new Error(`Base Branch ${r.branchName} for operations does not exis`)}let s=await $(t,e,r.branchName),o=!1;if(s)try{i=await X.resolveRef({fs:t,dir:e,ref:s}),o=!0}catch{try{i=await X.resolveRef({fs:t,dir:e,ref:`refs/heads/${s}`}),o=!0}catch{}}let l=await X.readCommit({fs:t,dir:e,oid:i}),{commit:h}=l,c=h.committer.timestamp*1e3;try{return{mode:420,size:40,atimeMs:c,mtimeMs:c,ctimeMs:c,birthtimeMs:c,atime:new Date(c),mtime:new Date(c),ctime:new Date(c),birthtime:new Date(c),isFile:n(()=>!0,"isFile"),isDirectory:n(()=>!1,"isDirectory"),isSymbolicLink:n(()=>!1,"isSymbolicLink"),isBlockDevice:n(()=>!1,"isBlockDevice"),isCharacterDevice:n(()=>!1,"isCharacterDevice"),isSocket:n(()=>!1,"isSocket"),isFIFO:n(()=>!1,"isFIFO"),isFileSync:n(()=>!0,"isFileSync"),isDirectorySync:n(()=>!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:n(async a=>{let{gitRoot:e,nodeFs:t,pathParams:r}=a,i=await $(t,e,r.branchName),s;if(i){let o="legit/",l=`__${r.branchName}-operation`;return i.startsWith(o)&&i.endsWith(l)?s=i.slice(o.length,i.length-l.length):s=i,{type:"file",content:Buffer.from(Ye(s)),mode:420,size:s.length}}return{type:"file",content:Buffer.from(""),mode:420,size:0}},"getFile"),writeFile:n(async({filePath:a,gitRoot:e,nodeFs:t,content:r,cacheFs:i,pathParams:s})=>{if(s.branchName===void 0)throw new Error("branchName should be in pathParams");let o=await $(t,e,s.branchName);if(o){let l=`legit/${Xe(r.toString())}__${s.branchName}-operation`;await X.renameBranch({fs:t,dir:e,oldref:o,ref:l}),o=l}},"writeFile"),rename:n(async function({filePath:a,newPath:e,gitRoot:t,nodeFs:r,pathParams:i,newPathParams:s}){throw new Error("not implemented")},"rename"),mkdir:n(async function(a){throw new Error("not implemented")},"mkdir")},Ct={type:"gitBranchHistory",getStats:n(async({gitRoot:a,nodeFs:e,pathParams:t})=>{if(t.branchName===void 0)throw new Error("branchName should be in pathParams");let r;try{r=await Y.resolveRef({fs:e,dir:a,ref:t.branchName})}catch{r=await Y.resolveRef({fs:e,dir:a,ref:`refs/heads/${t.branchName}`})}let i=await Y.readCommit({fs:e,dir:a,oid:r}),{commit:s}=i,o=s.committer.timestamp*1e3;return{mode:420,size:1e5,isFile:n(()=>!0,"isFile"),isDirectory:n(()=>!1,"isDirectory"),isSymbolicLink:n(()=>!1,"isSymbolicLink"),isBlockDevice:n(()=>!1,"isBlockDevice"),isCharacterDevice:n(()=>!1,"isCharacterDevice"),isSocket:n(()=>!1,"isSocket"),isFIFO:n(()=>!1,"isFIFO"),isFileSync:n(()=>!0,"isFileSync"),isDirectorySync:n(()=>!1,"isDirectorySync"),dev:0,ino:0,nlink:1,uid:0,gid:0,rdev:0,blksize:4096,blocks:Math.ceil(40/4096),atimeMs:o,mtimeMs:o,ctimeMs:o,birthtimeMs:o,atime:new Date(o),mtime:new Date(o),ctime:new Date(o),birthtime:new Date(o)}},"getStats"),getFile:n(async a=>{let{gitRoot:e,nodeFs:t,pathParams:r}=a,i=r.branchName,s=[];if(i){let l=await Y.resolveRef({fs:t,dir:e,ref:`refs/heads/${i}`}),h=!1,c=l;for(;c&&!h;){let d=await Y.readCommit({fs:t,dir:e,oid:c});s.push({oid:d.oid,...d.commit}),c=d.commit.parent[0]}}let o=Buffer.from(JSON.stringify(s,null,2),"utf-8");return{type:"file",content:o,mode:420,size:o.length}},"getFile"),rename:n(async a=>{throw new Error("not implemented")},"rename"),mkdir:n(async function(a){throw new Error("not implemented")},"mkdir")},Tt={type:"gitBranchOperationHeadVirtualFile",getStats:n(async({gitRoot:a,nodeFs:e,pathParams:t})=>{if(t.branchName===void 0)throw new Error("branchName should be in pathParams");let r=await $(e,a,t.branchName);if(!r){let h=new Date(0);return{mode:420,size:0,isFile:n(()=>!0,"isFile"),isDirectory:n(()=>!1,"isDirectory"),isSymbolicLink:n(()=>!1,"isSymbolicLink"),isBlockDevice:n(()=>!1,"isBlockDevice"),isCharacterDevice:n(()=>!1,"isCharacterDevice"),isSocket:n(()=>!1,"isSocket"),isFIFO:n(()=>!1,"isFIFO"),isFileSync:n(()=>!0,"isFileSync"),isDirectorySync:n(()=>!1,"isDirectorySync"),dev:0,ino:0,nlink:1,uid:0,gid:0,rdev:0,blksize:4096,blocks:Math.ceil(40/4096),atimeMs:h.getTime(),mtimeMs:h.getTime(),ctimeMs:h.getTime(),birthtimeMs:h.getTime(),atime:h,mtime:h,ctime:h,birthtime:h}}let i;try{i=await C.resolveRef({fs:e,dir:a,ref:r})}catch{i=await C.resolveRef({fs:e,dir:a,ref:`refs/heads/${r}`})}let s=await C.readCommit({fs:e,dir:a,oid:i}),{commit:o}=s,l=o.committer.timestamp*1e3;return{mode:420,size:40,isFile:n(()=>!0,"isFile"),isDirectory:n(()=>!1,"isDirectory"),isSymbolicLink:n(()=>!1,"isSymbolicLink"),isBlockDevice:n(()=>!1,"isBlockDevice"),isCharacterDevice:n(()=>!1,"isCharacterDevice"),isSocket:n(()=>!1,"isSocket"),isFIFO:n(()=>!1,"isFIFO"),isFileSync:n(()=>!0,"isFileSync"),isDirectorySync:n(()=>!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:n(async({gitRoot:a,nodeFs:e,pathParams:t})=>{if(t.branchName===void 0)throw new Error("branchName should be in pathParams");let r=await $(e,a,t.branchName);if(!r)return{type:"file",content:"",mode:420,size:0};try{let i;try{i=await C.resolveRef({fs:e,dir:a,ref:r})}catch{i=await C.resolveRef({fs:e,dir:a,ref:`refs/heads/${r}`})}return{type:"file",content:i+`
6
- `,mode:420,size:i.length}}catch{return}},"getFile"),writeFile:n(async({filePath:a,gitRoot:e,nodeFs:t,content:r,cacheFs:i,pathParams:s})=>{if(s.branchName===void 0)throw new Error("branchName should be in pathParams");let o=await $(t,e,s.branchName),l=await C.resolveRef({fs:t,dir:e,ref:`refs/heads/${o}`});if(!o)throw new Error(`Operation branch name could not be resolved for branch ${s.branchName}`);let h=r.toString().trim(),c,d,m=!1;if(!l)throw new Error(`Operation branch ref could not be resolved for branch ${o}`);let w=l;for(;w&&!m;){let f=await C.readCommit({fs:t,dir:e,oid:w});if(f.oid===h&&(c=f.oid),w=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])m=!0;else if(c!==void 0){d=f.commit.parent[1];break}}}if(c===void 0)throw new Error(`Cant rollback to ${h} couldn't find newOperationBranchHead ${c}`);if(d===void 0)throw new Error(`Cant rollback to ${h} couldn't find newBranchHead ${d}`);await C.writeRef({fs:t,dir:e,ref:"refs/heads/"+o,value:c,force:!0}),await C.writeRef({fs:t,dir:e,ref:"refs/heads/"+s.branchName,value:d,force:!0})},"writeFile"),rename(a){throw new Error("not implementsd")},mkdir:n(async function(a){throw new Error("not implemented")},"mkdir")},B,ie=(B=class extends Q{constructor({name:e,parentFs:t,gitStorageFs:r,gitRoot:i,virtualFiles:s=Pt}){super({name:e,parentFs:t,gitRoot:i}),u(this,"memFs"),u(this,"openFh",{}),u(this,"virtualFiles"),u(this,"legitFileNames"),u(this,"storageFs"),this.gitRoot=i,this.storageFs=r,this.memFs=bt(new vt),this.virtualFiles=s,this.legitFileNames=["branches","commits"]}async getAuthor(){let e=await ke.getConfig({fs:this.storageFs,dir:this.gitRoot,path:"user.name"}),t=await ke.getConfig({fs:this.storageFs,dir:this.gitRoot,path:"user.email"}),r=Math.floor(Date.now()/1e3),i=new Date().getTimezoneOffset();return{name:e,email:t,date:r,timezoneOffset:i}}async responsible(e){return this.isLegitPath(e)}isLegitPath(e){return e.includes(`/${B.LEGIT_DIR}/`)||e.includes(`/${B.LEGIT_DIR}`)}getRouteHandler(e){let t=e.indexOf(`/${B.LEGIT_DIR}`);if(t===-1)throw new Error("Not a legit path");let r=e.slice(t+1);return B.pathRouter.match(r)}async open(e,t,r){let i=this.getRouteHandler(e);if(!i)throw new Error("Not a virtual legit file");if(i?.handler.writeFile===void 0&&(t.includes("w")||t.includes("a")))throw new Error(`Write operations not allowed for ${i?.handler.type}`);if(t.includes("x")&&i?.handler.type!=="gitBranchFileVirtualFile")throw new Error(`Exclusive operations not allowed for ${i?.handler.type}`);let s=await i.handler.getFile({cacheFs:this.memFs,filePath:e,gitRoot:this.gitRoot,nodeFs:this.storageFs,pathParams:i.params,author:await this.getAuthor()}),o=!1;for(let m of Object.values(this.openFh))m.path===e&&(o=!0);if((s||o)&&t.includes("x"))throw Object.assign(new Error(`EEXIST: file already exists, open '${e}'`),{code:"EEXIST",errno:-17,syscall:"open",path:e});if(!s&&!o&&!(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 l=pe.dirname(e);if(await this.memFs.promises.mkdir(l,{recursive:!0}),s===void 0&&!t.includes("x")||s&&s.type==="file")try{let m=await this.memFs.promises.access(e)}catch{await this.memFs.promises.writeFile(e,"")}let h=await this.memFs.promises.open(e,t,r),c=h.fd,d=new se({fs:this,compositeFs:this.compositFs,subFsFileDescriptor:c,parentFsFileDescriptors:[]});return this.openFh[c]={path:e,mode:t,fh:h,openSha:s?.oid,readSha:void 0,unflushed:[]},(t.includes("x")||t.includes("w"))&&this.openFh[c].unflushed.push({length:0,start:0}),d}async mkdir(e,t){let r=e.toString(),i=this.getRouteHandler(r),s=t?{options:t}:{};try{await i?.handler.mkdir({cacheFs:this.memFs,filePath:e.toString(),nodeFs:this.storageFs,gitRoot:this.gitRoot,pathParams:i.params,...s,author:await this.getAuthor()});let o=typeof t=="object"?{...t,recursive:!0}:{recursive:!0};await this.memFs.promises.mkdir(e,o);let l=r.split("/"),h="";for(let c=1;c<=l.length;c++){h=l.slice(0,c).join("/");try{if((await this.memFs.promises.stat(h)).isDirectory()){let d=await this.memFs.promises.open(h,"r");this.openFh[d.fd]={path:h,mode:"r",fh:d,openSha:void 0,readSha:void 0,unflushed:[]}}}catch{}}}catch(o){throw o}}async access(e,t){await this.stat(e)}async futimes(e,t,r){let i=this.openFh[e.subFsFileDescriptor];if(!i)throw new Error("Invalid file handle");return await i.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(),i=Object.values(this.openFh).find(o=>o.path===r&&o.unflushed.length>0);if(i&&i.unflushed.length>0)return await i.fh.stat(t);let s=this.getRouteHandler(r);if(!s)throw new Error(`ENOENT: no such file or directory, stat '${r}'`);return await s.handler.getStats({cacheFs:this.memFs,filePath:r,gitRoot:this.gitRoot,nodeFs:this.storageFs,pathParams:s.params,author:await this.getAuthor()})}async lstat(e,t){return this.stat(e,t)}async readdir(e,t){let r=e.toString();if(!this.isLegitPath(r))return[".legit"];let i=this.getRouteHandler(r);if(!i)throw new Error(`ENOENT: no such file or directory, scandir '${r}'`);let s=await i?.handler.getFile({cacheFs:this.memFs,filePath:r,gitRoot:this.gitRoot,nodeFs:this.storageFs,pathParams:i.params,author:await this.getAuthor()});if(s){if(s.type!=="directory")throw new Error("not a folder");let o=i?.staticSiblings??[],l=s.content;return l&&!Array.isArray(s.content)&&(l=JSON.parse(s.content)),Array.from(new Set([...l,...o])).sort((h,c)=>h.localeCompare(c,void 0,{numeric:!0,sensitivity:"base"}))}return[]}async read(e,t,r,i,s){let o=e.subFsFileDescriptor,l=this.openFh[o];if(!l)throw new Error("Invalid file handle");if(l.unflushed.length===0){let h=this.getRouteHandler(l.path),c=await h.handler.getFile({cacheFs:this.memFs,filePath:l.path,gitRoot:this.gitRoot,nodeFs:this.storageFs,pathParams:h?.params,author:await this.getAuthor()});if(!c?.content)throw new Error("couldnt access content");if(c.type!=="file")throw new Error("not a file");let d=typeof c.content=="string"?Buffer.from(c.content):c.content,m=typeof s=="number"?s:0,w=Math.min(m+i,d.length),f=Math.max(0,w-m);return d.copy(t,r,m,m+f),{bytesRead:f,buffer:t}}return await l.fh.read(t,r,i,s)}async write(e,t,r,i,s){let o=this.openFh[e.subFsFileDescriptor];if(!o)throw new Error("Invalid file handle");let l=o.mode;if(!l.includes("w")&&!l.includes("a")&&!l.includes("+"))throw Object.assign(new Error("EBADF: bad file descriptor, write"),{code:"EBADF",errno:-9,syscall:"write"});if(o.unflushed.length===0){let m=this.getRouteHandler(o.path),w=await m.handler.getFile({cacheFs:this.memFs,filePath:o.path,gitRoot:this.gitRoot,nodeFs:this.storageFs,pathParams:m.params,author:await this.getAuthor()});w&&w.oid&&(await this.memFs.promises.writeFile(o.path,w.content),o.readSha=w.oid)}let h=await o.fh.write(t,r,i,s),c=r??0,d=s??0;return o.unflushed.push({start:d,length:i||t.byteLength-c+d}),h}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 i=this.getRouteHandler(r.path);if(i&&i.handler.writeFile){let s=await this.memFs.promises.readFile(r.path);await i.handler.writeFile({cacheFs:this.memFs,filePath:r.path,gitRoot:this.gitRoot,nodeFs:this.storageFs,content:s,pathParams:i.params,author:await this.getAuthor()})}r.unflushed=[]}}async readFile(e,t){let r=typeof e=="string"?e:Buffer.isBuffer(e)?e.toString():e.fd?`FileHandle(${e.fd})`:e.toString(),i=null;typeof t=="string"?i=t:t&&typeof t=="object"&&t.encoding&&(i=t.encoding);let s=await this.open(r,"r");try{let o=(await this.fstat(s)).size,l=Buffer.alloc(o);return await this.read(s,l,0,o,0),await this.close(s),i?l.toString(i):l}catch(o){try{await this.close(s)}catch{}throw o}}async writeFile(e,t,r){let i="w",s="utf8",o;typeof r=="string"?s=r:r&&typeof r=="object"&&(r.flag&&(i=String(r.flag)),r.encoding&&(s=r.encoding),r.mode&&(o=typeof r.mode=="string"?parseInt(r.mode,8):r.mode));let l=await this.open(e,i,o);try{let h;typeof t=="string"?h=Buffer.from(t,s):Buffer.isBuffer(t)?h=t:t instanceof Uint8Array?h=Buffer.from(t):ArrayBuffer.isView(t)?h=Buffer.from(t.buffer,t.byteOffset,t.byteLength):h=Buffer.from(t),await this.write(l,h,0,h.length,0)}finally{await this.close(l)}}async rename(e,t){let r=e.toString(),i=t.toString(),s=this.getRouteHandler(r),o=this.getRouteHandler(i);if(s?.handler.type==="gitBranchFileVirtualFile"&&o?.handler.type==="gitBranchFileVirtualFile"){let l=!0;try{await this.memFs.promises.access(i)}catch{l=!1}let h=!0;try{await this.stat(i)}catch{h=!1}let c=!0;try{await this.stat(r)}catch{c=!1}let d=!0;try{await this.memFs.promises.access(r)}catch{d=!1}if(d){let f=pe.dirname(i);try{await this.memFs.promises.access(f)}catch{await this.memFs.promises.mkdir(f,{recursive:!0})}await this.memFs.promises.rename(e,t)}let m=this.getRouteHandler(r);if(!m)throw new Error("VF not found");let w=await m.handler.rename({cacheFs:this.memFs,filePath:r,gitRoot:this.gitRoot,nodeFs:this.storageFs,newPath:i,pathParams:m?.params??{},newPathParams:o?.params??{},author:await this.getAuthor()})}else throw new Error(`Unsupported rename operation from ${s?.handler.type} to ${o?.handler.type}`)}async fchmod(e,t){}async unlink(e){let t=e.toString(),r=this.getRouteHandler(t);if(r?.handler.unlink!==void 0)try{await r.handler.unlink({cacheFs:this.memFs,filePath:t,nodeFs:this.storageFs,gitRoot:this.gitRoot,pathParams:r.params,author:await this.getAuthor()})}catch(i){let s=!1;for(let[o,l]of Object.entries(this.openFh))l.path===t&&l.unflushed.length>0&&(s=!0);if(!s)throw i}finally{let i=!1;for(let[s,o]of Object.entries(this.openFh))o.path===t&&(i=!0,await o.fh.close(),delete this.openFh[Number(s)]);i&&await this.memFs.promises.unlink(t)}else throw new Error(`Cannot unlink ${r?.handler.type} files`)}async rmdir(e,...t){let r=e.toString(),i=this.getRouteHandler(r);if(i?.handler.rmdir!==void 0){await i.handler.rmdir({cacheFs:this.memFs,filePath:r,nodeFs:this.storageFs,gitRoot:this.gitRoot,pathParams:i.params,author:await this.getAuthor()});let s=!1;for(let[o,l]of Object.entries(this.openFh))l.path===r&&(s=!0,await l.fh.close(),delete this.openFh[Number(o)]);s&&await this.memFs.promises.rmdir(r,{recursive:!0})}else throw new Error(`Cannot rmdir
7
- ${i?.handler.type} directories`)}fileType(){return 10}},g(B,"$"),B);n(ie,"GitSubFs"),u(ie,"LEGIT_DIR",".legit"),u(ie,"pathRouter",new kt({".legit":{".":ue,branches:{".":Ue,"[branchName]":{".legit":{".":ue,operation:Nt,head:Ve,operationHead:Tt,operationHistory:qe,threadName:Bt,history:Ct},"[[...filePath]]":ge}},commits:{".":Re,"[sha_1_1_2]":{".":Re,"[sha1_3__40]":{"[[...filePath]]":We}}}}}));var It=ie,L="legit",Lt=n(({fs:a,gitRepoPath:e,serverUrl:t="https://hub.legitcontrol.com",auth:r,anonymousBranch:i,authHeaderPrefix:s="Bearer "})=>{let o=!1;async function l(y){let v=await r.getMaxAccessTokenForBranch(y);if(!v)throw new Error(`No access token for branch ${y}`);await R.fetch({fs:a,http:me,dir:e,singleBranch:!0,ref:`${y}`,remote:L,url:t,headers:{Authorization:`${s}${v}`}});let p=await R.resolveRef({fs:a,dir:e,ref:`${L}/${y}`});await R.writeRef({fs:a,dir:e,ref:`refs/heads/${y}`,value:p})}g(l,"l"),n(l,"loadBranch");let h=[];async function c(){let y=await r.getMaxAccessTokenForBranch("todo");await R.fetch({fs:a,http:me,dir:e,remote:L,url:t,headers:{Authorization:`${s}${y}`}});let v=await R.listBranches({fs:a,dir:e});for(let p of v){if(p===i)continue;let F=`${L}/${p}`,S,k;try{S=await R.resolveRef({fs:a,dir:e,ref:p})}catch(I){console.log(`Could not resolve local ref ${p}:`,I)}try{k=await R.resolveRef({fs:a,dir:e,ref:F})}catch{k=void 0}if(S&&k){if(S!==k){let I=await R.findMergeBase({fs:a,dir:e,oids:[S,k]});if(I[0]!==S&&I[0]!==k){let ee=await R.merge({fs:a,dir:e,ours:S,theirs:k,fastForwardOnly:!1,abortOnConflict:!1,author:{name:"Your Name",email:"your.email@example.com"},mergeDriver:n(async({branches:te,contents:Z,path:ne})=>{let[Gt,nt,Ee]=Z;return console.log(`Merging ${te[0]} with ${te[1]}...`),console.log("merged:"),console.log(Z),{cleanMerge:!0,mergedText:Ee===void 0?nt:Ee}},"mergeDriver")});await R.writeRef({fs:a,dir:e,ref:`refs/heads/${p}`,value:ee.oid,force:!0})}I[0]===S?(console.log(`branch ${p} differs - remote ahaed, not behind`),await R.writeRef({fs:a,dir:e,ref:`refs/heads/${p}`,value:k,force:!0})):I[0]===k?(console.log(`branch ${p} differs - local ahead, not behind`),h.push(p)):(console.log(`branch ${p} differs - both changed`),h.push(p))}}else S&&!k&&h.push(p)}}g(c,"m"),n(c,"pull");async function d(y){if((await r.getUser()).type!=="local")for(let v of y){let p=await r.getMaxAccessTokenForBranch(v);await R.push({fs:a,http:me,dir:e,remote:L,url:t,ref:v,headers:{Authorization:`Bearer ${p}`}})}}g(d,"c"),n(d,"push");let m=Promise.resolve();async function w(y){m=m.then(()=>d(y)),await m}g(w,"u"),n(w,"sequentialPush");async function f(){await R.getConfig({fs:a,dir:e,path:`remote.${L}.fetch`})||await R.setConfig({fs:a,dir:e,path:`remote.${L}.fetch`,value:`+refs/heads/*:refs/remotes/${L}/*`});try{await c();let y=[...new Set(h)].filter(v=>v.indexOf(i)===-1);await w(y),h=[]}catch(y){console.error("Error monitoring changes:",y)}finally{o&&setTimeout(f,1e3)}}g(f,"f"),n(f,"pullPushTick");function E(){o=!0,f()}g(E,"g"),n(E,"startSync");function D(){o=!1}return g(D,"O"),n(D,"stopSync"),{start:n(()=>{o||(E(),o=!0)},"start"),stop:n(()=>{D()},"stop"),isRunning:n(()=>o,"isRunning"),loadBranch:l,sequentialPush:w}},"createLegitSyncService"),zt=n((a,e)=>{let t={type:"local",id:"local",name:"Local User",email:"local@legitcontrol.com"};return{getUser:n(async()=>t,"getUser"),signInAnonymously:n(async()=>{t.type="anonymous",t.id=crypto.randomUUID(),t.email=`anonymous-sha1-${t.id}-@legitcontrol.com`},"signInAnonymously"),addAccessToken:n(async r=>{let i=await a.getUserTokens(t.id);i.accessTokens.push(r),await a.setUserTokens(t.id,i)},"addAccessToken"),getMaxAccessTokenForBranch:n(async r=>{let i=await a.getUserTokens(t.id);if(!(i.accessTokens===void 0||i.accessTokens.length===0))return i.accessTokens[0]},"getMaxAccessTokenForBranch")}},"createSessionManager");function Qe(a){let e=JSON.stringify(a),t=new TextEncoder().encode(e),r="";return typeof btoa=="function"?r=btoa(String.fromCharCode(...t)):r=Buffer.from(t).toString("base64"),r.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}g(Qe,"Ge");n(Qe,"encodeConfigJson");function et(a){let e=a.replace(/-/g,"+").replace(/_/g,"/")+"===".slice((a.length+3)%4),t;typeof atob=="function"?t=atob(e):t=Buffer.from(e,"base64").toString("binary");let r=Uint8Array.from(t,s=>s.charCodeAt(0)),i=new TextDecoder().decode(r);return JSON.parse(i)}g(et,"Je");n(et,"decodeConfigJson");var $e="user.legit-tokens";function tt({storageFs:a,gitRoot:e}){return{getUserTokens:n(async t=>{let r=await Ne.getConfig({fs:a,dir:e,path:$e});return r?et(r):{accessTokens:[]}},"getUserTokens"),setUserTokens:n(async(t,r)=>await Ne.setConfig({fs:a,dir:e,path:$e,value:Qe(r)}),"setUserTokens")}}g(tt,"Xe");n(tt,"createGitConfigTokenStore");async function ye(a){let e=new xt,t=At(e);return rt({...a,storageFs:a?.storageFs?a.storageFs:t,gitRoot:a?.gitRoot||"/"})}g(ye,"cs");n(ye,"openLegitFsWithMemoryFs");async function rt({storageFs:a,gitRoot:e,anonymousBranch:t="anonymous",showKeepFiles:r=!1,initialAuthor:i={type:"local",id:"local",name:"Local User",email:"local@legitcontrol.com"},serverUrl:s="https://sync.legitcontrol.com",publicKey:o}){await a.promises.readdir(e+"/.git").then(()=>!0).catch(()=>!1)||(await P.init({fs:a,dir:"/",defaultBranch:t}),await a.promises.writeFile(e+"/.keep",""),await P.add({fs:a,dir:"/",filepath:".keep"}),await P.commit({fs:a,dir:"/",message:"Initial commit",author:{name:"Test",email:"test@example.com"}}),await P.setConfig({fs:a,dir:e,path:"init.defaultBranch",value:t})),await P.getConfig({fs:a,dir:e,path:"user.legit_user_id"})||await P.setConfig({fs:a,dir:e,path:"user.legit_user_id",value:i.name}),await P.getConfig({fs:a,dir:e,path:"user.name"})||await P.setConfig({fs:a,dir:e,path:"user.name",value:i.name}),await P.getConfig({fs:a,dir:e,path:"user.email"})||await P.setConfig({fs:a,dir:e,path:"user.email",value:i.email});let l=new Se({name:"root",parentFs:void 0,storageFs:a,gitRoot:e}),h=new Pe({name:"root-ephemeral",parentFs:l,gitRoot:e,ephemeralPatterns:[]}),c=new De({name:"root-hidden",parentFs:l,gitRoot:e,hiddenFiles:[]});l.setHiddenFilesSubFs(c),l.setEphemeralFilesSubFs(h);let d=new Se({name:"git",parentFs:l,storageFs:void 0,gitRoot:e,defaultBranch:t}),m=new It({name:"git-subfs",parentFs:d,gitRoot:e,gitStorageFs:l}),w=r?[".git"]:[".git",".keep"],f=new De({name:"git-hidden-subfs",parentFs:d,gitRoot:e,hiddenFiles:w}),E=new Pe({name:"git-ephemeral-subfs",parentFs:d,gitRoot:e,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","**/**.sb-**"]});d.addSubFs(m),d.setHiddenFilesSubFs(f),d.setEphemeralFilesSubFs(E);let D=tt({storageFs:a,gitRoot:e}),y=zt(D,o),v=Lt({fs:a,gitRepoPath:e,serverUrl:s,auth:y,anonymousBranch:t}),p=Object.assign(d,{auth:y,sync:v,setLogger(F){l.setLoggger(F),d.setLoggger(F)},push:n(async F=>{},"push"),shareCurrentBranch:n(async()=>{if((await y.getUser()).type==="local")throw new Error("login first - for example anonymously using legitfs.auth.signInAnonymously()");let F=await p.getCurrentBranch();return F===t&&(F=(await y.getUser()).id,await P.renameBranch({fs:a,dir:e,oldref:t,ref:F})),await v.sequentialPush([F]),p.setCurrentBranch(F),F},"shareCurrentBranch"),setCurrentBranch:n(async F=>{(await P.listBranches({fs:a,dir:e})).includes(F)||await v?.loadBranch(F);let S=(await P.listBranches({fs:a,dir:e})).includes(F);if(console.log("branchExistsAfter",S),!S)throw new Error(`Branch ${F} does not exist`);await P.setConfig({fs:a,dir:e,path:"init.defaultBranch",value:F})},"setCurrentBranch"),getCurrentBranch:n(async()=>{let F=await P.getConfig({fs:a,dir:e,path:"init.defaultBranch"});if(!F)throw new Error("No current branch set");return F},"getCurrentBranch")});return p}g(rt,"gt");n(rt,"openLegitFs");var Er=n(a=>async e=>{if(!e.path.includes(".legit/branches/")||(e.path.match(/\.legit/g)||[]).length>1)return;let[t,r]=e.path.split(".legit/branches/"),[i,...s]=r.split("/"),o=s.join("/"),l=t+".legit/branches/"+i+"/.legit/operation",h=JSON.stringify(e.operationArgs,(c,d)=>Buffer.isBuffer(d)?{__buffer__:d.toString("base64")}:d);await a.writeFile(l,`[${e.fsName}].${e.operation}(${e.fd?e.fd.fd+" - ":""}${e.path})
3
+ var Ft=Object.defineProperty;var w=(s,e)=>Ft(s,"name",{value:e,configurable:!0});import{createContext as Wt,useContext as Kt,useEffect as mt,useState as he,useRef as Gt}from"react";import*as ue from"path";import*as Ve from"path";import{createFsFromVolume as yt,Volume as bt}from"memfs";import*as Ge from"path";import{createFsFromVolume as St,Volume as Dt}from"memfs";import kt from"ignore";import*as ae from"path";import{createFsFromVolume as Pt,Volume as Rt}from"memfs";import Nt from"ignore";import Oe from"isomorphic-git";import*as Fe from"path";import{createFsFromVolume as $t,Volume as Bt}from"memfs";import Te from"isomorphic-git";import I from"isomorphic-git";import S from"isomorphic-git";import be from"isomorphic-git";import M from"isomorphic-git";import me from"isomorphic-git";import fe from"isomorphic-git";import pe from"isomorphic-git";import B from"isomorphic-git";import xt from"isomorphic-git";import U from"isomorphic-git";import ee from"isomorphic-git";import Le from"isomorphic-git";import L from"isomorphic-git";import $ from"isomorphic-git";import we from"isomorphic-git/http/node";import R from"isomorphic-git";import{createFsFromVolume as Ut,Volume as jt}from"memfs";import ze from"isomorphic-git";var _e=Object.defineProperty,gt=w((s,e,t)=>e in s?_e(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,"ot"),n=w((s,e)=>_e(s,"name",{value:e,configurable:!0}),"n"),F=w((s,e,t)=>gt(s,typeof e!="symbol"?e+"":e,t),"p"),V,He=(V=class{constructor(e,t){F(this,"entries",[]),F(this,"currentIndex",0),F(this,"closed",!1),F(this,"compositFs"),F(this,"dirPath"),F(this,"initialized",!1),this.compositFs=e,this.dirPath=t}async initialize(){if(this.initialized)return;let e=new Set;for(let t of[...this.compositFs.subFilesystems].reverse()){let r=await t.readdir(this.dirPath);for(let i of r)e.add(i)}for(let t of Array.from(e)){let r=this.dirPath+"/"+t;await this.compositFs.hiddenFilesFileSystem?.responsible(r)||this.entries.push({name:t,path:r})}this.initialized=!0}async*[Symbol.asyncIterator](){for(await this.initialize();this.currentIndex<this.entries.length&&!this.closed;){let e=this.entries[this.currentIndex++];try{let t=await this.compositFs.stat(e.path);yield{name:e.name,isFile:n(()=>t.isFile(),"isFile"),isDirectory:n(()=>t.isDirectory(),"isDirectory"),isBlockDevice:n(()=>t.isBlockDevice(),"isBlockDevice"),isCharacterDevice:n(()=>t.isCharacterDevice(),"isCharacterDevice"),isSymbolicLink:n(()=>t.isSymbolicLink(),"isSymbolicLink"),isFIFO:n(()=>t.isFIFO(),"isFIFO"),isSocket:n(()=>t.isSocket(),"isSocket")}}catch(t){console.debug(`Failed to stat ${e.path}:`,t)}}}async read(){if(this.closed)throw new Error("Directory handle is closed");if(await this.initialize(),this.currentIndex>=this.entries.length)return null;let e=this.entries[this.currentIndex++];try{let t=await this.compositFs.stat(e.path);return{name:e.name,isFile:n(()=>t.isFile(),"isFile"),isDirectory:n(()=>t.isDirectory(),"isDirectory"),isBlockDevice:n(()=>t.isBlockDevice(),"isBlockDevice"),isCharacterDevice:n(()=>t.isCharacterDevice(),"isCharacterDevice"),isSymbolicLink:n(()=>t.isSymbolicLink(),"isSymbolicLink"),isFIFO:n(()=>t.isFIFO(),"isFIFO"),isSocket:n(()=>t.isSocket(),"isSocket")}}catch{return this.read()}}async close(){this.closed=!0,this.entries=[]}get path(){return this.dirPath}},w(V,"he"),V);n(He,"CompositeFsDir");var Ue=He,W,je=(W=class{constructor(e){F(this,"delegate"),F(this,"compositeFs"),F(this,"_subFsFileDescriptor"),F(this,"handleType","file"),F(this,"_compositFsFileDescriptor",-1),this.delegate=e.fs,this._subFsFileDescriptor=e.subFsFileDescriptor,this._compositFsFileDescriptor=-1,this.compositeFs=e.compositeFs;let t=this._subFsFileDescriptor}get fsType(){return this.delegate.fileType()}get subFsFileDescriptor(){return this._subFsFileDescriptor}get fd(){return this._compositFsFileDescriptor}realize(e){if(this._compositFsFileDescriptor!==-1)throw new Error("was already realized");this._compositFsFileDescriptor=e}readableWebStream(e){throw new Error("Method not implemented.")}async appendFile(e,t){return await this.compositeFs.logOperationOnFileDescsriptor(this,"appendFile",{data:e,options:t}),await this.delegate.appendFile(this,e,t)}async chmod(e){return await this.compositeFs.logOperationOnFileDescsriptor(this,"chmod",{mode:e}),this.delegate.fchmod(this,e)}async chown(e,t){return await this.compositeFs.logOperationOnFileDescsriptor(this,"chown",{uid:e,gid:t}),this.delegate.fchown(this,e,t)}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(e,t,r,i){return await this.compositeFs.logOperationOnFileDescsriptor(this,"read",{targetBufferLength:e.length,offset:t,length:r,position:i}),await this.delegate.read(this,e,t,r,i)}async readv(e,t){return await this.compositeFs.logOperationOnFileDescsriptor(this,"readv",{buffers:e,position:t}),this.delegate.readv(this,e,t)}async stat(e){return await this.compositeFs.logOperationOnFileDescsriptor(this,"stat",{options:e}),this.delegate.fstat(this,e)}async truncate(e){return await this.compositeFs.logOperationOnFileDescsriptor(this,"truncate",{len:e}),this.delegate.ftruncate(this,e)}async utimes(e,t){return await this.compositeFs.logOperationOnFileDescsriptor(this,"utimes",{atime:e,mtime:t}),this.delegate.futimes(this,e,t)}async write(e,t,r,i){return await this.compositeFs.logOperationOnFileDescsriptor(this,"write",{buffer:e,offset:t,length:r,position:i}),this.delegate.write(this,e,t,r,i)}async writev(e,t){return await this.compositeFs.logOperationOnFileDescsriptor(this,"writev",{buffers:e,position:t}),this.delegate.writev(this,e,t)}async sync(){return await this.compositeFs.logOperationOnFileDescsriptor(this,"sync",{}),this.delegate.dataSync(this)}},w(W,"pe"),W);n(je,"CompositFsFileHandle");var le=je,K,We=(K=class{constructor({name:e,parentFs:t,gitRoot:r}){F(this,"compositFs"),F(this,"gitRoot"),F(this,"name"),this.name=e,this.compositFs=t,this.gitRoot=r}toStr(e){return typeof e=="string"?e:Buffer.isBuffer(e)?e.toString():e&&typeof e=="object"&&"fd"in e?`FileHandle(fd=${e.fd})`:String(e)}async open(e,t,r){throw new Error(`open not implemented for: ${this.toStr(e)}`)}async access(e,t){throw new Error(`access not implemented for: ${this.toStr(e)}`)}async stat(e,t){throw new Error(`lstat not implemented for: ${this.toStr(e)}`)}async lstat(e,t){throw new Error(`lstat not implemented for: ${this.toStr(e)}`)}async opendir(e,t){throw new Error(`opendir not implemented for: ${this.toStr(e)}`)}async link(e,t){throw new Error(`link not implemented for: ${this.toStr(e)}`)}async mkdir(e,t){throw new Error(`mkdir not implemented for: ${this.toStr(e)}`)}async readdir(e,t){throw new Error(`readdir not implemented for: ${this.toStr(e)}`)}async readlink(e,...t){throw new Error(`readlink not implemented for: ${this.toStr(e)}`)}async unlink(e){throw new Error(`unlink not implemented for: ${this.toStr(e)}`)}async rename(e,t){throw new Error(`rename not implemented for: ${this.toStr(e)}`)}async rmdir(e,...t){throw new Error(`rmdir not implemented for: ${this.toStr(e)}`)}async symlink(e,t,r){throw new Error(`symlink not implemented for: ${this.toStr(t)}`)}async lookup(e){throw new Error(`lookup not implemented for: ${this.toStr(e)}`)}resolvePath(e){throw new Error(`resolvePath not implemented for fd: ${e}`)}async close(e){this.compositFs.close(e)}async dataSync(e){throw new Error(`dataSync not implemented for: ${e.subFsFileDescriptor}`)}async read(e,t,r,i,a){throw new Error(`read not implemented for: ${e.subFsFileDescriptor}`)}async appendFile(e,t,r){throw new Error(`appendFile not implemented for: ${e.subFsFileDescriptor}`)}async fchmod(e,t){throw new Error(`fchmod not implemented for: ${e.subFsFileDescriptor}`)}async fchown(e,t,r){throw new Error(`fchown not implemented for: ${e.subFsFileDescriptor}`)}async ftruncate(e,t){throw new Error(`ftruncate not implemented for: ${e.subFsFileDescriptor}`)}async fstat(e,t){throw new Error(`fstat not implemented for: ${e.subFsFileDescriptor}`)}async futimes(e,t,r){throw new Error(`futimes not implemented for: ${e.subFsFileDescriptor}`)}async write(e,t,r,i,a){throw new Error(`write not implemented for: ${e.subFsFileDescriptor}`)}async writev(e,t,r){throw new Error(`writev not implemented for: ${e.subFsFileDescriptor}`)}async readv(e,t,r){throw new Error(`readv not implemented for: ${e.subFsFileDescriptor}`)}async readFile(e,t){throw new Error(`readFile not implemented for: ${this.toStr(e)}`)}async writeFile(e,t,r){throw new Error(`writeFile not implemented for: ${this.toStr(e)}`)}},w(K,"ue"),K);n(We,"BaseCompositeSubFs");var te=We,G,Ke=(G=class extends te{constructor({name:e,parentFs:t,gitRoot:r}){if(super({name:e,parentFs:t,gitRoot:r}),F(this,"openFh",new Map),F(this,"memFs",yt(new bt)),F(this,"targetFs"),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 i=Ve.dirname(e),a=await this.targetFs.promises.open(e,t,r);return this.openFh.set(a.fd,a),new le({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,i,a){let o=this.openFh.get(e.subFsFileDescriptor);if(o)return await o.read(t,r,i,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 i=this.openFh.get(e.subFsFileDescriptor);if(i)return await i.chown(t,r)}async write(e,t,r,i,a){let o=this.openFh.get(e.subFsFileDescriptor);if(o)return await o.write(t,r,i,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 i=this.openFh.get(e.subFsFileDescriptor);if(i)return await i.utimes(t,r)}async writev(e,t,r){let i=this.openFh.get(e.subFsFileDescriptor);if(i)return await i.writev(t,r??void 0);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async readv(e,t,r){let i=this.openFh.get(e.subFsFileDescriptor);if(i)return await i.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 i=typeof r=="object"&&r.flag?r.flag:"w",a=await this.targetFs.open(e,i);try{let o;if(typeof t=="string"){let l=typeof r=="object"&&r.encoding?r.encoding:"utf8";o=Buffer.from(t,l)}else Buffer.isBuffer(t)?o=t:o=Buffer.from(t);await a.write(o,0,o.length,0)}finally{await this.targetFs.close(a)}}},w(G,"Fe"),G);n(Ke,"PassThroughSubFs");var vt=Ke,J,Je=(J=class extends te{constructor({name:e,parentFs:t,gitRoot:r,passThroughFs:i}){super({name:e,parentFs:t,gitRoot:r}),F(this,"openFh",new Map),F(this,"memFs",St(new Dt)),F(this,"targetFs"),this.compositFs=t,this.gitRoot=r,this.targetFs=i}async responsible(e){return!0}fileType(){return 4}async open(e,t,r){let i=Ge.dirname(e),a=await this.targetFs.promises.open(e,t,r);return this.openFh.set(a.fd,a),new le({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 Ue(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,i,a){let o=this.openFh.get(e.subFsFileDescriptor);if(o)return await o.read(t,r,i,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 i=this.openFh.get(e.subFsFileDescriptor);if(i)return await i.chown(t,r)}async write(e,t,r,i,a){let o=this.openFh.get(e.subFsFileDescriptor);if(o)return await o.write(t,r,i,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 i=this.openFh.get(e.subFsFileDescriptor);if(i)return await i.utimes(t,r)}async writev(e,t,r){let i=this.openFh.get(e.subFsFileDescriptor);if(i)return await i.writev(t,r??void 0);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async readv(e,t,r){let i=this.openFh.get(e.subFsFileDescriptor);if(i)return await i.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)}},w(J,"ge"),J);n(Je,"PassThroughToAsyncFsSubFs");var Et=Je,q,qe=(q=class{constructor({name:e,parentFs:t,storageFs:r,gitRoot:i,defaultBranch:a="main"}){if(F(this,"promises"),F(this,"gitRoot"),F(this,"ephemeralFilesFileSystem"),F(this,"hiddenFilesFileSystem"),F(this,"passThroughFileSystem"),F(this,"subFilesystems",[]),F(this,"parentFs"),F(this,"name"),F(this,"defaultBranch"),F(this,"pathToFileDescriptors",new Map),F(this,"openFileHandles",new Map),F(this,"logOperation"),this.name=e,this.parentFs=t,this.gitRoot=i,this.defaultBranch=a,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)},!t&&r){this.passThroughFileSystem=new Et({name:e+"-passthrough",passThroughFs:r,gitRoot:i,parentFs:this});return}if(!r&&t){this.passThroughFileSystem=new vt({name:e+"-passthrough",parentFs:this,gitRoot:i});return}throw new Error("invalid configuration")}getNextFileDescriptor(){let e=Array.from(this.openFileHandles.keys());return e.length===0?1:Math.max(...e)+1}setLoggger(e){this.logOperation=e}async logOperationOnFileDescsriptor(e,t,r){if(!this.logOperation)return;let i=[];for(let[a,o]of this.pathToFileDescriptors.entries())o.includes(e.fd)&&i.push(a);if(i.length!==0)return this.logOperation?.({fsName:e.delegate.name,fd:e,path:i[0],operation:t,operationArgs:r})}getFilehandle(e){return this.openFileHandles.get(e)}setEphemeralFilesSubFs(e){this.ephemeralFilesFileSystem=e}setHiddenFilesSubFs(e){this.hiddenFilesFileSystem=e}addSubFs(e){this.subFilesystems.push(e)}async getResponsibleFs(e){if(!e.toString().startsWith(this.gitRoot)&&this.gitRoot!=="./")throw new Error("tried to access a file ("+e+") 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(e.toString()))return this.hiddenFilesFileSystem;if(await this.ephemeralFilesFileSystem.responsible(e.toString()))return this.ephemeralFilesFileSystem;for(let t of this.subFilesystems)if(await t.responsible(e.toString()))return t;return this.passThroughFileSystem}async access(e,t){let r=await this.getResponsibleFs(e);return await this.logOperation?.({fsName:r.name,path:e,operation:"access",operationArgs:{mode:t}}),r.access(e,t)}async opendir(e,t){await this.logOperation?.({fsName:this.name,path:e.toString(),operation:"opendir",operationArgs:{options:t}});let r=e.toString();if(!r.startsWith(this.gitRoot))throw new Error("tried to access a directory ("+r+") outside of the legit folder: "+this.gitRoot);return new Ue(this,r)}async mkdir(e,t){let r=await this.getResponsibleFs(e);return await this.logOperation?.({fsName:r.name,path:e.toString(),operation:"mkdir",operationArgs:{options:t}}),r.mkdir(e,t)}async readdir(e,t){await this.logOperation?.({fsName:this.name,path:e.toString(),operation:"readdir",operationArgs:{options:t}});let r=new Set;for(let i of[...this.subFilesystems].reverse()){let a=await i.readdir(e,t);for(let o of a)await this.ephemeralFilesFileSystem?.responsible((e=="/"?"":e)+"/"+o)||r.add(o)}try{let i=await this.passThroughFileSystem.readdir(e,t);for(let a of i)await this.ephemeralFilesFileSystem?.responsible((e=="/"?"":e)+"/"+a)||r.add(a)}catch(i){if(i.code!=="ENOENT")throw new Error("error reading ephemeral fs: "+i)}try{let i=await this.ephemeralFilesFileSystem.readdir(e,t);for(let a of i)r.add(a)}catch(i){if(i.code!=="ENOENT")throw new Error("error reading ephemeral fs: "+i)}for(let i of r){let a=(e=="/"?"":e)+"/"+i;await this.hiddenFilesFileSystem.responsible(a)&&r.delete(i)}return Array.from(r)}async open(e,t,r){let i=await this.getResponsibleFs(e);await this.logOperation?.({fsName:i.name,path:e,operation:"open",operationArgs:{flags:t,mode:r}});let a=await i.open(e,t,r),o=this.getNextFileDescriptor();return a.realize(o),this.openFileHandles.set(o,a),this.pathToFileDescriptors.get(e)||this.pathToFileDescriptors.set(e,[]),this.pathToFileDescriptors.get(e).push(o),a}async close(e){try{await e.delegate.close(e)}catch(t){throw t}finally{for(let[t,r]of this.pathToFileDescriptors.entries()){let i=r.indexOf(e.fd);if(i!==-1){r.splice(i,1),r.length===0&&this.pathToFileDescriptors.delete(t);break}}this.openFileHandles.delete(e.fd)}}async stat(e,t){let r=e.toString(),i=await this.getResponsibleFs(e);return await this.logOperation?.({fsName:i.name,path:r,operation:"stat",operationArgs:{opts:t}}),i.stat(e)}async lstat(e,t){let r=await this.getResponsibleFs(e);return await this.logOperation?.({fsName:r.name,path:e.toString(),operation:"lstat",operationArgs:{opts:t}}),r.lstat(e,t)}async link(e,t){throw new Error("not implemented")}async readlink(e,t){throw new Error("not implemented")}async unlink(e){let t=await this.getResponsibleFs(e);return await this.logOperation?.({fsName:t.name,path:e.toString(),operation:"unlink",operationArgs:{}}),t.unlink(e)}async rename(e,t){if(this.hiddenFilesFileSystem){if(await this.hiddenFilesFileSystem.responsible(ue.basename(e.toString())))throw new Error("Renaming of hidden Files is not allowed "+e);if(await this.hiddenFilesFileSystem.responsible(ue.basename(t.toString())))throw new Error("Renaming to hidden Files is not allowed "+t)}let r=await this.getResponsibleFs(e),i=await this.getResponsibleFs(t);if(r===i)return await this.logOperation?.({fsName:r.name,path:e.toString(),operation:"rename",operationArgs:{oldPath:e,newPath:t}}),r.rename(e,t);let a=await r.open(e.toString(),"r");try{let o=await r.fstat(a),l=Buffer.alloc(o.size);await r.read(a,l,0,o.size,0),await r.close(a),await i.writeFile(t.toString(),l,"utf8"),await r.unlink(e)}catch(o){try{await r.close(a)}catch{}throw o}}async rmdir(e,t){let r=await this.getResponsibleFs(e);return await this.logOperation?.({fsName:r.name,path:e.toString(),operation:"rmdir",operationArgs:{dirPath:e,options:t}}),r.rmdir(e,t)}async symlink(e,t,r){throw new Error("not implemented")}async readFile(e,t){await this.logOperation?.({fsName:this.name,path:e.toString(),operation:"readFile",operationArgs:{path:e,options:t}});let r=!0,i;if(typeof e=="number"){r=!1;let a=this.getFilehandle(e);if(!a)throw new Error("Invalid file descriptor");i=a}else if(typeof e=="string")i=await this.open(e,"r");else throw new Error("only filehandle and path are supported atm");try{let a=(await i.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 o=Buffer.alloc(a),{bytesRead:l}=await i.read(o,0,a,0);if(t&&typeof t.encoding=="string")return o.slice(0,l).toString(t.encoding);if(typeof t=="string"){if(t==="utf8"||t==="utf-8")return o.slice(0,l).toString(t);throw new Error("Unsupported encoding: "+t)}return o.slice(0,l)}finally{i&&r&&await i.close()}}async writeFile(e,t,r){await this.logOperation?.({fsName:this.name,path:e.toString(),operation:"writeFile",operationArgs:{data:t,options:r}});let i=typeof e!="number",a,o,l,h="w";if(typeof r=="string"?o=r:r&&typeof r=="object"&&(o=r.encoding,l=r.mode,h=r.flag||"w"),typeof e=="number"){let c=this.getFilehandle(e);if(!c)throw new Error("Invalid file descriptor");a=c}else if(typeof e=="string")a=await this.open(e,h,l);else throw new Error("only filehandle and path are supported atm");try{let c;if(typeof t=="string")c=Buffer.from(t,o||"utf8");else if(t instanceof Buffer)c=t;else if(t instanceof Uint8Array)c=Buffer.from(t);else throw new Error("Invalid data type for writeFile");let d=0;for(;d<c.length;){let{bytesWritten:m}=await a.write(c,d,c.length-d,d);d+=m}}finally{a&&i&&await a.close()}}},w(q,"ye"),q);n(qe,"CompositeFs");var Ne=qe,X,Xe=(X=class extends te{constructor({name:e,parentFs:t,gitRoot:r,hiddenFiles:i}){super({name:e,parentFs:t,gitRoot:r}),F(this,"ig"),this.ig=kt(),this.ig.add(i)}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,i,a){throw new Error("Access to hidden file is not allowed: readFileHandle: "+e.subFsFileDescriptor)}},w(X,"be"),X);n(Xe,"HiddenFileSubFs");var $e=Xe,Y,Ye=(Y=class extends te{constructor({name:e,parentFs:t,gitRoot:r,ephemeralPatterns:i}){super({name:e,parentFs:t,gitRoot:r}),F(this,"openFh",new Map),F(this,"memFs",Pt(new Rt)),F(this,"ig"),F(this,"patterns"),this.compositFs=t,this.gitRoot=r,this.ig=Nt(),this.ig.add(i),this.patterns=i}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 i=this.normalizePath(e),a=ae.dirname(i);a&&a!=="/"&&a!=="."&&await this.memFs.promises.mkdir(a,{recursive:!0});let o=await this.memFs.promises.open(i,t,r);return this.openFh.set(o.fd,o),new le({fs:this,compositeFs:this.compositFs,subFsFileDescriptor:o.fd,parentFsFileDescriptors:[o.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),i=this.normalizePath(t);return await this.memFs.promises.link(r,i)}async mkdir(e,t){let r=this.normalizePath(e);if(!(typeof t=="object"&&t&&"recursive"in t&&t.recursive)){let i=ae.dirname(r);if(i&&i!=="/"&&i!==".")try{await this.memFs.promises.stat(i)}catch{await this.memFs.promises.mkdir(i,{recursive:!0})}}await this.memFs.promises.mkdir(r,t)}async readdir(e,...t){let r=this.normalizePath(e),i=await this.memFs.promises.readdir(r,...t);return console.log("EPHEMERAL: READDIR: ",i),i}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),i=this.normalizePath(t);return await this.memFs.promises.rename(r,i)}async rmdir(e,t){let r=this.normalizePath(e);return await this.memFs.promises.rmdir(r,t)}async symlink(e,t,r){let i=this.normalizePath(e),a=this.normalizePath(t);return await this.memFs.promises.symlink(i,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,i,a){let o=this.openFh.get(e.subFsFileDescriptor);if(o)return await o.read(t,r,i,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 i=this.openFh.get(e.subFsFileDescriptor);if(i)return await i.chown(t,r)}async write(e,t,r,i,a){let o=this.openFh.get(e.subFsFileDescriptor);if(o)return await o.write(t,r,i,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 i=this.openFh.get(e.subFsFileDescriptor);if(i)return await i.utimes(t,r)}async writev(e,t,r){let i=this.openFh.get(e.subFsFileDescriptor);if(i)return await i.writev(t,r??void 0);throw new Error(`File handle not found: ${e.subFsFileDescriptor}`)}async readv(e,t,r){let i=this.openFh.get(e.subFsFileDescriptor);if(i)return await i.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 i=this.normalizePath(e),a=ae.dirname(i);return a&&a!=="/"&&a!=="."&&await this.memFs.promises.mkdir(a,{recursive:!0}),this.memFs.promises.writeFile(i,t,r)}},w(Y,"ve"),Y);n(Ye,"EphemeralSubFs");var Be=Ye,Ot=new Set([" ","~","^",":","?","*","[","\\"]),Tt=[/^\/|\/$/,/\/\//,/\.$/,/\.lock$/,/^@$/,/@\{/],Ze="\u2002";function ge(s){let e=s.codePointAt(0);return!(e>=0&&e<=31||e===127||Ot.has(s))}w(ge,"xe");n(ge,"isValidChar");function Qe(s){let e="";for(let t of s)t===" "?e+=Ze:ge(t)?e+=t:e+="%"+t.codePointAt(0);for(let t of Tt)if(t.test(e))return Array.from(e).map(r=>ge(r)?r:"%"+r.codePointAt(0)).join("");return e}w(Qe,"Me");n(Qe,"encodeName");function et(s){return s.replace(/%(\d+)/g,(e,t)=>String.fromCodePoint(parseInt(t,10))).replace(new RegExp(Ze,"g")," ")}w(et,"ze");n(et,"decodeName");function oe(s){return s.replace(/\./g,"%2E").replace(/\//g,".")}w(oe,"Q");n(oe,"encodeBranchNameForVfs");function T(s){return s.replace(/\./g,"/").replace(/%2E/g,".")}w(T,"N");n(T,"decodeBranchNameFromVfs");async function P(s,e,t){try{return await I.resolveRef({fs:s,dir:e,ref:`refs/heads/${T(t)}`})}catch{return}}w(P,"D");n(P,"tryResolveRef");async function A({dir:s,fs:e,treeOid:t,deletePathParts:r,addPathParts:i,addObj:a,addKeepIfEmpty:o,deleteKeepIfNotEmpty:l,keepFilename:h=".keep"}){let[c,...d]=i??[],[m,...u]=r??[],f=[];if(t){let{tree:v}=await I.readTree({fs:e,dir:s,oid:t});f=[...v]}if(c===m){let v=c;if(v===void 0)throw new Error("illegal arguement - called with out a path part");if(d.length===0)throw new Error("can not move into it self");if(u.length===0)throw new Error("can not move from it self");let k=f.findIndex(g=>g.path===v),y=(k!==-1?f[k]:void 0)?.oid,b=await A({dir:s,fs:e,treeOid:y,addPathParts:d,deletePathParts:u,addObj:a,addKeepIfEmpty:o,deleteKeepIfNotEmpty:l});if(b===void 0)throw new Error("on the same path we expect an update - respectivly a newly created subTreeOid");let p=!1;if(b!==y){p=!0;let g={mode:"040000",path:v,oid:b,type:"tree"};k!==-1?f[k]=g:f.push(g)}if(t==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 I.writeTree({fs:e,dir:s,tree:f});if(t===void 0)throw new Error("currentOid should be set - since the sub tree didn't exist and ");return t}else{let v=!1,k;if(m){let y=f.findIndex(p=>p.path===m),b=y!==-1?f[y]:void 0;if(b===void 0)throw new Error("Element doesnt exist in tree");if(u.length>0){if(b&&b.type!=="tree")throw new Error("SubPart of the path for the obj to delete is not a tree");let p=await A({dir:s,fs:e,treeOid:b.oid,addPathParts:void 0,deletePathParts:u,addObj:a,addKeepIfEmpty:o,deleteKeepIfNotEmpty:l});if(p===b.oid)throw new Error("in case of a delete we expect a different subtree oid");v=!0,p===void 0?f.splice(y,1):f[y]={mode:"040000",path:m,oid:p,type:"tree"}}else if(v=!0,f.splice(y,1),f.length===0&&o){let p=new Uint8Array(0),g=await I.writeBlob({fs:e,dir:s,blob:p});f.push({mode:"100644",oid:g,path:h,type:"blob"})}k=b}if(c){let y=f.findIndex(p=>p.path===c),b=y!==-1?f[y]:void 0;if(d.length>0){if(b&&b.type!=="tree")throw new Error("SubPart of the path for the obj to add is not a tree");let p=await A({dir:s,fs:e,treeOid:b?.oid,addPathParts:d,deletePathParts:void 0,addObj:a,addKeepIfEmpty:o,deleteKeepIfNotEmpty:l});if(p===void 0)throw new Error("in case we add, we expect an update - respectivly a newly created subTreeOid");if(p!==b?.oid){v=!0;let g={mode:"040000",path:c,oid:p,type:"tree"};if(y!==-1)f[y]=g;else if(f.push(g),l&&f.length>1){let E=f.findIndex(N=>N.path===h);E!==-1&&f.splice(E,1)}}}else{if(v=!0,a){let p={mode:a.type==="tree"?"040000":"100644",path:c,oid:a.oid,type:a.type};if(y!==-1)f[y]=p;else{if(l&&f.length>0){let g=f.findIndex(E=>E.path===h);g!==-1&&f.splice(g,1)}f.push(p)}}if(o&&f.length===0){let p=new Uint8Array(0),g=await I.writeBlob({fs:e,dir:s,blob:p});f.push({mode:"100644",oid:g,path:h,type:"blob"})}}}if(f.length===0)return;if(v)return await I.writeTree({fs:e,dir:s,tree:f});if(t===void 0)throw new Error("currentOid should be set - since the sub tree didn't exist and ");return t}}w(A,"x");n(A,"buildUpdatedTree");async function j({filePath:s,gitRoot:e,nodeFs:t,commitSha:r,pathParams:i}){if(!i.filePath){let a=await I.readTree({fs:t,dir:e,oid:r});return{type:"tree",entries:a.tree.map(o=>H({parent:s,name:o.path,isDir:o.type==="tree"})),oid:a.oid}}return(await I.walk({fs:t,dir:e,trees:[I.TREE({ref:r})],map:n(async(a,[o])=>{if(a===i.filePath&&o){let l=await o.type();if(l==="blob")return{type:"blob",oid:await o.oid()};if(l=="tree"){let h=await I.readTree({fs:t,dir:e,oid:await o.oid()});return{type:"tree",entries:h.tree.map(c=>H({parent:s,name:c.path,isDir:c.type==="tree"})),oid:h.oid}}}},"map")})).find(a=>a!==void 0)}w(j,"_");n(j,"resolveGitObjAtPath");function H(s){return{name:s.name,isFile:n(()=>!s.isDir,"isFile"),isDirectory:n(()=>s.isDir,"isDirectory"),isBlockDevice:n(()=>!0,"isBlockDevice"),isCharacterDevice:n(()=>!1,"isCharacterDevice"),isSymbolicLink:n(()=>!1,"isSymbolicLink"),isFIFO:n(()=>!1,"isFIFO"),isSocket:n(()=>!1,"isSocket"),parentPath:s.parent,path:s.parent}}w(H,"$");n(H,"toDirEntry");var tt={type:"gitBranchesListVirtualFile",rootType:"folder",getStats:n(async({gitRoot:s,nodeFs:e})=>{let t=s+"/.git";try{return await e.stat(t)}catch{throw new Error(`ENOENT: no such file or directory, stat '${t}'`)}},"getStats"),getFile:n(async({gitRoot:s,nodeFs:e,filePath:t})=>{try{let r=await Te.listBranches({fs:e,dir:s}),i=await Promise.all(r.map(async a=>{let o=await Te.resolveRef({fs:e,dir:s,ref:a});return H({parent:t,name:oe(a),isDir:!0})}));return{type:"directory",content:i,mode:493,size:i}}catch(r){throw r}},"getFile"),rename:n(async s=>{throw new Error("not implemented")},"rename"),mkdir:n(async function(s){throw new Error("not implemented")},"mkdir")},_,rt=(_=class extends Error{constructor(e,t){super(e),F(this,"code","ENOENT"),F(this,"path"),this.name="ENOENTError",this.path=t,Object.setPrototypeOf(this,_.prototype)}},w(_,"ne"),_);n(rt,"ENOENTError");var ye=rt;async function D(s,e){try{let t=await be.getConfig({fs:e,dir:s,path:"user.legit-current-branch"});if(t)return oe(t)}catch{}try{let t=await be.getConfig({fs:e,dir:s,path:"init.defaultBranch"});return oe(t)||"main"}catch{return"main"}}w(D,"b");n(D,"getCurrentBranch");async function it(s,e,t){await be.setConfig({fs:e,dir:s,path:"user.legit-current-branch",value:T(t)})}w(it,"We");n(it,"setCurrentBranch");var ne={type:"gitBranchFileVirtualFile",rootType:"folder",getStats:n(async({gitRoot:s,nodeFs:e,filePath:t,cacheFs:r,pathParams:i})=>{i.branchName===void 0&&(i.branchName=await D(s,e));let a=await P(e,s,i.branchName);if(!a)throw new ye(`ENOENT: no such file or directory, stat '${t}'`,t);let o=await j({filePath:t,gitRoot:s,nodeFs:e,commitSha:a,pathParams:i});if(!o)throw new ye(`ENOENT: no such file or directory, stat '${t}'`,t);let l=await S.readCommit({fs:e,dir:s,oid:a}),{commit:h}=l,c=await S.log({fs:e,dir:s,ref:a,filepath:i.filePath,depth:1}),d=h.committer.timestamp*1e3,m=c.length>0?c[0].commit.committer.timestamp*1e3:d;if(o.type==="tree")return{mode:420,size:0,isFile:n(()=>!0,"isFile"),isDirectory:n(()=>!0,"isDirectory"),isSymbolicLink:n(()=>!1,"isSymbolicLink"),isBlockDevice:n(()=>!1,"isBlockDevice"),isCharacterDevice:n(()=>!1,"isCharacterDevice"),isSocket:n(()=>!1,"isSocket"),isFIFO:n(()=>!1,"isFIFO"),isFileSync:n(()=>!0,"isFileSync"),isDirectorySync:n(()=>!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:d,atime:new Date(m),mtime:new Date(m),ctime:new Date(m),birthtime:new Date(m)};{let{blob:u}=await S.readBlob({fs:e,dir:s,oid:o.oid});return{mode:420,size:u.length,isFile:n(()=>!0,"isFile"),isDirectory:n(()=>!1,"isDirectory"),isSymbolicLink:n(()=>!1,"isSymbolicLink"),isBlockDevice:n(()=>!1,"isBlockDevice"),isCharacterDevice:n(()=>!1,"isCharacterDevice"),isSocket:n(()=>!1,"isSocket"),isFIFO:n(()=>!1,"isFIFO"),isFileSync:n(()=>!0,"isFileSync"),isDirectorySync:n(()=>!1,"isDirectorySync"),dev:0,ino:0,nlink:1,uid:0,gid:0,rdev:0,blksize:4096,blocks:Math.ceil(u.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:n(async({filePath:s,gitRoot:e,nodeFs:t,cacheFs:r,pathParams:i})=>{i.branchName===void 0&&(i.branchName=await D(e,t));try{let a=await P(t,e,i.branchName);if(!a){let l=await S.resolveRef({fs:t,dir:e,ref:"HEAD"});await S.branch({fs:t,dir:e,ref:i.branchName,object:l}),a=await S.resolveRef({fs:t,ref:`refs/heads/${i.branchName}`,dir:e})}let o=await j({filePath:s,gitRoot:e,nodeFs:t,commitSha:a,pathParams:i});if(!o)return;if(o.type==="blob"){let{blob:l}=await S.readBlob({fs:t,dir:e,oid:o.oid});return{type:"file",content:Buffer.from(l),mode:420,size:l.length,oid:o.oid}}else{let l=[];try{let h=await r.promises.stat(s);if(h&&h.isDirectory()){let c=await r.promises.readdir(s,{withFileTypes:!0});l.push(...c)}}catch{}return{type:"directory",content:Array.from(new Set([...l,...o.entries])).map(h=>({...h,name:h.name.toString(),path:`${s}`,parentPath:`${s}`})),mode:493}}}catch{return}},"getFile"),unlink:n(async({filePath:s,gitRoot:e,nodeFs:t,cacheFs:r,pathParams:i,author:a})=>{if(i.branchName===void 0&&(i.branchName=await D(e,t)),!i.filePath)throw new Error("filePath should be in pathParams");let o=await P(t,e,i.branchName);if(!o)throw new Error("Invalid branch file path - branch must exist");let l=await S.readTree({fs:t,dir:e,oid:o}),h=await A({dir:e,fs:t,treeOid:l.oid,deletePathParts:i.filePath.split("/"),addPathParts:void 0,addObj:void 0,deleteKeepIfNotEmpty:!1,addKeepIfEmpty:!0,keepFilename:".keep"});if(h!==l.oid){let c=await S.commit({fs:t,dir:e,message:`Delete ${i.filePath}`,tree:h,noUpdateBranch:!0,parent:[o],author:a});await S.writeRef({fs:t,dir:e,ref:`refs/heads/${T(i.branchName)}`,value:c,force:!0})}},"unlink"),writeFile:n(async({filePath:s,gitRoot:e,nodeFs:t,content:r,cacheFs:i,pathParams:a,author:o})=>{if(a.branchName===void 0&&(a.branchName=await D(e,t)),a.filePath===void 0)throw new Error("filePath should be in pathParams");let l;typeof r=="string"?l=new TextEncoder().encode(r):l=new Uint8Array(r);let h=await S.writeBlob({fs:t,dir:e,blob:l}),c=await P(t,e,a.branchName);if(!c){let u=await S.resolveRef({fs:t,dir:e,ref:"HEAD"});if(await S.branch({fs:t,dir:e,ref:T(a.branchName),object:u}),c=await P(t,e,a.branchName),!c)throw new Error("Could not create branch for writeFile")}let d=await S.readTree({fs:t,dir:e,oid:c}),m=await A({dir:e,fs:t,treeOid:d.oid,deletePathParts:void 0,addPathParts:a.filePath.split("/"),addObj:{type:"blob",oid:h},deleteKeepIfNotEmpty:!0,addKeepIfEmpty:!1,keepFilename:".keep"});if(m!==d.oid){let u=await S.commit({fs:t,dir:e,message:`\u{1F4BE} Change '${a.filePath}'`,tree:m,noUpdateBranch:!0,parent:[c],author:o});await S.writeRef({fs:t,dir:e,ref:`refs/heads/${T(a.branchName)}`,value:u,force:!0})}},"writeFile"),rename:n(async function({filePath:s,newPath:e,gitRoot:t,nodeFs:r,pathParams:i,newPathParams:a,author:o}){if(i.branchName===void 0&&(i.branchName=await D(t,r)),i.filePath===void 0)throw new Error("filePath should be in pathParams");if(a.branchName===void 0&&(a.branchName=await D(t,r)),a.filePath===void 0)throw new Error("filePath should be in newPathParams");let l=await P(r,t,i.branchName);if(!l)throw new Error("Invalid branch file path - source branch must exist");let h=await P(r,t,a.branchName);if(!h){let u=await S.resolveRef({fs:r,dir:t,ref:"HEAD"});if(await S.branch({fs:r,dir:t,ref:T(a.branchName),object:u}),h=await P(r,t,a.branchName),h===void 0)throw new Error("Could not create branch for rename operation")}if(a.branchName!==i.branchName)throw new Error("cross branch move not implemented yet");let c=await j({gitRoot:t,nodeFs:r,commitSha:l,filePath:s,pathParams:i});if(c===void 0)throw new Error("no obj at path exists");let d=await A({dir:t,fs:r,deletePathParts:i.filePath.split("/"),addPathParts:a.filePath.split("/"),addObj:c.type==="blob"?{type:"blob",oid:c.oid}:{type:"tree",oid:c.oid,entries:c.entries.map(u=>u.name.toString())},treeOid:h,addKeepIfEmpty:!0,deleteKeepIfNotEmpty:!0}),m=await S.readTree({fs:r,dir:t,oid:l});if(d!==m.oid){let u=await S.commit({fs:r,dir:t,message:`\u{1F500} Rename '${i.filePath}' to '${a.filePath}'`,tree:d,noUpdateBranch:!0,parent:[h],author:o});await S.writeRef({fs:r,dir:t,ref:`refs/heads/${T(a.branchName)}`,value:u,force:!0})}},"rename"),mkdir:n(async function(s){if(s.pathParams.branchName===void 0&&(s.pathParams.branchName=await D(s.gitRoot,s.nodeFs)),s.pathParams.filePath===void 0)throw new Error("filePath should be in pathParams");try{throw await ne.getStats(s),new Error("Folder exists")}catch{}s.filePath.endsWith("/")&&(s.filePath=s.filePath.replace(/\/+$/,"")),s.pathParams&&typeof s.pathParams.filePath=="string"&&(s.pathParams.filePath=s.pathParams.filePath.replace(/\/+$/,""));let e=await P(s.nodeFs,s.gitRoot,s.pathParams.branchName);if(!e){let o=await S.resolveRef({fs:s.nodeFs,dir:s.gitRoot,ref:"HEAD"});if(await S.branch({fs:s.nodeFs,dir:s.gitRoot,ref:T(s.pathParams.branchName),object:o}),e=await P(s.nodeFs,s.gitRoot,s.pathParams.branchName),e===void 0)throw new Error("Could not create branch for mkdir operation")}let t=await S.readTree({fs:s.nodeFs,dir:s.gitRoot,oid:e}),r=new Uint8Array(0),i=await S.writeBlob({fs:s.nodeFs,dir:s.gitRoot,blob:r}),a=await A({dir:s.gitRoot,fs:s.nodeFs,treeOid:t.oid,deletePathParts:void 0,addPathParts:[...s.pathParams.filePath.split("/"),".keep"],addObj:{type:"blob",oid:i},deleteKeepIfNotEmpty:!0,addKeepIfEmpty:!0,keepFilename:".keep"});if(a!==t.oid){let o=await S.commit({fs:s.nodeFs,dir:s.gitRoot,message:`\u{1F4BE} Change '${s.pathParams.filePath}'`,tree:a,noUpdateBranch:!0,parent:[e],author:s.author});await S.writeRef({fs:s.nodeFs,dir:s.gitRoot,ref:`refs/heads/${T(s.pathParams.branchName)}`,value:o,force:!0})}},"mkdir"),rmdir:n(async({filePath:s,gitRoot:e,nodeFs:t,cacheFs:r,pathParams:i,author:a})=>{if(i.branchName===void 0&&(i.branchName=await D(e,t)),!i.filePath)throw new Error("filePath should be in pathParams");let o=await P(t,e,i.branchName);if(!o)throw new Error("Invalid branch file path - branch must exist");let l=await S.readTree({fs:t,dir:e,oid:o}),h=await A({dir:e,fs:t,treeOid:l.oid,deletePathParts:i.filePath.split("/"),addPathParts:void 0,addObj:void 0,deleteKeepIfNotEmpty:!1,addKeepIfEmpty:!0,keepFilename:".keep"});if(h!==l.oid){let c=await S.commit({fs:t,dir:e,message:`Delete ${i.filePath}`,tree:h,noUpdateBranch:!0,parent:[o],author:a});await S.writeRef({fs:t,dir:e,ref:`refs/heads/${T(i.branchName)}`,value:c,force:!0})}},"rmdir")},ve={type:"gitBranchHeadVirtualFile",rootType:"file",getStats:n(async({gitRoot:s,nodeFs:e,pathParams:t})=>{t.branchName===void 0&&(t.branchName=await D(s,e));let r;try{r=await M.resolveRef({fs:e,dir:s,ref:t.branchName})}catch{r=await M.resolveRef({fs:e,dir:s,ref:`refs/heads/${t.branchName}`})}let i=await M.readCommit({fs:e,dir:s,oid:r}),{commit:a}=i,o=a.committer.timestamp*1e3;return{mode:420,size:40,isFile:n(()=>!0,"isFile"),isDirectory:n(()=>!1,"isDirectory"),isSymbolicLink:n(()=>!1,"isSymbolicLink"),isBlockDevice:n(()=>!1,"isBlockDevice"),isCharacterDevice:n(()=>!1,"isCharacterDevice"),isSocket:n(()=>!1,"isSocket"),isFIFO:n(()=>!1,"isFIFO"),isFileSync:n(()=>!0,"isFileSync"),isDirectorySync:n(()=>!1,"isDirectorySync"),dev:0,ino:0,nlink:1,uid:0,gid:0,rdev:0,blksize:4096,blocks:Math.ceil(40/4096),atimeMs:o,mtimeMs:o,ctimeMs:o,birthtimeMs:o,atime:new Date(o),mtime:new Date(o),ctime:new Date(o),birthtime:new Date(o)}},"getStats"),getFile:n(async({gitRoot:s,nodeFs:e,pathParams:t})=>{t.branchName===void 0&&(t.branchName=await D(s,e));try{let r;try{r=await M.resolveRef({fs:e,dir:s,ref:t.branchName})}catch{r=await M.resolveRef({fs:e,dir:s,ref:`refs/heads/${t.branchName}`})}return{type:"file",content:r+`
4
+ `,mode:420,size:r.length}}catch{return}},"getFile"),writeFile:n(async({filePath:s,gitRoot:e,nodeFs:t,content:r,cacheFs:i,pathParams:a})=>{console.log("gitBranchHeadVirtualFile writeFile called",{pathParams:a,content:r}),a.branchName===void 0&&(a.branchName=await D(e,t));let o=r.toString().trim();try{await M.readCommit({fs:t,dir:e,oid:o})}catch{throw new Error(`Commit ${o} does not exist in the repository`)}await M.writeRef({fs:t,dir:e,ref:"refs/heads/"+a.branchName,value:o,force:!0})},"writeFile"),rename(s){throw new Error("not implementsd")},mkdir:n(async function(s){throw new Error("not implemented")},"mkdir")},Ct={type:"gitBranchTipVirtualFile",rootType:"file",getStats:n(async s=>{let e=s.gitRoot+"/.git";try{return await s.nodeFs.stat(e)}catch{throw new Error(`ENOENT: no such file or directory, stat '${e}'`)}},"getStats"),getFile:n(async({filePath:s,gitRoot:e,nodeFs:t,pathParams:r})=>{if(!r.branchName)throw new Error("branchName should be in pathParams");let i=await P(t,e,r.branchName);if(i!==void 0)return{type:"file",content:i+`
5
+ `,mode:420,size:i.length+1}},"getFile"),rename(s){throw new Error("not implementsd")},mkdir:n(async function(s){throw new Error("not implemented")},"mkdir")},at={type:"gitCommitFileVirtualFile",rootType:"file",getStats:n(async({filePath:s,gitRoot:e,nodeFs:t,pathParams:r})=>{if(!r.sha_1_1_2)throw new Error("sha_1_1_2 should be in pathParams");if(!r.sha1_3__40)throw new Error("sha1_3__40 should be in pathParams");let i=r.sha_1_1_2+r.sha1_3__40,a=await j({filePath:s,gitRoot:e,nodeFs:t,commitSha:i,pathParams:r});if(!a)throw new ye(`ENOENT: no such file or directory, stat '${s}'`,s);let o=await me.readCommit({fs:t,dir:e,oid:i}),{commit:l}=o,h=l.committer.timestamp*1e3;if(a.type==="tree")return{mode:420,size:0,isFile:n(()=>!0,"isFile"),isDirectory:n(()=>!0,"isDirectory"),isSymbolicLink:n(()=>!1,"isSymbolicLink"),isBlockDevice:n(()=>!1,"isBlockDevice"),isCharacterDevice:n(()=>!1,"isCharacterDevice"),isSocket:n(()=>!1,"isSocket"),isFIFO:n(()=>!1,"isFIFO"),isFileSync:n(()=>!0,"isFileSync"),isDirectorySync:n(()=>!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:h,atime:new Date(h),mtime:new Date(h),ctime:new Date(h),birthtime:new Date(h)};{let{blob:c}=await me.readBlob({fs:t,dir:e,oid:a.oid});return{mode:420,size:c.length,isFile:n(()=>!0,"isFile"),isDirectory:n(()=>!1,"isDirectory"),isSymbolicLink:n(()=>!1,"isSymbolicLink"),isBlockDevice:n(()=>!1,"isBlockDevice"),isCharacterDevice:n(()=>!1,"isCharacterDevice"),isSocket:n(()=>!1,"isSocket"),isFIFO:n(()=>!1,"isFIFO"),isFileSync:n(()=>!0,"isFileSync"),isDirectorySync:n(()=>!1,"isDirectorySync"),dev:0,ino:0,nlink:1,uid:0,gid:0,rdev:0,blksize:4096,blocks:Math.ceil(c.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:n(async({filePath:s,gitRoot:e,nodeFs:t,pathParams:r})=>{if(!r.sha_1_1_2)throw new Error("sha_1_1_2 should be in pathParams");if(!r.sha1_3__40)throw new Error("sha1_3__40 should be in pathParams");let i=r.sha_1_1_2+r.sha1_3__40;try{let a=await j({filePath:s,gitRoot:e,nodeFs:t,commitSha:i,pathParams:r});if(!a)return;if(a.type==="blob"){let{blob:o}=await me.readBlob({fs:t,dir:e,oid:a.oid});return{type:"file",content:Buffer.from(o),mode:420,size:o.length,oid:a.oid}}else return{type:"directory",content:Array.from(new Set([...a.entries.filter(o=>o.name!==".keep")])).map(o=>({...o,name:o.name.toString(),path:`${s}`,parentPath:`${s}`})),mode:493}}catch{return}},"getFile"),rename(s){throw new Error("not implementsd")},mkdir:n(async function(s){throw new Error("not implemented")},"mkdir")};function st(s,e,t){return s===0&&e===2&&t===0?"untracked":s===1&&e===0&&t===0?"deleted":s===1&&e===2&&t!==0?"modified":s===0&&e===2&&t===2?"added":"unknown"}w(st,"gt");n(st,"getFileStatus");var It={type:"gitStatusVirtualFile",rootType:"file",getStats:n(async s=>{let e=s.gitRoot+"/.git";try{return await s.nodeFs.stat(e)}catch{throw new Error(`ENOENT: no such file or directory, stat '${e}'`)}},"getStats"),getFile:n(async({gitRoot:s,nodeFs:e})=>{try{let t=await fe.currentBranch({fs:e,dir:s})||"HEAD",r=await fe.resolveRef({fs:e,dir:s,ref:"HEAD"}),i=(await fe.statusMatrix({fs:e,dir:s})).filter(([,o,l,h])=>o!==l||l!==h).map(([o,l,h,c])=>({path:o,status:st(l,h,c)})),a=JSON.stringify({branch:t,commit:r,clean:i.length===0,files:i},null,2);return{type:"file",content:a,mode:33188,size:Buffer.byteLength(a)}}catch(t){throw console.error(t),t}},"getFile"),rename(s){throw new Error("not implementsd")},mkdir:n(async function(s){throw new Error("not implemented")},"mkdir")},Se={type:"legitVirtualFile",rootType:"folder",getStats:n(async({gitRoot:s,nodeFs:e})=>{let t=s+"/.git";try{return await e.stat(t)}catch{throw new Error(`ENOENT: no such file or directory, stat '${t}'`)}},"getStats"),getFile:n(async({gitRoot:s,nodeFs:e})=>{throw new Error("not implemented")},"getFile"),rename(s){throw new Error("not implemented")},mkdir:n(async function(s){throw new Error("not implemented")},"mkdir")},Lt=[Se,It,at,tt,ne,ve,Ct],Z,ot=(Z=class{constructor(e){this.routes=e,F(this,"compiledRoutes");let t={},r=n((i,a)=>{if(typeof i.type=="string"){t[a]={handler:i,siblings:[]};let o=i}else{let o=[];for(let[l,h]of Object.entries(i))if(l==="."){if(t[a])throw new Error(`Conflict: multiple handlers for path '${a}', '.' and optional '[[parameter_name]]' defined?`);t[a]={handler:h,siblings:o}}else if(l.startsWith("[[")&&l.endsWith("]]")){if(t[a])throw new Error(`Conflict: multiple handlers for path '${a}', '.' and optional '[[parameter_name]]' defined?`);t[a]={handler:h,siblings:o},l.startsWith("[[...")?t[a?`${a}/${l}`:l]={handler:h,siblings:[]}:r(h,a?`${a}/${l}`:l)}else l.startsWith("[")&&l.endsWith("]")?l.startsWith("[...")?t[a?`${a}/${l}`:l]={handler:h,siblings:[]}:r(h,a?`${a}/${l}`:l):(o.push({segment:l,type:h["."]?"folder":"file"}),r(h,a?`${a}/${l}`:l))}},"walk");r(e,""),this.compiledRoutes=Object.entries(t).map(([i,a])=>{let o=[],l=i.split("/").map(h=>{if(h.startsWith("[[")&&h.endsWith("]]")){let c=h.slice(2,-2).replace(/^\.\.\./,"");return o.push(c),"(.*)"}if(h.startsWith("[")&&h.endsWith("]")){let c=h.slice(1,-1);return o.push(c),"([^/]+)"}return h.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}).join("/");return{regex:new RegExp(`^${l}$`),paramNames:o,staticSiblings:a.siblings,handler:a.handler}})}match(e){e.length>1&&e.endsWith("/")&&(e=e.replace(/\/+$/,""));for(let{regex:t,paramNames:r,handler:i,staticSiblings:a}of this.compiledRoutes){let o=e.match(t);if(!o)continue;let l={};for(let h=0;h<r.length;h++)l[r[h]]=decodeURIComponent(o[h+1]||"");return{handler:i,params:l,staticSiblings:a}}}},w(Z,"Se"),Z);n(ot,"LegitPathRouter");var At=ot,Ce={type:"gitCommitVirtualFolder",rootType:"folder",getStats:n(async s=>{let e=s.gitRoot+"/.git";try{return await s.nodeFs.stat(e)}catch{throw new Error(`ENOENT: no such file or directory, stat '${e}'`)}},"getStats"),getFile:n(async({filePath:s,gitRoot:e,nodeFs:t,pathParams:r})=>{let i=await pe.listBranches({fs:t,dir:e}),a=new Set,o=new Set;for(let c of i){let d=`refs/heads/${c}`;try{let m=await pe.resolveRef({fs:t,dir:e,ref:d});a.add(m)}catch{}}for(let c of a){let d=await pe.log({fs:t,dir:e,ref:c});for(let m of d)o.add(m.oid)}if(!r.sha_1_1_2){let c=new Set;for(let m of o)if(c.add(m.slice(0,2)),c.size>=256)break;let d=Array.from(c).sort().map(m=>H({parent:s,name:m,isDir:!0}));return{type:"directory",content:d,mode:493,size:d}}let l=new Set;for(let c of o)c.startsWith(r.sha_1_1_2)&&l.add(c.slice(2,40));let h=Array.from(l).sort().map(c=>H({parent:s,name:c,isDir:!0}));return{type:"directory",content:h,mode:493,size:h.length}},"getFile"),rename(s){throw new Error("not implementsd")},mkdir:n(async function(s){throw new Error("not implemented")},"mkdir")},nt="-operation";async function O(s,e,t){return(await xt.listBranches({fs:s,dir:e})).filter(r=>r.endsWith("__"+t+nt))[0]}w(O,"O");n(O,"resolveOperationBranchName");var Ie={type:"gitBranchOperationVirtualFile",rootType:"file",getStats:n(async s=>{let{gitRoot:e,nodeFs:t,pathParams:r}=s;r.branchName===void 0&&(r.branchName=await D(e,t));let i;try{i=await B.resolveRef({fs:t,dir:e,ref:`refs/heads/${r.branchName}`})}catch{throw new Error(`Base Branch ${r.branchName} for operations does not exis`)}let a=await O(t,e,r.branchName),o=!1;if(a)try{i=await B.resolveRef({fs:t,dir:e,ref:a}),o=!0}catch{try{i=await B.resolveRef({fs:t,dir:e,ref:`refs/heads/${a}`}),o=!0}catch{}}let l=await B.readCommit({fs:t,dir:e,oid:i}),{commit:h}=l,c=h.committer.timestamp*1e3;try{return{mode:420,size:40,atimeMs:c,mtimeMs:c,ctimeMs:c,birthtimeMs:c,atime:new Date(c),mtime:new Date(c),ctime:new Date(c),birthtime:new Date(c),isFile:n(()=>!0,"isFile"),isDirectory:n(()=>!1,"isDirectory"),isSymbolicLink:n(()=>!1,"isSymbolicLink"),isBlockDevice:n(()=>!1,"isBlockDevice"),isCharacterDevice:n(()=>!1,"isCharacterDevice"),isSocket:n(()=>!1,"isSocket"),isFIFO:n(()=>!1,"isFIFO"),isFileSync:n(()=>!0,"isFileSync"),isDirectorySync:n(()=>!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:n(async s=>{let{gitRoot:e,nodeFs:t,pathParams:r}=s;r.branchName===void 0&&(r.branchName=await D(e,t));let i=await O(t,e,r.branchName),a,o=!1;return i?(a=await B.resolveRef({fs:t,dir:e,ref:`refs/heads/${i}`}),o=!0):a=await B.resolveRef({fs:t,dir:e,ref:`refs/heads/${r.branchName}`}),{type:"file",content:Buffer.from(a),mode:420,size:a.length}},"getFile"),writeFile:n(async({filePath:s,gitRoot:e,nodeFs:t,content:r,cacheFs:i,pathParams:a,author:o})=>{a.branchName===void 0&&(a.branchName=await D(e,t));let l;typeof r=="string"?l=new TextEncoder().encode(r):l=new Uint8Array(r);let h=await B.writeBlob({fs:t,dir:e,blob:l}),c=await P(t,e,a.branchName);if(!c)throw new Error("Invalid branch file path - branch doesn't exist");let d=await O(t,e,a.branchName),m=!1;d||(d="legit/__"+a.branchName+nt,await B.branch({fs:t,dir:e,ref:d,object:c}),m=!0);let u=await B.resolveRef({fs:t,dir:e,ref:`refs/heads/${d}`}),f=await B.readTree({fs:t,dir:e,oid:c}),v;r instanceof ArrayBuffer?v=Buffer.from(r).toString("utf-8"):typeof r=="string"?v=r:r instanceof Uint8Array?v=Buffer.from(r).toString("utf-8"):v=String(r);let k=!1;if(!m){let b=await B.findMergeBase({fs:t,dir:e,oids:k?[u]:[u,c]});b.length===1&&b[0]===c&&(k=!0)}let y=await B.commit({fs:t,dir:e,message:v,tree:f.oid,noUpdateBranch:!0,author:o,parent:k?m?[c,c]:[u]:[u,c]});await B.writeRef({fs:t,dir:e,ref:`refs/heads/${d}`,value:y,force:!0})},"writeFile"),rename:n(async function({filePath:s,newPath:e,gitRoot:t,nodeFs:r,pathParams:i,newPathParams:a}){throw new Error("not implemented")},"rename"),mkdir:n(async function(s){throw new Error("not implemented")},"mkdir")},De={type:"gitBranchOperationsVirtualFile",rootType:"file",getStats:n(async s=>{let{gitRoot:e,nodeFs:t,pathParams:r}=s;r.branchName===void 0&&(r.branchName=await D(e,t));let i=await O(t,e,r.branchName),a,o=!1;if(i)try{a=await U.resolveRef({fs:t,dir:e,ref:i}),o=!0}catch{try{a=await U.resolveRef({fs:t,dir:e,ref:`refs/heads/${i}`}),o=!0}catch{throw new Error(`Base Branch ${r.branchName} for operations does not exis`)}}else try{a=await U.resolveRef({fs:t,dir:e,ref:`refs/heads/${r.branchName}`})}catch{throw new Error(`Base Branch ${r.branchName} for operations does not exis`)}let l=await U.readCommit({fs:t,dir:e,oid:a}),{commit:h}=l,c=h.committer.timestamp*1e3;try{return{mode:420,size:(o?await De.getFile(s):void 0)?.content?.length??0,atimeMs:c,mtimeMs:c,ctimeMs:c,birthtimeMs:c,atime:new Date(c),mtime:new Date(c),ctime:new Date(c),birthtime:new Date(c),isFile:n(()=>!0,"isFile"),isDirectory:n(()=>!1,"isDirectory"),isSymbolicLink:n(()=>!1,"isSymbolicLink"),isBlockDevice:n(()=>!1,"isBlockDevice"),isCharacterDevice:n(()=>!1,"isCharacterDevice"),isSocket:n(()=>!1,"isSocket"),isFIFO:n(()=>!1,"isFIFO"),isFileSync:n(()=>!0,"isFileSync"),isDirectorySync:n(()=>!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:n(async s=>{let{gitRoot:e,nodeFs:t,pathParams:r}=s;r.branchName===void 0&&(r.branchName=await D(e,t));let i=await O(t,e,r.branchName),a=[];if(i){let h=await U.resolveRef({fs:t,dir:e,ref:`refs/heads/${i}`}),c=!1,d=h;for(;d&&!c;){let m=await U.readCommit({fs:t,dir:e,oid:d});a.push({oid:m.oid,parentOids:m.commit.parent,message:m.commit.message,originBranchOid:"unset"}),d=m.commit.parent&&m.commit.parent.length>0?m.commit.parent[0]:null,m.commit.parent.length===2&&m.commit.parent[0]===m.commit.parent[1]&&(c=!0)}}let o;for(let h=a.length-1;h>=0;h--){let c=a[h];if(o===void 0){if(c.parentOids.length!==2&&c.parentOids[0]!==c.parentOids[1])throw new Error(`Operation commit ${c.oid} does not have two parents as expected`);o=c.parentOids[1]}c.parentOids.length===2&&(o=c.parentOids[1]),c.originBranchOid=o}let l=Buffer.from(JSON.stringify(a,null,2),"utf-8");return{type:"file",content:l,mode:420,size:l.length}},"getFile"),rename:n(async function(s){throw new Error("not implemented")},"rename"),mkdir:n(async function(s){throw new Error("not implemented")},"mkdir")},zt={type:"getThreadName",rootType:"file",getStats:n(async s=>{let{gitRoot:e,nodeFs:t,pathParams:r}=s,i;try{i=await ee.resolveRef({fs:t,dir:e,ref:`refs/heads/${r.branchName}`})}catch{throw new Error(`Base Branch ${r.branchName} for operations does not exis`)}let a=await O(t,e,r.branchName),o=!1;if(a)try{i=await ee.resolveRef({fs:t,dir:e,ref:a}),o=!0}catch{try{i=await ee.resolveRef({fs:t,dir:e,ref:`refs/heads/${a}`}),o=!0}catch{}}let l=await ee.readCommit({fs:t,dir:e,oid:i}),{commit:h}=l,c=h.committer.timestamp*1e3;try{return{mode:420,size:40,atimeMs:c,mtimeMs:c,ctimeMs:c,birthtimeMs:c,atime:new Date(c),mtime:new Date(c),ctime:new Date(c),birthtime:new Date(c),isFile:n(()=>!0,"isFile"),isDirectory:n(()=>!1,"isDirectory"),isSymbolicLink:n(()=>!1,"isSymbolicLink"),isBlockDevice:n(()=>!1,"isBlockDevice"),isCharacterDevice:n(()=>!1,"isCharacterDevice"),isSocket:n(()=>!1,"isSocket"),isFIFO:n(()=>!1,"isFIFO"),isFileSync:n(()=>!0,"isFileSync"),isDirectorySync:n(()=>!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:n(async s=>{let{gitRoot:e,nodeFs:t,pathParams:r}=s,i=await O(t,e,r.branchName),a;if(i){let o="legit/",l=`__${r.branchName}-operation`;return i.startsWith(o)&&i.endsWith(l)?a=i.slice(o.length,i.length-l.length):a=i,{type:"file",content:Buffer.from(et(a)),mode:420,size:a.length}}return{type:"file",content:Buffer.from(""),mode:420,size:0}},"getFile"),writeFile:n(async({filePath:s,gitRoot:e,nodeFs:t,content:r,cacheFs:i,pathParams:a})=>{if(a.branchName===void 0)throw new Error("branchName should be in pathParams");let o=await O(t,e,a.branchName);if(o){let l=`legit/${Qe(r.toString())}__${a.branchName}-operation`;await ee.renameBranch({fs:t,dir:e,oldref:o,ref:l}),o=l}},"writeFile"),rename:n(async function({filePath:s,newPath:e,gitRoot:t,nodeFs:r,pathParams:i,newPathParams:a}){throw new Error("not implemented")},"rename"),mkdir:n(async function(s){throw new Error("not implemented")},"mkdir")},Ae={type:"gitBranchHistory",rootType:"file",getStats:n(async({gitRoot:s,nodeFs:e,pathParams:t})=>{t.branchName===void 0&&(t.branchName=await D(s,e));let r=await P(e,s,t.branchName);if(!r)throw new Error(`Branch ${t.branchName} does not exist`);let i=await Le.readCommit({fs:e,dir:s,oid:r}),{commit:a}=i,o=a.committer.timestamp*1e3;return{mode:420,size:1e5,isFile:n(()=>!0,"isFile"),isDirectory:n(()=>!1,"isDirectory"),isSymbolicLink:n(()=>!1,"isSymbolicLink"),isBlockDevice:n(()=>!1,"isBlockDevice"),isCharacterDevice:n(()=>!1,"isCharacterDevice"),isSocket:n(()=>!1,"isSocket"),isFIFO:n(()=>!1,"isFIFO"),isFileSync:n(()=>!0,"isFileSync"),isDirectorySync:n(()=>!1,"isDirectorySync"),dev:0,ino:0,nlink:1,uid:0,gid:0,rdev:0,blksize:4096,blocks:Math.ceil(40/4096),atimeMs:o,mtimeMs:o,ctimeMs:o,birthtimeMs:o,atime:new Date(o),mtime:new Date(o),ctime:new Date(o),birthtime:new Date(o)}},"getStats"),getFile:n(async s=>{let{gitRoot:e,nodeFs:t,pathParams:r}=s,i=r.branchName;i===void 0&&(i=await D(e,t));let a=[];if(i){let l=await P(t,e,i),h=!1,c=l;for(;c&&!h;){let d=await Le.readCommit({fs:t,dir:e,oid:c});a.push({oid:d.oid,...d.commit}),c=d.commit.parent[0]}}let o=Buffer.from(JSON.stringify(a,null,2),"utf-8");return{type:"file",content:o,mode:420,size:o.length}},"getFile"),rename:n(async s=>{throw new Error("not implemented")},"rename"),mkdir:n(async function(s){throw new Error("not implemented")},"mkdir")},xe={type:"gitBranchOperationHeadVirtualFile",rootType:"file",getStats:n(async({gitRoot:s,nodeFs:e,pathParams:t})=>{t.branchName===void 0&&(t.branchName=await D(s,e));let r=await O(e,s,t.branchName);if(!r){let h=new Date(0);return{mode:420,size:0,isFile:n(()=>!0,"isFile"),isDirectory:n(()=>!1,"isDirectory"),isSymbolicLink:n(()=>!1,"isSymbolicLink"),isBlockDevice:n(()=>!1,"isBlockDevice"),isCharacterDevice:n(()=>!1,"isCharacterDevice"),isSocket:n(()=>!1,"isSocket"),isFIFO:n(()=>!1,"isFIFO"),isFileSync:n(()=>!0,"isFileSync"),isDirectorySync:n(()=>!1,"isDirectorySync"),dev:0,ino:0,nlink:1,uid:0,gid:0,rdev:0,blksize:4096,blocks:Math.ceil(40/4096),atimeMs:h.getTime(),mtimeMs:h.getTime(),ctimeMs:h.getTime(),birthtimeMs:h.getTime(),atime:h,mtime:h,ctime:h,birthtime:h}}let i;try{i=await L.resolveRef({fs:e,dir:s,ref:r})}catch{i=await L.resolveRef({fs:e,dir:s,ref:`refs/heads/${r}`})}let a=await L.readCommit({fs:e,dir:s,oid:i}),{commit:o}=a,l=o.committer.timestamp*1e3;return{mode:420,size:40,isFile:n(()=>!0,"isFile"),isDirectory:n(()=>!1,"isDirectory"),isSymbolicLink:n(()=>!1,"isSymbolicLink"),isBlockDevice:n(()=>!1,"isBlockDevice"),isCharacterDevice:n(()=>!1,"isCharacterDevice"),isSocket:n(()=>!1,"isSocket"),isFIFO:n(()=>!1,"isFIFO"),isFileSync:n(()=>!0,"isFileSync"),isDirectorySync:n(()=>!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:n(async({gitRoot:s,nodeFs:e,pathParams:t})=>{t.branchName===void 0&&(t.branchName=await D(s,e));let r=await O(e,s,t.branchName);if(!r)return{type:"file",content:"",mode:420,size:0};try{let i;try{i=await L.resolveRef({fs:e,dir:s,ref:r})}catch{i=await L.resolveRef({fs:e,dir:s,ref:`refs/heads/${r}`})}return{type:"file",content:i+`
6
+ `,mode:420,size:i.length}}catch{return}},"getFile"),writeFile:n(async({filePath:s,gitRoot:e,nodeFs:t,content:r,cacheFs:i,pathParams:a})=>{a.branchName===void 0&&(a.branchName=await D(e,t));let o=await O(t,e,a.branchName),l=await L.resolveRef({fs:t,dir:e,ref:`refs/heads/${o}`});if(!o)throw new Error(`Operation branch name could not be resolved for branch ${a.branchName}`);let h=r.toString().trim(),c,d,m=!1;if(!l)throw new Error(`Operation branch ref could not be resolved for branch ${o}`);let u=l;for(;u&&!m;){let f=await L.readCommit({fs:t,dir:e,oid:u});if(f.oid===h&&(c=f.oid),u=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])m=!0;else if(c!==void 0){d=f.commit.parent[1];break}}}if(c===void 0)throw new Error(`Cant rollback to ${h} couldn't find newOperationBranchHead ${c}`);if(d===void 0)throw new Error(`Cant rollback to ${h} couldn't find newBranchHead ${d}`);await L.writeRef({fs:t,dir:e,ref:"refs/heads/"+o,value:c,force:!0}),await L.writeRef({fs:t,dir:e,ref:"refs/heads/"+a.branchName,value:d,force:!0})},"writeFile"),rename(s){throw new Error("not implementsd")},mkdir:n(async function(s){throw new Error("not implemented")},"mkdir")},Mt={type:"gitCurrentBranchVirtualFile",rootType:"folder",getStats:n(async({gitRoot:s,nodeFs:e})=>{let t=(await D(s,e)).length;return{mode:420,size:t,isFile:n(()=>!0,"isFile"),isDirectory:n(()=>!1,"isDirectory"),isSymbolicLink:n(()=>!1,"isSymbolicLink"),isBlockDevice:n(()=>!1,"isBlockDevice"),isCharacterDevice:n(()=>!1,"isCharacterDevice"),isSocket:n(()=>!1,"isSocket"),isFIFO:n(()=>!1,"isFIFO"),isFileSync:n(()=>!0,"isFileSync"),isDirectorySync:n(()=>!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:n(async({gitRoot:s,nodeFs:e})=>{let t=await D(s,e);return{type:"file",content:t+`
7
+ `,mode:420,size:t.length+1}},"getFile"),writeFile:n(async({gitRoot:s,nodeFs:e,content:t})=>{let r=t.toString().trim();if(!await P(e,s,r))throw new Error(`Branch ${r} does not exist in the repository`);await it(s,e,r)},"writeFile"),rename(s){throw new Error("not implemented")},mkdir:n(async function(s){throw new Error("not implemented")},"mkdir")},C,se=(C=class extends te{constructor({name:e,parentFs:t,gitStorageFs:r,gitRoot:i,virtualFiles:a=Lt}){super({name:e,parentFs:t,gitRoot:i}),F(this,"memFs"),F(this,"openFh",{}),F(this,"virtualFiles"),F(this,"legitFileNames"),F(this,"storageFs"),this.gitRoot=i,this.storageFs=r,this.memFs=$t(new Bt),this.virtualFiles=a,this.legitFileNames=["branches","commits"]}async getAuthor(){let e=await Oe.getConfig({fs:this.storageFs,dir:this.gitRoot,path:"user.name"}),t=await Oe.getConfig({fs:this.storageFs,dir:this.gitRoot,path:"user.email"}),r=Math.floor(Date.now()/1e3),i=new Date().getTimezoneOffset();return{name:e,email:t,date:r,timezoneOffset:i}}async responsible(e){return!0}isLegitPath(e){return e.includes(`/${C.LEGIT_DIR}/`)||e.includes(`/${C.LEGIT_DIR}`)}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(`/${C.LEGIT_DIR}`);if(r===-1)return C.pathRouter.match(t);let i=t.slice(r+1);return C.pathRouter.match(t)}async open(e,t,r){let i=this.getRouteHandler(e);if(!i)throw new Error("Not a virtual legit file");if(i?.handler.writeFile===void 0&&(t.includes("w")||t.includes("a")))throw new Error(`Write operations not allowed for ${i?.handler.type}`);if(t.includes("x")&&i?.handler.type!=="gitBranchFileVirtualFile")throw new Error(`Exclusive operations not allowed for ${i?.handler.type}`);let a=await i.handler.getFile({cacheFs:this.memFs,filePath:e,gitRoot:this.gitRoot,nodeFs:this.storageFs,pathParams:i.params,author:await this.getAuthor()}),o=!1;for(let m of Object.values(this.openFh))m.path===e&&(o=!0);if((a||o)&&t.includes("x"))throw Object.assign(new Error(`EEXIST: file already exists, open '${e}'`),{code:"EEXIST",errno:-17,syscall:"open",path:e});if(!a&&!o&&!(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 l=Fe.dirname(e);if(await this.memFs.promises.mkdir(l,{recursive:!0}),a===void 0&&!t.includes("x")||a&&a.type==="file")try{let m=await this.memFs.promises.access(e)}catch{await this.memFs.promises.writeFile(e,"")}let h=await this.memFs.promises.open(e,t,r),c=h.fd,d=new le({fs:this,compositeFs:this.compositFs,subFsFileDescriptor:c,parentFsFileDescriptors:[]});return this.openFh[c]={path:e,mode:t,fh:h,openSha:a?.oid,readSha:void 0,unflushed:[]},(t.includes("x")||t.includes("w"))&&this.openFh[c].unflushed.push({length:0,start:0}),d}async mkdir(e,t){let r=e.toString(),i=this.getRouteHandler(r),a=t?{options:t}:{};try{await i?.handler.mkdir({cacheFs:this.memFs,filePath:e.toString(),nodeFs:this.storageFs,gitRoot:this.gitRoot,pathParams:i.params,...a,author:await this.getAuthor()});let o=typeof t=="object"?{...t,recursive:!0}:{recursive:!0};await this.memFs.promises.mkdir(e,o);let l=r.split("/"),h="";for(let c=1;c<=l.length;c++){h=l.slice(0,c).join("/");try{if((await this.memFs.promises.stat(h)).isDirectory()){let d=await this.memFs.promises.open(h,"r");this.openFh[d.fd]={path:h,mode:"r",fh:d,openSha:void 0,readSha:void 0,unflushed:[]}}}catch{}}}catch(o){throw o}}async access(e,t){await this.stat(e)}async futimes(e,t,r){let i=this.openFh[e.subFsFileDescriptor];if(!i)throw new Error("Invalid file handle");return await i.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(),i=Object.values(this.openFh).find(o=>o.path===r&&o.unflushed.length>0);if(i&&i.unflushed.length>0)return await i.fh.stat(t);let a=this.getRouteHandler(r);if(!a)throw new Error(`ENOENT: no such file or directory, stat '${r}'`);return await a.handler.getStats({cacheFs:this.memFs,filePath:r,gitRoot:this.gitRoot,nodeFs:this.storageFs,pathParams:a.params,author:await this.getAuthor()})}async lstat(e,t){return this.stat(e,t)}async readdir(e,t){let r=e.toString(),i=this.getRouteHandler(r);if(!i)throw new Error(`ENOENT: no such file or directory, scandir '${r}'`);let a=await i?.handler.getFile({cacheFs:this.memFs,filePath:r,gitRoot:this.gitRoot,nodeFs:this.storageFs,pathParams:i.params,author:await this.getAuthor()});if(a){if(a.type!=="directory")throw new Error("not a folder");let o=i?.staticSiblings??[],l=Array.from(new Set([...a.content,...o.map(h=>H({name:h.segment,parent:r,isDir:h.type==="folder"}))])).sort((h,c)=>h.name.localeCompare(c.name,void 0,{numeric:!0,sensitivity:"base"}));return t?.withFileTypes?l:l.map(h=>h.name)}return[]}async read(e,t,r,i,a){let o=e.subFsFileDescriptor,l=this.openFh[o];if(!l)throw new Error("Invalid file handle");if(l.unflushed.length===0){let h=this.getRouteHandler(l.path),c=await h.handler.getFile({cacheFs:this.memFs,filePath:l.path,gitRoot:this.gitRoot,nodeFs:this.storageFs,pathParams:h?.params,author:await this.getAuthor()});if(!c?.content)throw new Error("couldnt access content");if(c.type!=="file")throw new Error("not a file");let d=typeof c.content=="string"?Buffer.from(c.content):c.content,m=typeof a=="number"?a:0,u=Math.min(m+i,d.length),f=Math.max(0,u-m);return d.copy(t,r,m,m+f),{bytesRead:f,buffer:t}}return await l.fh.read(t,r,i,a)}async write(e,t,r,i,a){let o=this.openFh[e.subFsFileDescriptor];if(!o)throw new Error("Invalid file handle");let l=o.mode;if(!l.includes("w")&&!l.includes("a")&&!l.includes("+"))throw Object.assign(new Error("EBADF: bad file descriptor, write"),{code:"EBADF",errno:-9,syscall:"write"});if(o.unflushed.length===0){let m=this.getRouteHandler(o.path),u=await m.handler.getFile({cacheFs:this.memFs,filePath:o.path,gitRoot:this.gitRoot,nodeFs:this.storageFs,pathParams:m.params,author:await this.getAuthor()});u&&u.oid&&(await this.memFs.promises.writeFile(o.path,u.content),o.readSha=u.oid)}let h=await o.fh.write(t,r,i,a),c=r??0,d=a??0;return o.unflushed.push({start:d,length:i||t.byteLength-c+d}),h}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 i=this.getRouteHandler(r.path);if(i&&i.handler.writeFile){let a=await this.memFs.promises.readFile(r.path);await i.handler.writeFile({cacheFs:this.memFs,filePath:r.path,gitRoot:this.gitRoot,nodeFs:this.storageFs,content:a,pathParams:i.params,author:await this.getAuthor()})}r.unflushed=[]}}async readFile(e,t){let r=typeof e=="string"?e:Buffer.isBuffer(e)?e.toString():e.fd?`FileHandle(${e.fd})`:e.toString(),i=null;typeof t=="string"?i=t:t&&typeof t=="object"&&t.encoding&&(i=t.encoding);let a=await this.open(r,"r");try{let o=(await this.fstat(a)).size,l=Buffer.alloc(o);return await this.read(a,l,0,o,0),await this.close(a),i?l.toString(i):l}catch(o){try{await this.close(a)}catch{}throw o}}async writeFile(e,t,r){let i="w",a="utf8",o;typeof r=="string"?a=r:r&&typeof r=="object"&&(r.flag&&(i=String(r.flag)),r.encoding&&(a=r.encoding),r.mode&&(o=typeof r.mode=="string"?parseInt(r.mode,8):r.mode));let l=await this.open(e,i,o);try{let h;typeof t=="string"?h=Buffer.from(t,a):Buffer.isBuffer(t)?h=t:t instanceof Uint8Array?h=Buffer.from(t):ArrayBuffer.isView(t)?h=Buffer.from(t.buffer,t.byteOffset,t.byteLength):h=Buffer.from(t),await this.write(l,h,0,h.length,0)}finally{await this.close(l)}}async rename(e,t){let r=e.toString(),i=t.toString(),a=this.getRouteHandler(r),o=this.getRouteHandler(i);if(a?.handler.type==="gitBranchFileVirtualFile"&&o?.handler.type==="gitBranchFileVirtualFile"){let l=!0;try{await this.memFs.promises.access(i)}catch{l=!1}let h=!0;try{await this.stat(i)}catch{h=!1}let c=!0;try{await this.stat(r)}catch{c=!1}let d=!0;try{await this.memFs.promises.access(r)}catch{d=!1}if(d){let f=Fe.dirname(i);try{await this.memFs.promises.access(f)}catch{await this.memFs.promises.mkdir(f,{recursive:!0})}await this.memFs.promises.rename(e,t)}let m=this.getRouteHandler(r);if(!m)throw new Error("VF not found");let u=await m.handler.rename({cacheFs:this.memFs,filePath:r,gitRoot:this.gitRoot,nodeFs:this.storageFs,newPath:i,pathParams:m?.params??{},newPathParams:o?.params??{},author:await this.getAuthor()})}else throw new Error(`Unsupported rename operation from ${a?.handler.type} to ${o?.handler.type}`)}async fchmod(e,t){}async unlink(e){let t=e.toString(),r=this.getRouteHandler(t);if(r?.handler.unlink!==void 0)try{await r.handler.unlink({cacheFs:this.memFs,filePath:t,nodeFs:this.storageFs,gitRoot:this.gitRoot,pathParams:r.params,author:await this.getAuthor()})}catch(i){let a=!1;for(let[o,l]of Object.entries(this.openFh))l.path===t&&l.unflushed.length>0&&(a=!0);if(!a)throw i}finally{let i=!1;for(let[a,o]of Object.entries(this.openFh))o.path===t&&(i=!0,await o.fh.close(),delete this.openFh[Number(a)]);i&&await this.memFs.promises.unlink(t)}else throw new Error(`Cannot unlink ${r?.handler.type} files`)}async rmdir(e,...t){let r=e.toString(),i=this.getRouteHandler(r);if(i?.handler.rmdir!==void 0){await i.handler.rmdir({cacheFs:this.memFs,filePath:r,nodeFs:this.storageFs,gitRoot:this.gitRoot,pathParams:i.params,author:await this.getAuthor()});let a=!1;for(let[o,l]of Object.entries(this.openFh))l.path===r&&(a=!0,await l.fh.close(),delete this.openFh[Number(o)]);a&&await this.memFs.promises.rmdir(r,{recursive:!0})}else throw new Error(`Cannot rmdir
8
+ ${i?.handler.type} directories`)}fileType(){return 10}},w(C,"V"),C);n(se,"GitSubFs"),F(se,"LEGIT_DIR",".legit"),F(se,"pathRouter",new At({".legit":{".":Se,operation:Ie,head:ve,operationHead:xe,operationHistory:De,history:Ae,currentBranch:Mt,branches:{".":tt,"[branchName]":{".legit":{".":Se,operation:Ie,head:ve,operationHead:xe,operationHistory:De,history:Ae,threadName:zt},"[[...filePath]]":ne}},commits:{".":Ce,"[sha_1_1_2]":{".":Ce,"[sha1_3__40]":{"[[...filePath]]":at}}}},"[[...filePath]]":ne}));var _t=se,z="legit",Ht=n(({fs:s,gitRepoPath:e,serverUrl:t="https://hub.legitcontrol.com",auth:r,anonymousBranch:i,authHeaderPrefix:a="Bearer "})=>{let o=!1;async function l(y){let b=await r.getMaxAccessTokenForBranch(y);if(!b)throw new Error(`No access token for branch ${y}`);await $.fetch({fs:s,http:we,dir:e,singleBranch:!0,ref:`${y}`,remote:z,url:t,headers:{Authorization:`${a}${b}`}});let p=await $.resolveRef({fs:s,dir:e,ref:`${z}/${y}`});await $.writeRef({fs:s,dir:e,ref:`refs/heads/${y}`,value:p})}w(l,"l"),n(l,"loadBranch");let h=[];async function c(){let y=await r.getMaxAccessTokenForBranch("todo");await $.fetch({fs:s,http:we,dir:e,remote:z,url:t,headers:{Authorization:`${a}${y}`}});let b=await $.listBranches({fs:s,dir:e});for(let p of b){if(p===i)continue;let g=`${z}/${p}`,E,N;try{E=await $.resolveRef({fs:s,dir:e,ref:p})}catch(x){console.log(`Could not resolve local ref ${p}:`,x)}try{N=await $.resolveRef({fs:s,dir:e,ref:g})}catch{N=void 0}if(E&&N){if(E!==N){let x=await $.findMergeBase({fs:s,dir:e,oids:[E,N]});if(x[0]!==E&&x[0]!==N){let re=await $.merge({fs:s,dir:e,ours:E,theirs:N,fastForwardOnly:!1,abortOnConflict:!1,author:{name:"Your Name",email:"your.email@example.com"},mergeDriver:n(async({branches:ie,contents:Q,path:de})=>{let[er,ut,Re]=Q;return console.log(`Merging ${ie[0]} with ${ie[1]}...`),console.log("merged:"),console.log(Q),{cleanMerge:!0,mergedText:Re===void 0?ut:Re}},"mergeDriver")});await $.writeRef({fs:s,dir:e,ref:`refs/heads/${p}`,value:re.oid,force:!0})}x[0]===E?(console.log(`branch ${p} differs - remote ahaed, not behind`),await $.writeRef({fs:s,dir:e,ref:`refs/heads/${p}`,value:N,force:!0})):x[0]===N?(console.log(`branch ${p} differs - local ahead, not behind`),h.push(p)):(console.log(`branch ${p} differs - both changed`),h.push(p))}}else E&&!N&&h.push(p)}}w(c,"m"),n(c,"pull");async function d(y){if((await r.getUser()).type!=="local")for(let b of y){let p=await r.getMaxAccessTokenForBranch(b);await $.push({fs:s,http:we,dir:e,remote:z,url:t,ref:b,headers:{Authorization:`Bearer ${p}`}})}}w(d,"c"),n(d,"push");let m=Promise.resolve();async function u(y){m=m.then(()=>d(y)),await m}w(u,"u"),n(u,"sequentialPush");async function f(){await $.getConfig({fs:s,dir:e,path:`remote.${z}.fetch`})||await $.setConfig({fs:s,dir:e,path:`remote.${z}.fetch`,value:`+refs/heads/*:refs/remotes/${z}/*`});try{await c();let y=[...new Set(h)].filter(b=>b.indexOf(i)===-1);await u(y),h=[]}catch(y){console.error("Error monitoring changes:",y)}finally{o&&setTimeout(f,1e3)}}w(f,"h"),n(f,"pullPushTick");function v(){o=!0,f()}w(v,"g"),n(v,"startSync");function k(){o=!1}return w(k,"T"),n(k,"stopSync"),{start:n(()=>{o||(v(),o=!0)},"start"),stop:n(()=>{k()},"stop"),isRunning:n(()=>o,"isRunning"),loadBranch:l,sequentialPush:u}},"createLegitSyncService"),Vt=n((s,e)=>{let t={type:"local",id:"local",name:"Local User",email:"local@legitcontrol.com"};return{getUser:n(async()=>t,"getUser"),signInAnonymously:n(async()=>{t.type="anonymous",t.id=crypto.randomUUID(),t.email=`anonymous-sha1-${t.id}-@legitcontrol.com`},"signInAnonymously"),addAccessToken:n(async r=>{let i=await s.getUserTokens(t.id);i.accessTokens.push(r),await s.setUserTokens(t.id,i)},"addAccessToken"),getMaxAccessTokenForBranch:n(async r=>{let i=await s.getUserTokens(t.id);if(!(i.accessTokens===void 0||i.accessTokens.length===0))return i.accessTokens[0]},"getMaxAccessTokenForBranch")}},"createSessionManager");function lt(s){let e=JSON.stringify(s),t=new TextEncoder().encode(e),r="";return typeof btoa=="function"?r=btoa(String.fromCharCode(...t)):r=Buffer.from(t).toString("base64"),r.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}w(lt,"Ze");n(lt,"encodeConfigJson");function ht(s){let e=s.replace(/-/g,"+").replace(/_/g,"/")+"===".slice((s.length+3)%4),t;typeof atob=="function"?t=atob(e):t=Buffer.from(e,"base64").toString("binary");let r=Uint8Array.from(t,a=>a.charCodeAt(0)),i=new TextDecoder().decode(r);return JSON.parse(i)}w(ht,"et");n(ht,"decodeConfigJson");var Me="user.legit-tokens";function ct({storageFs:s,gitRoot:e}){return{getUserTokens:n(async t=>{let r=await ze.getConfig({fs:s,dir:e,path:Me});return r?ht(r):{accessTokens:[]}},"getUserTokens"),setUserTokens:n(async(t,r)=>await ze.setConfig({fs:s,dir:e,path:Me,value:lt(r)}),"setUserTokens")}}w(ct,"rt");n(ct,"createGitConfigTokenStore");async function Ee(s){let e=new jt,t=Ut(e);return dt({...s,storageFs:s?.storageFs?s.storageFs:t,gitRoot:s?.gitRoot||"/"})}w(Ee,"$s");n(Ee,"openLegitFsWithMemoryFs");async function dt({storageFs:s,gitRoot:e,anonymousBranch:t="anonymous",showKeepFiles:r=!1,initialAuthor:i={type:"local",id:"local",name:"Local User",email:"local@legitcontrol.com"},serverUrl:a="https://sync.legitcontrol.com",publicKey:o}){await s.promises.readdir(e+"/.git").then(()=>!0).catch(()=>!1)||(await R.init({fs:s,dir:"/",defaultBranch:t}),await s.promises.writeFile(e+"/.keep",""),await R.add({fs:s,dir:"/",filepath:".keep"}),await R.commit({fs:s,dir:"/",message:"Initial commit",author:{name:"Test",email:"test@example.com"}}),await R.setConfig({fs:s,dir:e,path:"init.defaultBranch",value:t})),await R.getConfig({fs:s,dir:e,path:"user.legit_user_id"})||await R.setConfig({fs:s,dir:e,path:"user.legit_user_id",value:i.name}),await R.getConfig({fs:s,dir:e,path:"user.name"})||await R.setConfig({fs:s,dir:e,path:"user.name",value:i.name}),await R.getConfig({fs:s,dir:e,path:"user.email"})||await R.setConfig({fs:s,dir:e,path:"user.email",value:i.email});let l=new Ne({name:"root",parentFs:void 0,storageFs:s,gitRoot:e}),h=new Be({name:"root-ephemeral",parentFs:l,gitRoot:e,ephemeralPatterns:[]}),c=new $e({name:"root-hidden",parentFs:l,gitRoot:e,hiddenFiles:[]});l.setHiddenFilesSubFs(c),l.setEphemeralFilesSubFs(h);let d=new Ne({name:"git",parentFs:l,storageFs:void 0,gitRoot:e,defaultBranch:t}),m=new _t({name:"git-subfs",parentFs:d,gitRoot:e,gitStorageFs:l}),u=r?[".git"]:[".git",".keep"],f=new $e({name:"git-hidden-subfs",parentFs:d,gitRoot:e,hiddenFiles:u}),v=new Be({name:"git-ephemeral-subfs",parentFs:d,gitRoot:e,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","**/**.sb-**"]});d.addSubFs(m),d.setHiddenFilesSubFs(f),d.setEphemeralFilesSubFs(v);let k=ct({storageFs:s,gitRoot:e}),y=Vt(k,o),b=Ht({fs:s,gitRepoPath:e,serverUrl:a,auth:y,anonymousBranch:t}),p=Object.assign(d,{auth:y,sync:b,setLogger(g){l.setLoggger(g),d.setLoggger(g)},push:n(async g=>{},"push"),shareCurrentBranch:n(async()=>{if((await y.getUser()).type==="local")throw new Error("login first - for example anonymously using legitfs.auth.signInAnonymously()");let g=await p.getCurrentBranch();return g===t&&(g=(await y.getUser()).id,await R.renameBranch({fs:s,dir:e,oldref:t,ref:g})),await b.sequentialPush([g]),p.setCurrentBranch(g),g},"shareCurrentBranch"),setCurrentBranch:n(async g=>{(await R.listBranches({fs:s,dir:e})).includes(g)||await b?.loadBranch(g);let E=(await R.listBranches({fs:s,dir:e})).includes(g);if(console.log("branchExistsAfter",E),!E)throw new Error(`Branch ${g} does not exist`);await R.setConfig({fs:s,dir:e,path:"init.defaultBranch",value:g})},"setCurrentBranch"),getCurrentBranch:n(async()=>{let g=await R.getConfig({fs:s,dir:e,path:"init.defaultBranch"});if(!g)throw new Error("No current branch set");return g},"getCurrentBranch")});return p}w(dt,"kt");n(dt,"openLegitFs");var Nr=n(s=>async e=>{if(!e.path.includes(".legit/branches/")||(e.path.match(/\.legit/g)||[]).length>1)return;let[t,r]=e.path.split(".legit/branches/"),[i,...a]=r.split("/"),o=a.join("/"),l=t+".legit/branches/"+i+"/.legit/operation",h=JSON.stringify(e.operationArgs,(c,d)=>Buffer.isBuffer(d)?{__buffer__:d.toString("base64")}:d);await s.writeFile(l,`[${e.fsName}].${e.operation}(${e.fd?e.fd.fd+" - ":""}${e.path})
8
9
 
9
10
  ${h}
10
11
 
11
- `)},"createFsOperationFileLogger");import{jsx as Wt}from"react/jsx-runtime";var st=Mt({legitFs:null,loading:!0,head:null,rollback:g(async()=>{},"rollback")}),be=g(()=>_t(st),"useLegitContext"),Ut={gitRoot:"/"},jt=100,Vt=g(({children:a,config:e=Ut})=>{let[t,r]=ae(!0),[i,s]=ae(null),o=Ht(null),[l,h]=ae(),[c,d]=ae(null);it(()=>{if(!t)return;g(async()=>{try{let f=await ye({gitRoot:e.gitRoot,serverUrl:e.serverUrl,publicKey:e.publicKey});e.publicKey&&(await f.auth.addAccessToken(e.publicKey),f.sync.start()),f&&s(f)}catch(f){h(f)}},"init")(),r(!1)},[]),it(()=>{if(!i)return;window.legitFs=i;let w=setInterval(async()=>{let f=await i.getCurrentBranch();try{let E=await i.promises.readFile(`/.legit/branches/${f}/.legit/head`,"utf8");E!==o.current&&(o.current=E,d(E))}catch{}},jt);return()=>{clearInterval(w)}},[i]);let m=g(async w=>{if(!i){console.error("No legitFs instance available");return}try{let f=await i.getCurrentBranch();await i.promises.writeFile(`/.legit/branches/${f}/.legit/head`,w,"utf8")}catch(f){h(f)}},"rollback");return Wt(st.Provider,{value:{legitFs:i,loading:i===null,head:c,rollback:m,error:l},children:a})},"LegitProvider");import{useEffect as at,useState as oe,useRef as ve,useCallback as ot,useMemo as Kt}from"react";function Jt(a,e){let{legitFs:t,error:r,head:i}=be(),[s,o]=oe(null),[l,h]=oe([]),[c,d]=oe(!0),[m,w]=oe(),f=ve(null),E=ve(!1),D=ve(!1);at(()=>{if(!t)return;let p=!1;return g(async()=>{d(!0);try{let S=await t.getCurrentBranch(),k=`/.legit/branches/${S}${a}`,I=`/.legit/branches/${S}/.legit/history`,ee=await t.promises.readFile(k,"utf8"),te=await t.promises.readFile(I,"utf8").catch(()=>"");if(p)return;let Z=[],ne=te;ne&&(Z=JSON.parse(ne)),f.current===ee&&(f.current=null),o(ee),h(Z),w(void 0)}catch(S){S?.code!=="ENOENT"?w(S):(o(null),h([]))}finally{p||d(!1)}},"load")(),()=>{p=!0}},[t,a,i]);let y=ot(async p=>{if(t)try{f.current=p;let F=await t.getCurrentBranch();await t.promises.writeFile(`/.legit/branches/${F}${a}`,p,"utf8"),o(p)}catch(F){throw f.current=null,w(F),F}},[t,a]);at(()=>{E.current||D.current||!c&&s===null&&t&&e?.initialData&&(D.current=!0,E.current=!0,g(async()=>{try{await y(e.initialData)}catch(F){console.error("Failed to initialize file:",F),E.current=!1}finally{D.current=!1}},"initialize")())},[c,s,t,e?.initialData,y]);let v=ot(async p=>{if(!t)return"";try{let F=a.startsWith("/")?a.slice(1):a;return await t.promises.readFile(`/.legit/commits/${p.slice(0,2)}/${p.slice(2)}/${F}`,"utf8")}catch{return""}},[t,a]);return{data:s,setData:y,history:Kt(()=>l,[l]),getPastState:v,loading:c,error:m??r,legitFs:t}}g(Jt,"useLegitFile");export{Vt as LegitProvider,be as useLegitContext,Jt as useLegitFile};
12
+ `)},"createFsOperationFileLogger");import{jsx as Yt}from"react/jsx-runtime";var ft=Wt({legitFs:null,loading:!0,head:null,rollback:w(async()=>{},"rollback")}),ke=w(()=>Kt(ft),"useLegitContext"),Jt={gitRoot:"/"},qt=100,Xt=w(({children:s,config:e=Jt})=>{let[t,r]=he(!0),[i,a]=he(null),o=Gt(null),[l,h]=he(),[c,d]=he(null);mt(()=>{if(!t)return;w(async()=>{try{let f=await Ee({gitRoot:e.gitRoot,serverUrl:e.serverUrl,publicKey:e.publicKey});e.publicKey&&(await f.auth.addAccessToken(e.publicKey),f.sync.start()),f&&a(f)}catch(f){h(f)}},"init")(),r(!1)},[]),mt(()=>{if(!i)return;window.legitFs=i;let u=setInterval(async()=>{let f=await i.getCurrentBranch();try{let v=await i.promises.readFile(`/.legit/branches/${f}/.legit/head`,"utf8");v!==o.current&&(o.current=v,d(v))}catch{}},qt);return()=>{clearInterval(u)}},[i]);let m=w(async u=>{if(!i){console.error("No legitFs instance available");return}try{let f=await i.getCurrentBranch();await i.promises.writeFile(`/.legit/branches/${f}/.legit/head`,u,"utf8")}catch(f){h(f)}},"rollback");return Yt(ft.Provider,{value:{legitFs:i,loading:i===null,head:c,rollback:m,error:l},children:s})},"LegitProvider");import{useEffect as pt,useState as ce,useRef as Pe,useCallback as wt,useMemo as Zt}from"react";function Qt(s,e){let{legitFs:t,error:r,head:i}=ke(),[a,o]=ce(null),[l,h]=ce([]),[c,d]=ce(!0),[m,u]=ce(),f=Pe(null),v=Pe(!1),k=Pe(!1);pt(()=>{if(!t)return;let p=!1;return w(async()=>{d(!0);try{let E=await t.getCurrentBranch(),N=`/.legit/branches/${E}${s}`,x=`/.legit/branches/${E}/.legit/history`,re=await t.promises.readFile(N,"utf8"),ie=await t.promises.readFile(x,"utf8").catch(()=>"");if(p)return;let Q=[],de=ie;de&&(Q=JSON.parse(de)),f.current===re&&(f.current=null),o(re),h(Q),u(void 0)}catch(E){E?.code!=="ENOENT"?u(E):(o(null),h([]))}finally{p||d(!1)}},"load")(),()=>{p=!0}},[t,s,i]);let y=wt(async p=>{if(t)try{f.current=p;let g=await t.getCurrentBranch();await t.promises.writeFile(`/.legit/branches/${g}${s}`,p,"utf8"),o(p)}catch(g){throw f.current=null,u(g),g}},[t,s]);pt(()=>{v.current||k.current||!c&&a===null&&t&&e?.initialData&&(k.current=!0,v.current=!0,w(async()=>{try{await y(e.initialData)}catch(g){console.error("Failed to initialize file:",g),v.current=!1}finally{k.current=!1}},"initialize")())},[c,a,t,e?.initialData,y]);let b=wt(async p=>{if(!t)return"";try{let g=s.startsWith("/")?s.slice(1):s;return await t.promises.readFile(`/.legit/commits/${p.slice(0,2)}/${p.slice(2)}/${g}`,"utf8")}catch{return""}},[t,s]);return{data:a,setData:y,history:Zt(()=>l,[l]),getPastState:b,loading:c,error:m??r,legitFs:t}}w(Qt,"useLegitFile");export{Xt as LegitProvider,ke as useLegitContext,Qt as useLegitFile};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@legit-sdk/react",
3
- "version": "0.2.7",
3
+ "version": "0.2.9",
4
4
  "description": "React wrapper for @legit-sdk/core",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -32,8 +32,11 @@
32
32
  "react": ">=18"
33
33
  },
34
34
  "devDependencies": {
35
+ "react": "19.2.0",
36
+ "react-dom": "19.2.0",
35
37
  "@testing-library/react": "^16.3.0",
36
38
  "@types/react": "^18.3.12",
39
+ "@types/react-dom": "^19.2.0",
37
40
  "happy-dom": "^14.12.3",
38
41
  "esbuild": "^0.24.0",
39
42
  "esbuild-plugins-node-modules-polyfill": "^1.7.1",
@@ -43,7 +46,7 @@
43
46
  "vitest": "^3.1.1"
44
47
  },
45
48
  "dependencies": {
46
- "@legit-sdk/core": "0.2.3"
49
+ "@legit-sdk/core": "0.2.4"
47
50
  },
48
51
  "publishConfig": {
49
52
  "access": "public"