just-bash 2.4.1 → 2.4.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,10 @@
1
+ import{a as Z}from"./chunk-UJMN5NLH.js";import{a as ae,b as le,c as oe}from"./chunk-NWEGHOXL.js";import{a as re,b as ie}from"./chunk-74CEPOFO.js";import"./chunk-DXB73IDG.js";function N(e,t){switch(e.type){case"name":{let n=e.pattern,r=n.match(/^\*(\.[a-zA-Z0-9]+)$/);if(r){let s=r[1],o=t.name;if(e.ignoreCase){if(!o.toLowerCase().endsWith(s.toLowerCase()))return{matches:!1,pruned:!1,printed:!1}}else if(!o.endsWith(s))return{matches:!1,pruned:!1,printed:!1};return{matches:!0,pruned:!1,printed:!1}}return{matches:Z(t.name,n,e.ignoreCase),pruned:!1,printed:!1}}case"path":{let n=e.pattern,r=t.relativePath,s=n.split("/");for(let a=0;a<s.length-1;a++){let i=s[a];if(i&&i!=="."&&i!==".."&&!i.includes("*")&&!i.includes("?")&&!i.includes("[")){let c=`/${i}/`;if(e.ignoreCase){if(!r.toLowerCase().includes(c.toLowerCase()))return{matches:!1,pruned:!1,printed:!1}}else if(!r.includes(c))return{matches:!1,pruned:!1,printed:!1}}}let o=n.match(/\*(\.[a-zA-Z0-9]+)$/);if(o){let a=o[1];if(e.ignoreCase){if(!r.toLowerCase().endsWith(a.toLowerCase()))return{matches:!1,pruned:!1,printed:!1}}else if(!r.endsWith(a))return{matches:!1,pruned:!1,printed:!1}}return{matches:Z(r,n,e.ignoreCase),pruned:!1,printed:!1}}case"regex":try{let n=e.ignoreCase?"i":"";return{matches:new RegExp(e.pattern,n).test(t.relativePath),pruned:!1,printed:!1}}catch{return{matches:!1,pruned:!1,printed:!1}}case"type":return e.fileType==="f"?{matches:t.isFile,pruned:!1,printed:!1}:e.fileType==="d"?{matches:t.isDirectory,pruned:!1,printed:!1}:{matches:!1,pruned:!1,printed:!1};case"empty":return{matches:t.isEmpty,pruned:!1,printed:!1};case"mtime":{let r=(Date.now()-t.mtime)/(1e3*60*60*24),s;return e.comparison==="more"?s=r>e.days:e.comparison==="less"?s=r<e.days:s=Math.floor(r)===e.days,{matches:s,pruned:!1,printed:!1}}case"newer":{let n=t.newerRefTimes.get(e.refPath);return n===void 0?{matches:!1,pruned:!1,printed:!1}:{matches:t.mtime>n,pruned:!1,printed:!1}}case"size":{let n=e.value;switch(e.unit){case"c":n=e.value;break;case"k":n=e.value*1024;break;case"M":n=e.value*1024*1024;break;case"G":n=e.value*1024*1024*1024;break;case"b":n=e.value*512;break}let r;return e.comparison==="more"?r=t.size>n:e.comparison==="less"?r=t.size<n:e.unit==="b"?r=Math.ceil(t.size/512)===e.value:r=t.size===n,{matches:r,pruned:!1,printed:!1}}case"perm":{let n=t.mode&511,r=e.mode&511,s;return e.matchType==="exact"?s=n===r:e.matchType==="all"?s=(n&r)===r:s=(n&r)!==0,{matches:s,pruned:!1,printed:!1}}case"prune":return{matches:!0,pruned:!0,printed:!1};case"print":return{matches:!0,pruned:!1,printed:!0};case"not":{let n=N(e.expr,t);return{matches:!n.matches,pruned:n.pruned,printed:!1}}case"and":{let n=N(e.left,t);if(!n.matches)return{matches:!1,pruned:n.pruned,printed:!1};let r=N(e.right,t);return{matches:r.matches,pruned:n.pruned||r.pruned,printed:n.printed||r.printed}}case"or":{let n=N(e.left,t);if(n.matches)return n;let r=N(e.right,t);return{matches:r.matches,pruned:n.pruned||r.pruned,printed:r.printed}}}}function Y(e){if(!e)return!1;switch(e.type){case"name":case"path":case"regex":case"type":case"prune":case"print":return!1;case"empty":case"mtime":case"newer":case"size":case"perm":return!0;case"not":return Y(e.expr);case"and":case"or":return Y(e.left)||Y(e.right)}}function _(e){if(!e)return!1;switch(e.type){case"empty":return!0;case"not":return _(e.expr);case"and":case"or":return _(e.left)||_(e.right);default:return!1}}function ce(e){let t={terminalDirName:null,requiredExtension:null};if(!e)return t;let n=Se(e);if(Ee(e)&&n.length===1){let o=n[0].split("/").filter(a=>a.length>0);if(o.length>=2)for(let a=o.length-2;a>=0;a--){let i=o[a];if(!i.includes("*")&&!i.includes("?")&&!i.includes("[")&&i!=="."&&i!==".."){let c=o[a+1];if(c&&(c.includes("*")||c.includes("?"))){t.terminalDirName=i;let l=c.match(/^\*(\.[a-zA-Z0-9]+)$/);l&&(t.requiredExtension=l[1])}break}}}return t}function Se(e){let t=[],n=r=>{r.type==="path"?t.push(r.pattern):r.type==="not"?n(r.expr):(r.type==="and"||r.type==="or")&&(n(r.left),n(r.right))};return n(e),t}function Ee(e){let t=n=>n.type==="type"&&n.fileType==="f"?!0:n.type==="not"?t(n.expr):n.type==="and"||n.type==="or"?t(n.left)||t(n.right):!1;return t(e)}function pe(e){let t=[],n=r=>{r&&(r.type==="newer"?t.push(r.refPath):r.type==="not"?n(r.expr):(r.type==="and"||r.type==="or")&&(n(r.left),n(r.right)))};return n(e),t}function V(e){if(!e)return!0;switch(e.type){case"name":case"path":case"regex":case"type":case"prune":case"print":return!0;case"empty":case"mtime":case"newer":case"size":case"perm":return!1;case"not":return V(e.expr);case"and":case"or":return V(e.left)&&V(e.right)}}function O(e,t,n,r,s){switch(e.type){case"name":{let o=e.pattern,a=o.match(/^\*(\.[a-zA-Z0-9]+)$/);if(a){let i=a[1];if(e.ignoreCase){if(!t.toLowerCase().endsWith(i.toLowerCase()))return{matches:!1,pruned:!1,printed:!1}}else if(!t.endsWith(i))return{matches:!1,pruned:!1,printed:!1};return{matches:!0,pruned:!1,printed:!1}}return{matches:Z(t,o,e.ignoreCase),pruned:!1,printed:!1}}case"path":{let o=e.pattern,a=o.split("/");for(let c=0;c<a.length-1;c++){let l=a[c];if(l&&l!=="."&&l!==".."&&!l.includes("*")&&!l.includes("?")&&!l.includes("[")){let d=`/${l}/`;if(e.ignoreCase){if(!n.toLowerCase().includes(d.toLowerCase()))return{matches:!1,pruned:!1,printed:!1}}else if(!n.includes(d))return{matches:!1,pruned:!1,printed:!1}}}let i=o.match(/\*(\.[a-zA-Z0-9]+)$/);if(i){let c=i[1];if(e.ignoreCase){if(!n.toLowerCase().endsWith(c.toLowerCase()))return{matches:!1,pruned:!1,printed:!1}}else if(!n.endsWith(c))return{matches:!1,pruned:!1,printed:!1}}return{matches:Z(n,o,e.ignoreCase),pruned:!1,printed:!1}}case"regex":try{let o=e.ignoreCase?"i":"";return{matches:new RegExp(e.pattern,o).test(n),pruned:!1,printed:!1}}catch{return{matches:!1,pruned:!1,printed:!1}}case"type":return e.fileType==="f"?{matches:r,pruned:!1,printed:!1}:e.fileType==="d"?{matches:s,pruned:!1,printed:!1}:{matches:!1,pruned:!1,printed:!1};case"prune":return{matches:!0,pruned:!0,printed:!1};case"print":return{matches:!0,pruned:!1,printed:!0};case"not":{let o=O(e.expr,t,n,r,s);return{matches:!o.matches,pruned:o.pruned,printed:!1}}case"and":{let o=O(e.left,t,n,r,s);if(!o.matches)return{matches:!1,pruned:o.pruned,printed:!1};let a=O(e.right,t,n,r,s);return{matches:a.matches,pruned:o.pruned||a.pruned,printed:o.printed||a.printed}}case"or":{let o=O(e.left,t,n,r,s);if(o.matches)return o;let a=O(e.right,t,n,r,s);return{matches:a.matches,pruned:o.pruned||a.pruned,printed:a.printed}}default:return{matches:!1,pruned:!1,printed:!1}}}function J(e){if(!e)return!1;switch(e.type){case"prune":return!0;case"not":return J(e.expr);case"and":case"or":return J(e.left)||J(e.right);default:return!1}}function z(e){switch(e.type){case"name":case"path":case"regex":case"type":case"prune":case"print":return!0;case"empty":case"mtime":case"newer":case"size":case"perm":return!1;case"not":return z(e.expr);case"and":case"or":return z(e.left)&&z(e.right)}}function fe(e,t){if(!e||!t.isDirectory)return{shouldPrune:!1};if(!z(e))return te(e,t);let n={name:t.name,relativePath:t.relativePath,isFile:t.isFile,isDirectory:t.isDirectory,isEmpty:!1,mtime:0,size:0,mode:0,newerRefTimes:new Map};return{shouldPrune:N(e,n).pruned}}function te(e,t){switch(e.type){case"or":{if(z(e.left)){let n={name:t.name,relativePath:t.relativePath,isFile:t.isFile,isDirectory:t.isDirectory,isEmpty:!1,mtime:0,size:0,mode:0,newerRefTimes:new Map};if(N(e.left,n).pruned)return{shouldPrune:!0}}return te(e.right,t)}case"and":{if(z(e.left)&&z(e.right)){let n={name:t.name,relativePath:t.relativePath,isFile:t.isFile,isDirectory:t.isDirectory,isEmpty:!1,mtime:0,size:0,mode:0,newerRefTimes:new Map};return{shouldPrune:N(e,n).pruned}}if(z(e.left)){let n={name:t.name,relativePath:t.relativePath,isFile:t.isFile,isDirectory:t.isDirectory,isEmpty:!1,mtime:0,size:0,mode:0,newerRefTimes:new Map};return N(e.left,n).matches?te(e.right,t):{shouldPrune:!1}}return{shouldPrune:!1}}case"not":return{shouldPrune:!1};default:return{shouldPrune:!1}}}function ue(e,t){let n=[],r=[],s=t;for(;s<e.length;){let a=e[s];if(a==="("||a==="\\("){n.push({type:"lparen"}),s++;continue}if(a===")"||a==="\\)"){n.push({type:"rparen"}),s++;continue}if(a==="-name"&&s+1<e.length)n.push({type:"expr",expr:{type:"name",pattern:e[++s]}});else if(a==="-iname"&&s+1<e.length)n.push({type:"expr",expr:{type:"name",pattern:e[++s],ignoreCase:!0}});else if(a==="-path"&&s+1<e.length)n.push({type:"expr",expr:{type:"path",pattern:e[++s]}});else if(a==="-ipath"&&s+1<e.length)n.push({type:"expr",expr:{type:"path",pattern:e[++s],ignoreCase:!0}});else if(a==="-regex"&&s+1<e.length)n.push({type:"expr",expr:{type:"regex",pattern:e[++s]}});else if(a==="-iregex"&&s+1<e.length)n.push({type:"expr",expr:{type:"regex",pattern:e[++s],ignoreCase:!0}});else if(a==="-type"&&s+1<e.length){let i=e[++s];if(i==="f"||i==="d")n.push({type:"expr",expr:{type:"type",fileType:i}});else return{expr:null,pathIndex:s,error:`find: Unknown argument to -type: ${i}
2
+ `,actions:[]}}else if(a==="-empty")n.push({type:"expr",expr:{type:"empty"}});else if(a==="-mtime"&&s+1<e.length){let i=e[++s],c="exact",l=i;i.startsWith("+")?(c="more",l=i.slice(1)):i.startsWith("-")&&(c="less",l=i.slice(1));let d=parseInt(l,10);Number.isNaN(d)||n.push({type:"expr",expr:{type:"mtime",days:d,comparison:c}})}else if(a==="-newer"&&s+1<e.length){let i=e[++s];n.push({type:"expr",expr:{type:"newer",refPath:i}})}else if(a==="-size"&&s+1<e.length){let i=e[++s],c="exact",l=i;i.startsWith("+")?(c="more",l=i.slice(1)):i.startsWith("-")&&(c="less",l=i.slice(1));let d=l.match(/^(\d+)([ckMGb])?$/);if(d){let B=parseInt(d[1],10),F=d[2]||"b";n.push({type:"expr",expr:{type:"size",value:B,unit:F,comparison:c}})}}else if(a==="-perm"&&s+1<e.length){let i=e[++s],c="exact",l=i;i.startsWith("-")?(c="all",l=i.slice(1)):i.startsWith("/")&&(c="any",l=i.slice(1));let d=parseInt(l,8);Number.isNaN(d)||n.push({type:"expr",expr:{type:"perm",mode:d,matchType:c}})}else if(a==="-prune")n.push({type:"expr",expr:{type:"prune"}});else if(a==="-not"||a==="!")n.push({type:"not"});else if(a==="-o"||a==="-or")n.push({type:"op",op:"or"});else if(a==="-a"||a==="-and")n.push({type:"op",op:"and"});else if(a==="-maxdepth"||a==="-mindepth")s++;else if(a!=="-depth")if(a==="-exec"){let i=[];for(s++;s<e.length&&e[s]!==";"&&e[s]!=="+";)i.push(e[s]),s++;if(s>=e.length)return{expr:null,pathIndex:s,error:"find: missing argument to `-exec'\n",actions:[]};let c=e[s]==="+";r.push({type:"exec",command:i,batchMode:c})}else if(a==="-print")n.push({type:"expr",expr:{type:"print"}}),r.push({type:"print"});else if(a==="-print0")r.push({type:"print0"});else if(a==="-printf"&&s+1<e.length){let i=e[++s];r.push({type:"printf",format:i})}else if(a==="-delete")r.push({type:"delete"});else{if(a.startsWith("-"))return{expr:null,pathIndex:s,error:`find: unknown predicate '${a}'
3
+ `,actions:[]};if(n.length===0){s++;continue}break}s++}if(n.length===0)return{expr:null,pathIndex:s,actions:r};let o=be(n);return o.error?{expr:null,pathIndex:s,error:o.error,actions:r}:{expr:o.expr,pathIndex:s,actions:r}}function be(e){let t=0;function n(){let i=r();if(!i)return null;for(;t<e.length;){let c=e[t];if(c.type==="op"&&c.op==="or"){t++;let l=r();if(!l)return i;i={type:"or",left:i,right:l}}else break}return i}function r(){let i=s();if(!i)return null;for(;t<e.length;){let c=e[t];if(c.type==="op"&&c.op==="and"){t++;let l=s();if(!l)return i;i={type:"and",left:i,right:l}}else if(c.type==="expr"||c.type==="not"||c.type==="lparen"){let l=s();if(!l)return i;i={type:"and",left:i,right:l}}else break}return i}function s(){if(t<e.length&&e[t].type==="not"){t++;let i=s();return i?{type:"not",expr:i}:null}return o()}function o(){if(t>=e.length)return null;let i=e[t];if(i.type==="lparen"){t++;let c=n();return t<e.length&&e[t].type==="rparen"&&t++,c}return i.type==="expr"?(t++,i.expr):(i.type==="rparen",null)}return{expr:n()}}var he=500;function Me(){return{readdirCalls:0,readdirTime:0,statCalls:0,statTime:0,evalCalls:0,evalTime:0,nodeCount:0,batchCount:0,batchTime:0,earlyPrunes:0}}function ve(e,t,n){e({category:"find",name:"summary",durationMs:n,details:{readdirCalls:t.readdirCalls,readdirTimeMs:t.readdirTime,statCalls:t.statCalls,statTimeMs:t.statTime,evalCalls:t.evalCalls,evalTimeMs:t.evalTime,nodeCount:t.nodeCount,batchCount:t.batchCount,batchTimeMs:t.batchTime,earlyPrunes:t.earlyPrunes,otherTimeMs:n-t.readdirTime-t.statTime-t.evalTime-t.batchTime}})}var xe={name:"find",summary:"search for files in a directory hierarchy",usage:"find [path...] [expression]",options:["-name PATTERN file name matches shell pattern PATTERN","-iname PATTERN like -name but case insensitive","-path PATTERN file path matches shell pattern PATTERN","-ipath PATTERN like -path but case insensitive","-regex PATTERN file path matches regular expression PATTERN","-iregex PATTERN like -regex but case insensitive","-type TYPE file is of type: f (regular file), d (directory)","-empty file is empty or directory is empty","-mtime N file's data was modified N*24 hours ago","-newer FILE file was modified more recently than FILE","-size N[ckMGb] file uses N units of space (c=bytes, k=KB, M=MB, G=GB, b=512B blocks)","-perm MODE file's permission bits are exactly MODE (octal)","-perm -MODE all permission bits MODE are set","-perm /MODE any permission bits MODE are set","-maxdepth LEVELS descend at most LEVELS directories","-mindepth LEVELS do not apply tests at levels less than LEVELS","-depth process directory contents before directory itself","-prune do not descend into this directory","-not, ! negate the following expression","-a, -and logical AND (default)","-o, -or logical OR","-exec CMD {} ; execute CMD on each file ({} is replaced by filename)","-exec CMD {} + execute CMD with multiple files at once","-print print the full file name (default action)","-print0 print the full file name followed by a null character","-printf FORMAT print FORMAT with directives: %f %h %p %P %s %d %m %M %t","-delete delete found files/directories"," --help display this help and exit"]},Ie=new Set(["-name","-iname","-path","-ipath","-regex","-iregex","-type","-maxdepth","-mindepth","-mtime","-newer","-size","-perm"]),qe={name:"find",async execute(e,t){if(ie(e))return re(xe);let n=[],r=null,s=null,o=!1,a=!1;for(let p=0;p<e.length;p++){let f=e[p];if(f==="-maxdepth"&&p+1<e.length)a=!0,r=parseInt(e[++p],10);else if(f==="-mindepth"&&p+1<e.length)a=!0,s=parseInt(e[++p],10);else if(f==="-depth")a=!0,o=!0;else if(f==="-exec")for(a=!0,p++;p<e.length&&e[p]!==";"&&e[p]!=="+";)p++;else!f.startsWith("-")&&f!==";"&&f!=="+"&&f!=="("&&f!==")"&&f!=="\\("&&f!=="\\)"&&f!=="!"?a||n.push(f):Ie.has(f)?(a=!0,p++):(f.startsWith("-")||f==="("||f==="\\("||f==="!")&&(a=!0)}n.length===0&&n.push(".");let{expr:i,error:c,actions:l}=ue(e,0);if(c)return{stdout:"",stderr:c,exitCode:1};let d=l.some(p=>p.type==="print"),B=l.length===0,F=[],de=l.some(p=>p.type==="printf"),ne=[],q="",G=0,me=pe(i),K=new Map;for(let p of me){let f=t.fs.resolvePath(t.cwd,p);try{let h=await t.fs.stat(f);K.set(p,h.mtime?.getTime()??Date.now())}catch{}}let ye=l.some(p=>{if(p.type!=="printf")return!1;let f=p.format.replace(/%%/g,"");return/%[-+]?[0-9]*\.?[0-9]*(s|m|M|t|T)/.test(f)}),ge=Y(i)||ye,we=_(i),U=ce(i),se=J(i),De=V(i),Te=typeof t.fs.readdirWithFileTypes=="function";for(let p of n){let W=function(u){let R=s===null||u.depth>=s,P=!1;if(R&&i!==null){let S=Date.now(),y;if(De)y=O(i,u.name,u.relativePath,u.isFile,u.isDirectory);else{let m={name:u.name,relativePath:u.relativePath,isFile:u.isFile,isDirectory:u.isDirectory,isEmpty:u.isEmpty,mtime:u.stat?.mtime?.getTime()??Date.now(),size:u.stat?.size??0,mode:u.stat?.mode??420,newerRefTimes:K};y=N(i,m)}R=y.matches,P=d?y.printed:R,h.evalCalls++,h.evalTime+=Date.now()-S}else R&&(P=!0);return P?{print:!0,printfData:de?{path:u.relativePath,name:u.name,size:u.stat?.size??0,mtime:u.stat?.mtime?.getTime()??Date.now(),mode:u.stat?.mode??420,isDirectory:u.isDirectory,depth:u.depth,startingPoint:p}:null}:{print:!1,printfData:null}};var Ne=W;p.length>1&&p.endsWith("/")&&(p=p.slice(0,-1));let f=t.fs.resolvePath(t.cwd,p);try{await t.fs.stat(f)}catch{q+=`find: ${p}: No such file or directory
4
+ `,G=1;continue}let h=Me(),$=Date.now();async function E(u){let{path:b,depth:R,typeInfo:P}=u;if(h.nodeCount++,r!==null&&R>r)return null;let M,S,y;if(P&&!ge)M=P.isFile,S=P.isDirectory;else{try{let L=Date.now();y=await t.fs.stat(b),h.statCalls++,h.statTime+=Date.now()-L}catch{return null}if(!y)return null;M=y.isFile,S=y.isDirectory}let m;b===f?m=p.split("/").pop()||p:m=b.split("/").pop()||"";let g=b===f?p:p==="."?`./${b.slice(f==="/"?f.length:f.length+1)}`:p+b.slice(f.length),T=[],C=null,w=null,D=!1;S&&se&&!o&&(D=fe(i,{name:m,relativePath:g,isFile:M,isDirectory:S}).shouldPrune,D&&h.earlyPrunes++);let x=r!==null&&R>=r,I=U.terminalDirName!==null&&m===U.terminalDirName,j=!x&&!I&&!D;if(S&&((j||we||I)&&!D)){let L=Date.now();if(Te&&t.fs.readdirWithFileTypes){if(C=await t.fs.readdirWithFileTypes(b),w=C.map(v=>v.name),h.readdirCalls++,h.readdirTime+=Date.now()-L,j)T=C.map((v,k)=>({path:b==="/"?`/${v.name}`:`${b}/${v.name}`,depth:R+1,typeInfo:{isFile:v.isFile,isDirectory:v.isDirectory},resultIndex:k}));else if(I){let v=U.requiredExtension;T=C.filter(k=>k.isFile&&(!v||k.name.endsWith(v))).map((k,Pe)=>({path:b==="/"?`/${k.name}`:`${b}/${k.name}`,depth:R+1,typeInfo:{isFile:k.isFile,isDirectory:k.isDirectory},resultIndex:Pe}))}}else w=await t.fs.readdir(b),h.readdirCalls++,h.readdirTime+=Date.now()-L,j&&(T=w.map((v,k)=>({path:b==="/"?`/${v}`:`${b}/${v}`,depth:R+1,resultIndex:k})))}let Q=M?(y?.size??0)===0:w!==null&&w.length===0,H=D;if(!o&&i!==null&&!D&&se){let L=Date.now(),v={name:m,relativePath:g,isFile:M,isDirectory:S,isEmpty:Q,mtime:y?.mtime?.getTime()??Date.now(),size:y?.size??0,mode:y?.mode??420,newerRefTimes:K};H=N(i,v).pruned,h.evalCalls++,h.evalTime+=Date.now()-L}return{relativePath:g,name:m,isFile:M,isDirectory:S,isEmpty:Q,stat:y,depth:R,children:H?[]:T,pruned:H}}async function Ce(){let u={paths:[],printfData:[]};if(o){let y=function(m){let g={paths:[],printfData:[]},T=P[m];if(!T)return g;for(let D of T.childIndices){let x=y(D);g.paths.push(...x.paths),g.printfData.push(...x.printfData)}let{print:C,printfData:w}=W(T.node);return C&&(g.paths.push(T.node.relativePath),w&&g.printfData.push(w)),g};var b=y;let P=[],M=[{item:{path:f,depth:0,resultIndex:0},parentIndex:-1,childOrderInParent:0}],S=new Map;for(;M.length>0;){let m=Date.now(),g=M.splice(0,he),T=await Promise.all(g.map(C=>E(C.item)));h.batchCount++,h.batchTime+=Date.now()-m;for(let C=0;C<g.length;C++){let w=T[C],D=g[C];if(!w)continue;let x=P.length;if(D.parentIndex>=0){let I=S.get(D.parentIndex)||[];I.push(x),S.set(D.parentIndex,I)}P.push({node:w,parentIndex:D.parentIndex,childIndices:[]});for(let I=0;I<w.children.length;I++)M.push({item:w.children[I],parentIndex:x,childOrderInParent:I})}}for(let[m,g]of S)m>=0&&m<P.length&&(P[m].childIndices=g);if(P.length>0){let m=y(0);u.paths.push(...m.paths),u.printfData.push(...m.printfData)}}else{let m=function(g){let T=P.get(g);T&&(u.paths.push(T.path),T.printfData&&u.printfData.push(T.printfData));let C=y.get(g);if(C)for(let w of C)m(w)};var R=m;let P=new Map,M=0,S=[{item:{path:f,depth:0,resultIndex:0},orderIndex:M++}],y=new Map;for(;S.length>0;){let g=Date.now(),T=S.splice(0,he),C=await Promise.all(T.map(async({item:w,orderIndex:D})=>{let x=await E(w);return x?{node:x,orderIndex:D}:null}));h.batchCount++,h.batchTime+=Date.now()-g;for(let w of C){if(!w)continue;let{node:D,orderIndex:x}=w,{print:I,printfData:j}=W(D);if(I&&P.set(x,{path:D.relativePath,printfData:j}),D.children.length>0){let ee=[];for(let Q of D.children){let H=M++;ee.push(H),S.push({item:Q,orderIndex:H})}y.set(x,ee)}}}m(0)}return u}let X=await Ce();if(F.push(...X.paths),ne.push(...X.printfData),t.trace){let u=Date.now()-$;ve(t.trace,h,u),t.trace({category:"find",name:"searchPath",durationMs:u,details:{path:p,resultsFound:X.paths.length}})}}let A="";if(l.length>0)for(let p of l)switch(p.type){case"print":A+=F.length>0?`${F.join(`
5
+ `)}
6
+ `:"";break;case"print0":A+=F.length>0?`${F.join("\0")}\0`:"";break;case"delete":{let f=[...F].sort((h,$)=>$.length-h.length);for(let h of f){let $=t.fs.resolvePath(t.cwd,h);try{await t.fs.rm($,{recursive:!1})}catch(E){let W=E instanceof Error?E.message:String(E);q+=`find: cannot delete '${h}': ${W}
7
+ `,G=1}}break}case"printf":for(let f of ne)A+=Fe(p.format,f);break;case"exec":if(!t.exec)return{stdout:"",stderr:`find: -exec not supported in this context
8
+ `,exitCode:1};if(p.batchMode){let f=[];for(let E of p.command)E==="{}"?f.push(...F):f.push(E);let h=f.map(E=>`"${E}"`).join(" "),$=await t.exec(h,{cwd:t.cwd});A+=$.stdout,q+=$.stderr,$.exitCode!==0&&(G=$.exitCode)}else for(let f of F){let $=p.command.map(W=>W==="{}"?f:W).map(W=>`"${W}"`).join(" "),E=await t.exec($,{cwd:t.cwd});A+=E.stdout,q+=E.stderr,E.exitCode!==0&&(G=E.exitCode)}break}else B&&(A=F.length>0?`${F.join(`
9
+ `)}
10
+ `:"");return{stdout:A,stderr:q,exitCode:G}}};function Fe(e,t){let n=oe(e),r="",s=0;for(;s<n.length;)if(n[s]==="%"&&s+1<n.length){if(s++,n[s]==="%"){r+="%",s++;continue}let[o,a,i]=le(n,s);if(s+=i,s>=n.length){r+="%";break}let c=n[s],l;switch(c){case"f":l=t.name,s++;break;case"h":{let d=t.path.lastIndexOf("/");l=d>0?t.path.slice(0,d):".",s++;break}case"p":l=t.path,s++;break;case"P":{let d=t.startingPoint;t.path===d?l="":t.path.startsWith(`${d}/`)?l=t.path.slice(d.length+1):d==="."&&t.path.startsWith("./")?l=t.path.slice(2):l=t.path,s++;break}case"s":l=String(t.size),s++;break;case"d":l=String(t.depth),s++;break;case"m":l=(t.mode&511).toString(8),s++;break;case"M":l=$e(t.mode,t.isDirectory),s++;break;case"t":{let d=new Date(t.mtime);l=Re(d),s++;break}case"T":{if(s+1<n.length){let d=n[s+1],B=new Date(t.mtime);l=ke(B,d),s+=2}else l="%T",s++;break}default:r+=`%${o!==0||a!==-1?`${o}.${a}`:""}${c}`,s++;continue}r+=ae(l,o,a)}else r+=n[s],s++;return r}function $e(e,t){let n=e&511,r=t?"d":"-";return r+=n&256?"r":"-",r+=n&128?"w":"-",r+=n&64?"x":"-",r+=n&32?"r":"-",r+=n&16?"w":"-",r+=n&8?"x":"-",r+=n&4?"r":"-",r+=n&2?"w":"-",r+=n&1?"x":"-",r}function Re(e){let t=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],n=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],r=t[e.getDay()],s=n[e.getMonth()],o=String(e.getDate()).padStart(2," "),a=String(e.getHours()).padStart(2,"0"),i=String(e.getMinutes()).padStart(2,"0"),c=String(e.getSeconds()).padStart(2,"0"),l=e.getFullYear();return`${r} ${s} ${o} ${a}:${i}:${c} ${l}`}function ke(e,t){switch(t){case"@":return String(e.getTime()/1e3);case"Y":return String(e.getFullYear());case"m":return String(e.getMonth()+1).padStart(2,"0");case"d":return String(e.getDate()).padStart(2,"0");case"H":return String(e.getHours()).padStart(2,"0");case"M":return String(e.getMinutes()).padStart(2,"0");case"S":return String(e.getSeconds()).padStart(2,"0");case"T":return`${String(e.getHours()).padStart(2,"0")}:${String(e.getMinutes()).padStart(2,"0")}:${String(e.getSeconds()).padStart(2,"0")}`;case"F":return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,"0")}-${String(e.getDate()).padStart(2,"0")}`;default:return`%T${t}`}}export{qe as findCommand};
@@ -1,4 +1,4 @@
1
- import{a as U,b as Y,c as G,d as te,e as J,f as k,g as W,h as Ee,i as z,j as le,k as qe}from"./chunks/chunk-CG2HXOFG.js";import"./chunks/chunk-NUFRM6SI.js";import{a as ce}from"./chunks/chunk-44UOCSGV.js";import"./chunks/chunk-DXB73IDG.js";var be=[{name:"echo",load:async()=>(await import("./chunks/echo-VUHWYV6L.js")).echoCommand},{name:"cat",load:async()=>(await import("./chunks/cat-W5XITXDC.js")).catCommand},{name:"printf",load:async()=>(await import("./chunks/printf-VG2POOXB.js")).printfCommand},{name:"ls",load:async()=>(await import("./chunks/ls-5W3NU5OJ.js")).lsCommand},{name:"mkdir",load:async()=>(await import("./chunks/mkdir-7UKY4B3B.js")).mkdirCommand},{name:"touch",load:async()=>(await import("./chunks/touch-MVQSKQKT.js")).touchCommand},{name:"rm",load:async()=>(await import("./chunks/rm-I2SRVF7H.js")).rmCommand},{name:"cp",load:async()=>(await import("./chunks/cp-PBJT3GBF.js")).cpCommand},{name:"mv",load:async()=>(await import("./chunks/mv-FXHEKRTB.js")).mvCommand},{name:"ln",load:async()=>(await import("./chunks/ln-Y7YB677N.js")).lnCommand},{name:"chmod",load:async()=>(await import("./chunks/chmod-FBHLEIY6.js")).chmodCommand},{name:"pwd",load:async()=>(await import("./chunks/pwd-AC4P3JKI.js")).pwdCommand},{name:"readlink",load:async()=>(await import("./chunks/readlink-EM4O3U4P.js")).readlinkCommand},{name:"head",load:async()=>(await import("./chunks/head-FZ6IQHYW.js")).headCommand},{name:"tail",load:async()=>(await import("./chunks/tail-PD4RZR6J.js")).tailCommand},{name:"wc",load:async()=>(await import("./chunks/wc-52FZ4QGS.js")).wcCommand},{name:"stat",load:async()=>(await import("./chunks/stat-IVQBBOKN.js")).statCommand},{name:"grep",load:async()=>(await import("./chunks/grep-CTJRP2G3.js")).grepCommand},{name:"fgrep",load:async()=>(await import("./chunks/grep-CTJRP2G3.js")).fgrepCommand},{name:"egrep",load:async()=>(await import("./chunks/grep-CTJRP2G3.js")).egrepCommand},{name:"sed",load:async()=>(await import("./chunks/sed-ZKODWZ6F.js")).sedCommand},{name:"awk",load:async()=>(await import("./chunks/awk2-46RTIZKB.js")).awkCommand2},{name:"sort",load:async()=>(await import("./chunks/sort-JHO22QVO.js")).sortCommand},{name:"uniq",load:async()=>(await import("./chunks/uniq-SEKCFR7B.js")).uniqCommand},{name:"comm",load:async()=>(await import("./chunks/comm-AXQM7FFF.js")).commCommand},{name:"cut",load:async()=>(await import("./chunks/cut-KKAAQJVD.js")).cutCommand},{name:"paste",load:async()=>(await import("./chunks/paste-QTGVEPH5.js")).pasteCommand},{name:"tr",load:async()=>(await import("./chunks/tr-EDGW5FG6.js")).trCommand},{name:"rev",load:async()=>(await import("./chunks/rev-FKUV5GH5.js")).rev},{name:"nl",load:async()=>(await import("./chunks/nl-KWQGFZH5.js")).nl},{name:"fold",load:async()=>(await import("./chunks/fold-6CFXIPYZ.js")).fold},{name:"expand",load:async()=>(await import("./chunks/expand-VSTNOVF5.js")).expand},{name:"unexpand",load:async()=>(await import("./chunks/unexpand-I7A2VXFD.js")).unexpand},{name:"strings",load:async()=>(await import("./chunks/strings-LRU5XCFP.js")).strings},{name:"split",load:async()=>(await import("./chunks/split-YBTFW7MT.js")).split},{name:"column",load:async()=>(await import("./chunks/column-XPDNNO5Y.js")).column},{name:"join",load:async()=>(await import("./chunks/join-X3QYPZUA.js")).join},{name:"tee",load:async()=>(await import("./chunks/tee-2QU4NRSJ.js")).teeCommand},{name:"find",load:async()=>(await import("./chunks/find-GPKJFOPK.js")).findCommand},{name:"basename",load:async()=>(await import("./chunks/basename-CFA5ZIGT.js")).basenameCommand},{name:"dirname",load:async()=>(await import("./chunks/dirname-YPJLCQYA.js")).dirnameCommand},{name:"tree",load:async()=>(await import("./chunks/tree-MEM64BW3.js")).treeCommand},{name:"du",load:async()=>(await import("./chunks/du-NQXEC3EF.js")).duCommand},{name:"env",load:async()=>(await import("./chunks/env-EG5SQSAQ.js")).envCommand},{name:"printenv",load:async()=>(await import("./chunks/env-EG5SQSAQ.js")).printenvCommand},{name:"alias",load:async()=>(await import("./chunks/alias-4UGRF4DM.js")).aliasCommand},{name:"unalias",load:async()=>(await import("./chunks/alias-4UGRF4DM.js")).unaliasCommand},{name:"history",load:async()=>(await import("./chunks/history-MQDK2OPD.js")).historyCommand},{name:"xargs",load:async()=>(await import("./chunks/xargs-4FRA6OJ7.js")).xargsCommand},{name:"true",load:async()=>(await import("./chunks/true-CNJ54NE6.js")).trueCommand},{name:"false",load:async()=>(await import("./chunks/true-CNJ54NE6.js")).falseCommand},{name:"clear",load:async()=>(await import("./chunks/clear-VT2LJIDX.js")).clearCommand},{name:"bash",load:async()=>(await import("./chunks/bash-ZILV3VHA.js")).bashCommand},{name:"sh",load:async()=>(await import("./chunks/bash-ZILV3VHA.js")).shCommand},{name:"jq",load:async()=>(await import("./chunks/jq-AAWVUTC4.js")).jqCommand},{name:"base64",load:async()=>(await import("./chunks/base64-F5R4G5EG.js")).base64Command},{name:"diff",load:async()=>(await import("./chunks/diff-ZLJYSBRK.js")).diffCommand},{name:"date",load:async()=>(await import("./chunks/date-PN3CMG7K.js")).dateCommand},{name:"sleep",load:async()=>(await import("./chunks/sleep-AK4QE4WR.js")).sleepCommand},{name:"timeout",load:async()=>(await import("./chunks/timeout-X3X3N6IE.js")).timeoutCommand},{name:"seq",load:async()=>(await import("./chunks/seq-5VRIVQYP.js")).seqCommand},{name:"expr",load:async()=>(await import("./chunks/expr-DG4E7SIS.js")).exprCommand},{name:"md5sum",load:async()=>(await import("./chunks/md5sum-LJHKXLVT.js")).md5sumCommand},{name:"sha1sum",load:async()=>(await import("./chunks/sha1sum-NRUZZ4Q6.js")).sha1sumCommand},{name:"sha256sum",load:async()=>(await import("./chunks/sha256sum-5ZGJ4NJL.js")).sha256sumCommand},{name:"file",load:async()=>(await import("./chunks/file-AWZ3TUFP.js")).fileCommand},{name:"html-to-markdown",load:async()=>(await import("./chunks/html-to-markdown-ZK6GQVSL.js")).htmlToMarkdownCommand},{name:"help",load:async()=>(await import("./chunks/help-75YOGKM4.js")).helpCommand},{name:"which",load:async()=>(await import("./chunks/which-M5MQ6QXQ.js")).whichCommand},{name:"tac",load:async()=>(await import("./chunks/tac-2X4JLF4W.js")).tac},{name:"hostname",load:async()=>(await import("./chunks/hostname-NWR32CGF.js")).hostname},{name:"od",load:async()=>(await import("./chunks/od-ECWXNUB4.js")).od},{name:"gzip",load:async()=>(await import("./chunks/gzip-7QAS5P2Y.js")).gzipCommand},{name:"gunzip",load:async()=>(await import("./chunks/gzip-7QAS5P2Y.js")).gunzipCommand},{name:"zcat",load:async()=>(await import("./chunks/gzip-7QAS5P2Y.js")).zcatCommand}];(typeof __BROWSER__>"u"||!__BROWSER__)&&(be.push({name:"yq",load:async()=>(await import("./chunks/yq-KANM4MD2.js")).yqCommand}),be.push({name:"xan",load:async()=>(await import("./chunks/xan-ZHXYF6B4.js")).xanCommand}),be.push({name:"sqlite3",load:async()=>(await import("./chunks/sqlite3-CX5D36A5.js")).sqlite3Command}));var gr=[{name:"curl",load:async()=>(await import("./chunks/curl-TVZH24MD.js")).curlCommand}],wr=new Map;function Ar(t){return{name:t.name,async execute(e,n){let r=wr.get(t.name);return r||(r=await t.load(),wr.set(t.name,r)),r.execute(e,n)}}}function Hn(){return be.map(t=>t.name)}function jn(){return gr.map(t=>t.name)}function xr(t){return(t?be.filter(n=>t.includes(n.name)):be).map(Ar)}function Sr(){return gr.map(Ar)}function br(t){return"load"in t&&typeof t.load=="function"}function qn(t,e){return{name:t,execute:e}}function Nr(t){let e=null;return{name:t.name,async execute(n,r){return e||(e=await t.load()),e.execute(n,r)}}}var Zn=new TextEncoder,Qn=new TextDecoder;function re(t,e){if(t instanceof Uint8Array)return t;switch(e){case"base64":return Uint8Array.from(atob(t),n=>n.charCodeAt(0));case"hex":{let n=new Uint8Array(t.length/2);for(let r=0;r<t.length;r+=2)n[r/2]=parseInt(t.slice(r,r+2),16);return n}case"binary":case"latin1":return Uint8Array.from(t,n=>n.charCodeAt(0));default:return Zn.encode(t)}}function Ne(t,e){switch(e){case"base64":return btoa(String.fromCharCode(...t));case"hex":return Array.from(t).map(n=>n.toString(16).padStart(2,"0")).join("");case"binary":case"latin1":return String.fromCharCode(...t);default:return Qn.decode(t)}}function q(t){if(t!=null)return typeof t=="string"?t:t.encoding??void 0}var Ze=new TextEncoder;function Kn(t){return typeof t=="object"&&t!==null&&!(t instanceof Uint8Array)&&"content"in t}var we=class{data=new Map;constructor(e){if(this.data.set("/",{type:"directory",mode:493,mtime:new Date}),e)for(let[n,r]of Object.entries(e))Kn(r)?this.writeFileSync(n,r.content,void 0,{mode:r.mode,mtime:r.mtime}):this.writeFileSync(n,r)}normalizePath(e){if(!e||e==="/")return"/";let n=e.endsWith("/")&&e!=="/"?e.slice(0,-1):e;n.startsWith("/")||(n=`/${n}`);let r=n.split("/").filter(o=>o&&o!=="."),s=[];for(let o of r)o===".."?s.pop():s.push(o);return`/${s.join("/")}`||"/"}dirname(e){let n=this.normalizePath(e);if(n==="/")return"/";let r=n.lastIndexOf("/");return r===0?"/":n.slice(0,r)}ensureParentDirs(e){let n=this.dirname(e);n!=="/"&&(this.data.has(n)||(this.ensureParentDirs(n),this.data.set(n,{type:"directory",mode:493,mtime:new Date})))}writeFileSync(e,n,r,s){let o=this.normalizePath(e);this.ensureParentDirs(o);let i=q(r),a=re(n,i);this.data.set(o,{type:"file",content:a,mode:s?.mode??420,mtime:s?.mtime??new Date})}async readFile(e,n){let r=await this.readFileBuffer(e),s=q(n);return Ne(r,s)}async readFileBuffer(e){let n=this.normalizePath(e),r=this.data.get(n),s=n;if(!r)throw new Error(`ENOENT: no such file or directory, open '${e}'`);let o=new Set;for(;r&&r.type==="symlink";){if(o.has(s))throw new Error(`ELOOP: too many levels of symbolic links, open '${e}'`);o.add(s),s=this.resolveSymlink(s,r.target),r=this.data.get(s)}if(!r)throw new Error(`ENOENT: no such file or directory, open '${e}'`);if(r.type!=="file")throw new Error(`EISDIR: illegal operation on a directory, read '${e}'`);return r.content instanceof Uint8Array?r.content:Ze.encode(r.content)}async writeFile(e,n,r){this.writeFileSync(e,n,r)}async appendFile(e,n,r){let s=this.normalizePath(e),o=this.data.get(s);if(o&&o.type==="directory")throw new Error(`EISDIR: illegal operation on a directory, write '${e}'`);let i=q(r),a=re(n,i);if(o?.type==="file"){let l=o.content instanceof Uint8Array?o.content:Ze.encode(o.content),c=new Uint8Array(l.length+a.length);c.set(l),c.set(a,l.length),this.data.set(s,{type:"file",content:c,mode:o.mode,mtime:new Date})}else this.writeFileSync(e,n,r)}async exists(e){return this.data.has(this.normalizePath(e))}async stat(e){let n=this.normalizePath(e),r=this.data.get(n);if(!r)throw new Error(`ENOENT: no such file or directory, stat '${e}'`);if(r.type==="symlink"){let o=this.resolveSymlink(n,r.target),i=this.data.get(o);if(!i)throw new Error(`ENOENT: no such file or directory, stat '${e}'`);r=i}let s=0;return r.type==="file"&&r.content&&(r.content instanceof Uint8Array?s=r.content.length:s=Ze.encode(r.content).length),{isFile:r.type==="file",isDirectory:r.type==="directory",isSymbolicLink:!1,mode:r.mode,size:s,mtime:r.mtime||new Date}}async lstat(e){let n=this.normalizePath(e),r=this.data.get(n);if(!r)throw new Error(`ENOENT: no such file or directory, lstat '${e}'`);if(r.type==="symlink")return{isFile:!1,isDirectory:!1,isSymbolicLink:!0,mode:r.mode,size:r.target.length,mtime:r.mtime||new Date};let s=0;return r.type==="file"&&r.content&&(r.content instanceof Uint8Array?s=r.content.length:s=Ze.encode(r.content).length),{isFile:r.type==="file",isDirectory:r.type==="directory",isSymbolicLink:!1,mode:r.mode,size:s,mtime:r.mtime||new Date}}resolveSymlink(e,n){if(n.startsWith("/"))return this.normalizePath(n);let r=this.dirname(e);return this.normalizePath(r==="/"?`/${n}`:`${r}/${n}`)}async mkdir(e,n){this.mkdirSync(e,n)}mkdirSync(e,n){let r=this.normalizePath(e);if(this.data.has(r)){if(this.data.get(r)?.type==="file")throw new Error(`EEXIST: file already exists, mkdir '${e}'`);if(!n?.recursive)throw new Error(`EEXIST: directory already exists, mkdir '${e}'`);return}let s=this.dirname(r);if(s!=="/"&&!this.data.has(s))if(n?.recursive)this.mkdirSync(s,{recursive:!0});else throw new Error(`ENOENT: no such file or directory, mkdir '${e}'`);this.data.set(r,{type:"directory",mode:493,mtime:new Date})}async readdir(e){return(await this.readdirWithFileTypes(e)).map(r=>r.name)}async readdirWithFileTypes(e){let n=this.normalizePath(e),r=this.data.get(n);if(!r)throw new Error(`ENOENT: no such file or directory, scandir '${e}'`);if(r.type!=="directory")throw new Error(`ENOTDIR: not a directory, scandir '${e}'`);let s=n==="/"?"/":`${n}/`,o=new Map;for(let[i,a]of this.data.entries())if(i!==n&&i.startsWith(s)){let l=i.slice(s.length),c=l.split("/")[0];c&&!l.includes("/",c.length)&&!o.has(c)&&o.set(c,{name:c,isFile:a.type==="file",isDirectory:a.type==="directory",isSymbolicLink:a.type==="symlink"})}return Array.from(o.values()).sort((i,a)=>i.name<a.name?-1:i.name>a.name?1:0)}async rm(e,n){let r=this.normalizePath(e),s=this.data.get(r);if(!s){if(n?.force)return;throw new Error(`ENOENT: no such file or directory, rm '${e}'`)}if(s.type==="directory"){let o=await this.readdir(r);if(o.length>0){if(!n?.recursive)throw new Error(`ENOTEMPTY: directory not empty, rm '${e}'`);for(let i of o){let a=r==="/"?`/${i}`:`${r}/${i}`;await this.rm(a,n)}}}this.data.delete(r)}async cp(e,n,r){let s=this.normalizePath(e),o=this.normalizePath(n),i=this.data.get(s);if(!i)throw new Error(`ENOENT: no such file or directory, cp '${e}'`);if(i.type==="file")this.ensureParentDirs(o),this.data.set(o,{...i});else if(i.type==="directory"){if(!r?.recursive)throw new Error(`EISDIR: is a directory, cp '${e}'`);await this.mkdir(o,{recursive:!0});let a=await this.readdir(s);for(let l of a){let c=s==="/"?`/${l}`:`${s}/${l}`,f=o==="/"?`/${l}`:`${o}/${l}`;await this.cp(c,f,r)}}}async mv(e,n){await this.cp(e,n,{recursive:!0}),await this.rm(e,{recursive:!0})}getAllPaths(){return Array.from(this.data.keys())}resolvePath(e,n){if(n.startsWith("/"))return this.normalizePath(n);let r=e==="/"?`/${n}`:`${e}/${n}`;return this.normalizePath(r)}async chmod(e,n){let r=this.normalizePath(e),s=this.data.get(r);if(!s)throw new Error(`ENOENT: no such file or directory, chmod '${e}'`);s.mode=n}async symlink(e,n){let r=this.normalizePath(n);if(this.data.has(r))throw new Error(`EEXIST: file already exists, symlink '${n}'`);this.ensureParentDirs(r),this.data.set(r,{type:"symlink",target:e,mode:511,mtime:new Date})}async link(e,n){let r=this.normalizePath(e),s=this.normalizePath(n),o=this.data.get(r);if(!o)throw new Error(`ENOENT: no such file or directory, link '${e}'`);if(o.type!=="file")throw new Error(`EPERM: operation not permitted, link '${e}'`);if(this.data.has(s))throw new Error(`EEXIST: file already exists, link '${n}'`);this.ensureParentDirs(s),this.data.set(s,{type:"file",content:o.content,mode:o.mode,mtime:o.mtime})}async readlink(e){let n=this.normalizePath(e),r=this.data.get(n);if(!r)throw new Error(`ENOENT: no such file or directory, readlink '${e}'`);if(r.type!=="symlink")throw new Error(`EINVAL: invalid argument, readlink '${e}'`);return r.target}};var Cr="5.1.0(1)-release",$r="Linux version 5.15.0-generic (just-bash) #1 SMP PREEMPT";function We(){return{pid:process.pid,ppid:process.ppid,uid:process.getuid?.()??1e3,gid:process.getgid?.()??1e3}}function Pr(){let{pid:t,ppid:e,uid:n,gid:r}=We();return`Name: bash
1
+ import{a as U,b as Y,c as G,d as te,e as J,f as k,g as W,h as Ee,i as z,j as le,k as qe}from"./chunks/chunk-CG2HXOFG.js";import"./chunks/chunk-NUFRM6SI.js";import{a as ce}from"./chunks/chunk-44UOCSGV.js";import"./chunks/chunk-DXB73IDG.js";var be=[{name:"echo",load:async()=>(await import("./chunks/echo-VUHWYV6L.js")).echoCommand},{name:"cat",load:async()=>(await import("./chunks/cat-W5XITXDC.js")).catCommand},{name:"printf",load:async()=>(await import("./chunks/printf-VG2POOXB.js")).printfCommand},{name:"ls",load:async()=>(await import("./chunks/ls-5W3NU5OJ.js")).lsCommand},{name:"mkdir",load:async()=>(await import("./chunks/mkdir-7UKY4B3B.js")).mkdirCommand},{name:"touch",load:async()=>(await import("./chunks/touch-MVQSKQKT.js")).touchCommand},{name:"rm",load:async()=>(await import("./chunks/rm-I2SRVF7H.js")).rmCommand},{name:"cp",load:async()=>(await import("./chunks/cp-PBJT3GBF.js")).cpCommand},{name:"mv",load:async()=>(await import("./chunks/mv-FXHEKRTB.js")).mvCommand},{name:"ln",load:async()=>(await import("./chunks/ln-Y7YB677N.js")).lnCommand},{name:"chmod",load:async()=>(await import("./chunks/chmod-FBHLEIY6.js")).chmodCommand},{name:"pwd",load:async()=>(await import("./chunks/pwd-AC4P3JKI.js")).pwdCommand},{name:"readlink",load:async()=>(await import("./chunks/readlink-EM4O3U4P.js")).readlinkCommand},{name:"head",load:async()=>(await import("./chunks/head-FZ6IQHYW.js")).headCommand},{name:"tail",load:async()=>(await import("./chunks/tail-PD4RZR6J.js")).tailCommand},{name:"wc",load:async()=>(await import("./chunks/wc-52FZ4QGS.js")).wcCommand},{name:"stat",load:async()=>(await import("./chunks/stat-IVQBBOKN.js")).statCommand},{name:"grep",load:async()=>(await import("./chunks/grep-CTJRP2G3.js")).grepCommand},{name:"fgrep",load:async()=>(await import("./chunks/grep-CTJRP2G3.js")).fgrepCommand},{name:"egrep",load:async()=>(await import("./chunks/grep-CTJRP2G3.js")).egrepCommand},{name:"sed",load:async()=>(await import("./chunks/sed-ZKODWZ6F.js")).sedCommand},{name:"awk",load:async()=>(await import("./chunks/awk2-46RTIZKB.js")).awkCommand2},{name:"sort",load:async()=>(await import("./chunks/sort-JHO22QVO.js")).sortCommand},{name:"uniq",load:async()=>(await import("./chunks/uniq-SEKCFR7B.js")).uniqCommand},{name:"comm",load:async()=>(await import("./chunks/comm-AXQM7FFF.js")).commCommand},{name:"cut",load:async()=>(await import("./chunks/cut-KKAAQJVD.js")).cutCommand},{name:"paste",load:async()=>(await import("./chunks/paste-QTGVEPH5.js")).pasteCommand},{name:"tr",load:async()=>(await import("./chunks/tr-EDGW5FG6.js")).trCommand},{name:"rev",load:async()=>(await import("./chunks/rev-FKUV5GH5.js")).rev},{name:"nl",load:async()=>(await import("./chunks/nl-KWQGFZH5.js")).nl},{name:"fold",load:async()=>(await import("./chunks/fold-6CFXIPYZ.js")).fold},{name:"expand",load:async()=>(await import("./chunks/expand-VSTNOVF5.js")).expand},{name:"unexpand",load:async()=>(await import("./chunks/unexpand-I7A2VXFD.js")).unexpand},{name:"strings",load:async()=>(await import("./chunks/strings-LRU5XCFP.js")).strings},{name:"split",load:async()=>(await import("./chunks/split-YBTFW7MT.js")).split},{name:"column",load:async()=>(await import("./chunks/column-XPDNNO5Y.js")).column},{name:"join",load:async()=>(await import("./chunks/join-X3QYPZUA.js")).join},{name:"tee",load:async()=>(await import("./chunks/tee-2QU4NRSJ.js")).teeCommand},{name:"find",load:async()=>(await import("./chunks/find-ACOAWALE.js")).findCommand},{name:"basename",load:async()=>(await import("./chunks/basename-CFA5ZIGT.js")).basenameCommand},{name:"dirname",load:async()=>(await import("./chunks/dirname-YPJLCQYA.js")).dirnameCommand},{name:"tree",load:async()=>(await import("./chunks/tree-MEM64BW3.js")).treeCommand},{name:"du",load:async()=>(await import("./chunks/du-NQXEC3EF.js")).duCommand},{name:"env",load:async()=>(await import("./chunks/env-EG5SQSAQ.js")).envCommand},{name:"printenv",load:async()=>(await import("./chunks/env-EG5SQSAQ.js")).printenvCommand},{name:"alias",load:async()=>(await import("./chunks/alias-4UGRF4DM.js")).aliasCommand},{name:"unalias",load:async()=>(await import("./chunks/alias-4UGRF4DM.js")).unaliasCommand},{name:"history",load:async()=>(await import("./chunks/history-MQDK2OPD.js")).historyCommand},{name:"xargs",load:async()=>(await import("./chunks/xargs-4FRA6OJ7.js")).xargsCommand},{name:"true",load:async()=>(await import("./chunks/true-CNJ54NE6.js")).trueCommand},{name:"false",load:async()=>(await import("./chunks/true-CNJ54NE6.js")).falseCommand},{name:"clear",load:async()=>(await import("./chunks/clear-VT2LJIDX.js")).clearCommand},{name:"bash",load:async()=>(await import("./chunks/bash-ZILV3VHA.js")).bashCommand},{name:"sh",load:async()=>(await import("./chunks/bash-ZILV3VHA.js")).shCommand},{name:"jq",load:async()=>(await import("./chunks/jq-AAWVUTC4.js")).jqCommand},{name:"base64",load:async()=>(await import("./chunks/base64-F5R4G5EG.js")).base64Command},{name:"diff",load:async()=>(await import("./chunks/diff-ZLJYSBRK.js")).diffCommand},{name:"date",load:async()=>(await import("./chunks/date-PN3CMG7K.js")).dateCommand},{name:"sleep",load:async()=>(await import("./chunks/sleep-AK4QE4WR.js")).sleepCommand},{name:"timeout",load:async()=>(await import("./chunks/timeout-X3X3N6IE.js")).timeoutCommand},{name:"seq",load:async()=>(await import("./chunks/seq-5VRIVQYP.js")).seqCommand},{name:"expr",load:async()=>(await import("./chunks/expr-DG4E7SIS.js")).exprCommand},{name:"md5sum",load:async()=>(await import("./chunks/md5sum-LJHKXLVT.js")).md5sumCommand},{name:"sha1sum",load:async()=>(await import("./chunks/sha1sum-NRUZZ4Q6.js")).sha1sumCommand},{name:"sha256sum",load:async()=>(await import("./chunks/sha256sum-5ZGJ4NJL.js")).sha256sumCommand},{name:"file",load:async()=>(await import("./chunks/file-AWZ3TUFP.js")).fileCommand},{name:"html-to-markdown",load:async()=>(await import("./chunks/html-to-markdown-ZK6GQVSL.js")).htmlToMarkdownCommand},{name:"help",load:async()=>(await import("./chunks/help-75YOGKM4.js")).helpCommand},{name:"which",load:async()=>(await import("./chunks/which-M5MQ6QXQ.js")).whichCommand},{name:"tac",load:async()=>(await import("./chunks/tac-2X4JLF4W.js")).tac},{name:"hostname",load:async()=>(await import("./chunks/hostname-NWR32CGF.js")).hostname},{name:"od",load:async()=>(await import("./chunks/od-ECWXNUB4.js")).od},{name:"gzip",load:async()=>(await import("./chunks/gzip-7QAS5P2Y.js")).gzipCommand},{name:"gunzip",load:async()=>(await import("./chunks/gzip-7QAS5P2Y.js")).gunzipCommand},{name:"zcat",load:async()=>(await import("./chunks/gzip-7QAS5P2Y.js")).zcatCommand}];(typeof __BROWSER__>"u"||!__BROWSER__)&&(be.push({name:"yq",load:async()=>(await import("./chunks/yq-KANM4MD2.js")).yqCommand}),be.push({name:"xan",load:async()=>(await import("./chunks/xan-ZHXYF6B4.js")).xanCommand}),be.push({name:"sqlite3",load:async()=>(await import("./chunks/sqlite3-CX5D36A5.js")).sqlite3Command}));var gr=[{name:"curl",load:async()=>(await import("./chunks/curl-TVZH24MD.js")).curlCommand}],wr=new Map;function Ar(t){return{name:t.name,async execute(e,n){let r=wr.get(t.name);return r||(r=await t.load(),wr.set(t.name,r)),r.execute(e,n)}}}function Hn(){return be.map(t=>t.name)}function jn(){return gr.map(t=>t.name)}function xr(t){return(t?be.filter(n=>t.includes(n.name)):be).map(Ar)}function Sr(){return gr.map(Ar)}function br(t){return"load"in t&&typeof t.load=="function"}function qn(t,e){return{name:t,execute:e}}function Nr(t){let e=null;return{name:t.name,async execute(n,r){return e||(e=await t.load()),e.execute(n,r)}}}var Zn=new TextEncoder,Qn=new TextDecoder;function re(t,e){if(t instanceof Uint8Array)return t;switch(e){case"base64":return Uint8Array.from(atob(t),n=>n.charCodeAt(0));case"hex":{let n=new Uint8Array(t.length/2);for(let r=0;r<t.length;r+=2)n[r/2]=parseInt(t.slice(r,r+2),16);return n}case"binary":case"latin1":return Uint8Array.from(t,n=>n.charCodeAt(0));default:return Zn.encode(t)}}function Ne(t,e){switch(e){case"base64":return btoa(String.fromCharCode(...t));case"hex":return Array.from(t).map(n=>n.toString(16).padStart(2,"0")).join("");case"binary":case"latin1":return String.fromCharCode(...t);default:return Qn.decode(t)}}function q(t){if(t!=null)return typeof t=="string"?t:t.encoding??void 0}var Ze=new TextEncoder;function Kn(t){return typeof t=="object"&&t!==null&&!(t instanceof Uint8Array)&&"content"in t}var we=class{data=new Map;constructor(e){if(this.data.set("/",{type:"directory",mode:493,mtime:new Date}),e)for(let[n,r]of Object.entries(e))Kn(r)?this.writeFileSync(n,r.content,void 0,{mode:r.mode,mtime:r.mtime}):this.writeFileSync(n,r)}normalizePath(e){if(!e||e==="/")return"/";let n=e.endsWith("/")&&e!=="/"?e.slice(0,-1):e;n.startsWith("/")||(n=`/${n}`);let r=n.split("/").filter(o=>o&&o!=="."),s=[];for(let o of r)o===".."?s.pop():s.push(o);return`/${s.join("/")}`||"/"}dirname(e){let n=this.normalizePath(e);if(n==="/")return"/";let r=n.lastIndexOf("/");return r===0?"/":n.slice(0,r)}ensureParentDirs(e){let n=this.dirname(e);n!=="/"&&(this.data.has(n)||(this.ensureParentDirs(n),this.data.set(n,{type:"directory",mode:493,mtime:new Date})))}writeFileSync(e,n,r,s){let o=this.normalizePath(e);this.ensureParentDirs(o);let i=q(r),a=re(n,i);this.data.set(o,{type:"file",content:a,mode:s?.mode??420,mtime:s?.mtime??new Date})}async readFile(e,n){let r=await this.readFileBuffer(e),s=q(n);return Ne(r,s)}async readFileBuffer(e){let n=this.normalizePath(e),r=this.data.get(n),s=n;if(!r)throw new Error(`ENOENT: no such file or directory, open '${e}'`);let o=new Set;for(;r&&r.type==="symlink";){if(o.has(s))throw new Error(`ELOOP: too many levels of symbolic links, open '${e}'`);o.add(s),s=this.resolveSymlink(s,r.target),r=this.data.get(s)}if(!r)throw new Error(`ENOENT: no such file or directory, open '${e}'`);if(r.type!=="file")throw new Error(`EISDIR: illegal operation on a directory, read '${e}'`);return r.content instanceof Uint8Array?r.content:Ze.encode(r.content)}async writeFile(e,n,r){this.writeFileSync(e,n,r)}async appendFile(e,n,r){let s=this.normalizePath(e),o=this.data.get(s);if(o&&o.type==="directory")throw new Error(`EISDIR: illegal operation on a directory, write '${e}'`);let i=q(r),a=re(n,i);if(o?.type==="file"){let l=o.content instanceof Uint8Array?o.content:Ze.encode(o.content),c=new Uint8Array(l.length+a.length);c.set(l),c.set(a,l.length),this.data.set(s,{type:"file",content:c,mode:o.mode,mtime:new Date})}else this.writeFileSync(e,n,r)}async exists(e){return this.data.has(this.normalizePath(e))}async stat(e){let n=this.normalizePath(e),r=this.data.get(n);if(!r)throw new Error(`ENOENT: no such file or directory, stat '${e}'`);if(r.type==="symlink"){let o=this.resolveSymlink(n,r.target),i=this.data.get(o);if(!i)throw new Error(`ENOENT: no such file or directory, stat '${e}'`);r=i}let s=0;return r.type==="file"&&r.content&&(r.content instanceof Uint8Array?s=r.content.length:s=Ze.encode(r.content).length),{isFile:r.type==="file",isDirectory:r.type==="directory",isSymbolicLink:!1,mode:r.mode,size:s,mtime:r.mtime||new Date}}async lstat(e){let n=this.normalizePath(e),r=this.data.get(n);if(!r)throw new Error(`ENOENT: no such file or directory, lstat '${e}'`);if(r.type==="symlink")return{isFile:!1,isDirectory:!1,isSymbolicLink:!0,mode:r.mode,size:r.target.length,mtime:r.mtime||new Date};let s=0;return r.type==="file"&&r.content&&(r.content instanceof Uint8Array?s=r.content.length:s=Ze.encode(r.content).length),{isFile:r.type==="file",isDirectory:r.type==="directory",isSymbolicLink:!1,mode:r.mode,size:s,mtime:r.mtime||new Date}}resolveSymlink(e,n){if(n.startsWith("/"))return this.normalizePath(n);let r=this.dirname(e);return this.normalizePath(r==="/"?`/${n}`:`${r}/${n}`)}async mkdir(e,n){this.mkdirSync(e,n)}mkdirSync(e,n){let r=this.normalizePath(e);if(this.data.has(r)){if(this.data.get(r)?.type==="file")throw new Error(`EEXIST: file already exists, mkdir '${e}'`);if(!n?.recursive)throw new Error(`EEXIST: directory already exists, mkdir '${e}'`);return}let s=this.dirname(r);if(s!=="/"&&!this.data.has(s))if(n?.recursive)this.mkdirSync(s,{recursive:!0});else throw new Error(`ENOENT: no such file or directory, mkdir '${e}'`);this.data.set(r,{type:"directory",mode:493,mtime:new Date})}async readdir(e){return(await this.readdirWithFileTypes(e)).map(r=>r.name)}async readdirWithFileTypes(e){let n=this.normalizePath(e),r=this.data.get(n);if(!r)throw new Error(`ENOENT: no such file or directory, scandir '${e}'`);if(r.type!=="directory")throw new Error(`ENOTDIR: not a directory, scandir '${e}'`);let s=n==="/"?"/":`${n}/`,o=new Map;for(let[i,a]of this.data.entries())if(i!==n&&i.startsWith(s)){let l=i.slice(s.length),c=l.split("/")[0];c&&!l.includes("/",c.length)&&!o.has(c)&&o.set(c,{name:c,isFile:a.type==="file",isDirectory:a.type==="directory",isSymbolicLink:a.type==="symlink"})}return Array.from(o.values()).sort((i,a)=>i.name<a.name?-1:i.name>a.name?1:0)}async rm(e,n){let r=this.normalizePath(e),s=this.data.get(r);if(!s){if(n?.force)return;throw new Error(`ENOENT: no such file or directory, rm '${e}'`)}if(s.type==="directory"){let o=await this.readdir(r);if(o.length>0){if(!n?.recursive)throw new Error(`ENOTEMPTY: directory not empty, rm '${e}'`);for(let i of o){let a=r==="/"?`/${i}`:`${r}/${i}`;await this.rm(a,n)}}}this.data.delete(r)}async cp(e,n,r){let s=this.normalizePath(e),o=this.normalizePath(n),i=this.data.get(s);if(!i)throw new Error(`ENOENT: no such file or directory, cp '${e}'`);if(i.type==="file")this.ensureParentDirs(o),this.data.set(o,{...i});else if(i.type==="directory"){if(!r?.recursive)throw new Error(`EISDIR: is a directory, cp '${e}'`);await this.mkdir(o,{recursive:!0});let a=await this.readdir(s);for(let l of a){let c=s==="/"?`/${l}`:`${s}/${l}`,f=o==="/"?`/${l}`:`${o}/${l}`;await this.cp(c,f,r)}}}async mv(e,n){await this.cp(e,n,{recursive:!0}),await this.rm(e,{recursive:!0})}getAllPaths(){return Array.from(this.data.keys())}resolvePath(e,n){if(n.startsWith("/"))return this.normalizePath(n);let r=e==="/"?`/${n}`:`${e}/${n}`;return this.normalizePath(r)}async chmod(e,n){let r=this.normalizePath(e),s=this.data.get(r);if(!s)throw new Error(`ENOENT: no such file or directory, chmod '${e}'`);s.mode=n}async symlink(e,n){let r=this.normalizePath(n);if(this.data.has(r))throw new Error(`EEXIST: file already exists, symlink '${n}'`);this.ensureParentDirs(r),this.data.set(r,{type:"symlink",target:e,mode:511,mtime:new Date})}async link(e,n){let r=this.normalizePath(e),s=this.normalizePath(n),o=this.data.get(r);if(!o)throw new Error(`ENOENT: no such file or directory, link '${e}'`);if(o.type!=="file")throw new Error(`EPERM: operation not permitted, link '${e}'`);if(this.data.has(s))throw new Error(`EEXIST: file already exists, link '${n}'`);this.ensureParentDirs(s),this.data.set(s,{type:"file",content:o.content,mode:o.mode,mtime:o.mtime})}async readlink(e){let n=this.normalizePath(e),r=this.data.get(n);if(!r)throw new Error(`ENOENT: no such file or directory, readlink '${e}'`);if(r.type!=="symlink")throw new Error(`EINVAL: invalid argument, readlink '${e}'`);return r.target}};var Cr="5.1.0(1)-release",$r="Linux version 5.15.0-generic (just-bash) #1 SMP PREEMPT";function We(){return{pid:process.pid,ppid:process.ppid,uid:process.getuid?.()??1e3,gid:process.getgid?.()??1e3}}function Pr(){let{pid:t,ppid:e,uid:n,gid:r}=We();return`Name: bash
2
2
  State: R (running)
3
3
  Pid: ${t}
4
4
  PPid: ${e}
@@ -120,7 +120,7 @@ ${ot}`):(ar(t,e.slice(n)),C)}return C}function ar(t,e){let n=1;for(;t.state.env[
120
120
  `,o=1,r="";break}}catch{}await t.fs.appendFile(c,r),r=""}else if(l===2){let c=t.fs.resolvePath(t.state.cwd,a);try{if((await t.fs.stat(c)).isDirectory){s+=`bash: ${a}: Is a directory
121
121
  `,o=1;break}}catch{}await t.fs.appendFile(c,s),s=""}break}case">&":{let l=i.fd??1;a==="2"||a==="&2"?l===1&&(s+=r,r=""):(a==="1"||a==="&1")&&(r+=s,s="");break}case"&>":{let l=t.fs.resolvePath(t.state.cwd,a);try{if((await t.fs.stat(l)).isDirectory){s=`bash: ${a}: Is a directory
122
122
  `,o=1,r="";break}}catch{}await t.fs.writeFile(l,r+s),r="",s="";break}case"&>>":{let l=t.fs.resolvePath(t.state.cwd,a);try{if((await t.fs.stat(l)).isDirectory){s=`bash: ${a}: Is a directory
123
- `,o=1,r="";break}}catch{}await t.fs.appendFile(l,r+s),r="",s="";break}}}return x(r,s,o)}var He=class{ctx;constructor(e,n){this.ctx={state:n,fs:e.fs,commands:e.commands,limits:e.limits,execFn:e.exec,executeScript:this.executeScript.bind(this),executeStatement:this.executeStatement.bind(this),executeCommand:this.executeCommand.bind(this),fetch:e.fetch,sleep:e.sleep}}async executeScript(e){let n="",r="",s=0;for(let o of e.statements)try{let i=await this.executeStatement(o);n+=i.stdout,r+=i.stderr,s=i.exitCode,this.ctx.state.lastExitCode=s,this.ctx.state.env["?"]=String(s)}catch(i){if(i instanceof k)throw i.prependOutput(n,r),i;if(i instanceof z)throw i;if(i instanceof te)return n+=i.stdout,r+=i.stderr,s=i.exitCode,this.ctx.state.lastExitCode=s,this.ctx.state.env["?"]=String(s),{stdout:n,stderr:r,exitCode:s,env:{...this.ctx.state.env}};if(i instanceof J)return n+=i.stdout,r+=i.stderr,s=1,this.ctx.state.lastExitCode=s,this.ctx.state.env["?"]=String(s),{stdout:n,stderr:r,exitCode:s,env:{...this.ctx.state.env}};if(i instanceof Ee)return n+=i.stdout,r+=i.stderr,s=1,this.ctx.state.lastExitCode=s,this.ctx.state.env["?"]=String(s),{stdout:n,stderr:r,exitCode:s,env:{...this.ctx.state.env}};if(i instanceof U||i instanceof Y){if(this.ctx.state.loopDepth>0)throw i.prependOutput(n,r),i;n+=i.stdout,r+=i.stderr;continue}throw i instanceof G&&i.prependOutput(n,r),i}return{stdout:n,stderr:r,exitCode:s,env:{...this.ctx.state.env}}}async executeStatement(e){this.ctx.state.commandCount++,this.ctx.state.commandCount>this.ctx.limits.maxCommandCount&&ae(`too many commands executed (>${this.ctx.limits.maxCommandCount}), increase executionLimits.maxCommandCount`,"commands");let n="",r="",s=0,o=-1,i=!1;for(let a=0;a<e.pipelines.length;a++){let l=e.pipelines[a],c=a>0?e.operators[a-1]:null;if(c==="&&"&&s!==0||c==="||"&&s===0)continue;let f=await this.executePipeline(l);n+=f.stdout,r+=f.stderr,s=f.exitCode,o=a,i=l.negated,this.ctx.state.lastExitCode=s,this.ctx.state.env["?"]=String(s)}if(this.ctx.state.options.errexit&&s!==0&&o===e.pipelines.length-1&&!i&&!this.ctx.state.inCondition)throw new te(s,n,r);return x(n,r,s)}async executePipeline(e){let n="",r=C,s=0,o=[];for(let i=0;i<e.commands.length;i++){let a=e.commands[i],l=i===e.commands.length-1,c;try{c=await this.executeCommand(a,n)}catch(f){if(f instanceof Ee)c={stdout:f.stdout,stderr:f.stderr,exitCode:1};else if(f instanceof k&&e.commands.length>1)c={stdout:f.stdout,stderr:f.stderr,exitCode:f.exitCode};else throw f}o.push(c.exitCode),c.exitCode!==0&&(s=c.exitCode),l?r=c:(n=c.stdout,r={stdout:"",stderr:c.stderr,exitCode:c.exitCode})}for(let i of Object.keys(this.ctx.state.env))i.startsWith("PIPESTATUS_")&&delete this.ctx.state.env[i];for(let i=0;i<o.length;i++)this.ctx.state.env[`PIPESTATUS_${i}`]=String(o[i]);return this.ctx.state.env.PIPESTATUS__length=String(o.length),this.ctx.state.options.pipefail&&s!==0&&(r={...r,exitCode:s}),e.negated&&(r={...r,exitCode:r.exitCode===0?1:0}),r}async executeCommand(e,n){switch(e.type){case"SimpleCommand":return this.executeSimpleCommand(e,n);case"If":return On(this.ctx,e);case"For":return _n(this.ctx,e);case"CStyleFor":return Ln(this.ctx,e);case"While":return Tn(this.ctx,e,n);case"Until":return Fn(this.ctx,e);case"Case":return Wn(this.ctx,e);case"Subshell":return this.executeSubshell(e,n);case"Group":return this.executeGroup(e,n);case"FunctionDef":return Mn(this.ctx,e);case"ArithmeticCommand":return this.executeArithmeticCommand(e);case"ConditionalCommand":return this.executeConditionalCommand(e);default:return C}}async executeSimpleCommand(e,n){try{return await this.executeSimpleCommandInner(e,n)}catch(r){if(r instanceof W)return S(r.stderr);throw r}}async executeSimpleCommandInner(e,n){e.line!==void 0&&(this.ctx.state.currentLine=e.line),this.ctx.state.expansionStderr="";let r={};for(let l of e.assignments){let c=l.name;if(l.array){if(/\[.+\]$/.test(c))return x("",`bash: ${c}: cannot assign list to array member
123
+ `,o=1,r="";break}}catch{}await t.fs.appendFile(l,r+s),r="",s="";break}}}return x(r,s,o)}var He=class{ctx;constructor(e,n){this.ctx={state:n,fs:e.fs,commands:e.commands,limits:e.limits,execFn:e.exec,executeScript:this.executeScript.bind(this),executeStatement:this.executeStatement.bind(this),executeCommand:this.executeCommand.bind(this),fetch:e.fetch,sleep:e.sleep,trace:e.trace}}async executeScript(e){let n="",r="",s=0;for(let o of e.statements)try{let i=await this.executeStatement(o);n+=i.stdout,r+=i.stderr,s=i.exitCode,this.ctx.state.lastExitCode=s,this.ctx.state.env["?"]=String(s)}catch(i){if(i instanceof k)throw i.prependOutput(n,r),i;if(i instanceof z)throw i;if(i instanceof te)return n+=i.stdout,r+=i.stderr,s=i.exitCode,this.ctx.state.lastExitCode=s,this.ctx.state.env["?"]=String(s),{stdout:n,stderr:r,exitCode:s,env:{...this.ctx.state.env}};if(i instanceof J)return n+=i.stdout,r+=i.stderr,s=1,this.ctx.state.lastExitCode=s,this.ctx.state.env["?"]=String(s),{stdout:n,stderr:r,exitCode:s,env:{...this.ctx.state.env}};if(i instanceof Ee)return n+=i.stdout,r+=i.stderr,s=1,this.ctx.state.lastExitCode=s,this.ctx.state.env["?"]=String(s),{stdout:n,stderr:r,exitCode:s,env:{...this.ctx.state.env}};if(i instanceof U||i instanceof Y){if(this.ctx.state.loopDepth>0)throw i.prependOutput(n,r),i;n+=i.stdout,r+=i.stderr;continue}throw i instanceof G&&i.prependOutput(n,r),i}return{stdout:n,stderr:r,exitCode:s,env:{...this.ctx.state.env}}}async executeStatement(e){this.ctx.state.commandCount++,this.ctx.state.commandCount>this.ctx.limits.maxCommandCount&&ae(`too many commands executed (>${this.ctx.limits.maxCommandCount}), increase executionLimits.maxCommandCount`,"commands");let n="",r="",s=0,o=-1,i=!1;for(let a=0;a<e.pipelines.length;a++){let l=e.pipelines[a],c=a>0?e.operators[a-1]:null;if(c==="&&"&&s!==0||c==="||"&&s===0)continue;let f=await this.executePipeline(l);n+=f.stdout,r+=f.stderr,s=f.exitCode,o=a,i=l.negated,this.ctx.state.lastExitCode=s,this.ctx.state.env["?"]=String(s)}if(this.ctx.state.options.errexit&&s!==0&&o===e.pipelines.length-1&&!i&&!this.ctx.state.inCondition)throw new te(s,n,r);return x(n,r,s)}async executePipeline(e){let n="",r=C,s=0,o=[];for(let i=0;i<e.commands.length;i++){let a=e.commands[i],l=i===e.commands.length-1,c;try{c=await this.executeCommand(a,n)}catch(f){if(f instanceof Ee)c={stdout:f.stdout,stderr:f.stderr,exitCode:1};else if(f instanceof k&&e.commands.length>1)c={stdout:f.stdout,stderr:f.stderr,exitCode:f.exitCode};else throw f}o.push(c.exitCode),c.exitCode!==0&&(s=c.exitCode),l?r=c:(n=c.stdout,r={stdout:"",stderr:c.stderr,exitCode:c.exitCode})}for(let i of Object.keys(this.ctx.state.env))i.startsWith("PIPESTATUS_")&&delete this.ctx.state.env[i];for(let i=0;i<o.length;i++)this.ctx.state.env[`PIPESTATUS_${i}`]=String(o[i]);return this.ctx.state.env.PIPESTATUS__length=String(o.length),this.ctx.state.options.pipefail&&s!==0&&(r={...r,exitCode:s}),e.negated&&(r={...r,exitCode:r.exitCode===0?1:0}),r}async executeCommand(e,n){switch(e.type){case"SimpleCommand":return this.executeSimpleCommand(e,n);case"If":return On(this.ctx,e);case"For":return _n(this.ctx,e);case"CStyleFor":return Ln(this.ctx,e);case"While":return Tn(this.ctx,e,n);case"Until":return Fn(this.ctx,e);case"Case":return Wn(this.ctx,e);case"Subshell":return this.executeSubshell(e,n);case"Group":return this.executeGroup(e,n);case"FunctionDef":return Mn(this.ctx,e);case"ArithmeticCommand":return this.executeArithmeticCommand(e);case"ConditionalCommand":return this.executeConditionalCommand(e);default:return C}}async executeSimpleCommand(e,n){try{return await this.executeSimpleCommandInner(e,n)}catch(r){if(r instanceof W)return S(r.stderr);throw r}}async executeSimpleCommandInner(e,n){e.line!==void 0&&(this.ctx.state.currentLine=e.line),this.ctx.state.expansionStderr="";let r={};for(let l of e.assignments){let c=l.name;if(l.array){if(/\[.+\]$/.test(c))return x("",`bash: ${c}: cannot assign list to array member
124
124
  `,1);let w=he(this.ctx,c);if(w)return w;let p=[];for(let g of l.array){let b=await Ge(this.ctx,g);p.push(...b.values)}let E=0;if(l.append){let g=F(this.ctx,c);g.length>0&&(E=Math.max(...g.map(([N])=>typeof N=="number"?N:0))+1)}else{let g=`${c}_`;for(let b of Object.keys(this.ctx.state.env))b.startsWith(g)&&!b.includes("__")&&delete this.ctx.state.env[b]}for(let g=0;g<p.length;g++)this.ctx.state.env[`${c}_${E+g}`]=p[g];l.append||(this.ctx.state.env[`${c}__length`]=String(p.length));continue}let f=l.value?await I(this.ctx,l.value):"";if(c.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[\]$/))return x("",`bash: ${c}: bad array subscript
125
125
  `,1);let h=c.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(h){let w=h[1],p=h[2],E=he(this.ctx,w);if(E)return E;let g=this.ctx.state.associativeArrays?.has(w),b;if(g){let R;if(p.startsWith("'")&&p.endsWith("'"))R=p.slice(1,-1);else if(p.startsWith('"')&&p.endsWith('"')){let D=p.slice(1,-1),L=new M().parseWordFromString(D,!0,!1);R=await I(this.ctx,L)}else if(p.includes("$")){let ye=new M().parseWordFromString(p,!1,!1);R=await I(this.ctx,ye)}else R=p;b=`${w}_${R}`}else{let R;if(/^-?\d+$/.test(p))R=Number.parseInt(p,10);else{try{let D=new M,ye=T(D,p);R=$(this.ctx,ye.expression)}catch{let D=this.ctx.state.env[p];R=D?Number.parseInt(D,10):0}Number.isNaN(R)&&(R=0)}if(R<0){let D=F(this.ctx,w);if(D.length===0)return x("",`bash: ${w}[${p}]: bad array subscript
126
126
  `,1);if(R=Math.max(...D.map(([L])=>typeof L=="number"?L:0))+1+R,R<0)return x("",`bash: ${w}[${p}]: bad array subscript
@@ -131,7 +131,7 @@ ${ot}`):(ar(t,e.slice(n)),C)}return C}function ar(t,e){let n=1;for(;t.state.env[
131
131
  `)}}let s=await I(this.ctx,e.name),o=[],i=[];for(let l of e.args){let c=await Ge(this.ctx,l);for(let f of c.values)o.push(f),i.push(c.quoted)}if(!s){if(e.name.parts.every(c=>c.type==="CommandSubstitution"||c.type==="ParameterExpansion"||c.type==="ArithmeticExpansion")){if(o.length>0){let c=o.shift();return i.shift(),await this.runCommand(c,o,i,n)}return x("","",this.ctx.state.lastExitCode)}return S(`bash: : command not found
132
132
  `,127)}let a=await this.runCommand(s,o,i,n);a=await zn(this.ctx,a,e.redirections),this.ctx.state.lastArg=o.length>0?o[o.length-1]:s;for(let[l,c]of Object.entries(r))c===void 0?delete this.ctx.state.env[l]:this.ctx.state.env[l]=c;return this.ctx.state.expansionStderr&&(a={...a,stderr:this.ctx.state.expansionStderr+a.stderr},this.ctx.state.expansionStderr=""),a}async runCommand(e,n,r,s,o=!1){if(e==="cd")return await Zt(this.ctx,n);if(e==="export")return tr(this.ctx,n);if(e==="unset")return ur(this.ctx,n);if(e==="exit")return er(this.ctx,n);if(e==="local")return nr(this.ctx,n);if(e==="set")return cr(this.ctx,n);if(e==="break")return qt(this.ctx,n);if(e==="continue")return Qt(this.ctx,n);if(e==="return")return or(this.ctx,n);if(e==="eval")return Jt(this.ctx,n);if(e==="shift")return lr(this.ctx,n);if(e==="source"||e===".")return fr(this.ctx,n);if(e==="read")return ir(this.ctx,n,s);if(e==="mapfile"||e==="readarray")return sr(this.ctx,n,s);if(e==="declare"||e==="typeset")return Xt(this.ctx,n);if(e==="readonly")return Yt(this.ctx,n);if(!o){let f=this.ctx.state.functions.get(e);if(f)return Bn(this.ctx,f,n)}if(e===":"||e==="true")return C;if(e==="false")return _(!1);if(e==="let")return rr(this.ctx,n);if(e==="command"){if(n.length===0)return C;let f=n;for(;f.length>0&&f[0].startsWith("-");)f=f.slice(1);if(f.length===0)return C;let[d,...h]=f;return this.runCommand(d,h,[],s,!0)}if(e==="builtin"){if(n.length===0)return C;let[f,...d]=n;return this.runCommand(f,d,[],s)}if(e==="shopt")return C;if(e==="exec"){if(n.length===0)return C;let[f,...d]=n;return this.runCommand(f,d,[],s)}if(e==="wait")return C;if(e==="type")return this.handleType(n);if(e==="[["){let f=n.lastIndexOf("]]");if(f!==-1){let d=n.slice(0,f);return ke(this.ctx,d)}return S("bash: [[: missing `]]'\n",2)}if(e==="["||e==="test"){let f=n;if(e==="["){if(n[n.length-1]!=="]")return S("[: missing `]'\n",2);f=n.slice(0,-1)}return ke(this.ctx,f)}let i=await this.resolveCommand(e);if(!i)return Ir(e)?S(`bash: ${e}: command not available in browser environments. Exclude '${e}' from your commands or use the Node.js bundle.
133
133
  `,127):S(`bash: ${e}: command not found
134
- `,127);let{cmd:a,path:l}=i,c={fs:this.ctx.fs,cwd:this.ctx.state.cwd,env:this.ctx.state.env,stdin:s,limits:this.ctx.limits,exec:this.ctx.execFn,fetch:this.ctx.fetch,getRegisteredCommands:()=>Array.from(this.ctx.commands.keys()),sleep:this.ctx.sleep};try{return await a.execute(n,c)}catch(f){return S(`${e}: ${ce(f)}
134
+ `,127);let{cmd:a,path:l}=i,c={fs:this.ctx.fs,cwd:this.ctx.state.cwd,env:this.ctx.state.env,stdin:s,limits:this.ctx.limits,exec:this.ctx.execFn,fetch:this.ctx.fetch,getRegisteredCommands:()=>Array.from(this.ctx.commands.keys()),sleep:this.ctx.sleep,trace:this.ctx.trace};try{return await a.execute(n,c)}catch(f){return S(`${e}: ${ce(f)}
135
135
  `)}}async resolveCommand(e){if(e.includes("/")){let o=this.ctx.fs.resolvePath(this.ctx.state.cwd,e);if(!await this.ctx.fs.exists(o))return null;let i=o.split("/").pop()||e,a=this.ctx.commands.get(i);return a?{cmd:a,path:o}:null}let r=(this.ctx.state.env.PATH||"/bin:/usr/bin").split(":");for(let o of r){if(!o)continue;let i=`${o}/${e}`;if(await this.ctx.fs.exists(i)){let a=this.ctx.commands.get(e);if(a)return{cmd:a,path:i}}}if(!await this.ctx.fs.exists("/bin")){let o=this.ctx.commands.get(e);if(o)return{cmd:o,path:`/bin/${e}`}}return null}async findCommandInPath(e){let n=[],s=(this.ctx.state.env.PATH||"/bin:/usr/bin").split(":");for(let o of s){if(!o)continue;let i=`${o}/${e}`;await this.ctx.fs.exists(i)&&n.push(i)}return n}handleType(e){let n=new Set(["if","then","else","elif","fi","case","esac","for","select","while","until","do","done","in","function","{","}","time","[[","]]","!"]),r=new Set(["cd","export","unset","exit","local","set","break","continue","return","eval","shift","source",".","read","declare","typeset","readonly",":","true","false","let","command","builtin","shopt","exec","wait","type","[","test"]),s="",o="",i=0;for(let a of e)n.has(a)?s+=`${a} is a shell keyword
136
136
  `:r.has(a)?s+=`${a} is a shell builtin
137
137
  `:this.ctx.state.functions.has(a)?s+=`${a} is a function
@@ -141,12 +141,12 @@ ${ot}`):(ar(t,e.slice(n)),C)}return C}function ar(t,e){let n=1;for(;t.state.env[
141
141
  `,1)}return this.ctx.state.env=r,this.ctx.state.cwd=s,this.ctx.state.loopDepth=o,this.ctx.state.parentHasLoopContext=i,this.ctx.state.groupStdin=a,x(l,c,f)}async executeGroup(e,n=""){let r="",s="",o=0,i=this.ctx.state.groupStdin;n&&(this.ctx.state.groupStdin=n);try{for(let a of e.body){let l=await this.executeStatement(a);r+=l.stdout,s+=l.stderr,o=l.exitCode}}catch(a){if(this.ctx.state.groupStdin=i,a instanceof z)throw a;if(qe(a)||a instanceof te||a instanceof k)throw a.prependOutput(r,s),a;return x(r,`${s}${ce(a)}
142
142
  `,1)}return this.ctx.state.groupStdin=i,x(r,s,o)}async executeArithmeticCommand(e){try{let n=await P(this.ctx,e.expression.expression);return _(n!==0)}catch(n){return S(`bash: arithmetic expression: ${n.message}
143
143
  `)}}async executeConditionalCommand(e){try{let n=await me(this.ctx,e.expression);return _(n)}catch(n){return S(`bash: conditional expression: ${n.message}
144
- `,2)}}};var pe={maxCallDepth:100,maxCommandCount:1e4,maxLoopIterations:1e4,maxAwkIterations:1e4,maxSedIterations:1e4,maxJqIterations:1e4,maxSqliteTimeoutMs:5e3};function Un(t){return t?{maxCallDepth:t.maxCallDepth??pe.maxCallDepth,maxCommandCount:t.maxCommandCount??pe.maxCommandCount,maxLoopIterations:t.maxLoopIterations??pe.maxLoopIterations,maxAwkIterations:t.maxAwkIterations??pe.maxAwkIterations,maxSedIterations:t.maxSedIterations??pe.maxSedIterations,maxJqIterations:t.maxJqIterations??pe.maxJqIterations,maxSqliteTimeoutMs:t.maxSqliteTimeoutMs??pe.maxSqliteTimeoutMs}:{...pe}}function Gn(t){try{let e=new URL(t);return{origin:e.origin,pathname:e.pathname,href:e.href}}catch{return null}}function ri(t){let e=Gn(t);return e?{origin:e.origin,pathPrefix:e.pathname}:null}function ni(t,e){let n=Gn(t);if(!n)return!1;let r=ri(e);return!r||n.origin!==r.origin?!1:r.pathPrefix==="/"||r.pathPrefix===""?!0:n.pathname.startsWith(r.pathPrefix)}function yr(t,e){return!e||e.length===0?!1:e.some(n=>ni(t,n))}var De=class extends Error{constructor(e){super(`Network access denied: URL not in allow-list: ${e}`),this.name="NetworkAccessDeniedError"}},Oe=class extends Error{constructor(e){super(`Too many redirects (max: ${e})`),this.name="TooManyRedirectsError"}},_e=class extends Error{constructor(e){super(`Redirect target not in allow-list: ${e}`),this.name="RedirectNotAllowedError"}},xt=class extends Error{constructor(e,n){super(`HTTP method '${e}' not allowed. Allowed methods: ${n.join(", ")}`),this.name="MethodNotAllowedError"}};var si=20,ii=3e4,oi=["GET","HEAD"],ai=new Set(["GET","HEAD","OPTIONS"]),ci=new Set([301,302,303,307,308]);function Er(t){let e=t.maxRedirects??si,n=t.timeoutMs??ii,r=t.dangerouslyAllowFullInternetAccess?["GET","HEAD","POST","PUT","DELETE","PATCH","OPTIONS"]:t.allowedMethods??oi;function s(a){if(!t.dangerouslyAllowFullInternetAccess&&!yr(a,t.allowedUrlPrefixes??[]))throw new De(a)}function o(a){if(t.dangerouslyAllowFullInternetAccess)return;let l=a.toUpperCase();if(!r.includes(l))throw new xt(l,r)}async function i(a,l={}){let c=l.method?.toUpperCase()??"GET";s(a),o(c);let f=a,d=0,h=l.followRedirects??!0,m=l.timeoutMs!==void 0?Math.min(l.timeoutMs,n):n;for(;;){let y=new AbortController,w=setTimeout(()=>y.abort(),m);try{let p={method:c,headers:l.headers,signal:y.signal,redirect:"manual"};l.body&&!ai.has(c)&&(p.body=l.body);let E=await fetch(f,p);if(ci.has(E.status)&&h){let g=E.headers.get("location");if(!g)return await Vn(E,f);let b=new URL(g,f).href;if(!t.dangerouslyAllowFullInternetAccess&&!yr(b,t.allowedUrlPrefixes??[]))throw new _e(b);if(d++,d>e)throw new Oe(e);f=b;continue}return await Vn(E,f)}finally{clearTimeout(w)}}}return i}async function Vn(t,e){let n={};return t.headers.forEach((r,s)=>{n[s.toLowerCase()]=r}),{status:t.status,statusText:t.statusText,headers:n,body:await t.text(),url:e}}var je=class{fs;commands=new Map;useDefaultLayout=!1;limits;secureFetch;sleepFn;logger;state;constructor(e={}){let n=e.fs??new we(e.files);this.fs=n,this.useDefaultLayout=!e.cwd&&!e.files;let r=e.cwd||(this.useDefaultLayout?"/home/user":"/"),s={HOME:this.useDefaultLayout?"/home/user":"/",PATH:"/bin:/usr/bin",IFS:`
145
- `,OSTYPE:"linux-gnu",MACHTYPE:"x86_64-pc-linux-gnu",HOSTTYPE:"x86_64",PWD:r,OLDPWD:r,...e.env};if(this.limits=Un({...e.executionLimits,...e.maxCallDepth!==void 0&&{maxCallDepth:e.maxCallDepth},...e.maxCommandCount!==void 0&&{maxCommandCount:e.maxCommandCount},...e.maxLoopIterations!==void 0&&{maxLoopIterations:e.maxLoopIterations}}),e.network&&(this.secureFetch=Er(e.network)),this.sleepFn=e.sleep,this.logger=e.logger,this.state={env:s,cwd:r,previousDir:"/home/user",functions:new Map,localScopes:[],callDepth:0,sourceDepth:0,commandCount:0,lastExitCode:0,lastArg:"",startTime:Date.now(),lastBackgroundPid:0,currentLine:1,options:{errexit:!1,pipefail:!1,nounset:!1,xtrace:!1,verbose:!1},inCondition:!1,loopDepth:0},vr(n,this.useDefaultLayout),r!=="/"&&n instanceof we)try{n.mkdirSync(r,{recursive:!0})}catch{}for(let o of xr(e.commands))this.registerCommand(o);if(e.network)for(let o of Sr())this.registerCommand(o);if(e.customCommands)for(let o of e.customCommands)br(o)?this.registerCommand(Nr(o)):this.registerCommand(o)}registerCommand(e){this.commands.set(e.name,e);let n=this.fs;if(typeof n.writeFileSync=="function")try{n.writeFileSync(`/bin/${e.name}`,`#!/bin/bash
144
+ `,2)}}};var pe={maxCallDepth:100,maxCommandCount:1e4,maxLoopIterations:1e4,maxAwkIterations:1e4,maxSedIterations:1e4,maxJqIterations:1e4,maxSqliteTimeoutMs:5e3};function Un(t){return t?{maxCallDepth:t.maxCallDepth??pe.maxCallDepth,maxCommandCount:t.maxCommandCount??pe.maxCommandCount,maxLoopIterations:t.maxLoopIterations??pe.maxLoopIterations,maxAwkIterations:t.maxAwkIterations??pe.maxAwkIterations,maxSedIterations:t.maxSedIterations??pe.maxSedIterations,maxJqIterations:t.maxJqIterations??pe.maxJqIterations,maxSqliteTimeoutMs:t.maxSqliteTimeoutMs??pe.maxSqliteTimeoutMs}:{...pe}}function Gn(t){try{let e=new URL(t);return{origin:e.origin,pathname:e.pathname,href:e.href}}catch{return null}}function ri(t){let e=Gn(t);return e?{origin:e.origin,pathPrefix:e.pathname}:null}function ni(t,e){let n=Gn(t);if(!n)return!1;let r=ri(e);return!r||n.origin!==r.origin?!1:r.pathPrefix==="/"||r.pathPrefix===""?!0:n.pathname.startsWith(r.pathPrefix)}function yr(t,e){return!e||e.length===0?!1:e.some(n=>ni(t,n))}var De=class extends Error{constructor(e){super(`Network access denied: URL not in allow-list: ${e}`),this.name="NetworkAccessDeniedError"}},Oe=class extends Error{constructor(e){super(`Too many redirects (max: ${e})`),this.name="TooManyRedirectsError"}},_e=class extends Error{constructor(e){super(`Redirect target not in allow-list: ${e}`),this.name="RedirectNotAllowedError"}},xt=class extends Error{constructor(e,n){super(`HTTP method '${e}' not allowed. Allowed methods: ${n.join(", ")}`),this.name="MethodNotAllowedError"}};var si=20,ii=3e4,oi=["GET","HEAD"],ai=new Set(["GET","HEAD","OPTIONS"]),ci=new Set([301,302,303,307,308]);function Er(t){let e=t.maxRedirects??si,n=t.timeoutMs??ii,r=t.dangerouslyAllowFullInternetAccess?["GET","HEAD","POST","PUT","DELETE","PATCH","OPTIONS"]:t.allowedMethods??oi;function s(a){if(!t.dangerouslyAllowFullInternetAccess&&!yr(a,t.allowedUrlPrefixes??[]))throw new De(a)}function o(a){if(t.dangerouslyAllowFullInternetAccess)return;let l=a.toUpperCase();if(!r.includes(l))throw new xt(l,r)}async function i(a,l={}){let c=l.method?.toUpperCase()??"GET";s(a),o(c);let f=a,d=0,h=l.followRedirects??!0,m=l.timeoutMs!==void 0?Math.min(l.timeoutMs,n):n;for(;;){let y=new AbortController,w=setTimeout(()=>y.abort(),m);try{let p={method:c,headers:l.headers,signal:y.signal,redirect:"manual"};l.body&&!ai.has(c)&&(p.body=l.body);let E=await fetch(f,p);if(ci.has(E.status)&&h){let g=E.headers.get("location");if(!g)return await Vn(E,f);let b=new URL(g,f).href;if(!t.dangerouslyAllowFullInternetAccess&&!yr(b,t.allowedUrlPrefixes??[]))throw new _e(b);if(d++,d>e)throw new Oe(e);f=b;continue}return await Vn(E,f)}finally{clearTimeout(w)}}}return i}async function Vn(t,e){let n={};return t.headers.forEach((r,s)=>{n[s.toLowerCase()]=r}),{status:t.status,statusText:t.statusText,headers:n,body:await t.text(),url:e}}var je=class{fs;commands=new Map;useDefaultLayout=!1;limits;secureFetch;sleepFn;traceFn;logger;state;constructor(e={}){let n=e.fs??new we(e.files);this.fs=n,this.useDefaultLayout=!e.cwd&&!e.files;let r=e.cwd||(this.useDefaultLayout?"/home/user":"/"),s={HOME:this.useDefaultLayout?"/home/user":"/",PATH:"/bin:/usr/bin",IFS:`
145
+ `,OSTYPE:"linux-gnu",MACHTYPE:"x86_64-pc-linux-gnu",HOSTTYPE:"x86_64",PWD:r,OLDPWD:r,...e.env};if(this.limits=Un({...e.executionLimits,...e.maxCallDepth!==void 0&&{maxCallDepth:e.maxCallDepth},...e.maxCommandCount!==void 0&&{maxCommandCount:e.maxCommandCount},...e.maxLoopIterations!==void 0&&{maxLoopIterations:e.maxLoopIterations}}),e.network&&(this.secureFetch=Er(e.network)),this.sleepFn=e.sleep,this.traceFn=e.trace,this.logger=e.logger,this.state={env:s,cwd:r,previousDir:"/home/user",functions:new Map,localScopes:[],callDepth:0,sourceDepth:0,commandCount:0,lastExitCode:0,lastArg:"",startTime:Date.now(),lastBackgroundPid:0,currentLine:1,options:{errexit:!1,pipefail:!1,nounset:!1,xtrace:!1,verbose:!1},inCondition:!1,loopDepth:0},vr(n,this.useDefaultLayout),r!=="/"&&n instanceof we)try{n.mkdirSync(r,{recursive:!0})}catch{}for(let o of xr(e.commands))this.registerCommand(o);if(e.network)for(let o of Sr())this.registerCommand(o);if(e.customCommands)for(let o of e.customCommands)br(o)?this.registerCommand(Nr(o)):this.registerCommand(o)}registerCommand(e){this.commands.set(e.name,e);let n=this.fs;if(typeof n.writeFileSync=="function")try{n.writeFileSync(`/bin/${e.name}`,`#!/bin/bash
146
146
  # Built-in command: ${e.name}
147
147
  `)}catch{}}logResult(e){return this.logger&&(e.stdout&&this.logger.debug("stdout",{output:e.stdout}),e.stderr&&this.logger.info("stderr",{output:e.stderr}),this.logger.info("exit",{exitCode:e.exitCode})),e}async exec(e,n){if(this.state.callDepth===0&&(this.state.commandCount=0),this.state.commandCount++,this.state.commandCount>this.limits.maxCommandCount)return{stdout:"",stderr:`bash: maximum command count (${this.limits.maxCommandCount}) exceeded (possible infinite loop). Increase with executionLimits.maxCommandCount option.
148
148
  `,exitCode:1,env:{...this.state.env,...n?.env}};if(!e.trim())return{stdout:"",stderr:"",exitCode:0,env:{...this.state.env,...n?.env}};this.logger?.info("exec",{command:e});let r=n?.cwd??this.state.cwd,s={...this.state,env:{...this.state.env,...n?.env,...n?.cwd?{PWD:n.cwd}:{}},cwd:r,functions:new Map(this.state.functions),localScopes:[...this.state.localScopes],options:{...this.state.options}},o=e;n?.rawScript||(o=e.split(`
149
149
  `).map(a=>a.trimStart()).join(`
150
- `));try{let i=ue(o),a={fs:this.fs,commands:this.commands,limits:this.limits,exec:this.exec.bind(this),fetch:this.secureFetch,sleep:this.sleepFn},c=await new He(a,s).executeScript(i);return this.logResult(c)}catch(i){if(i instanceof k)return this.logResult({stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode,env:{...this.state.env,...n?.env}});if(i instanceof W)return this.logResult({stdout:i.stdout,stderr:i.stderr,exitCode:1,env:{...this.state.env,...n?.env}});if(i instanceof z)return this.logResult({stdout:i.stdout,stderr:i.stderr,exitCode:z.EXIT_CODE,env:{...this.state.env,...n?.env}});if(i.name==="ParseException")return this.logResult({stdout:"",stderr:`bash: syntax error: ${i.message}
150
+ `));try{let i=ue(o),a={fs:this.fs,commands:this.commands,limits:this.limits,exec:this.exec.bind(this),fetch:this.secureFetch,sleep:this.sleepFn,trace:this.traceFn},c=await new He(a,s).executeScript(i);return this.logResult(c)}catch(i){if(i instanceof k)return this.logResult({stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode,env:{...this.state.env,...n?.env}});if(i instanceof W)return this.logResult({stdout:i.stdout,stderr:i.stderr,exitCode:1,env:{...this.state.env,...n?.env}});if(i instanceof z)return this.logResult({stdout:i.stdout,stderr:i.stderr,exitCode:z.EXIT_CODE,env:{...this.state.env,...n?.env}});if(i.name==="ParseException")return this.logResult({stdout:"",stderr:`bash: syntax error: ${i.message}
151
151
  `,exitCode:2,env:{...this.state.env,...n?.env}});if(i instanceof RangeError)return this.logResult({stdout:"",stderr:`bash: ${i.message}
152
152
  `,exitCode:1,env:{...this.state.env,...n?.env}});throw i}}async readFile(e){return this.fs.readFile(this.fs.resolvePath(this.state.cwd,e))}async writeFile(e,n){return this.fs.writeFile(this.fs.resolvePath(this.state.cwd,e),n)}getCwd(){return this.state.cwd}getEnv(){return{...this.state.env}}};import*as B from"node:fs";import*as Le from"node:path";var li="/home/user/project",Te=class{root;mountPoint;readOnly;memory=new Map;deleted=new Set;constructor(e){this.root=Le.resolve(e.root);let n=e.mountPoint??li;if(this.mountPoint=n==="/"?"/":n.replace(/\/+$/,""),!this.mountPoint.startsWith("/"))throw new Error(`Mount point must be an absolute path: ${n}`);if(this.readOnly=e.readOnly??!1,!B.existsSync(this.root))throw new Error(`OverlayFs root does not exist: ${this.root}`);if(!B.statSync(this.root).isDirectory())throw new Error(`OverlayFs root is not a directory: ${this.root}`);this.createMountPointDirs()}assertWritable(e){if(this.readOnly)throw new Error(`EROFS: read-only file system, ${e}`)}createMountPointDirs(){let e=this.mountPoint.split("/").filter(Boolean),n="";for(let r of e)n+=`/${r}`,this.memory.has(n)||this.memory.set(n,{type:"directory",mode:493,mtime:new Date});this.memory.has("/")||this.memory.set("/",{type:"directory",mode:493,mtime:new Date})}getMountPoint(){return this.mountPoint}mkdirSync(e,n){let s=this.normalizePath(e).split("/").filter(Boolean),o="";for(let i of s)o+=`/${i}`,this.memory.has(o)||this.memory.set(o,{type:"directory",mode:493,mtime:new Date})}writeFileSync(e,n){let r=this.normalizePath(e),s=this.getDirname(r);s!=="/"&&this.mkdirSync(s);let o=n instanceof Uint8Array?n:new TextEncoder().encode(n);this.memory.set(r,{type:"file",content:o,mode:420,mtime:new Date})}getDirname(e){let n=e.lastIndexOf("/");return n===0?"/":e.slice(0,n)}normalizePath(e){if(!e||e==="/")return"/";let n=e.endsWith("/")&&e!=="/"?e.slice(0,-1):e;n.startsWith("/")||(n=`/${n}`);let r=n.split("/").filter(o=>o&&o!=="."),s=[];for(let o of r)o===".."?s.pop():s.push(o);return`/${s.join("/")}`||"/"}getRelativeToMount(e){return this.mountPoint==="/"?e:e===this.mountPoint?"/":e.startsWith(`${this.mountPoint}/`)?e.slice(this.mountPoint.length):null}toRealPath(e){let n=this.normalizePath(e),r=this.getRelativeToMount(n);if(r===null)return null;let s=Le.join(this.root,r),o=Le.resolve(s);return!o.startsWith(this.root)&&o!==this.root.replace(/\/$/,"")?null:o}dirname(e){let n=this.normalizePath(e);if(n==="/")return"/";let r=n.lastIndexOf("/");return r===0?"/":n.slice(0,r)}ensureParentDirs(e){let n=this.dirname(e);n!=="/"&&(this.memory.has(n)||(this.ensureParentDirs(n),this.memory.set(n,{type:"directory",mode:493,mtime:new Date})),this.deleted.delete(n))}async existsInOverlay(e){let n=this.normalizePath(e);if(this.deleted.has(n))return!1;if(this.memory.has(n))return!0;let r=this.toRealPath(n);if(!r)return!1;try{return await B.promises.access(r),!0}catch{return!1}}async readFile(e,n){let r=await this.readFileBuffer(e),s=q(n);return Ne(r,s)}async readFileBuffer(e,n=new Set){let r=this.normalizePath(e);if(n.has(r))throw new Error(`ELOOP: too many levels of symbolic links, open '${e}'`);if(n.add(r),this.deleted.has(r))throw new Error(`ENOENT: no such file or directory, open '${e}'`);let s=this.memory.get(r);if(s){if(s.type==="symlink"){let i=this.resolveSymlink(r,s.target);return this.readFileBuffer(i,n)}if(s.type!=="file")throw new Error(`EISDIR: illegal operation on a directory, read '${e}'`);return s.content}let o=this.toRealPath(r);if(!o)throw new Error(`ENOENT: no such file or directory, open '${e}'`);try{let i=await B.promises.lstat(o);if(i.isSymbolicLink()){let l=await B.promises.readlink(o),c=this.resolveSymlink(r,l);return this.readFileBuffer(c,n)}if(i.isDirectory())throw new Error(`EISDIR: illegal operation on a directory, read '${e}'`);let a=await B.promises.readFile(o);return new Uint8Array(a)}catch(i){throw i.code==="ENOENT"?new Error(`ENOENT: no such file or directory, open '${e}'`):i}}async writeFile(e,n,r){this.assertWritable(`write '${e}'`);let s=this.normalizePath(e);this.ensureParentDirs(s);let o=q(r),i=re(n,o);this.memory.set(s,{type:"file",content:i,mode:420,mtime:new Date}),this.deleted.delete(s)}async appendFile(e,n,r){this.assertWritable(`append '${e}'`);let s=this.normalizePath(e),o=q(r),i=re(n,o),a;try{a=await this.readFileBuffer(s)}catch{a=new Uint8Array(0)}let l=new Uint8Array(a.length+i.length);l.set(a),l.set(i,a.length),this.ensureParentDirs(s),this.memory.set(s,{type:"file",content:l,mode:420,mtime:new Date}),this.deleted.delete(s)}async exists(e){return this.existsInOverlay(e)}async stat(e,n=new Set){let r=this.normalizePath(e);if(n.has(r))throw new Error(`ELOOP: too many levels of symbolic links, stat '${e}'`);if(n.add(r),this.deleted.has(r))throw new Error(`ENOENT: no such file or directory, stat '${e}'`);let s=this.memory.get(r);if(s){if(s.type==="symlink"){let a=this.resolveSymlink(r,s.target);return this.stat(a,n)}let i=0;return s.type==="file"&&(i=s.content.length),{isFile:s.type==="file",isDirectory:s.type==="directory",isSymbolicLink:!1,mode:s.mode,size:i,mtime:s.mtime}}let o=this.toRealPath(r);if(!o)throw new Error(`ENOENT: no such file or directory, stat '${e}'`);try{let i=await B.promises.stat(o);return{isFile:i.isFile(),isDirectory:i.isDirectory(),isSymbolicLink:!1,mode:i.mode,size:i.size,mtime:i.mtime}}catch(i){throw i.code==="ENOENT"?new Error(`ENOENT: no such file or directory, stat '${e}'`):i}}async lstat(e){let n=this.normalizePath(e);if(this.deleted.has(n))throw new Error(`ENOENT: no such file or directory, lstat '${e}'`);let r=this.memory.get(n);if(r){if(r.type==="symlink")return{isFile:!1,isDirectory:!1,isSymbolicLink:!0,mode:r.mode,size:r.target.length,mtime:r.mtime};let o=0;return r.type==="file"&&(o=r.content.length),{isFile:r.type==="file",isDirectory:r.type==="directory",isSymbolicLink:!1,mode:r.mode,size:o,mtime:r.mtime}}let s=this.toRealPath(n);if(!s)throw new Error(`ENOENT: no such file or directory, lstat '${e}'`);try{let o=await B.promises.lstat(s);return{isFile:o.isFile(),isDirectory:o.isDirectory(),isSymbolicLink:o.isSymbolicLink(),mode:o.mode,size:o.size,mtime:o.mtime}}catch(o){throw o.code==="ENOENT"?new Error(`ENOENT: no such file or directory, lstat '${e}'`):o}}resolveSymlink(e,n){if(n.startsWith("/"))return this.normalizePath(n);let r=this.dirname(e);return this.normalizePath(r==="/"?`/${n}`:`${r}/${n}`)}async mkdir(e,n){this.assertWritable(`mkdir '${e}'`);let r=this.normalizePath(e);if(await this.existsInOverlay(r)){if(!n?.recursive)throw new Error(`EEXIST: file already exists, mkdir '${e}'`);return}let o=this.dirname(r);if(o!=="/"&&!await this.existsInOverlay(o))if(n?.recursive)await this.mkdir(o,{recursive:!0});else throw new Error(`ENOENT: no such file or directory, mkdir '${e}'`);this.memory.set(r,{type:"directory",mode:493,mtime:new Date}),this.deleted.delete(r)}async readdirCore(e,n){if(this.deleted.has(n))throw new Error(`ENOENT: no such file or directory, scandir '${e}'`);let r=new Map,s=new Set,o=n==="/"?"/":`${n}/`;for(let a of this.deleted)if(a.startsWith(o)){let l=a.slice(o.length),c=l.split("/")[0];c&&!l.includes("/",c.length)&&s.add(c)}for(let[a,l]of this.memory)if(a!==n&&a.startsWith(o)){let c=a.slice(o.length),f=c.split("/")[0];f&&!s.has(f)&&!c.includes("/",1)&&r.set(f,{name:f,isFile:l.type==="file",isDirectory:l.type==="directory",isSymbolicLink:l.type==="symlink"})}let i=this.toRealPath(n);if(i)try{let a=await B.promises.readdir(i,{withFileTypes:!0});for(let l of a)!s.has(l.name)&&!r.has(l.name)&&r.set(l.name,{name:l.name,isFile:l.isFile(),isDirectory:l.isDirectory(),isSymbolicLink:l.isSymbolicLink()})}catch(a){if(a.code==="ENOENT"){if(!this.memory.has(n))throw new Error(`ENOENT: no such file or directory, scandir '${e}'`)}else if(a.code!=="ENOTDIR")throw a}return r}async readdir(e){let n=this.normalizePath(e),r=await this.readdirCore(e,n);return Array.from(r.keys()).sort((s,o)=>s<o?-1:s>o?1:0)}async readdirWithFileTypes(e){let n=this.normalizePath(e),r=await this.readdirCore(e,n);return Array.from(r.values()).sort((s,o)=>s.name<o.name?-1:s.name>o.name?1:0)}async rm(e,n){this.assertWritable(`rm '${e}'`);let r=this.normalizePath(e);if(!await this.existsInOverlay(r)){if(n?.force)return;throw new Error(`ENOENT: no such file or directory, rm '${e}'`)}try{if((await this.stat(r)).isDirectory){let i=await this.readdir(r);if(i.length>0){if(!n?.recursive)throw new Error(`ENOTEMPTY: directory not empty, rm '${e}'`);for(let a of i){let l=r==="/"?`/${a}`:`${r}/${a}`;await this.rm(l,n)}}}}catch{}this.deleted.add(r),this.memory.delete(r)}async cp(e,n,r){this.assertWritable(`cp '${n}'`);let s=this.normalizePath(e),o=this.normalizePath(n);if(!await this.existsInOverlay(s))throw new Error(`ENOENT: no such file or directory, cp '${e}'`);let a=await this.stat(s);if(a.isFile){let l=await this.readFileBuffer(s);await this.writeFile(o,l)}else if(a.isDirectory){if(!r?.recursive)throw new Error(`EISDIR: is a directory, cp '${e}'`);await this.mkdir(o,{recursive:!0});let l=await this.readdir(s);for(let c of l){let f=s==="/"?`/${c}`:`${s}/${c}`,d=o==="/"?`/${c}`:`${o}/${c}`;await this.cp(f,d,r)}}}async mv(e,n){this.assertWritable(`mv '${n}'`),await this.cp(e,n,{recursive:!0}),await this.rm(e,{recursive:!0})}resolvePath(e,n){if(n.startsWith("/"))return this.normalizePath(n);let r=e==="/"?`/${n}`:`${e}/${n}`;return this.normalizePath(r)}getAllPaths(){let e=new Set(this.memory.keys());for(let n of this.deleted)e.delete(n);return this.scanRealFs("/",e),Array.from(e)}scanRealFs(e,n){if(this.deleted.has(e))return;let r=this.toRealPath(e);if(r)try{let s=B.readdirSync(r);for(let o of s){let i=e==="/"?`/${o}`:`${e}/${o}`;if(this.deleted.has(i))continue;n.add(i);let a=Le.join(r,o);B.statSync(a).isDirectory()&&this.scanRealFs(i,n)}}catch{}}async chmod(e,n){this.assertWritable(`chmod '${e}'`);let r=this.normalizePath(e);if(!await this.existsInOverlay(r))throw new Error(`ENOENT: no such file or directory, chmod '${e}'`);let o=this.memory.get(r);if(o){o.mode=n;return}let i=await this.stat(r);if(i.isFile){let a=await this.readFileBuffer(r);this.memory.set(r,{type:"file",content:a,mode:n,mtime:new Date})}else i.isDirectory&&this.memory.set(r,{type:"directory",mode:n,mtime:new Date})}async symlink(e,n){this.assertWritable(`symlink '${n}'`);let r=this.normalizePath(n);if(await this.existsInOverlay(r))throw new Error(`EEXIST: file already exists, symlink '${n}'`);this.ensureParentDirs(r),this.memory.set(r,{type:"symlink",target:e,mode:511,mtime:new Date}),this.deleted.delete(r)}async link(e,n){this.assertWritable(`link '${n}'`);let r=this.normalizePath(e),s=this.normalizePath(n);if(!await this.existsInOverlay(r))throw new Error(`ENOENT: no such file or directory, link '${e}'`);let i=await this.stat(r);if(!i.isFile)throw new Error(`EPERM: operation not permitted, link '${e}'`);if(await this.existsInOverlay(s))throw new Error(`EEXIST: file already exists, link '${n}'`);let l=await this.readFileBuffer(r);this.ensureParentDirs(s),this.memory.set(s,{type:"file",content:l,mode:i.mode,mtime:new Date}),this.deleted.delete(s)}async readlink(e){let n=this.normalizePath(e);if(this.deleted.has(n))throw new Error(`ENOENT: no such file or directory, readlink '${e}'`);let r=this.memory.get(n);if(r){if(r.type!=="symlink")throw new Error(`EINVAL: invalid argument, readlink '${e}'`);return r.target}let s=this.toRealPath(n);if(!s)throw new Error(`ENOENT: no such file or directory, readlink '${e}'`);try{return await B.promises.readlink(s)}catch(o){throw o.code==="ENOENT"?new Error(`ENOENT: no such file or directory, readlink '${e}'`):o.code==="EINVAL"?new Error(`EINVAL: invalid argument, readlink '${e}'`):o}}};import*as v from"node:fs";import*as ee from"node:path";var St=class{root;constructor(e){if(this.root=ee.resolve(e.root),!v.existsSync(this.root))throw new Error(`ReadWriteFs root does not exist: ${this.root}`);if(!v.statSync(this.root).isDirectory())throw new Error(`ReadWriteFs root is not a directory: ${this.root}`)}toRealPath(e){let n=this.normalizePath(e),r=ee.join(this.root,n);return ee.resolve(r)}normalizePath(e){if(!e||e==="/")return"/";let n=e.endsWith("/")&&e!=="/"?e.slice(0,-1):e;n.startsWith("/")||(n=`/${n}`);let r=n.split("/").filter(o=>o&&o!=="."),s=[];for(let o of r)o===".."?s.pop():s.push(o);return`/${s.join("/")}`||"/"}async readFile(e,n){let r=await this.readFileBuffer(e),s=q(n);return Ne(r,s)}async readFileBuffer(e){let n=this.toRealPath(e);try{let r=await v.promises.readFile(n);return new Uint8Array(r)}catch(r){let s=r;throw s.code==="ENOENT"?new Error(`ENOENT: no such file or directory, open '${e}'`):s.code==="EISDIR"?new Error(`EISDIR: illegal operation on a directory, read '${e}'`):r}}async writeFile(e,n,r){let s=this.toRealPath(e),o=q(r),i=re(n,o),a=ee.dirname(s);await v.promises.mkdir(a,{recursive:!0}),await v.promises.writeFile(s,i)}async appendFile(e,n,r){let s=this.toRealPath(e),o=q(r),i=re(n,o),a=ee.dirname(s);await v.promises.mkdir(a,{recursive:!0}),await v.promises.appendFile(s,i)}async exists(e){let n=this.toRealPath(e);try{return await v.promises.access(n),!0}catch{return!1}}async stat(e){let n=this.toRealPath(e);try{let r=await v.promises.stat(n);return{isFile:r.isFile(),isDirectory:r.isDirectory(),isSymbolicLink:!1,mode:r.mode,size:r.size,mtime:r.mtime}}catch(r){throw r.code==="ENOENT"?new Error(`ENOENT: no such file or directory, stat '${e}'`):r}}async lstat(e){let n=this.toRealPath(e);try{let r=await v.promises.lstat(n);return{isFile:r.isFile(),isDirectory:r.isDirectory(),isSymbolicLink:r.isSymbolicLink(),mode:r.mode,size:r.size,mtime:r.mtime}}catch(r){throw r.code==="ENOENT"?new Error(`ENOENT: no such file or directory, lstat '${e}'`):r}}async mkdir(e,n){let r=this.toRealPath(e);try{await v.promises.mkdir(r,{recursive:n?.recursive})}catch(s){let o=s;throw o.code==="EEXIST"?new Error(`EEXIST: file already exists, mkdir '${e}'`):o.code==="ENOENT"?new Error(`ENOENT: no such file or directory, mkdir '${e}'`):s}}async readdir(e){return(await this.readdirWithFileTypes(e)).map(r=>r.name)}async readdirWithFileTypes(e){let n=this.toRealPath(e);try{return(await v.promises.readdir(n,{withFileTypes:!0})).map(s=>({name:s.name,isFile:s.isFile(),isDirectory:s.isDirectory(),isSymbolicLink:s.isSymbolicLink()})).sort((s,o)=>s.name<o.name?-1:s.name>o.name?1:0)}catch(r){let s=r;throw s.code==="ENOENT"?new Error(`ENOENT: no such file or directory, scandir '${e}'`):s.code==="ENOTDIR"?new Error(`ENOTDIR: not a directory, scandir '${e}'`):r}}async rm(e,n){let r=this.toRealPath(e);try{await v.promises.rm(r,{recursive:n?.recursive??!1,force:n?.force??!1})}catch(s){let o=s;throw o.code==="ENOENT"&&!n?.force?new Error(`ENOENT: no such file or directory, rm '${e}'`):o.code==="ENOTEMPTY"?new Error(`ENOTEMPTY: directory not empty, rm '${e}'`):s}}async cp(e,n,r){let s=this.toRealPath(e),o=this.toRealPath(n);try{await v.promises.cp(s,o,{recursive:r?.recursive??!1})}catch(i){let a=i;throw a.code==="ENOENT"?new Error(`ENOENT: no such file or directory, cp '${e}'`):a.code==="EISDIR"?new Error(`EISDIR: is a directory, cp '${e}'`):i}}async mv(e,n){let r=this.toRealPath(e),s=this.toRealPath(n),o=ee.dirname(s);await v.promises.mkdir(o,{recursive:!0});try{await v.promises.rename(r,s)}catch(i){let a=i;if(a.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, mv '${e}'`);if(a.code==="EXDEV"){await this.cp(e,n,{recursive:!0}),await this.rm(e,{recursive:!0});return}throw i}}resolvePath(e,n){if(n.startsWith("/"))return this.normalizePath(n);let r=e==="/"?`/${n}`:`${e}/${n}`;return this.normalizePath(r)}getAllPaths(){let e=[];return this.scanDir("/",e),e}scanDir(e,n){let r=this.toRealPath(e);try{let s=v.readdirSync(r);for(let o of s){let i=e==="/"?`/${o}`:`${e}/${o}`;n.push(i);let a=ee.join(r,o);v.statSync(a).isDirectory()&&this.scanDir(i,n)}}catch{}}async chmod(e,n){let r=this.toRealPath(e);try{await v.promises.chmod(r,n)}catch(s){throw s.code==="ENOENT"?new Error(`ENOENT: no such file or directory, chmod '${e}'`):s}}async symlink(e,n){let r=this.toRealPath(n);try{await v.promises.symlink(e,r)}catch(s){throw s.code==="EEXIST"?new Error(`EEXIST: file already exists, symlink '${n}'`):s}}async link(e,n){let r=this.toRealPath(e),s=this.toRealPath(n);try{await v.promises.link(r,s)}catch(o){let i=o;throw i.code==="ENOENT"?new Error(`ENOENT: no such file or directory, link '${e}'`):i.code==="EEXIST"?new Error(`EEXIST: file already exists, link '${n}'`):i.code==="EPERM"?new Error(`EPERM: operation not permitted, link '${e}'`):o}}async readlink(e){let n=this.toRealPath(e);try{return await v.promises.readlink(n)}catch(r){let s=r;throw s.code==="ENOENT"?new Error(`ENOENT: no such file or directory, readlink '${e}'`):s.code==="EINVAL"?new Error(`EINVAL: invalid argument, readlink '${e}'`):r}}};var Fe=class{cmdId;cwd;startedAt;exitCode;bashEnv;cmdLine;env;explicitCwd;resultPromise;constructor(e,n,r,s,o=!1){this.cmdId=crypto.randomUUID(),this.cwd=r,this.startedAt=new Date,this.bashEnv=e,this.cmdLine=n,this.env=s,this.explicitCwd=o,this.resultPromise=this.execute()}async execute(){let e=this.env||this.explicitCwd?{cwd:this.explicitCwd?this.cwd:void 0,env:this.env}:void 0,n=await this.bashEnv.exec(this.cmdLine,e);return this.exitCode=n.exitCode,n}async*logs(){let e=await this.resultPromise;e.stdout&&(yield{type:"stdout",data:e.stdout,timestamp:new Date}),e.stderr&&(yield{type:"stderr",data:e.stderr,timestamp:new Date})}async wait(){return await this.resultPromise,this}async output(){let e=await this.resultPromise;return e.stdout+e.stderr}async stdout(){return(await this.resultPromise).stdout}async stderr(){return(await this.resultPromise).stderr}async kill(){}};var bt=class t{bashEnv;constructor(e){this.bashEnv=e}static async create(e){let n=e?.fs;if(e?.overlayRoot){if(e?.fs)throw new Error("Cannot specify both 'fs' and 'overlayRoot' options");n=new Te({root:e.overlayRoot})}let r=new je({env:e?.env,cwd:e?.cwd,fs:n,maxCallDepth:e?.maxCallDepth,maxCommandCount:e?.maxCommandCount,maxLoopIterations:e?.maxLoopIterations,network:e?.network});return new t(r)}async runCommand(e,n){let r=n?.cwd??this.bashEnv.getCwd(),s=n?.cwd!==void 0;return new Fe(this.bashEnv,e,r,n?.env,s)}async writeFiles(e){for(let[n,r]of Object.entries(e)){let s;typeof r=="string"?s=r:r.encoding==="base64"?s=Buffer.from(r.content,"base64").toString("utf-8"):s=r.content;let o=n.substring(0,n.lastIndexOf("/"))||"/";o!=="/"&&await this.bashEnv.exec(`mkdir -p ${o}`),await this.bashEnv.writeFile(n,s)}}async readFile(e,n){let r=await this.bashEnv.readFile(e);return n==="base64"?Buffer.from(r).toString("base64"):r}async mkDir(e,n){let r=n?.recursive?"-p":"";await this.bashEnv.exec(`mkdir ${r} ${e}`)}async stop(){}async extendTimeout(e){}get domain(){}get bashEnvInstance(){return this.bashEnv}};export{je as Bash,we as InMemoryFs,De as NetworkAccessDeniedError,Te as OverlayFs,St as ReadWriteFs,_e as RedirectNotAllowedError,bt as Sandbox,Fe as SandboxCommand,Oe as TooManyRedirectsError,qn as defineCommand,Hn as getCommandNames,jn as getNetworkCommandNames};
@@ -9,4 +9,61 @@ export declare function evaluateExpressionWithPrune(expr: Expression, ctx: EvalC
9
9
  * vs just type info (isFile/isDirectory) which can come from dirent
10
10
  */
11
11
  export declare function expressionNeedsStatMetadata(expr: Expression | null): boolean;
12
+ /**
13
+ * Check if an expression uses -empty (needs directory entry count)
14
+ */
15
+ export declare function expressionNeedsEmptyCheck(expr: Expression | null): boolean;
16
+ /**
17
+ * Analyze a path expression for pruning opportunities.
18
+ * For patterns like "*\/pulls\/*.json", we can skip descending into "pulls" subdirectories
19
+ * since files must be directly inside "pulls".
20
+ */
21
+ export interface PathPruningHint {
22
+ /** If set, when in a directory with this name, don't descend into subdirs */
23
+ terminalDirName: string | null;
24
+ /** If set, files must have this extension (e.g., ".json") */
25
+ requiredExtension: string | null;
26
+ }
27
+ /**
28
+ * Extract path pruning hints from an expression tree.
29
+ * Returns hints that can be used to skip unnecessary directory traversal.
30
+ */
31
+ export declare function extractPathPruningHints(expr: Expression | null): PathPruningHint;
12
32
  export declare function collectNewerRefs(expr: Expression | null): string[];
33
+ /**
34
+ * Context for early prune evaluation (before readdir).
35
+ * Only includes info available without reading directory contents or stat.
36
+ */
37
+ export interface EarlyEvalContext {
38
+ name: string;
39
+ relativePath: string;
40
+ isFile: boolean;
41
+ isDirectory: boolean;
42
+ }
43
+ /**
44
+ * Check if an expression is "simple" - only uses name/path/regex/type/prune/print.
45
+ * Simple expressions can be evaluated without creating EvalContext objects.
46
+ */
47
+ export declare function isSimpleExpression(expr: Expression | null): boolean;
48
+ /**
49
+ * Fast-path evaluator for simple expressions.
50
+ * Avoids creating EvalContext objects by taking arguments directly.
51
+ * Only use this when isSimpleExpression() returns true.
52
+ */
53
+ export declare function evaluateSimpleExpression(expr: Expression, name: string, relativePath: string, isFile: boolean, isDirectory: boolean): EvalResult;
54
+ /**
55
+ * Check if an expression contains -prune and can potentially be evaluated
56
+ * early (before readdir) to avoid unnecessary I/O.
57
+ */
58
+ export declare function expressionHasPrune(expr: Expression | null): boolean;
59
+ /**
60
+ * Evaluate an expression for early prune detection.
61
+ * Returns { shouldPrune: true } if we should skip reading this directory.
62
+ * Returns { shouldPrune: false } if we can't determine or shouldn't prune.
63
+ *
64
+ * This is used to avoid reading directory contents when we know we'll prune.
65
+ * For expressions that need stat info, we conservatively return false.
66
+ */
67
+ export declare function evaluateForEarlyPrune(expr: Expression | null, ctx: EarlyEvalContext): {
68
+ shouldPrune: boolean;
69
+ };
@@ -13,7 +13,7 @@ import type { ScriptNode } from "../ast/types.js";
13
13
  import type { IFileSystem } from "../fs/interface.js";
14
14
  import type { ExecutionLimits } from "../limits.js";
15
15
  import type { SecureFetch } from "../network/index.js";
16
- import type { CommandRegistry, ExecResult } from "../types.js";
16
+ import type { CommandRegistry, ExecResult, TraceCallback } from "../types.js";
17
17
  import type { InterpreterState } from "./types.js";
18
18
  export type { InterpreterContext, InterpreterState } from "./types.js";
19
19
  export interface InterpreterOptions {
@@ -28,6 +28,8 @@ export interface InterpreterOptions {
28
28
  fetch?: SecureFetch;
29
29
  /** Optional sleep function for testing with mock clocks */
30
30
  sleep?: (ms: number) => Promise<void>;
31
+ /** Optional trace callback for performance profiling */
32
+ trace?: TraceCallback;
31
33
  }
32
34
  export declare class Interpreter {
33
35
  private ctx;
@@ -5,7 +5,7 @@ import type { CommandNode, FunctionDefNode, ScriptNode, StatementNode } from "..
5
5
  import type { IFileSystem } from "../fs/interface.js";
6
6
  import type { ExecutionLimits } from "../limits.js";
7
7
  import type { SecureFetch } from "../network/index.js";
8
- import type { CommandRegistry, ExecResult } from "../types.js";
8
+ import type { CommandRegistry, ExecResult, TraceCallback } from "../types.js";
9
9
  export interface ShellOptions {
10
10
  /** set -e: Exit immediately if a command exits with non-zero status */
11
11
  errexit: boolean;
@@ -73,4 +73,6 @@ export interface InterpreterContext {
73
73
  fetch?: SecureFetch;
74
74
  /** Optional sleep function for testing with mock clocks */
75
75
  sleep?: (ms: number) => Promise<void>;
76
+ /** Optional trace callback for performance profiling */
77
+ trace?: TraceCallback;
76
78
  }
package/dist/types.d.ts CHANGED
@@ -39,6 +39,23 @@ export interface CommandExecOptions {
39
39
  * - `fetch` - Only when `network` option is configured in BashEnv
40
40
  * - `sleep` - Only when a custom sleep function is provided (e.g., for testing)
41
41
  */
42
+ /**
43
+ * Performance trace event for profiling command execution
44
+ */
45
+ export interface TraceEvent {
46
+ /** Event category (e.g., "find", "grep") */
47
+ category: string;
48
+ /** Event name (e.g., "readdir", "stat", "eval") */
49
+ name: string;
50
+ /** Duration in milliseconds */
51
+ durationMs: number;
52
+ /** Optional details (e.g., path, count) */
53
+ details?: Record<string, unknown>;
54
+ }
55
+ /**
56
+ * Trace callback function for receiving performance events
57
+ */
58
+ export type TraceCallback = (event: TraceEvent) => void;
42
59
  export interface CommandContext {
43
60
  /** Virtual filesystem interface for file operations */
44
61
  fs: IFileSystem;
@@ -53,6 +70,11 @@ export interface CommandContext {
53
70
  * Available when running commands via BashEnv interpreter.
54
71
  */
55
72
  limits?: Required<ExecutionLimits>;
73
+ /**
74
+ * Performance trace callback for profiling.
75
+ * If provided, commands emit timing events for analysis.
76
+ */
77
+ trace?: TraceCallback;
56
78
  /**
57
79
  * Execute a subcommand (e.g., for `xargs`, `bash -c`).
58
80
  * Available when running commands via BashEnv interpreter.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "just-bash",
3
- "version": "2.4.1",
3
+ "version": "2.4.3",
4
4
  "description": "A simulated bash environment with virtual filesystem",
5
5
  "repository": {
6
6
  "type": "git",
@@ -1,11 +0,0 @@
1
- #!/usr/bin/env node
2
- import{a as H}from"./chunk-26Q3PZQ6.js";import{a as J,b as U,c as q}from"./chunk-PM2DS2YW.js";import"./chunk-OBH7XN5N.js";import{a as _,b as V}from"./chunk-GTNBSMZR.js";import"./chunk-KGOUQS5A.js";function F(e,s){switch(e.type){case"name":return{matches:H(s.name,e.pattern,e.ignoreCase),pruned:!1,printed:!1};case"path":return{matches:H(s.relativePath,e.pattern,e.ignoreCase),pruned:!1,printed:!1};case"regex":try{let n=e.ignoreCase?"i":"";return{matches:new RegExp(e.pattern,n).test(s.relativePath),pruned:!1,printed:!1}}catch{return{matches:!1,pruned:!1,printed:!1}}case"type":return e.fileType==="f"?{matches:s.isFile,pruned:!1,printed:!1}:e.fileType==="d"?{matches:s.isDirectory,pruned:!1,printed:!1}:{matches:!1,pruned:!1,printed:!1};case"empty":return{matches:s.isEmpty,pruned:!1,printed:!1};case"mtime":{let r=(Date.now()-s.mtime)/(1e3*60*60*24),t;return e.comparison==="more"?t=r>e.days:e.comparison==="less"?t=r<e.days:t=Math.floor(r)===e.days,{matches:t,pruned:!1,printed:!1}}case"newer":{let n=s.newerRefTimes.get(e.refPath);return n===void 0?{matches:!1,pruned:!1,printed:!1}:{matches:s.mtime>n,pruned:!1,printed:!1}}case"size":{let n=e.value;switch(e.unit){case"c":n=e.value;break;case"k":n=e.value*1024;break;case"M":n=e.value*1024*1024;break;case"G":n=e.value*1024*1024*1024;break;case"b":n=e.value*512;break}let r;return e.comparison==="more"?r=s.size>n:e.comparison==="less"?r=s.size<n:e.unit==="b"?r=Math.ceil(s.size/512)===e.value:r=s.size===n,{matches:r,pruned:!1,printed:!1}}case"perm":{let n=s.mode&511,r=e.mode&511,t;return e.matchType==="exact"?t=n===r:e.matchType==="all"?t=(n&r)===r:t=(n&r)!==0,{matches:t,pruned:!1,printed:!1}}case"prune":return{matches:!0,pruned:!0,printed:!1};case"print":return{matches:!0,pruned:!1,printed:!0};case"not":{let n=F(e.expr,s);return{matches:!n.matches,pruned:n.pruned,printed:!1}}case"and":{let n=F(e.left,s);if(!n.matches)return{matches:!1,pruned:n.pruned,printed:!1};let r=F(e.right,s);return{matches:r.matches,pruned:n.pruned||r.pruned,printed:n.printed||r.printed}}case"or":{let n=F(e.left,s);if(n.matches)return n;let r=F(e.right,s);return{matches:r.matches,pruned:n.pruned||r.pruned,printed:r.printed}}}}function z(e){if(!e)return!1;switch(e.type){case"name":case"path":case"regex":case"type":case"prune":case"print":return!1;case"empty":case"mtime":case"newer":case"size":case"perm":return!0;case"not":return z(e.expr);case"and":case"or":return z(e.left)||z(e.right)}}function K(e){let s=[],n=r=>{r&&(r.type==="newer"?s.push(r.refPath):r.type==="not"?n(r.expr):(r.type==="and"||r.type==="or")&&(n(r.left),n(r.right)))};return n(e),s}function Q(e,s){let n=[],r=[],t=s;for(;t<e.length;){let a=e[t];if(a==="("||a==="\\("){n.push({type:"lparen"}),t++;continue}if(a===")"||a==="\\)"){n.push({type:"rparen"}),t++;continue}if(a==="-name"&&t+1<e.length)n.push({type:"expr",expr:{type:"name",pattern:e[++t]}});else if(a==="-iname"&&t+1<e.length)n.push({type:"expr",expr:{type:"name",pattern:e[++t],ignoreCase:!0}});else if(a==="-path"&&t+1<e.length)n.push({type:"expr",expr:{type:"path",pattern:e[++t]}});else if(a==="-ipath"&&t+1<e.length)n.push({type:"expr",expr:{type:"path",pattern:e[++t],ignoreCase:!0}});else if(a==="-regex"&&t+1<e.length)n.push({type:"expr",expr:{type:"regex",pattern:e[++t]}});else if(a==="-iregex"&&t+1<e.length)n.push({type:"expr",expr:{type:"regex",pattern:e[++t],ignoreCase:!0}});else if(a==="-type"&&t+1<e.length){let i=e[++t];if(i==="f"||i==="d")n.push({type:"expr",expr:{type:"type",fileType:i}});else return{expr:null,pathIndex:t,error:`find: Unknown argument to -type: ${i}
3
- `,actions:[]}}else if(a==="-empty")n.push({type:"expr",expr:{type:"empty"}});else if(a==="-mtime"&&t+1<e.length){let i=e[++t],c="exact",p=i;i.startsWith("+")?(c="more",p=i.slice(1)):i.startsWith("-")&&(c="less",p=i.slice(1));let u=parseInt(p,10);Number.isNaN(u)||n.push({type:"expr",expr:{type:"mtime",days:u,comparison:c}})}else if(a==="-newer"&&t+1<e.length){let i=e[++t];n.push({type:"expr",expr:{type:"newer",refPath:i}})}else if(a==="-size"&&t+1<e.length){let i=e[++t],c="exact",p=i;i.startsWith("+")?(c="more",p=i.slice(1)):i.startsWith("-")&&(c="less",p=i.slice(1));let u=p.match(/^(\d+)([ckMGb])?$/);if(u){let W=parseInt(u[1],10),E=u[2]||"b";n.push({type:"expr",expr:{type:"size",value:W,unit:E,comparison:c}})}}else if(a==="-perm"&&t+1<e.length){let i=e[++t],c="exact",p=i;i.startsWith("-")?(c="all",p=i.slice(1)):i.startsWith("/")&&(c="any",p=i.slice(1));let u=parseInt(p,8);Number.isNaN(u)||n.push({type:"expr",expr:{type:"perm",mode:u,matchType:c}})}else if(a==="-prune")n.push({type:"expr",expr:{type:"prune"}});else if(a==="-not"||a==="!")n.push({type:"not"});else if(a==="-o"||a==="-or")n.push({type:"op",op:"or"});else if(a==="-a"||a==="-and")n.push({type:"op",op:"and"});else if(a==="-maxdepth"||a==="-mindepth")t++;else if(a!=="-depth")if(a==="-exec"){let i=[];for(t++;t<e.length&&e[t]!==";"&&e[t]!=="+";)i.push(e[t]),t++;if(t>=e.length)return{expr:null,pathIndex:t,error:"find: missing argument to `-exec'\n",actions:[]};let c=e[t]==="+";r.push({type:"exec",command:i,batchMode:c})}else if(a==="-print")n.push({type:"expr",expr:{type:"print"}}),r.push({type:"print"});else if(a==="-print0")r.push({type:"print0"});else if(a==="-printf"&&t+1<e.length){let i=e[++t];r.push({type:"printf",format:i})}else if(a==="-delete")r.push({type:"delete"});else{if(a.startsWith("-"))return{expr:null,pathIndex:t,error:`find: unknown predicate '${a}'
4
- `,actions:[]};if(n.length===0){t++;continue}break}t++}if(n.length===0)return{expr:null,pathIndex:t,actions:r};let D=te(n);return D.error?{expr:null,pathIndex:t,error:D.error,actions:r}:{expr:D.expr,pathIndex:t,actions:r}}function te(e){let s=0;function n(){let i=r();if(!i)return null;for(;s<e.length;){let c=e[s];if(c.type==="op"&&c.op==="or"){s++;let p=r();if(!p)return i;i={type:"or",left:i,right:p}}else break}return i}function r(){let i=t();if(!i)return null;for(;s<e.length;){let c=e[s];if(c.type==="op"&&c.op==="and"){s++;let p=t();if(!p)return i;i={type:"and",left:i,right:p}}else if(c.type==="expr"||c.type==="not"||c.type==="lparen"){let p=t();if(!p)return i;i={type:"and",left:i,right:p}}else break}return i}function t(){if(s<e.length&&e[s].type==="not"){s++;let i=t();return i?{type:"not",expr:i}:null}return D()}function D(){if(s>=e.length)return null;let i=e[s];if(i.type==="lparen"){s++;let c=n();return s<e.length&&e[s].type==="rparen"&&s++,c}return i.type==="expr"?(s++,i.expr):(i.type==="rparen",null)}return{expr:n()}}var ne={name:"find",summary:"search for files in a directory hierarchy",usage:"find [path...] [expression]",options:["-name PATTERN file name matches shell pattern PATTERN","-iname PATTERN like -name but case insensitive","-path PATTERN file path matches shell pattern PATTERN","-ipath PATTERN like -path but case insensitive","-regex PATTERN file path matches regular expression PATTERN","-iregex PATTERN like -regex but case insensitive","-type TYPE file is of type: f (regular file), d (directory)","-empty file is empty or directory is empty","-mtime N file's data was modified N*24 hours ago","-newer FILE file was modified more recently than FILE","-size N[ckMGb] file uses N units of space (c=bytes, k=KB, M=MB, G=GB, b=512B blocks)","-perm MODE file's permission bits are exactly MODE (octal)","-perm -MODE all permission bits MODE are set","-perm /MODE any permission bits MODE are set","-maxdepth LEVELS descend at most LEVELS directories","-mindepth LEVELS do not apply tests at levels less than LEVELS","-depth process directory contents before directory itself","-prune do not descend into this directory","-not, ! negate the following expression","-a, -and logical AND (default)","-o, -or logical OR","-exec CMD {} ; execute CMD on each file ({} is replaced by filename)","-exec CMD {} + execute CMD with multiple files at once","-print print the full file name (default action)","-print0 print the full file name followed by a null character","-printf FORMAT print FORMAT with directives: %f %h %p %P %s %d %m %M %t","-delete delete found files/directories"," --help display this help and exit"]},se=new Set(["-name","-iname","-path","-ipath","-regex","-iregex","-type","-maxdepth","-mindepth","-mtime","-newer","-size","-perm"]),ge={name:"find",async execute(e,s){if(V(e))return _(ne);let n=[],r=null,t=null,D=!1,a=!1;for(let o=0;o<e.length;o++){let l=e[o];if(l==="-maxdepth"&&o+1<e.length)a=!0,r=parseInt(e[++o],10);else if(l==="-mindepth"&&o+1<e.length)a=!0,t=parseInt(e[++o],10);else if(l==="-depth")a=!0,D=!0;else if(l==="-exec")for(a=!0,o++;o<e.length&&e[o]!==";"&&e[o]!=="+";)o++;else!l.startsWith("-")&&l!==";"&&l!=="+"&&l!=="("&&l!==")"&&l!=="\\("&&l!=="\\)"&&l!=="!"?a||n.push(l):se.has(l)?(a=!0,o++):(l.startsWith("-")||l==="("||l==="\\("||l==="!")&&(a=!0)}n.length===0&&n.push(".");let{expr:i,error:c,actions:p}=Q(e,0);if(c)return{stdout:"",stderr:c,exitCode:1};let u=p.some(o=>o.type==="print"),W=p.length===0,E=[],j=p.some(o=>o.type==="printf"),Y=[],A="",C=0,Z=K(i),L=new Map;for(let o of Z){let l=s.fs.resolvePath(s.cwd,o);try{let I=await s.fs.stat(l);L.set(o,I.mtime?.getTime()??Date.now())}catch{}}let X=z(i)||j,ee=typeof s.fs.readdirWithFileTypes=="function";for(let o of n){let b=function(h){let d=t===null||h.depth>=t,T=!1;if(d&&i!==null){let m={name:h.name,relativePath:h.relativePath,isFile:h.isFile,isDirectory:h.isDirectory,isEmpty:h.isEmpty,mtime:h.stat?.mtime?.getTime()??Date.now(),size:h.stat?.size??0,mode:h.stat?.mode??420,newerRefTimes:L},f=F(i,m);d=f.matches,T=u?f.printed:d}else d&&(T=!0);return T?{print:!0,printfData:j?{path:h.relativePath,name:h.name,size:h.stat?.size??0,mtime:h.stat?.mtime?.getTime()??Date.now(),mode:h.stat?.mode??420,isDirectory:h.isDirectory,depth:h.depth,startingPoint:o}:null}:{print:!1,printfData:null}};var le=b;o.length>1&&o.endsWith("/")&&(o=o.slice(0,-1));let l=s.fs.resolvePath(s.cwd,o);try{await s.fs.stat(l)}catch{A+=`find: ${o}: No such file or directory
5
- `,C=1;continue}async function I(h){let{path:P,depth:d,typeInfo:T}=h;if(r!==null&&d>r)return null;let v,m,f;if(T&&!X)v=T.isFile,m=T.isDirectory;else{try{f=await s.fs.stat(P)}catch{return null}if(!f)return null;v=f.isFile,m=f.isDirectory}let y;P===l?y=o.split("/").pop()||o:y=P.split("/").pop()||"";let g=P===l?o:o==="."?`./${P.slice(l==="/"?l.length:l.length+1)}`:o+P.slice(l.length),S=[],M=null,$=null;m&&(ee&&s.fs.readdirWithFileTypes?(M=await s.fs.readdirWithFileTypes(P),S=M.map((R,O)=>({path:P==="/"?`/${R.name}`:`${P}/${R.name}`,depth:d+1,typeInfo:{isFile:R.isFile,isDirectory:R.isDirectory},resultIndex:O})),$=M.map(R=>R.name)):($=await s.fs.readdir(P),S=$.map((R,O)=>({path:P==="/"?`/${R}`:`${P}/${R}`,depth:d+1,resultIndex:O}))));let w=v?(f?.size??0)===0:$!==null&&$.length===0,B=!1;if(!D&&i!==null){let R={name:y,relativePath:g,isFile:v,isDirectory:m,isEmpty:w,mtime:f?.mtime?.getTime()??Date.now(),size:f?.size??0,mode:f?.mode??420,newerRefTimes:L};B=F(i,R).pruned}return{relativePath:g,name:y,isFile:v,isDirectory:m,isEmpty:w,stat:f,depth:d,children:B?[]:S,pruned:B}}async function x(){let h={paths:[],printfData:[]};if(D){let m=function(f){let y={paths:[],printfData:[]},g=d[f];if(!g)return y;for(let $ of g.childIndices){let w=m($);y.paths.push(...w.paths),y.printfData.push(...w.printfData)}let{print:S,printfData:M}=b(g.node);return S&&(y.paths.push(g.node.relativePath),M&&y.printfData.push(M)),y};var P=m;let d=[],T=[{item:{path:l,depth:0,resultIndex:0},parentIndex:-1,childOrderInParent:0}],v=new Map;for(;T.length>0;){let f=T.splice(0,100),y=await Promise.all(f.map(g=>I(g.item)));for(let g=0;g<f.length;g++){let S=y[g],M=f[g];if(!S)continue;let $=d.length;if(M.parentIndex>=0){let w=v.get(M.parentIndex)||[];w.push($),v.set(M.parentIndex,w)}d.push({node:S,parentIndex:M.parentIndex,childIndices:[]});for(let w=0;w<S.children.length;w++)T.push({item:S.children[w],parentIndex:$,childOrderInParent:w})}}for(let[f,y]of v)f>=0&&f<d.length&&(d[f].childIndices=y);if(d.length>0){let f=m(0);h.paths.push(...f.paths),h.printfData.push(...f.printfData)}}else{async function d(v){let m={paths:[],printfData:[]},f=await I(v);if(!f)return m;let{print:y,printfData:g}=b(f);y&&(m.paths.push(f.relativePath),g&&m.printfData.push(g));for(let S=0;S<f.children.length;S+=100){let M=f.children.slice(S,S+100),$=await Promise.all(M.map(d));for(let w of $)m.paths.push(...w.paths),m.printfData.push(...w.printfData)}return m}let T=await d({path:l,depth:0,resultIndex:0});h.paths.push(...T.paths),h.printfData.push(...T.printfData)}return h}let k=await x();E.push(...k.paths),Y.push(...k.printfData)}let N="";if(p.length>0)for(let o of p)switch(o.type){case"print":N+=E.length>0?`${E.join(`
6
- `)}
7
- `:"";break;case"print0":N+=E.length>0?`${E.join("\0")}\0`:"";break;case"delete":{let l=[...E].sort((I,b)=>b.length-I.length);for(let I of l){let b=s.fs.resolvePath(s.cwd,I);try{await s.fs.rm(b,{recursive:!1})}catch(x){let k=x instanceof Error?x.message:String(x);A+=`find: cannot delete '${I}': ${k}
8
- `,C=1}}break}case"printf":for(let l of Y)N+=re(o.format,l);break;case"exec":if(!s.exec)return{stdout:"",stderr:`find: -exec not supported in this context
9
- `,exitCode:1};if(o.batchMode){let l=[];for(let x of o.command)x==="{}"?l.push(...E):l.push(x);let I=l.map(x=>`"${x}"`).join(" "),b=await s.exec(I,{cwd:s.cwd});N+=b.stdout,A+=b.stderr,b.exitCode!==0&&(C=b.exitCode)}else for(let l of E){let b=o.command.map(k=>k==="{}"?l:k).map(k=>`"${k}"`).join(" "),x=await s.exec(b,{cwd:s.cwd});N+=x.stdout,A+=x.stderr,x.exitCode!==0&&(C=x.exitCode)}break}else W&&(N=E.length>0?`${E.join(`
10
- `)}
11
- `:"");return{stdout:N,stderr:A,exitCode:C}}};function re(e,s){let n=q(e),r="",t=0;for(;t<n.length;)if(n[t]==="%"&&t+1<n.length){if(t++,n[t]==="%"){r+="%",t++;continue}let[D,a,i]=U(n,t);if(t+=i,t>=n.length){r+="%";break}let c=n[t],p;switch(c){case"f":p=s.name,t++;break;case"h":{let u=s.path.lastIndexOf("/");p=u>0?s.path.slice(0,u):".",t++;break}case"p":p=s.path,t++;break;case"P":{let u=s.startingPoint;s.path===u?p="":s.path.startsWith(`${u}/`)?p=s.path.slice(u.length+1):u==="."&&s.path.startsWith("./")?p=s.path.slice(2):p=s.path,t++;break}case"s":p=String(s.size),t++;break;case"d":p=String(s.depth),t++;break;case"m":p=(s.mode&511).toString(8),t++;break;case"M":p=ie(s.mode,s.isDirectory),t++;break;case"t":{let u=new Date(s.mtime);p=ae(u),t++;break}case"T":{if(t+1<n.length){let u=n[t+1],W=new Date(s.mtime);p=pe(W,u),t+=2}else p="%T",t++;break}default:r+=`%${D!==0||a!==-1?`${D}.${a}`:""}${c}`,t++;continue}r+=J(p,D,a)}else r+=n[t],t++;return r}function ie(e,s){let n=e&511,r=s?"d":"-";return r+=n&256?"r":"-",r+=n&128?"w":"-",r+=n&64?"x":"-",r+=n&32?"r":"-",r+=n&16?"w":"-",r+=n&8?"x":"-",r+=n&4?"r":"-",r+=n&2?"w":"-",r+=n&1?"x":"-",r}function ae(e){let s=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],n=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],r=s[e.getDay()],t=n[e.getMonth()],D=String(e.getDate()).padStart(2," "),a=String(e.getHours()).padStart(2,"0"),i=String(e.getMinutes()).padStart(2,"0"),c=String(e.getSeconds()).padStart(2,"0"),p=e.getFullYear();return`${r} ${t} ${D} ${a}:${i}:${c} ${p}`}function pe(e,s){switch(s){case"@":return String(e.getTime()/1e3);case"Y":return String(e.getFullYear());case"m":return String(e.getMonth()+1).padStart(2,"0");case"d":return String(e.getDate()).padStart(2,"0");case"H":return String(e.getHours()).padStart(2,"0");case"M":return String(e.getMinutes()).padStart(2,"0");case"S":return String(e.getSeconds()).padStart(2,"0");case"T":return`${String(e.getHours()).padStart(2,"0")}:${String(e.getMinutes()).padStart(2,"0")}:${String(e.getSeconds()).padStart(2,"0")}`;case"F":return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,"0")}-${String(e.getDate()).padStart(2,"0")}`;default:return`%T${s}`}}export{ge as findCommand};
@@ -1,11 +0,0 @@
1
- #!/usr/bin/env node
2
- import{a as H}from"./chunk-26Q3PZQ6.js";import{a as J,b as U,c as q}from"./chunk-PM2DS2YW.js";import"./chunk-OBH7XN5N.js";import{a as _,b as V}from"./chunk-GTNBSMZR.js";import"./chunk-KGOUQS5A.js";function F(e,s){switch(e.type){case"name":return{matches:H(s.name,e.pattern,e.ignoreCase),pruned:!1,printed:!1};case"path":return{matches:H(s.relativePath,e.pattern,e.ignoreCase),pruned:!1,printed:!1};case"regex":try{let n=e.ignoreCase?"i":"";return{matches:new RegExp(e.pattern,n).test(s.relativePath),pruned:!1,printed:!1}}catch{return{matches:!1,pruned:!1,printed:!1}}case"type":return e.fileType==="f"?{matches:s.isFile,pruned:!1,printed:!1}:e.fileType==="d"?{matches:s.isDirectory,pruned:!1,printed:!1}:{matches:!1,pruned:!1,printed:!1};case"empty":return{matches:s.isEmpty,pruned:!1,printed:!1};case"mtime":{let r=(Date.now()-s.mtime)/(1e3*60*60*24),t;return e.comparison==="more"?t=r>e.days:e.comparison==="less"?t=r<e.days:t=Math.floor(r)===e.days,{matches:t,pruned:!1,printed:!1}}case"newer":{let n=s.newerRefTimes.get(e.refPath);return n===void 0?{matches:!1,pruned:!1,printed:!1}:{matches:s.mtime>n,pruned:!1,printed:!1}}case"size":{let n=e.value;switch(e.unit){case"c":n=e.value;break;case"k":n=e.value*1024;break;case"M":n=e.value*1024*1024;break;case"G":n=e.value*1024*1024*1024;break;case"b":n=e.value*512;break}let r;return e.comparison==="more"?r=s.size>n:e.comparison==="less"?r=s.size<n:e.unit==="b"?r=Math.ceil(s.size/512)===e.value:r=s.size===n,{matches:r,pruned:!1,printed:!1}}case"perm":{let n=s.mode&511,r=e.mode&511,t;return e.matchType==="exact"?t=n===r:e.matchType==="all"?t=(n&r)===r:t=(n&r)!==0,{matches:t,pruned:!1,printed:!1}}case"prune":return{matches:!0,pruned:!0,printed:!1};case"print":return{matches:!0,pruned:!1,printed:!0};case"not":{let n=F(e.expr,s);return{matches:!n.matches,pruned:n.pruned,printed:!1}}case"and":{let n=F(e.left,s);if(!n.matches)return{matches:!1,pruned:n.pruned,printed:!1};let r=F(e.right,s);return{matches:r.matches,pruned:n.pruned||r.pruned,printed:n.printed||r.printed}}case"or":{let n=F(e.left,s);if(n.matches)return n;let r=F(e.right,s);return{matches:r.matches,pruned:n.pruned||r.pruned,printed:r.printed}}}}function z(e){if(!e)return!1;switch(e.type){case"name":case"path":case"regex":case"type":case"prune":case"print":return!1;case"empty":case"mtime":case"newer":case"size":case"perm":return!0;case"not":return z(e.expr);case"and":case"or":return z(e.left)||z(e.right)}}function K(e){let s=[],n=r=>{r&&(r.type==="newer"?s.push(r.refPath):r.type==="not"?n(r.expr):(r.type==="and"||r.type==="or")&&(n(r.left),n(r.right)))};return n(e),s}function Q(e,s){let n=[],r=[],t=s;for(;t<e.length;){let a=e[t];if(a==="("||a==="\\("){n.push({type:"lparen"}),t++;continue}if(a===")"||a==="\\)"){n.push({type:"rparen"}),t++;continue}if(a==="-name"&&t+1<e.length)n.push({type:"expr",expr:{type:"name",pattern:e[++t]}});else if(a==="-iname"&&t+1<e.length)n.push({type:"expr",expr:{type:"name",pattern:e[++t],ignoreCase:!0}});else if(a==="-path"&&t+1<e.length)n.push({type:"expr",expr:{type:"path",pattern:e[++t]}});else if(a==="-ipath"&&t+1<e.length)n.push({type:"expr",expr:{type:"path",pattern:e[++t],ignoreCase:!0}});else if(a==="-regex"&&t+1<e.length)n.push({type:"expr",expr:{type:"regex",pattern:e[++t]}});else if(a==="-iregex"&&t+1<e.length)n.push({type:"expr",expr:{type:"regex",pattern:e[++t],ignoreCase:!0}});else if(a==="-type"&&t+1<e.length){let i=e[++t];if(i==="f"||i==="d")n.push({type:"expr",expr:{type:"type",fileType:i}});else return{expr:null,pathIndex:t,error:`find: Unknown argument to -type: ${i}
3
- `,actions:[]}}else if(a==="-empty")n.push({type:"expr",expr:{type:"empty"}});else if(a==="-mtime"&&t+1<e.length){let i=e[++t],c="exact",p=i;i.startsWith("+")?(c="more",p=i.slice(1)):i.startsWith("-")&&(c="less",p=i.slice(1));let u=parseInt(p,10);Number.isNaN(u)||n.push({type:"expr",expr:{type:"mtime",days:u,comparison:c}})}else if(a==="-newer"&&t+1<e.length){let i=e[++t];n.push({type:"expr",expr:{type:"newer",refPath:i}})}else if(a==="-size"&&t+1<e.length){let i=e[++t],c="exact",p=i;i.startsWith("+")?(c="more",p=i.slice(1)):i.startsWith("-")&&(c="less",p=i.slice(1));let u=p.match(/^(\d+)([ckMGb])?$/);if(u){let W=parseInt(u[1],10),E=u[2]||"b";n.push({type:"expr",expr:{type:"size",value:W,unit:E,comparison:c}})}}else if(a==="-perm"&&t+1<e.length){let i=e[++t],c="exact",p=i;i.startsWith("-")?(c="all",p=i.slice(1)):i.startsWith("/")&&(c="any",p=i.slice(1));let u=parseInt(p,8);Number.isNaN(u)||n.push({type:"expr",expr:{type:"perm",mode:u,matchType:c}})}else if(a==="-prune")n.push({type:"expr",expr:{type:"prune"}});else if(a==="-not"||a==="!")n.push({type:"not"});else if(a==="-o"||a==="-or")n.push({type:"op",op:"or"});else if(a==="-a"||a==="-and")n.push({type:"op",op:"and"});else if(a==="-maxdepth"||a==="-mindepth")t++;else if(a!=="-depth")if(a==="-exec"){let i=[];for(t++;t<e.length&&e[t]!==";"&&e[t]!=="+";)i.push(e[t]),t++;if(t>=e.length)return{expr:null,pathIndex:t,error:"find: missing argument to `-exec'\n",actions:[]};let c=e[t]==="+";r.push({type:"exec",command:i,batchMode:c})}else if(a==="-print")n.push({type:"expr",expr:{type:"print"}}),r.push({type:"print"});else if(a==="-print0")r.push({type:"print0"});else if(a==="-printf"&&t+1<e.length){let i=e[++t];r.push({type:"printf",format:i})}else if(a==="-delete")r.push({type:"delete"});else{if(a.startsWith("-"))return{expr:null,pathIndex:t,error:`find: unknown predicate '${a}'
4
- `,actions:[]};if(n.length===0){t++;continue}break}t++}if(n.length===0)return{expr:null,pathIndex:t,actions:r};let D=te(n);return D.error?{expr:null,pathIndex:t,error:D.error,actions:r}:{expr:D.expr,pathIndex:t,actions:r}}function te(e){let s=0;function n(){let i=r();if(!i)return null;for(;s<e.length;){let c=e[s];if(c.type==="op"&&c.op==="or"){s++;let p=r();if(!p)return i;i={type:"or",left:i,right:p}}else break}return i}function r(){let i=t();if(!i)return null;for(;s<e.length;){let c=e[s];if(c.type==="op"&&c.op==="and"){s++;let p=t();if(!p)return i;i={type:"and",left:i,right:p}}else if(c.type==="expr"||c.type==="not"||c.type==="lparen"){let p=t();if(!p)return i;i={type:"and",left:i,right:p}}else break}return i}function t(){if(s<e.length&&e[s].type==="not"){s++;let i=t();return i?{type:"not",expr:i}:null}return D()}function D(){if(s>=e.length)return null;let i=e[s];if(i.type==="lparen"){s++;let c=n();return s<e.length&&e[s].type==="rparen"&&s++,c}return i.type==="expr"?(s++,i.expr):(i.type==="rparen",null)}return{expr:n()}}var ne={name:"find",summary:"search for files in a directory hierarchy",usage:"find [path...] [expression]",options:["-name PATTERN file name matches shell pattern PATTERN","-iname PATTERN like -name but case insensitive","-path PATTERN file path matches shell pattern PATTERN","-ipath PATTERN like -path but case insensitive","-regex PATTERN file path matches regular expression PATTERN","-iregex PATTERN like -regex but case insensitive","-type TYPE file is of type: f (regular file), d (directory)","-empty file is empty or directory is empty","-mtime N file's data was modified N*24 hours ago","-newer FILE file was modified more recently than FILE","-size N[ckMGb] file uses N units of space (c=bytes, k=KB, M=MB, G=GB, b=512B blocks)","-perm MODE file's permission bits are exactly MODE (octal)","-perm -MODE all permission bits MODE are set","-perm /MODE any permission bits MODE are set","-maxdepth LEVELS descend at most LEVELS directories","-mindepth LEVELS do not apply tests at levels less than LEVELS","-depth process directory contents before directory itself","-prune do not descend into this directory","-not, ! negate the following expression","-a, -and logical AND (default)","-o, -or logical OR","-exec CMD {} ; execute CMD on each file ({} is replaced by filename)","-exec CMD {} + execute CMD with multiple files at once","-print print the full file name (default action)","-print0 print the full file name followed by a null character","-printf FORMAT print FORMAT with directives: %f %h %p %P %s %d %m %M %t","-delete delete found files/directories"," --help display this help and exit"]},se=new Set(["-name","-iname","-path","-ipath","-regex","-iregex","-type","-maxdepth","-mindepth","-mtime","-newer","-size","-perm"]),ge={name:"find",async execute(e,s){if(V(e))return _(ne);let n=[],r=null,t=null,D=!1,a=!1;for(let o=0;o<e.length;o++){let l=e[o];if(l==="-maxdepth"&&o+1<e.length)a=!0,r=parseInt(e[++o],10);else if(l==="-mindepth"&&o+1<e.length)a=!0,t=parseInt(e[++o],10);else if(l==="-depth")a=!0,D=!0;else if(l==="-exec")for(a=!0,o++;o<e.length&&e[o]!==";"&&e[o]!=="+";)o++;else!l.startsWith("-")&&l!==";"&&l!=="+"&&l!=="("&&l!==")"&&l!=="\\("&&l!=="\\)"&&l!=="!"?a||n.push(l):se.has(l)?(a=!0,o++):(l.startsWith("-")||l==="("||l==="\\("||l==="!")&&(a=!0)}n.length===0&&n.push(".");let{expr:i,error:c,actions:p}=Q(e,0);if(c)return{stdout:"",stderr:c,exitCode:1};let u=p.some(o=>o.type==="print"),W=p.length===0,E=[],j=p.some(o=>o.type==="printf"),Y=[],A="",C=0,Z=K(i),L=new Map;for(let o of Z){let l=s.fs.resolvePath(s.cwd,o);try{let I=await s.fs.stat(l);L.set(o,I.mtime?.getTime()??Date.now())}catch{}}let X=z(i)||j,ee=typeof s.fs.readdirWithFileTypes=="function";for(let o of n){let b=function(h){let d=t===null||h.depth>=t,T=!1;if(d&&i!==null){let m={name:h.name,relativePath:h.relativePath,isFile:h.isFile,isDirectory:h.isDirectory,isEmpty:h.isEmpty,mtime:h.stat?.mtime?.getTime()??Date.now(),size:h.stat?.size??0,mode:h.stat?.mode??420,newerRefTimes:L},f=F(i,m);d=f.matches,T=u?f.printed:d}else d&&(T=!0);return T?{print:!0,printfData:j?{path:h.relativePath,name:h.name,size:h.stat?.size??0,mtime:h.stat?.mtime?.getTime()??Date.now(),mode:h.stat?.mode??420,isDirectory:h.isDirectory,depth:h.depth,startingPoint:o}:null}:{print:!1,printfData:null}};var le=b;o.length>1&&o.endsWith("/")&&(o=o.slice(0,-1));let l=s.fs.resolvePath(s.cwd,o);try{await s.fs.stat(l)}catch{A+=`find: ${o}: No such file or directory
5
- `,C=1;continue}async function I(h){let{path:P,depth:d,typeInfo:T}=h;if(r!==null&&d>r)return null;let v,m,f;if(T&&!X)v=T.isFile,m=T.isDirectory;else{try{f=await s.fs.stat(P)}catch{return null}if(!f)return null;v=f.isFile,m=f.isDirectory}let y;P===l?y=o.split("/").pop()||o:y=P.split("/").pop()||"";let g=P===l?o:o==="."?`./${P.slice(l==="/"?l.length:l.length+1)}`:o+P.slice(l.length),S=[],M=null,$=null;m&&(ee&&s.fs.readdirWithFileTypes?(M=await s.fs.readdirWithFileTypes(P),S=M.map((R,O)=>({path:P==="/"?`/${R.name}`:`${P}/${R.name}`,depth:d+1,typeInfo:{isFile:R.isFile,isDirectory:R.isDirectory},resultIndex:O})),$=M.map(R=>R.name)):($=await s.fs.readdir(P),S=$.map((R,O)=>({path:P==="/"?`/${R}`:`${P}/${R}`,depth:d+1,resultIndex:O}))));let w=v?(f?.size??0)===0:$!==null&&$.length===0,B=!1;if(!D&&i!==null){let R={name:y,relativePath:g,isFile:v,isDirectory:m,isEmpty:w,mtime:f?.mtime?.getTime()??Date.now(),size:f?.size??0,mode:f?.mode??420,newerRefTimes:L};B=F(i,R).pruned}return{relativePath:g,name:y,isFile:v,isDirectory:m,isEmpty:w,stat:f,depth:d,children:B?[]:S,pruned:B}}async function x(){let h={paths:[],printfData:[]};if(D){let m=function(f){let y={paths:[],printfData:[]},g=d[f];if(!g)return y;for(let $ of g.childIndices){let w=m($);y.paths.push(...w.paths),y.printfData.push(...w.printfData)}let{print:S,printfData:M}=b(g.node);return S&&(y.paths.push(g.node.relativePath),M&&y.printfData.push(M)),y};var P=m;let d=[],T=[{item:{path:l,depth:0,resultIndex:0},parentIndex:-1,childOrderInParent:0}],v=new Map;for(;T.length>0;){let f=T.splice(0,100),y=await Promise.all(f.map(g=>I(g.item)));for(let g=0;g<f.length;g++){let S=y[g],M=f[g];if(!S)continue;let $=d.length;if(M.parentIndex>=0){let w=v.get(M.parentIndex)||[];w.push($),v.set(M.parentIndex,w)}d.push({node:S,parentIndex:M.parentIndex,childIndices:[]});for(let w=0;w<S.children.length;w++)T.push({item:S.children[w],parentIndex:$,childOrderInParent:w})}}for(let[f,y]of v)f>=0&&f<d.length&&(d[f].childIndices=y);if(d.length>0){let f=m(0);h.paths.push(...f.paths),h.printfData.push(...f.printfData)}}else{async function d(v){let m={paths:[],printfData:[]},f=await I(v);if(!f)return m;let{print:y,printfData:g}=b(f);y&&(m.paths.push(f.relativePath),g&&m.printfData.push(g));for(let S=0;S<f.children.length;S+=100){let M=f.children.slice(S,S+100),$=await Promise.all(M.map(d));for(let w of $)m.paths.push(...w.paths),m.printfData.push(...w.printfData)}return m}let T=await d({path:l,depth:0,resultIndex:0});h.paths.push(...T.paths),h.printfData.push(...T.printfData)}return h}let k=await x();E.push(...k.paths),Y.push(...k.printfData)}let N="";if(p.length>0)for(let o of p)switch(o.type){case"print":N+=E.length>0?`${E.join(`
6
- `)}
7
- `:"";break;case"print0":N+=E.length>0?`${E.join("\0")}\0`:"";break;case"delete":{let l=[...E].sort((I,b)=>b.length-I.length);for(let I of l){let b=s.fs.resolvePath(s.cwd,I);try{await s.fs.rm(b,{recursive:!1})}catch(x){let k=x instanceof Error?x.message:String(x);A+=`find: cannot delete '${I}': ${k}
8
- `,C=1}}break}case"printf":for(let l of Y)N+=re(o.format,l);break;case"exec":if(!s.exec)return{stdout:"",stderr:`find: -exec not supported in this context
9
- `,exitCode:1};if(o.batchMode){let l=[];for(let x of o.command)x==="{}"?l.push(...E):l.push(x);let I=l.map(x=>`"${x}"`).join(" "),b=await s.exec(I,{cwd:s.cwd});N+=b.stdout,A+=b.stderr,b.exitCode!==0&&(C=b.exitCode)}else for(let l of E){let b=o.command.map(k=>k==="{}"?l:k).map(k=>`"${k}"`).join(" "),x=await s.exec(b,{cwd:s.cwd});N+=x.stdout,A+=x.stderr,x.exitCode!==0&&(C=x.exitCode)}break}else W&&(N=E.length>0?`${E.join(`
10
- `)}
11
- `:"");return{stdout:N,stderr:A,exitCode:C}}};function re(e,s){let n=q(e),r="",t=0;for(;t<n.length;)if(n[t]==="%"&&t+1<n.length){if(t++,n[t]==="%"){r+="%",t++;continue}let[D,a,i]=U(n,t);if(t+=i,t>=n.length){r+="%";break}let c=n[t],p;switch(c){case"f":p=s.name,t++;break;case"h":{let u=s.path.lastIndexOf("/");p=u>0?s.path.slice(0,u):".",t++;break}case"p":p=s.path,t++;break;case"P":{let u=s.startingPoint;s.path===u?p="":s.path.startsWith(`${u}/`)?p=s.path.slice(u.length+1):u==="."&&s.path.startsWith("./")?p=s.path.slice(2):p=s.path,t++;break}case"s":p=String(s.size),t++;break;case"d":p=String(s.depth),t++;break;case"m":p=(s.mode&511).toString(8),t++;break;case"M":p=ie(s.mode,s.isDirectory),t++;break;case"t":{let u=new Date(s.mtime);p=ae(u),t++;break}case"T":{if(t+1<n.length){let u=n[t+1],W=new Date(s.mtime);p=pe(W,u),t+=2}else p="%T",t++;break}default:r+=`%${D!==0||a!==-1?`${D}.${a}`:""}${c}`,t++;continue}r+=J(p,D,a)}else r+=n[t],t++;return r}function ie(e,s){let n=e&511,r=s?"d":"-";return r+=n&256?"r":"-",r+=n&128?"w":"-",r+=n&64?"x":"-",r+=n&32?"r":"-",r+=n&16?"w":"-",r+=n&8?"x":"-",r+=n&4?"r":"-",r+=n&2?"w":"-",r+=n&1?"x":"-",r}function ae(e){let s=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],n=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],r=s[e.getDay()],t=n[e.getMonth()],D=String(e.getDate()).padStart(2," "),a=String(e.getHours()).padStart(2,"0"),i=String(e.getMinutes()).padStart(2,"0"),c=String(e.getSeconds()).padStart(2,"0"),p=e.getFullYear();return`${r} ${t} ${D} ${a}:${i}:${c} ${p}`}function pe(e,s){switch(s){case"@":return String(e.getTime()/1e3);case"Y":return String(e.getFullYear());case"m":return String(e.getMonth()+1).padStart(2,"0");case"d":return String(e.getDate()).padStart(2,"0");case"H":return String(e.getHours()).padStart(2,"0");case"M":return String(e.getMinutes()).padStart(2,"0");case"S":return String(e.getSeconds()).padStart(2,"0");case"T":return`${String(e.getHours()).padStart(2,"0")}:${String(e.getMinutes()).padStart(2,"0")}:${String(e.getSeconds()).padStart(2,"0")}`;case"F":return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,"0")}-${String(e.getDate()).padStart(2,"0")}`;default:return`%T${s}`}}export{ge as findCommand};