just-bash 2.15.0-executor.0 → 2.15.1-executor.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/Bash.d.ts +2 -0
- package/dist/bin/chunks/js-exec-RGKNWHHL.js +100 -0
- package/dist/bin/just-bash.js +43 -43
- package/dist/bin/shell/chunks/js-exec-DUGJM6RL.js +100 -0
- package/dist/bin/shell/shell.js +68 -68
- package/dist/bundle/browser.js +5 -5
- package/dist/bundle/chunks/js-exec-LSIPMWTQ.js +99 -0
- package/dist/bundle/index.cjs +11 -8
- package/dist/bundle/index.js +49 -49
- package/dist/executor-init.d.ts +11 -2
- package/dist/interpreter/interpreter.d.ts +5 -0
- package/dist/interpreter/types.d.ts +5 -0
- package/dist/types.d.ts +11 -0
- package/package.json +1 -1
- package/vendor/executor/executor-sdk-bundle.mjs +345 -805
- package/vendor/executor/openapi-extractor-wasm/openapi_extractor_bg.wasm +0 -0
- package/dist/bin/chunks/js-exec-6UJKEL4G.js +0 -97
- package/dist/bin/shell/chunks/js-exec-H26D5H6V.js +0 -97
- package/dist/bundle/chunks/js-exec-OOPTBRNB.js +0 -96
package/dist/bin/just-bash.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{B as Mr,C as Wr,D as le,E as je,F as ee,G as $e,H as Ot,I as zr,J as T,K as Vr,L as jr,M as Ae,N as gs,O as Dt,P as B,a as Or,b as fs,c as Dr,d as Pt,e as Q,f as V,g as ve,h as se,i as Se,j as Re,k as ds,l as Nt,m as xr,n as hs,o as Tr,p as me,q as Oe,r as Ir,s as Rr,t as ps,u as ms,v as Le,w as Lr,x as Fr,y as be,z as ys}from"./chunks/chunk-A3HQTYHR.js";import{a as M,b as W,c as Ke,d as Ct,e as kt,f as Xe,g as us,h as _r,i as Cr,j as kr,k as Pr,l as Nr}from"./chunks/chunk-MY5PY2PL.js";import{c as cs}from"./chunks/chunk-LIYVQA3X.js";import{a as br,b as $r}from"./chunks/chunk-OOJCYVYF.js";import{a as Ie,b as pe,c as ls}from"./chunks/chunk-4PRVMER6.js";import{a as ut,b as Ar}from"./chunks/chunk-MO4RPBN2.js";import{a as Ge,b as ge}from"./chunks/chunk-YU6OGPZR.js";import{a as ct}from"./chunks/chunk-SE4C7FJY.js";import{a as ue,b as fe,c as oe,d as de,e as Er,f as j,g as Ve,h as Et,i as St,j as Sr,k as Y,l as At,m as Te,n as _t,o as we}from"./chunks/chunk-6KZRLMG3.js";import"./chunks/chunk-OBH7XN5N.js";import{a as he}from"./chunks/chunk-RLNOQILG.js";import{a as Ne}from"./chunks/chunk-4VDEBYW7.js";import"./chunks/chunk-KGOUQS5A.js";import{resolve as Di}from"node:path";var Ye=[{name:"echo",load:async()=>(await import("./chunks/echo-2MUAOGUE.js")).echoCommand},{name:"cat",load:async()=>(await import("./chunks/cat-XZIJZXKP.js")).catCommand},{name:"printf",load:async()=>(await import("./chunks/printf-P3QVL4IO.js")).printfCommand},{name:"ls",load:async()=>(await import("./chunks/ls-G2PXHSNX.js")).lsCommand},{name:"mkdir",load:async()=>(await import("./chunks/mkdir-Z47OISSR.js")).mkdirCommand},{name:"rmdir",load:async()=>(await import("./chunks/rmdir-5KLM4EA6.js")).rmdirCommand},{name:"touch",load:async()=>(await import("./chunks/touch-DWKSZGOQ.js")).touchCommand},{name:"rm",load:async()=>(await import("./chunks/rm-L3NZOLLG.js")).rmCommand},{name:"cp",load:async()=>(await import("./chunks/cp-XH2ZB7WT.js")).cpCommand},{name:"mv",load:async()=>(await import("./chunks/mv-OY7X62QC.js")).mvCommand},{name:"ln",load:async()=>(await import("./chunks/ln-EGC4HRXZ.js")).lnCommand},{name:"chmod",load:async()=>(await import("./chunks/chmod-N5CQATDW.js")).chmodCommand},{name:"pwd",load:async()=>(await import("./chunks/pwd-6VBAPL3Y.js")).pwdCommand},{name:"readlink",load:async()=>(await import("./chunks/readlink-BD5VFOC5.js")).readlinkCommand},{name:"head",load:async()=>(await import("./chunks/head-YMNRW3F3.js")).headCommand},{name:"tail",load:async()=>(await import("./chunks/tail-V537TDFR.js")).tailCommand},{name:"wc",load:async()=>(await import("./chunks/wc-ZIV3TFVG.js")).wcCommand},{name:"stat",load:async()=>(await import("./chunks/stat-XS2LXYS2.js")).statCommand},{name:"grep",load:async()=>(await import("./chunks/grep-OZJTRD4D.js")).grepCommand},{name:"fgrep",load:async()=>(await import("./chunks/grep-OZJTRD4D.js")).fgrepCommand},{name:"egrep",load:async()=>(await import("./chunks/grep-OZJTRD4D.js")).egrepCommand},{name:"rg",load:async()=>(await import("./chunks/rg-C6KMBFNG.js")).rgCommand},{name:"sed",load:async()=>(await import("./chunks/sed-HALRQZKY.js")).sedCommand},{name:"awk",load:async()=>(await import("./chunks/awk2-VTJMI54B.js")).awkCommand2},{name:"sort",load:async()=>(await import("./chunks/sort-7GENYU2I.js")).sortCommand},{name:"uniq",load:async()=>(await import("./chunks/uniq-TMSAIZM3.js")).uniqCommand},{name:"comm",load:async()=>(await import("./chunks/comm-R3F3Z5DX.js")).commCommand},{name:"cut",load:async()=>(await import("./chunks/cut-5EY2XPXX.js")).cutCommand},{name:"paste",load:async()=>(await import("./chunks/paste-3UVLMQ2K.js")).pasteCommand},{name:"tr",load:async()=>(await import("./chunks/tr-4FPGAEVB.js")).trCommand},{name:"rev",load:async()=>(await import("./chunks/rev-UHEPS2UL.js")).rev},{name:"nl",load:async()=>(await import("./chunks/nl-XH3L75DR.js")).nl},{name:"fold",load:async()=>(await import("./chunks/fold-XSVNTAWH.js")).fold},{name:"expand",load:async()=>(await import("./chunks/expand-26XPP5KB.js")).expand},{name:"unexpand",load:async()=>(await import("./chunks/unexpand-OYZ7KOYR.js")).unexpand},{name:"strings",load:async()=>(await import("./chunks/strings-XXKZCWY5.js")).strings},{name:"split",load:async()=>(await import("./chunks/split-YWV64TJH.js")).split},{name:"column",load:async()=>(await import("./chunks/column-XGV32UPN.js")).column},{name:"join",load:async()=>(await import("./chunks/join-Y4Q5WVVE.js")).join},{name:"tee",load:async()=>(await import("./chunks/tee-HK2SYCAR.js")).teeCommand},{name:"find",load:async()=>(await import("./chunks/find-GAYRV4IF.js")).findCommand},{name:"basename",load:async()=>(await import("./chunks/basename-KBUKWB2E.js")).basenameCommand},{name:"dirname",load:async()=>(await import("./chunks/dirname-5FAOMLBL.js")).dirnameCommand},{name:"tree",load:async()=>(await import("./chunks/tree-HEKABARE.js")).treeCommand},{name:"du",load:async()=>(await import("./chunks/du-LDAPXSGF.js")).duCommand},{name:"env",load:async()=>(await import("./chunks/env-NTPN5QYM.js")).envCommand},{name:"printenv",load:async()=>(await import("./chunks/env-NTPN5QYM.js")).printenvCommand},{name:"alias",load:async()=>(await import("./chunks/alias-3GODYSFD.js")).aliasCommand},{name:"unalias",load:async()=>(await import("./chunks/alias-3GODYSFD.js")).unaliasCommand},{name:"history",load:async()=>(await import("./chunks/history-UUKG55YW.js")).historyCommand},{name:"xargs",load:async()=>(await import("./chunks/xargs-SCYIFXOW.js")).xargsCommand},{name:"true",load:async()=>(await import("./chunks/true-DP5UZP52.js")).trueCommand},{name:"false",load:async()=>(await import("./chunks/true-DP5UZP52.js")).falseCommand},{name:"clear",load:async()=>(await import("./chunks/clear-KRGKPFOI.js")).clearCommand},{name:"bash",load:async()=>(await import("./chunks/bash-6ZHZ6BX7.js")).bashCommand},{name:"sh",load:async()=>(await import("./chunks/bash-6ZHZ6BX7.js")).shCommand},{name:"jq",load:async()=>(await import("./chunks/jq-FIV5Q5T4.js")).jqCommand},{name:"base64",load:async()=>(await import("./chunks/base64-43M2R3GA.js")).base64Command},{name:"diff",load:async()=>(await import("./chunks/diff-LE7GMFZD.js")).diffCommand},{name:"date",load:async()=>(await import("./chunks/date-WUPBL2TL.js")).dateCommand},{name:"sleep",load:async()=>(await import("./chunks/sleep-ND6FZRZ4.js")).sleepCommand},{name:"timeout",load:async()=>(await import("./chunks/timeout-Z24MNWOP.js")).timeoutCommand},{name:"time",load:async()=>(await import("./chunks/time-5R4QWCYF.js")).timeCommand},{name:"seq",load:async()=>(await import("./chunks/seq-V7KBLSQ7.js")).seqCommand},{name:"expr",load:async()=>(await import("./chunks/expr-4CJYC4LY.js")).exprCommand},{name:"md5sum",load:async()=>(await import("./chunks/md5sum-NCLXV2S3.js")).md5sumCommand},{name:"sha1sum",load:async()=>(await import("./chunks/sha1sum-BHNJ5ALF.js")).sha1sumCommand},{name:"sha256sum",load:async()=>(await import("./chunks/sha256sum-HJJ3NJ5L.js")).sha256sumCommand},{name:"file",load:async()=>(await import("./chunks/file-D5YKS5NV.js")).fileCommand},{name:"html-to-markdown",load:async()=>(await import("./chunks/html-to-markdown-WVZA3MCP.js")).htmlToMarkdownCommand},{name:"help",load:async()=>(await import("./chunks/help-DVG4AAGE.js")).helpCommand},{name:"which",load:async()=>(await import("./chunks/which-5PO4LAOG.js")).whichCommand},{name:"tac",load:async()=>(await import("./chunks/tac-T42SKDDI.js")).tac},{name:"hostname",load:async()=>(await import("./chunks/hostname-WY6RKE32.js")).hostname},{name:"whoami",load:async()=>(await import("./chunks/whoami-E7PN2UWC.js")).whoami},{name:"od",load:async()=>(await import("./chunks/od-52FBC34W.js")).od},{name:"gzip",load:async()=>(await import("./chunks/gzip-LHOO65AN.js")).gzipCommand},{name:"gunzip",load:async()=>(await import("./chunks/gzip-LHOO65AN.js")).gunzipCommand},{name:"zcat",load:async()=>(await import("./chunks/gzip-LHOO65AN.js")).zcatCommand}];(typeof __BROWSER__>"u"||!__BROWSER__)&&(Ye.push({name:"tar",load:async()=>(await import("./chunks/tar-TOWX2TDU.js")).tarCommand}),Ye.push({name:"yq",load:async()=>(await import("./chunks/yq-Q47JUWL6.js")).yqCommand}),Ye.push({name:"xan",load:async()=>(await import("./chunks/xan-MOZFJGMY.js")).xanCommand}),Ye.push({name:"sqlite3",load:async()=>(await import("./chunks/sqlite3-CVNFMP3Z.js")).sqlite3Command}));var ws=[];(typeof __BROWSER__>"u"||!__BROWSER__)&&(ws.push({name:"python3",load:async()=>(await import("./chunks/python3-QOJU2POC.js")).python3Command}),ws.push({name:"python",load:async()=>(await import("./chunks/python3-QOJU2POC.js")).pythonCommand}));var vs=[];(typeof __BROWSER__>"u"||!__BROWSER__)&&(vs.push({name:"js-exec",load:async()=>(await import("./chunks/js-exec-6UJKEL4G.js")).jsExecCommand}),vs.push({name:"node",load:async()=>(await import("./chunks/js-exec-6UJKEL4G.js")).nodeStubCommand}));var Li=[{name:"curl",load:async()=>(await import("./chunks/curl-SRTMGOVV.js")).curlCommand}],Br=new Map;function xt(e){return{name:e.name,async execute(t,s){let r=Br.get(e.name);if(r||(r=await ge.runTrustedAsync(()=>e.load()),Br.set(e.name,r)),s.coverage&&(typeof __BROWSER__>"u"||!__BROWSER__)){let{emitFlagCoverage:n}=await import("./chunks/flag-coverage-LBMWMYOO.js");n(s.coverage,e.name,t)}return r.execute(t,s)}}}function Hr(e){return(e?Ye.filter(s=>e.includes(s.name)):Ye).map(xt)}function Ur(){return Li.map(xt)}function Zr(){return ws.map(xt)}function qr(){return vs.map(xt)}function Gr(e){return"load"in e&&typeof e.load=="function"}function Kr(e){let t=null;return{name:e.name,trusted:!0,async execute(s,r){return t||(t=await e.load()),t.execute(s,r)}}}var Fi=new TextEncoder,Mi=new TextDecoder;function Qe(e,t){if(e instanceof Uint8Array)return e;if(t==="base64")return Uint8Array.from(atob(e),s=>s.charCodeAt(0));if(t==="hex"){let s=new Uint8Array(e.length/2);for(let r=0;r<e.length;r+=2)s[r/2]=parseInt(e.slice(r,r+2),16);return s}if(t==="binary"||t==="latin1"){if(e.length<=65536)return Uint8Array.from(e,n=>n.charCodeAt(0));let r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return r}return Fi.encode(e)}function Tt(e,t){if(t==="base64"){if(typeof Buffer<"u")return Buffer.from(e).toString("base64");let s=65536,r="";for(let n=0;n<e.length;n+=s){let i=e.subarray(n,n+s);r+=String.fromCharCode(...i)}return btoa(r)}if(t==="hex")return Array.from(e).map(s=>s.toString(16).padStart(2,"0")).join("");if(t==="binary"||t==="latin1"){if(typeof Buffer<"u")return Buffer.from(e).toString(t);let s=65536;if(e.length<=s)return String.fromCharCode(...e);let r="";for(let n=0;n<e.length;n+=s){let i=e.subarray(n,n+s);r+=String.fromCharCode(...i)}return r}return Mi.decode(e)}function Fe(e){if(e!=null)return typeof e=="string"?e:e.encoding??void 0}var Je=new TextEncoder;function Wi(e){return typeof e=="object"&&e!==null&&!(e instanceof Uint8Array)&&"content"in e}var ft=class{data=new Map;constructor(t){if(this.data.set("/",{type:"directory",mode:493,mtime:new Date}),t)for(let[s,r]of Object.entries(t))typeof r=="function"?this.writeFileLazy(s,r):Wi(r)?this.writeFileSync(s,r.content,void 0,{mode:r.mode,mtime:r.mtime}):this.writeFileSync(s,r)}ensureParentDirs(t){let s=Ke(t);s!=="/"&&(this.data.has(s)||(this.ensureParentDirs(s),this.data.set(s,{type:"directory",mode:493,mtime:new Date})))}writeFileSync(t,s,r,n){W(t,"write");let i=M(t);this.ensureParentDirs(i);let a=Fe(r),o=Qe(s,a);this.data.set(i,{type:"file",content:o,mode:n?.mode??420,mtime:n?.mtime??new Date})}writeFileLazy(t,s,r){W(t,"write");let n=M(t);this.ensureParentDirs(n),this.data.set(n,{type:"file",lazy:s,mode:r?.mode??420,mtime:r?.mtime??new Date})}async materializeLazy(t,s){let r=await s.lazy(),i={type:"file",content:typeof r=="string"?Je.encode(r):r,mode:s.mode,mtime:s.mtime};return this.data.set(t,i),i}async readFile(t,s){let r=await this.readFileBuffer(t),n=Fe(s);return Tt(r,n)}async readFileBuffer(t){W(t,"open");let s=this.resolvePathWithSymlinks(t),r=this.data.get(s);if(!r)throw new Error(`ENOENT: no such file or directory, open '${t}'`);if(r.type!=="file")throw new Error(`EISDIR: illegal operation on a directory, read '${t}'`);if("lazy"in r){let n=await this.materializeLazy(s,r);return n.content instanceof Uint8Array?n.content:Je.encode(n.content)}return r.content instanceof Uint8Array?r.content:Je.encode(r.content)}async writeFile(t,s,r){this.writeFileSync(t,s,r)}async appendFile(t,s,r){W(t,"append");let n=M(t),i=this.data.get(n);if(i&&i.type==="directory")throw new Error(`EISDIR: illegal operation on a directory, write '${t}'`);let a=Fe(r),o=Qe(s,a);if(i?.type==="file"){let l=i;"lazy"in l&&(l=await this.materializeLazy(n,l));let c="content"in l&&l.content instanceof Uint8Array?l.content:Je.encode("content"in l?l.content:""),u=new Uint8Array(c.length+o.length);u.set(c),u.set(o,c.length),this.data.set(n,{type:"file",content:u,mode:l.mode,mtime:new Date})}else this.writeFileSync(t,s,r)}async exists(t){if(t.includes("\0"))return!1;try{let s=this.resolvePathWithSymlinks(t);return this.data.has(s)}catch{return!1}}async stat(t){W(t,"stat");let s=this.resolvePathWithSymlinks(t),r=this.data.get(s);if(!r)throw new Error(`ENOENT: no such file or directory, stat '${t}'`);r.type==="file"&&"lazy"in r&&(r=await this.materializeLazy(s,r));let n=0;return r.type==="file"&&"content"in r&&r.content&&(r.content instanceof Uint8Array?n=r.content.length:n=Je.encode(r.content).length),{isFile:r.type==="file",isDirectory:r.type==="directory",isSymbolicLink:!1,mode:r.mode,size:n,mtime:r.mtime||new Date}}async lstat(t){W(t,"lstat");let s=this.resolveIntermediateSymlinks(t),r=this.data.get(s);if(!r)throw new Error(`ENOENT: no such file or directory, lstat '${t}'`);if(r.type==="symlink")return{isFile:!1,isDirectory:!1,isSymbolicLink:!0,mode:r.mode,size:r.target.length,mtime:r.mtime||new Date};r.type==="file"&&"lazy"in r&&(r=await this.materializeLazy(s,r));let n=0;return r.type==="file"&&"content"in r&&r.content&&(r.content instanceof Uint8Array?n=r.content.length:n=Je.encode(r.content).length),{isFile:r.type==="file",isDirectory:r.type==="directory",isSymbolicLink:!1,mode:r.mode,size:n,mtime:r.mtime||new Date}}resolveIntermediateSymlinks(t){let s=M(t);if(s==="/")return"/";let r=s.slice(1).split("/");if(r.length<=1)return s;let n="",i=new Set;for(let a=0;a<r.length-1;a++){let o=r[a];n=`${n}/${o}`;let l=this.data.get(n),c=0,u=40;for(;l&&l.type==="symlink"&&c<u;){if(i.has(n))throw new Error(`ELOOP: too many levels of symbolic links, lstat '${t}'`);i.add(n),n=Xe(n,l.target),l=this.data.get(n),c++}if(c>=u)throw new Error(`ELOOP: too many levels of symbolic links, lstat '${t}'`)}return`${n}/${r[r.length-1]}`}resolvePathWithSymlinks(t){let s=M(t);if(s==="/")return"/";let r=s.slice(1).split("/"),n="",i=new Set;for(let a of r){n=`${n}/${a}`;let o=this.data.get(n),l=0,c=40;for(;o&&o.type==="symlink"&&l<c;){if(i.has(n))throw new Error(`ELOOP: too many levels of symbolic links, open '${t}'`);i.add(n),n=Xe(n,o.target),o=this.data.get(n),l++}if(l>=c)throw new Error(`ELOOP: too many levels of symbolic links, open '${t}'`)}return n}async mkdir(t,s){this.mkdirSync(t,s)}mkdirSync(t,s){W(t,"mkdir");let r=M(t);if(this.data.has(r)){if(this.data.get(r)?.type==="file")throw new Error(`EEXIST: file already exists, mkdir '${t}'`);if(!s?.recursive)throw new Error(`EEXIST: directory already exists, mkdir '${t}'`);return}let n=Ke(r);if(n!=="/"&&!this.data.has(n))if(s?.recursive)this.mkdirSync(n,{recursive:!0});else throw new Error(`ENOENT: no such file or directory, mkdir '${t}'`);this.data.set(r,{type:"directory",mode:493,mtime:new Date})}async readdir(t){return(await this.readdirWithFileTypes(t)).map(r=>r.name)}async readdirWithFileTypes(t){W(t,"scandir");let s=M(t),r=this.data.get(s);if(!r)throw new Error(`ENOENT: no such file or directory, scandir '${t}'`);let n=new Set;for(;r&&r.type==="symlink";){if(n.has(s))throw new Error(`ELOOP: too many levels of symbolic links, scandir '${t}'`);n.add(s),s=Xe(s,r.target),r=this.data.get(s)}if(!r)throw new Error(`ENOENT: no such file or directory, scandir '${t}'`);if(r.type!=="directory")throw new Error(`ENOTDIR: not a directory, scandir '${t}'`);let i=s==="/"?"/":`${s}/`,a=new Map;for(let[o,l]of this.data.entries())if(o!==s&&o.startsWith(i)){let c=o.slice(i.length),u=c.split("/")[0];u&&!c.includes("/",u.length)&&!a.has(u)&&a.set(u,{name:u,isFile:l.type==="file",isDirectory:l.type==="directory",isSymbolicLink:l.type==="symlink"})}return Array.from(a.values()).sort((o,l)=>o.name<l.name?-1:o.name>l.name?1:0)}async rm(t,s){W(t,"rm");let r=M(t),n=this.data.get(r);if(!n){if(s?.force)return;throw new Error(`ENOENT: no such file or directory, rm '${t}'`)}if(n.type==="directory"){let i=await this.readdir(r);if(i.length>0){if(!s?.recursive)throw new Error(`ENOTEMPTY: directory not empty, rm '${t}'`);for(let a of i){let o=kt(r,a);await this.rm(o,s)}}}this.data.delete(r)}async cp(t,s,r){W(t,"cp"),W(s,"cp");let n=M(t),i=M(s),a=this.data.get(n);if(!a)throw new Error(`ENOENT: no such file or directory, cp '${t}'`);if(a.type==="file")if(this.ensureParentDirs(i),"content"in a){let o=a.content instanceof Uint8Array?new Uint8Array(a.content):a.content;this.data.set(i,{...a,content:o})}else this.data.set(i,{...a});else if(a.type==="symlink")this.ensureParentDirs(i),this.data.set(i,{...a});else if(a.type==="directory"){if(!r?.recursive)throw new Error(`EISDIR: is a directory, cp '${t}'`);await this.mkdir(i,{recursive:!0});let o=await this.readdir(n);for(let l of o){let c=kt(n,l),u=kt(i,l);await this.cp(c,u,r)}}}async mv(t,s){await this.cp(t,s,{recursive:!0}),await this.rm(t,{recursive:!0})}getAllPaths(){return Array.from(this.data.keys())}resolvePath(t,s){return Ct(t,s)}async chmod(t,s){W(t,"chmod");let r=M(t),n=this.data.get(r);if(!n)throw new Error(`ENOENT: no such file or directory, chmod '${t}'`);n.mode=s}async symlink(t,s){W(s,"symlink");let r=M(s);if(this.data.has(r))throw new Error(`EEXIST: file already exists, symlink '${s}'`);this.ensureParentDirs(r),this.data.set(r,{type:"symlink",target:t,mode:511,mtime:new Date})}async link(t,s){W(t,"link"),W(s,"link");let r=M(t),n=M(s),i=this.data.get(r);if(!i)throw new Error(`ENOENT: no such file or directory, link '${t}'`);if(i.type!=="file")throw new Error(`EPERM: operation not permitted, link '${t}'`);if(this.data.has(n))throw new Error(`EEXIST: file already exists, link '${s}'`);let a=i;"lazy"in a&&(a=await this.materializeLazy(r,a)),this.ensureParentDirs(n),this.data.set(n,{type:"file",content:a.content,mode:a.mode,mtime:a.mtime})}async readlink(t){W(t,"readlink");let s=M(t),r=this.data.get(s);if(!r)throw new Error(`ENOENT: no such file or directory, readlink '${t}'`);if(r.type!=="symlink")throw new Error(`EINVAL: invalid argument, readlink '${t}'`);return r.target}async realpath(t){W(t,"realpath");let s=this.resolvePathWithSymlinks(t);if(!this.data.has(s))throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);return s}async utimes(t,s,r){W(t,"utimes");let n=M(t),i=this.resolvePathWithSymlinks(n),a=this.data.get(i);if(!a)throw new Error(`ENOENT: no such file or directory, utimes '${t}'`);a.mtime=r}};function zi(e){let t=e;return typeof t.mkdirSync=="function"&&typeof t.writeFileSync=="function"}function Vi(e,t){e.mkdirSync("/bin",{recursive:!0}),e.mkdirSync("/usr/bin",{recursive:!0}),t&&(e.mkdirSync("/home/user",{recursive:!0}),e.mkdirSync("/tmp",{recursive:!0}))}function ji(e){e.mkdirSync("/dev",{recursive:!0}),e.writeFileSync("/dev/null",""),e.writeFileSync("/dev/zero",new Uint8Array(0)),e.writeFileSync("/dev/stdin",""),e.writeFileSync("/dev/stdout",""),e.writeFileSync("/dev/stderr","")}function Bi(e,t){e.mkdirSync("/proc/self/fd",{recursive:!0}),e.writeFileSync("/proc/version",`${Or}
|
|
2
|
+
import{B as Mr,C as Wr,D as le,E as je,F as ee,G as $e,H as Ot,I as zr,J as T,K as Vr,L as jr,M as Ae,N as gs,O as xt,P as B,a as Or,b as fs,c as xr,d as Pt,e as Q,f as V,g as ve,h as se,i as Se,j as Re,k as ds,l as Nt,m as Dr,n as hs,o as Tr,p as me,q as Oe,r as Ir,s as Rr,t as ps,u as ms,v as Le,w as Lr,x as Fr,y as be,z as ys}from"./chunks/chunk-A3HQTYHR.js";import{a as M,b as W,c as Ke,d as Ct,e as kt,f as Xe,g as us,h as _r,i as Cr,j as kr,k as Pr,l as Nr}from"./chunks/chunk-MY5PY2PL.js";import{c as cs}from"./chunks/chunk-LIYVQA3X.js";import{a as br,b as $r}from"./chunks/chunk-OOJCYVYF.js";import{a as Ie,b as pe,c as ls}from"./chunks/chunk-4PRVMER6.js";import{a as ut,b as Ar}from"./chunks/chunk-MO4RPBN2.js";import{a as Ge,b as ge}from"./chunks/chunk-YU6OGPZR.js";import{a as ct}from"./chunks/chunk-SE4C7FJY.js";import{a as ue,b as fe,c as oe,d as de,e as Er,f as j,g as Ve,h as Et,i as St,j as Sr,k as Y,l as At,m as Te,n as _t,o as we}from"./chunks/chunk-6KZRLMG3.js";import"./chunks/chunk-OBH7XN5N.js";import{a as he}from"./chunks/chunk-RLNOQILG.js";import{a as Ne}from"./chunks/chunk-4VDEBYW7.js";import"./chunks/chunk-KGOUQS5A.js";import{resolve as xi}from"node:path";var Ye=[{name:"echo",load:async()=>(await import("./chunks/echo-2MUAOGUE.js")).echoCommand},{name:"cat",load:async()=>(await import("./chunks/cat-XZIJZXKP.js")).catCommand},{name:"printf",load:async()=>(await import("./chunks/printf-P3QVL4IO.js")).printfCommand},{name:"ls",load:async()=>(await import("./chunks/ls-G2PXHSNX.js")).lsCommand},{name:"mkdir",load:async()=>(await import("./chunks/mkdir-Z47OISSR.js")).mkdirCommand},{name:"rmdir",load:async()=>(await import("./chunks/rmdir-5KLM4EA6.js")).rmdirCommand},{name:"touch",load:async()=>(await import("./chunks/touch-DWKSZGOQ.js")).touchCommand},{name:"rm",load:async()=>(await import("./chunks/rm-L3NZOLLG.js")).rmCommand},{name:"cp",load:async()=>(await import("./chunks/cp-XH2ZB7WT.js")).cpCommand},{name:"mv",load:async()=>(await import("./chunks/mv-OY7X62QC.js")).mvCommand},{name:"ln",load:async()=>(await import("./chunks/ln-EGC4HRXZ.js")).lnCommand},{name:"chmod",load:async()=>(await import("./chunks/chmod-N5CQATDW.js")).chmodCommand},{name:"pwd",load:async()=>(await import("./chunks/pwd-6VBAPL3Y.js")).pwdCommand},{name:"readlink",load:async()=>(await import("./chunks/readlink-BD5VFOC5.js")).readlinkCommand},{name:"head",load:async()=>(await import("./chunks/head-YMNRW3F3.js")).headCommand},{name:"tail",load:async()=>(await import("./chunks/tail-V537TDFR.js")).tailCommand},{name:"wc",load:async()=>(await import("./chunks/wc-ZIV3TFVG.js")).wcCommand},{name:"stat",load:async()=>(await import("./chunks/stat-XS2LXYS2.js")).statCommand},{name:"grep",load:async()=>(await import("./chunks/grep-OZJTRD4D.js")).grepCommand},{name:"fgrep",load:async()=>(await import("./chunks/grep-OZJTRD4D.js")).fgrepCommand},{name:"egrep",load:async()=>(await import("./chunks/grep-OZJTRD4D.js")).egrepCommand},{name:"rg",load:async()=>(await import("./chunks/rg-C6KMBFNG.js")).rgCommand},{name:"sed",load:async()=>(await import("./chunks/sed-HALRQZKY.js")).sedCommand},{name:"awk",load:async()=>(await import("./chunks/awk2-VTJMI54B.js")).awkCommand2},{name:"sort",load:async()=>(await import("./chunks/sort-7GENYU2I.js")).sortCommand},{name:"uniq",load:async()=>(await import("./chunks/uniq-TMSAIZM3.js")).uniqCommand},{name:"comm",load:async()=>(await import("./chunks/comm-R3F3Z5DX.js")).commCommand},{name:"cut",load:async()=>(await import("./chunks/cut-5EY2XPXX.js")).cutCommand},{name:"paste",load:async()=>(await import("./chunks/paste-3UVLMQ2K.js")).pasteCommand},{name:"tr",load:async()=>(await import("./chunks/tr-4FPGAEVB.js")).trCommand},{name:"rev",load:async()=>(await import("./chunks/rev-UHEPS2UL.js")).rev},{name:"nl",load:async()=>(await import("./chunks/nl-XH3L75DR.js")).nl},{name:"fold",load:async()=>(await import("./chunks/fold-XSVNTAWH.js")).fold},{name:"expand",load:async()=>(await import("./chunks/expand-26XPP5KB.js")).expand},{name:"unexpand",load:async()=>(await import("./chunks/unexpand-OYZ7KOYR.js")).unexpand},{name:"strings",load:async()=>(await import("./chunks/strings-XXKZCWY5.js")).strings},{name:"split",load:async()=>(await import("./chunks/split-YWV64TJH.js")).split},{name:"column",load:async()=>(await import("./chunks/column-XGV32UPN.js")).column},{name:"join",load:async()=>(await import("./chunks/join-Y4Q5WVVE.js")).join},{name:"tee",load:async()=>(await import("./chunks/tee-HK2SYCAR.js")).teeCommand},{name:"find",load:async()=>(await import("./chunks/find-GAYRV4IF.js")).findCommand},{name:"basename",load:async()=>(await import("./chunks/basename-KBUKWB2E.js")).basenameCommand},{name:"dirname",load:async()=>(await import("./chunks/dirname-5FAOMLBL.js")).dirnameCommand},{name:"tree",load:async()=>(await import("./chunks/tree-HEKABARE.js")).treeCommand},{name:"du",load:async()=>(await import("./chunks/du-LDAPXSGF.js")).duCommand},{name:"env",load:async()=>(await import("./chunks/env-NTPN5QYM.js")).envCommand},{name:"printenv",load:async()=>(await import("./chunks/env-NTPN5QYM.js")).printenvCommand},{name:"alias",load:async()=>(await import("./chunks/alias-3GODYSFD.js")).aliasCommand},{name:"unalias",load:async()=>(await import("./chunks/alias-3GODYSFD.js")).unaliasCommand},{name:"history",load:async()=>(await import("./chunks/history-UUKG55YW.js")).historyCommand},{name:"xargs",load:async()=>(await import("./chunks/xargs-SCYIFXOW.js")).xargsCommand},{name:"true",load:async()=>(await import("./chunks/true-DP5UZP52.js")).trueCommand},{name:"false",load:async()=>(await import("./chunks/true-DP5UZP52.js")).falseCommand},{name:"clear",load:async()=>(await import("./chunks/clear-KRGKPFOI.js")).clearCommand},{name:"bash",load:async()=>(await import("./chunks/bash-6ZHZ6BX7.js")).bashCommand},{name:"sh",load:async()=>(await import("./chunks/bash-6ZHZ6BX7.js")).shCommand},{name:"jq",load:async()=>(await import("./chunks/jq-FIV5Q5T4.js")).jqCommand},{name:"base64",load:async()=>(await import("./chunks/base64-43M2R3GA.js")).base64Command},{name:"diff",load:async()=>(await import("./chunks/diff-LE7GMFZD.js")).diffCommand},{name:"date",load:async()=>(await import("./chunks/date-WUPBL2TL.js")).dateCommand},{name:"sleep",load:async()=>(await import("./chunks/sleep-ND6FZRZ4.js")).sleepCommand},{name:"timeout",load:async()=>(await import("./chunks/timeout-Z24MNWOP.js")).timeoutCommand},{name:"time",load:async()=>(await import("./chunks/time-5R4QWCYF.js")).timeCommand},{name:"seq",load:async()=>(await import("./chunks/seq-V7KBLSQ7.js")).seqCommand},{name:"expr",load:async()=>(await import("./chunks/expr-4CJYC4LY.js")).exprCommand},{name:"md5sum",load:async()=>(await import("./chunks/md5sum-NCLXV2S3.js")).md5sumCommand},{name:"sha1sum",load:async()=>(await import("./chunks/sha1sum-BHNJ5ALF.js")).sha1sumCommand},{name:"sha256sum",load:async()=>(await import("./chunks/sha256sum-HJJ3NJ5L.js")).sha256sumCommand},{name:"file",load:async()=>(await import("./chunks/file-D5YKS5NV.js")).fileCommand},{name:"html-to-markdown",load:async()=>(await import("./chunks/html-to-markdown-WVZA3MCP.js")).htmlToMarkdownCommand},{name:"help",load:async()=>(await import("./chunks/help-DVG4AAGE.js")).helpCommand},{name:"which",load:async()=>(await import("./chunks/which-5PO4LAOG.js")).whichCommand},{name:"tac",load:async()=>(await import("./chunks/tac-T42SKDDI.js")).tac},{name:"hostname",load:async()=>(await import("./chunks/hostname-WY6RKE32.js")).hostname},{name:"whoami",load:async()=>(await import("./chunks/whoami-E7PN2UWC.js")).whoami},{name:"od",load:async()=>(await import("./chunks/od-52FBC34W.js")).od},{name:"gzip",load:async()=>(await import("./chunks/gzip-LHOO65AN.js")).gzipCommand},{name:"gunzip",load:async()=>(await import("./chunks/gzip-LHOO65AN.js")).gunzipCommand},{name:"zcat",load:async()=>(await import("./chunks/gzip-LHOO65AN.js")).zcatCommand}];(typeof __BROWSER__>"u"||!__BROWSER__)&&(Ye.push({name:"tar",load:async()=>(await import("./chunks/tar-TOWX2TDU.js")).tarCommand}),Ye.push({name:"yq",load:async()=>(await import("./chunks/yq-Q47JUWL6.js")).yqCommand}),Ye.push({name:"xan",load:async()=>(await import("./chunks/xan-MOZFJGMY.js")).xanCommand}),Ye.push({name:"sqlite3",load:async()=>(await import("./chunks/sqlite3-CVNFMP3Z.js")).sqlite3Command}));var ws=[];(typeof __BROWSER__>"u"||!__BROWSER__)&&(ws.push({name:"python3",load:async()=>(await import("./chunks/python3-QOJU2POC.js")).python3Command}),ws.push({name:"python",load:async()=>(await import("./chunks/python3-QOJU2POC.js")).pythonCommand}));var vs=[];(typeof __BROWSER__>"u"||!__BROWSER__)&&(vs.push({name:"js-exec",load:async()=>(await import("./chunks/js-exec-RGKNWHHL.js")).jsExecCommand}),vs.push({name:"node",load:async()=>(await import("./chunks/js-exec-RGKNWHHL.js")).nodeStubCommand}));var Li=[{name:"curl",load:async()=>(await import("./chunks/curl-SRTMGOVV.js")).curlCommand}],Br=new Map;function Dt(e){return{name:e.name,async execute(t,s){let r=Br.get(e.name);if(r||(r=await ge.runTrustedAsync(()=>e.load()),Br.set(e.name,r)),s.coverage&&(typeof __BROWSER__>"u"||!__BROWSER__)){let{emitFlagCoverage:n}=await import("./chunks/flag-coverage-LBMWMYOO.js");n(s.coverage,e.name,t)}return r.execute(t,s)}}}function Hr(e){return(e?Ye.filter(s=>e.includes(s.name)):Ye).map(Dt)}function Ur(){return Li.map(Dt)}function Zr(){return ws.map(Dt)}function qr(){return vs.map(Dt)}function Gr(e){return"load"in e&&typeof e.load=="function"}function Kr(e){let t=null;return{name:e.name,trusted:!0,async execute(s,r){return t||(t=await e.load()),t.execute(s,r)}}}var Fi=new TextEncoder,Mi=new TextDecoder;function Qe(e,t){if(e instanceof Uint8Array)return e;if(t==="base64")return Uint8Array.from(atob(e),s=>s.charCodeAt(0));if(t==="hex"){let s=new Uint8Array(e.length/2);for(let r=0;r<e.length;r+=2)s[r/2]=parseInt(e.slice(r,r+2),16);return s}if(t==="binary"||t==="latin1"){if(e.length<=65536)return Uint8Array.from(e,n=>n.charCodeAt(0));let r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return r}return Fi.encode(e)}function Tt(e,t){if(t==="base64"){if(typeof Buffer<"u")return Buffer.from(e).toString("base64");let s=65536,r="";for(let n=0;n<e.length;n+=s){let i=e.subarray(n,n+s);r+=String.fromCharCode(...i)}return btoa(r)}if(t==="hex")return Array.from(e).map(s=>s.toString(16).padStart(2,"0")).join("");if(t==="binary"||t==="latin1"){if(typeof Buffer<"u")return Buffer.from(e).toString(t);let s=65536;if(e.length<=s)return String.fromCharCode(...e);let r="";for(let n=0;n<e.length;n+=s){let i=e.subarray(n,n+s);r+=String.fromCharCode(...i)}return r}return Mi.decode(e)}function Fe(e){if(e!=null)return typeof e=="string"?e:e.encoding??void 0}var Je=new TextEncoder;function Wi(e){return typeof e=="object"&&e!==null&&!(e instanceof Uint8Array)&&"content"in e}var ft=class{data=new Map;constructor(t){if(this.data.set("/",{type:"directory",mode:493,mtime:new Date}),t)for(let[s,r]of Object.entries(t))typeof r=="function"?this.writeFileLazy(s,r):Wi(r)?this.writeFileSync(s,r.content,void 0,{mode:r.mode,mtime:r.mtime}):this.writeFileSync(s,r)}ensureParentDirs(t){let s=Ke(t);s!=="/"&&(this.data.has(s)||(this.ensureParentDirs(s),this.data.set(s,{type:"directory",mode:493,mtime:new Date})))}writeFileSync(t,s,r,n){W(t,"write");let i=M(t);this.ensureParentDirs(i);let a=Fe(r),o=Qe(s,a);this.data.set(i,{type:"file",content:o,mode:n?.mode??420,mtime:n?.mtime??new Date})}writeFileLazy(t,s,r){W(t,"write");let n=M(t);this.ensureParentDirs(n),this.data.set(n,{type:"file",lazy:s,mode:r?.mode??420,mtime:r?.mtime??new Date})}async materializeLazy(t,s){let r=await s.lazy(),i={type:"file",content:typeof r=="string"?Je.encode(r):r,mode:s.mode,mtime:s.mtime};return this.data.set(t,i),i}async readFile(t,s){let r=await this.readFileBuffer(t),n=Fe(s);return Tt(r,n)}async readFileBuffer(t){W(t,"open");let s=this.resolvePathWithSymlinks(t),r=this.data.get(s);if(!r)throw new Error(`ENOENT: no such file or directory, open '${t}'`);if(r.type!=="file")throw new Error(`EISDIR: illegal operation on a directory, read '${t}'`);if("lazy"in r){let n=await this.materializeLazy(s,r);return n.content instanceof Uint8Array?n.content:Je.encode(n.content)}return r.content instanceof Uint8Array?r.content:Je.encode(r.content)}async writeFile(t,s,r){this.writeFileSync(t,s,r)}async appendFile(t,s,r){W(t,"append");let n=M(t),i=this.data.get(n);if(i&&i.type==="directory")throw new Error(`EISDIR: illegal operation on a directory, write '${t}'`);let a=Fe(r),o=Qe(s,a);if(i?.type==="file"){let l=i;"lazy"in l&&(l=await this.materializeLazy(n,l));let c="content"in l&&l.content instanceof Uint8Array?l.content:Je.encode("content"in l?l.content:""),u=new Uint8Array(c.length+o.length);u.set(c),u.set(o,c.length),this.data.set(n,{type:"file",content:u,mode:l.mode,mtime:new Date})}else this.writeFileSync(t,s,r)}async exists(t){if(t.includes("\0"))return!1;try{let s=this.resolvePathWithSymlinks(t);return this.data.has(s)}catch{return!1}}async stat(t){W(t,"stat");let s=this.resolvePathWithSymlinks(t),r=this.data.get(s);if(!r)throw new Error(`ENOENT: no such file or directory, stat '${t}'`);r.type==="file"&&"lazy"in r&&(r=await this.materializeLazy(s,r));let n=0;return r.type==="file"&&"content"in r&&r.content&&(r.content instanceof Uint8Array?n=r.content.length:n=Je.encode(r.content).length),{isFile:r.type==="file",isDirectory:r.type==="directory",isSymbolicLink:!1,mode:r.mode,size:n,mtime:r.mtime||new Date}}async lstat(t){W(t,"lstat");let s=this.resolveIntermediateSymlinks(t),r=this.data.get(s);if(!r)throw new Error(`ENOENT: no such file or directory, lstat '${t}'`);if(r.type==="symlink")return{isFile:!1,isDirectory:!1,isSymbolicLink:!0,mode:r.mode,size:r.target.length,mtime:r.mtime||new Date};r.type==="file"&&"lazy"in r&&(r=await this.materializeLazy(s,r));let n=0;return r.type==="file"&&"content"in r&&r.content&&(r.content instanceof Uint8Array?n=r.content.length:n=Je.encode(r.content).length),{isFile:r.type==="file",isDirectory:r.type==="directory",isSymbolicLink:!1,mode:r.mode,size:n,mtime:r.mtime||new Date}}resolveIntermediateSymlinks(t){let s=M(t);if(s==="/")return"/";let r=s.slice(1).split("/");if(r.length<=1)return s;let n="",i=new Set;for(let a=0;a<r.length-1;a++){let o=r[a];n=`${n}/${o}`;let l=this.data.get(n),c=0,u=40;for(;l&&l.type==="symlink"&&c<u;){if(i.has(n))throw new Error(`ELOOP: too many levels of symbolic links, lstat '${t}'`);i.add(n),n=Xe(n,l.target),l=this.data.get(n),c++}if(c>=u)throw new Error(`ELOOP: too many levels of symbolic links, lstat '${t}'`)}return`${n}/${r[r.length-1]}`}resolvePathWithSymlinks(t){let s=M(t);if(s==="/")return"/";let r=s.slice(1).split("/"),n="",i=new Set;for(let a of r){n=`${n}/${a}`;let o=this.data.get(n),l=0,c=40;for(;o&&o.type==="symlink"&&l<c;){if(i.has(n))throw new Error(`ELOOP: too many levels of symbolic links, open '${t}'`);i.add(n),n=Xe(n,o.target),o=this.data.get(n),l++}if(l>=c)throw new Error(`ELOOP: too many levels of symbolic links, open '${t}'`)}return n}async mkdir(t,s){this.mkdirSync(t,s)}mkdirSync(t,s){W(t,"mkdir");let r=M(t);if(this.data.has(r)){if(this.data.get(r)?.type==="file")throw new Error(`EEXIST: file already exists, mkdir '${t}'`);if(!s?.recursive)throw new Error(`EEXIST: directory already exists, mkdir '${t}'`);return}let n=Ke(r);if(n!=="/"&&!this.data.has(n))if(s?.recursive)this.mkdirSync(n,{recursive:!0});else throw new Error(`ENOENT: no such file or directory, mkdir '${t}'`);this.data.set(r,{type:"directory",mode:493,mtime:new Date})}async readdir(t){return(await this.readdirWithFileTypes(t)).map(r=>r.name)}async readdirWithFileTypes(t){W(t,"scandir");let s=M(t),r=this.data.get(s);if(!r)throw new Error(`ENOENT: no such file or directory, scandir '${t}'`);let n=new Set;for(;r&&r.type==="symlink";){if(n.has(s))throw new Error(`ELOOP: too many levels of symbolic links, scandir '${t}'`);n.add(s),s=Xe(s,r.target),r=this.data.get(s)}if(!r)throw new Error(`ENOENT: no such file or directory, scandir '${t}'`);if(r.type!=="directory")throw new Error(`ENOTDIR: not a directory, scandir '${t}'`);let i=s==="/"?"/":`${s}/`,a=new Map;for(let[o,l]of this.data.entries())if(o!==s&&o.startsWith(i)){let c=o.slice(i.length),u=c.split("/")[0];u&&!c.includes("/",u.length)&&!a.has(u)&&a.set(u,{name:u,isFile:l.type==="file",isDirectory:l.type==="directory",isSymbolicLink:l.type==="symlink"})}return Array.from(a.values()).sort((o,l)=>o.name<l.name?-1:o.name>l.name?1:0)}async rm(t,s){W(t,"rm");let r=M(t),n=this.data.get(r);if(!n){if(s?.force)return;throw new Error(`ENOENT: no such file or directory, rm '${t}'`)}if(n.type==="directory"){let i=await this.readdir(r);if(i.length>0){if(!s?.recursive)throw new Error(`ENOTEMPTY: directory not empty, rm '${t}'`);for(let a of i){let o=kt(r,a);await this.rm(o,s)}}}this.data.delete(r)}async cp(t,s,r){W(t,"cp"),W(s,"cp");let n=M(t),i=M(s),a=this.data.get(n);if(!a)throw new Error(`ENOENT: no such file or directory, cp '${t}'`);if(a.type==="file")if(this.ensureParentDirs(i),"content"in a){let o=a.content instanceof Uint8Array?new Uint8Array(a.content):a.content;this.data.set(i,{...a,content:o})}else this.data.set(i,{...a});else if(a.type==="symlink")this.ensureParentDirs(i),this.data.set(i,{...a});else if(a.type==="directory"){if(!r?.recursive)throw new Error(`EISDIR: is a directory, cp '${t}'`);await this.mkdir(i,{recursive:!0});let o=await this.readdir(n);for(let l of o){let c=kt(n,l),u=kt(i,l);await this.cp(c,u,r)}}}async mv(t,s){await this.cp(t,s,{recursive:!0}),await this.rm(t,{recursive:!0})}getAllPaths(){return Array.from(this.data.keys())}resolvePath(t,s){return Ct(t,s)}async chmod(t,s){W(t,"chmod");let r=M(t),n=this.data.get(r);if(!n)throw new Error(`ENOENT: no such file or directory, chmod '${t}'`);n.mode=s}async symlink(t,s){W(s,"symlink");let r=M(s);if(this.data.has(r))throw new Error(`EEXIST: file already exists, symlink '${s}'`);this.ensureParentDirs(r),this.data.set(r,{type:"symlink",target:t,mode:511,mtime:new Date})}async link(t,s){W(t,"link"),W(s,"link");let r=M(t),n=M(s),i=this.data.get(r);if(!i)throw new Error(`ENOENT: no such file or directory, link '${t}'`);if(i.type!=="file")throw new Error(`EPERM: operation not permitted, link '${t}'`);if(this.data.has(n))throw new Error(`EEXIST: file already exists, link '${s}'`);let a=i;"lazy"in a&&(a=await this.materializeLazy(r,a)),this.ensureParentDirs(n),this.data.set(n,{type:"file",content:a.content,mode:a.mode,mtime:a.mtime})}async readlink(t){W(t,"readlink");let s=M(t),r=this.data.get(s);if(!r)throw new Error(`ENOENT: no such file or directory, readlink '${t}'`);if(r.type!=="symlink")throw new Error(`EINVAL: invalid argument, readlink '${t}'`);return r.target}async realpath(t){W(t,"realpath");let s=this.resolvePathWithSymlinks(t);if(!this.data.has(s))throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);return s}async utimes(t,s,r){W(t,"utimes");let n=M(t),i=this.resolvePathWithSymlinks(n),a=this.data.get(i);if(!a)throw new Error(`ENOENT: no such file or directory, utimes '${t}'`);a.mtime=r}};function zi(e){let t=e;return typeof t.mkdirSync=="function"&&typeof t.writeFileSync=="function"}function Vi(e,t){e.mkdirSync("/bin",{recursive:!0}),e.mkdirSync("/usr/bin",{recursive:!0}),t&&(e.mkdirSync("/home/user",{recursive:!0}),e.mkdirSync("/tmp",{recursive:!0}))}function ji(e){e.mkdirSync("/dev",{recursive:!0}),e.writeFileSync("/dev/null",""),e.writeFileSync("/dev/zero",new Uint8Array(0)),e.writeFileSync("/dev/stdin",""),e.writeFileSync("/dev/stdout",""),e.writeFileSync("/dev/stderr","")}function Bi(e,t){e.mkdirSync("/proc/self/fd",{recursive:!0}),e.writeFileSync("/proc/version",`${Or}
|
|
3
3
|
`),e.writeFileSync("/proc/self/exe","/bin/bash"),e.writeFileSync("/proc/self/cmdline","bash\0"),e.writeFileSync("/proc/self/comm",`bash
|
|
4
4
|
`),e.writeFileLazy?e.writeFileLazy("/proc/self/status",()=>fs(t)):e.writeFileSync("/proc/self/status",fs(t)),e.writeFileSync("/proc/self/fd/0","/dev/stdin"),e.writeFileSync("/proc/self/fd/1","/dev/stdout"),e.writeFileSync("/proc/self/fd/2","/dev/stderr")}function Xr(e,t,s={pid:1,ppid:0,uid:1e3,gid:1e3}){zi(e)&&(Vi(e,t),ji(e),Bi(e,s))}var Hi=["allexport","errexit","noglob","noclobber","noexec","nounset","pipefail","posix","verbose","xtrace"],Ui=["braceexpand","hashall","interactive-comments"];function $s(e){let t=[],s=[...Ui.map(r=>({name:r,enabled:!0})),...Hi.map(r=>({name:r,enabled:e[r]}))].sort((r,n)=>r.name.localeCompare(n.name));for(let r of s)r.enabled&&t.push(r.name);return t.join(":")}function tt(e){e.state.env.set("SHELLOPTS",$s(e.state.options))}var Zi=["dotglob","expand_aliases","extglob","failglob","globskipdots","globstar","lastpipe","nocaseglob","nocasematch","nullglob","xpg_echo"];function Es(e){let t=[];for(let s of Zi)e[s]&&t.push(s);return t.join(":")}function Ss(e){e.state.env.set("BASHOPTS",Es(e.state.shoptOptions))}var qi="BASH_ALIAS_";function Yr(e){return e.parts.length!==1?!1:e.parts[0].type==="Literal"}function Qr(e){if(e.parts.length!==1)return null;let t=e.parts[0];return t.type==="Literal"?t.value:null}function Jr(e,t){return e.env.get(`${qi}${t}`)}function As(e,t,s){if(!t.name||!Yr(t.name))return t;let r=Qr(t.name);if(!r)return t;let n=Jr(e,r);if(!n||s.has(r))return t;try{s.add(r);let i=new V,a=n,o=n.endsWith(" ");if(!o)for(let f of t.args){let d=tn(f);a+=` ${d}`}let l;try{l=i.parse(a)}catch(f){if(f instanceof Pt)throw f;return t}if(l.statements.length!==1||l.statements[0].pipelines.length!==1||l.statements[0].pipelines[0].commands.length!==1)return en(t,n);let c=l.statements[0].pipelines[0].commands[0];if(c.type!=="SimpleCommand")return en(t,n);let u={...c,assignments:[...t.assignments,...c.assignments],redirections:[...c.redirections,...t.redirections],line:t.line};if(o&&t.args.length>0&&(u={...u,args:[...u.args,...t.args]},u.args.length>0)){let f=u.args[0];if(Yr(f)){let d=Qr(f);if(d&&Jr(e,d)){let h={type:"SimpleCommand",name:f,args:u.args.slice(1),assignments:[],redirections:[]},p=As(e,h,s);p!==h&&(u={...u,name:p.name,args:[...p.args]})}}}return u}catch(i){throw s.delete(r),i}}function en(e,t){let s=t;for(let a of e.args){let o=tn(a);s+=` ${o}`}let r=new V,n=r.parseWordFromString("eval",!1,!1),i=r.parseWordFromString(`'${s.replace(/'/g,"'\\''")}'`,!1,!1);return{type:"SimpleCommand",name:n,args:[i],assignments:e.assignments,redirections:e.redirections,line:e.line}}function tn(e){let t="";for(let s of e.parts)switch(s.type){case"Literal":t+=s.value.replace(/([\s"'$`\\*?[\]{}()<>|&;#!])/g,"\\$1");break;case"SingleQuoted":t+=`'${s.value}'`;break;case"DoubleQuoted":t+=`"${s.parts.map(r=>r.type==="Literal"?r.value:`$${r.type}`).join("")}"`;break;case"ParameterExpansion":t+=`\${${s.parameter}}`;break;case"CommandSubstitution":t+="$(...)";break;case"ArithmeticExpansion":t+=`$((${s.expression}))`;break;case"Glob":t+=s.pattern;break;default:break}return t}async function sn(e,t){let s=t.parts.map(u=>u.type==="Literal"?u.value:"\0").join(""),r=s.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\(/);if(!r||!s.endsWith(")"))return null;let n=r[1],i=[],a=!1,o="",l=!1;for(let u of t.parts)if(u.type==="Literal"){let f=u.value;if(!a){let d=f.indexOf("=(");d!==-1&&(a=!0,f=f.slice(d+2))}if(a){f.endsWith(")")&&(f=f.slice(0,-1));let d=f.split(/(\s+)/);for(let h of d)/^\s+$/.test(h)?(o||l)&&(i.push(o),o="",l=!1):h&&(o+=h)}}else if(a)if(u.type==="BraceExpansion")if(/^\[.+\]=/.test(o))o+=Nt({type:"Word",parts:[u]});else{(o||l)&&(i.push(o),o="",l=!1);let d=await Ae(e,{type:"Word",parts:[u]});i.push(...d.values)}else{(u.type==="SingleQuoted"||u.type==="DoubleQuoted"||u.type==="Escaped")&&(l=!0);let f=await T(e,{type:"Word",parts:[u]});o+=f}(o||l)&&i.push(o);let c=i.map(u=>/^\[.+\]=/.test(u)?u:u===""?"''":/[\s"'\\$`!*?[\]{}|&;<>()]/.test(u)&&!u.startsWith("'")&&!u.startsWith('"')?`'${u.replace(/'/g,"'\\''")}'`:u);return`${n}=(${c.join(" ")})`}async function rn(e,t){let s=-1,r=-1,n=!1;for(let m=0;m<t.parts.length;m++){let y=t.parts[m];if(y.type==="Literal"){let b=y.value.indexOf("+=");if(b!==-1){let A=y.value.slice(0,b);if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(A)){s=m,r=b,n=!0;break}if(/^[a-zA-Z_][a-zA-Z0-9_]*\[[^\]]+\]$/.test(A)){s=m,r=b,n=!0;break}}let v=y.value.indexOf("=");if(v!==-1&&(v===0||y.value[v-1]!=="+")){let A=y.value.slice(0,v);if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(A)||/^[a-zA-Z_][a-zA-Z0-9_]*\[[^\]]+\]$/.test(A)){s=m,r=v;break}}}}if(s===-1)return null;let i=t.parts.slice(0,s),a=t.parts[s];if(a.type!=="Literal")return null;let o=n?2:1,l=a.value.slice(0,r),c=a.value.slice(r+o),u=t.parts.slice(s+1),f="";for(let m of i)f+=await T(e,{type:"Word",parts:[m]});f+=l;let d={type:"Word",parts:c!==""?[{type:"Literal",value:c},...u]:u},h=d.parts.length>0?await T(e,d):"";return`${f}${n?"+=":"="}${h}`}var Gi=["tar","yq","xan","sqlite3","python3","python"];function nn(e){return Gi.includes(e)}var L=Object.freeze({stdout:"",stderr:"",exitCode:0});function F(e=""){return{stdout:e,stderr:"",exitCode:0}}function _(e,t=1){return{stdout:"",stderr:e,exitCode:t}}function k(e,t,s){return{stdout:e,stderr:t,exitCode:s}}function X(e){return{stdout:"",stderr:"",exitCode:e?0:1}}function _e(e,t,s="",r=""){throw new Y(e,t,s,r)}function ie(e){let t=e.state.fileDescriptors;if(t&&t.size>=e.limits.maxFileDescriptors)throw new Y(`too many open file descriptors (max ${e.limits.maxFileDescriptors})`,"file_descriptors")}function _s(e,t){if(e.state.loopDepth===0){if(e.state.parentHasLoopContext)throw new Te;return L}if(t.length>1)throw new j(1,"",`bash: break: too many arguments
|
|
5
5
|
`);let s=1;if(t.length>0){let r=Number.parseInt(t[0],10);if(Number.isNaN(r)||r<1)throw new j(128,"",`bash: break: ${t[0]}: numeric argument required
|
|
@@ -12,27 +12,27 @@ import{B as Mr,C as Wr,D as le,E as je,F as ee,G as $e,H as Ot,I as zr,J as T,K
|
|
|
12
12
|
`,2):Rt(r)?X(await Lt(e,r,n)):jt(r)?X(Bt(r,n)):r==="!"?X(!n):r==="-v"?X(await Ht(e,n)):r==="-o"?X(Ns(e,n)):r==="="||r==="=="||r==="!="||r==="<"||r===">"||r==="-eq"||r==="-ne"||r==="-lt"||r==="-le"||r==="-gt"||r==="-ge"||r==="-nt"||r==="-ot"||r==="-ef"?_(`test: ${r}: unary operator expected
|
|
13
13
|
`,2):k("","",1)}if(t.length===3){let r=t[0],n=t[1],i=t[2];if(dt(n))return X(Vt(n,r,i));if(Wt(n)){let a=Ut(r),o=Ut(i);return!a.valid||!o.valid?k("","",2):X(zt(n,a.value,o.value))}if(Ft(n))return X(await Mt(e,n,r,i));switch(n){case"-a":return X(r!==""&&i!=="");case"-o":return X(r!==""||i!=="");case">":return X(r>i);case"<":return X(r<i)}if(r==="!"){let a=await ht(e,[n,i]);return k("",a.stderr,a.exitCode===0?1:a.exitCode===1?0:a.exitCode)}if(r==="("&&i===")")return X(n!=="")}if(t.length===4){if(t[0]==="!"){let r=await ht(e,t.slice(1));return k("",r.stderr,r.exitCode===0?1:r.exitCode===1?0:r.exitCode)}if(t[0]==="("&&t[3]===")")return ht(e,[t[1],t[2]])}let s=await cn(e,t,0);return s.pos<t.length?_(`test: too many arguments
|
|
14
14
|
`,2):X(s.value)}async function cn(e,t,s){return Ji(e,t,s)}async function Ji(e,t,s){let{value:r,pos:n}=await an(e,t,s);for(;t[n]==="-o";){let i=await an(e,t,n+1);r=r||i.value,n=i.pos}return{value:r,pos:n}}async function an(e,t,s){let{value:r,pos:n}=await Ps(e,t,s);for(;t[n]==="-a";){let i=await Ps(e,t,n+1);r=r&&i.value,n=i.pos}return{value:r,pos:n}}async function Ps(e,t,s){if(t[s]==="!"){let{value:r,pos:n}=await Ps(e,t,s+1);return{value:!r,pos:n}}return ea(e,t,s)}async function ea(e,t,s){let r=t[s];if(r==="("){let{value:i,pos:a}=await cn(e,t,s+1);return{value:i,pos:t[a]===")"?a+1:a}}let n=t[s+1];if(dt(n)){let i=r,a=t[s+2]??"";return{value:Vt(n,i,a),pos:s+3}}if(Wt(n)){let i=Ut(r),a=Ut(t[s+2]??"0");return!i.valid||!a.valid?{value:!1,pos:s+3}:{value:zt(n,i.value,a.value),pos:s+3}}if(Ft(n)){let i=r,a=t[s+2]??"";return{value:await Mt(e,n,i,a),pos:s+3}}if(Rt(r)){let i=t[s+1]??"";return{value:await Lt(e,r,i),pos:s+2}}if(jt(r)){let i=t[s+1]??"";return{value:Bt(r,i),pos:s+2}}if(r==="-v"){let i=t[s+1]??"";return{value:await Ht(e,i),pos:s+2}}if(r==="-o"){let i=t[s+1]??"";return{value:Ns(e,i),pos:s+2}}return{value:r!==void 0&&r!=="",pos:s+1}}function st(e,t,s=!1,r=!1){let n=`^${un(t,r)}$`;return ct(n,s?"is":"s").test(e)}function un(e,t){let s="";for(let r=0;r<e.length;r++){let n=e[r];if(t&&(n==="@"||n==="*"||n==="+"||n==="?"||n==="!")&&r+1<e.length&&e[r+1]==="("){let i=fn(e,r+1);if(i!==-1){let a=e.slice(r+2,i),o=dn(a),l=o.map(u=>un(u,t)),c=l.length>0?l.join("|"):"(?:)";if(n==="@")s+=`(?:${c})`;else if(n==="*")s+=`(?:${c})*`;else if(n==="+")s+=`(?:${c})+`;else if(n==="?")s+=`(?:${c})?`;else if(n==="!")if(i<e.length-1){let f=o.map(h=>hn(h,t));if(f.every(h=>h!==null)&&f.every(h=>h===f[0])&&f[0]!==null){let h=f[0];if(h===0)s+="(?:.+)";else{let p=[];h>0&&p.push(`.{0,${h-1}}`),p.push(`.{${h+1},}`),p.push(`(?!(?:${c})).{${h}}`),s+=`(?:${p.join("|")})`}}else s+=`(?:(?!(?:${c})).)*?`}else s+=`(?!(?:${c})$).*`;r=i;continue}}if(n==="\\")if(r+1<e.length){let i=e[r+1];/[\\^$.|+(){}[\]*?]/.test(i)?s+=`\\${i}`:s+=i,r++}else s+="\\\\";else if(n==="*")s+=".*";else if(n==="?")s+=".";else if(n==="["){let i=e.indexOf("]",r+1);i!==-1?(s+=e.slice(r,i+1),r=i):s+="\\["}else/[\\^$.|+(){}]/.test(n)?s+=`\\${n}`:s+=n}return s}function fn(e,t){let s=1,r=t+1;for(;r<e.length&&s>0;){let n=e[r];if(n==="\\"){r+=2;continue}if(n==="(")s++;else if(n===")"&&(s--,s===0))return r;r++}return-1}function dn(e){let t=[],s="",r=0,n=0;for(;n<e.length;){let i=e[n];if(i==="\\"){s+=i,n+1<e.length?(s+=e[n+1],n+=2):n++;continue}i==="("?(r++,s+=i):i===")"?(r--,s+=i):i==="|"&&r===0?(t.push(s),s=""):s+=i,n++}return t.push(s),t}function hn(e,t){let s=0,r=0;for(;r<e.length;){let n=e[r];if(t&&(n==="@"||n==="*"||n==="+"||n==="?"||n==="!")&&r+1<e.length&&e[r+1]==="("){let i=fn(e,r+1);if(i!==-1){if(n==="@"){let a=e.slice(r+2,i),l=dn(a).map(c=>hn(c,t));if(l.every(c=>c!==null)&&l.every(c=>c===l[0])){s+=l[0],r=i+1;continue}return null}return null}}if(n==="*")return null;if(n==="?"){s+=1,r++;continue}if(n==="["){let i=e.indexOf("]",r+1);if(i!==-1){s+=1,r=i+1;continue}s+=1,r++;continue}if(n==="\\"){s+=1,r+=2;continue}s+=1,r++}return s}function Ns(e,t){let r=new Map([["errexit",()=>e.state.options.errexit===!0],["nounset",()=>e.state.options.nounset===!0],["pipefail",()=>e.state.options.pipefail===!0],["xtrace",()=>e.state.options.xtrace===!0],["e",()=>e.state.options.errexit===!0],["u",()=>e.state.options.nounset===!0],["x",()=>e.state.options.xtrace===!0]]).get(t);return r?r():!1}async function on(e,t){if(t=t.trim(),t==="")return 0;if(/^[+-]?(\d+#[a-zA-Z0-9@_]+|0[xX][0-9a-fA-F]+|0[0-7]+|\d+)$/.test(t))return ln(t);try{let s=new V,r=Q(s,t);return await B(e,r.expression)}catch{return ln(t)}}function ta(e,t){let s=0;for(let r of e){let n;if(r>="0"&&r<="9")n=r.charCodeAt(0)-48;else if(r>="a"&&r<="z")n=r.charCodeAt(0)-97+10;else if(r>="A"&&r<="Z")n=r.charCodeAt(0)-65+36;else if(r==="@")n=62;else if(r==="_")n=63;else return Number.NaN;if(n>=t)return Number.NaN;s=s*t+n}return s}function ln(e){if(e=e.trim(),e==="")return 0;let t=!1;e.startsWith("-")?(t=!0,e=e.slice(1)):e.startsWith("+")&&(e=e.slice(1));let s,r=e.match(/^(\d+)#([a-zA-Z0-9@_]+)$/);if(r){let n=Number.parseInt(r[1],10);n>=2&&n<=64?s=ta(r[2],n):s=0}else/^0[xX][0-9a-fA-F]+$/.test(e)?s=Number.parseInt(e,16):/^0[0-7]+$/.test(e)?s=Number.parseInt(e,8):s=Number.parseInt(e,10);return Number.isNaN(s)&&(s=0),t?-s:s}function Ut(e){if(e=e.trim(),e==="")return{value:0,valid:!0};let t=!1;if(e.startsWith("-")?(t=!0,e=e.slice(1)):e.startsWith("+")&&(e=e.slice(1)),!/^\d+$/.test(e))return{value:0,valid:!1};let s=Number.parseInt(e,10);return Number.isNaN(s)?{value:0,valid:!1}:{value:t?-s:s,valid:!0}}function sa(e){let t="",s=0;for(;s<e.length;)if(e[s]==="\\"&&s+1<e.length)t+=e[s]+e[s+1],s+=2;else if(e[s]==="["){let r=ra(e,s);t+=r.converted,s=r.endIndex}else t+=e[s],s++;return t}function ra(e,t){let s=t+1,r="[";s<e.length&&(e[s]==="^"||e[s]==="!")&&(r+="^",s++);let n=!1;s<e.length&&e[s]==="]"&&(n=!0,s++);let i=!1;s<e.length&&e[s]==="["&&s+1<e.length&&e[s+1]!==":"&&(i=!0,s++);let a="",o=!1;for(;s<e.length;){let l=e[s];if(l==="]"){o=!0,s++;break}if(l==="["&&s+1<e.length&&e[s+1]===":"){let c=e.indexOf(":]",s+2);if(c!==-1){let u=e.slice(s+2,c);a+=na(u),s=c+2;continue}}if(l==="["&&s+1<e.length){let c=e[s+1];if(c==="."||c==="="){let u=`${c}]`,f=e.indexOf(u,s+2);if(f!==-1){let d=e.slice(s+2,f);a+=d,s=f+2;continue}}}if(l==="\\"&&s+1<e.length){a+=l+e[s+1],s+=2;continue}a+=l,s++}return o?(n&&(r+="\\]"),i&&(r+="\\["),r+=a,r+="]",{converted:r,endIndex:s}):{converted:"\\[",endIndex:t+1}}function na(e){return new Map([["alnum","a-zA-Z0-9"],["alpha","a-zA-Z"],["ascii","\\x00-\\x7F"],["blank"," \\t"],["cntrl","\\x00-\\x1F\\x7F"],["digit","0-9"],["graph","!-~"],["lower","a-z"],["print"," -~"],["punct","!-/:-@\\[-`{-~"],["space"," \\t\\n\\r\\f\\v"],["upper","A-Z"],["word","a-zA-Z0-9_"],["xdigit","0-9A-Fa-f"]]).get(e)??""}function Ce(e){let t=[],s="",r=!1,n=!1,i=!1,a=!1;for(let o of e){if(i){s+=o,i=!1,a=!0;continue}if(o==="\\"){i=!0;continue}if(o==="'"&&!n){r||(a=!0),r=!r;continue}if(o==='"'&&!r){n||(a=!0),n=!n;continue}if((o===" "||o===" "||o===`
|
|
15
|
-
`)&&!r&&!n){a&&(t.push(s),s="",a=!1);continue}s+=o,a=!0}return a&&t.push(s),t}function Zt(e){let t=[],s=0;for(;s<e.length;){for(;s<e.length&&/\s/.test(e[s]);)s++;if(s>=e.length)break;if(e[s]!=="["){s++;continue}s++;let r="";if(e[s]==="'"||e[s]==='"'){let i=e[s];for(s++;s<e.length&&e[s]!==i;)r+=e[s],s++;e[s]===i&&s++}else for(;s<e.length&&e[s]!=="]"&&e[s]!=="=";)r+=e[s],s++;for(;s<e.length&&e[s]!=="]";)s++;if(e[s]==="]"&&s++,e[s]!=="=")continue;s++;let n="";if(e[s]==="'"||e[s]==='"'){let i=e[s];for(s++;s<e.length&&e[s]!==i;)e[s]==="\\"&&s+1<e.length&&s++,n+=e[s],s++;e[s]===i&&s++}else for(;s<e.length&&!/\s/.test(e[s]);)n+=e[s],s++;t.push([r,n])}return t}function pn(e){let t=e.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\((.*)\)$/s);if(t)return{name:t[1],isArray:!0,arrayElements:Ce(t[2])};let s=e.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([^\]]+)\]=(.*)$/s);if(s)return{name:s[1],isArray:!1,arrayIndex:s[2],value:s[3]};if(e.includes("=")){let r=e.indexOf("=");return{name:e.slice(0,r),isArray:!1,value:e.slice(r+1)}}return{name:e,isArray:!1}}async function ia(e,t){try{let s=new V,r=Q(s,t);return await B(e,r.expression)}catch{let s=parseInt(t,10);return Number.isNaN(s)?0:s}}async function mn(e,t,s={}){let{name:r,isArray:n,arrayElements:i,value:a,arrayIndex:o}=t,{makeReadonly:l=!1,checkReadonly:c=!0}=s;if(c){let u=ee(e,r);if(u)return u}if(n&&i){for(let u=0;u<i.length;u++)e.state.env.set(`${r}_${u}`,i[u]);e.state.env.set(`${r}__length`,String(i.length))}else if(o!==void 0&&a!==void 0){let u=await ia(e,o);e.state.env.set(`${r}_${u}`,a);let f=parseInt(e.state.env.get(`${r}__length`)??"0",10);u>=f&&e.state.env.set(`${r}__length`,String(u+1))}else a!==void 0&&e.state.env.set(r,a);return l&&le(e,r),null}function We(e,t){e.state.localVarDepth=e.state.localVarDepth||new Map,e.state.localVarDepth.set(t,e.state.callDepth)}function rt(e,t){return e.state.localVarDepth?.get(t)}function qt(e,t){e.state.localVarDepth?.delete(t)}function yn(e,t,s){e.state.localVarStack=e.state.localVarStack||new Map;let r=e.state.localVarStack.get(t)||[];r.push({value:s,scopeIndex:e.state.localScopes.length-1}),e.state.localVarStack.set(t,r)}function Gt(e,t){let s=e.state.localVarStack?.get(t);if(!(!s||s.length===0))return s.pop()}function gn(e,t){if(e.state.localVarStack)for(let[s,r]of e.state.localVarStack.entries()){for(;r.length>0&&r[r.length-1].scopeIndex===t;)r.pop();r.length===0&&e.state.localVarStack.delete(s)}}var Os=new Set([":",".","break","continue","eval","exec","exit","export","readonly","return","set","shift","trap","unset"]);function wn(e){return Os.has(e)}var
|
|
15
|
+
`)&&!r&&!n){a&&(t.push(s),s="",a=!1);continue}s+=o,a=!0}return a&&t.push(s),t}function Zt(e){let t=[],s=0;for(;s<e.length;){for(;s<e.length&&/\s/.test(e[s]);)s++;if(s>=e.length)break;if(e[s]!=="["){s++;continue}s++;let r="";if(e[s]==="'"||e[s]==='"'){let i=e[s];for(s++;s<e.length&&e[s]!==i;)r+=e[s],s++;e[s]===i&&s++}else for(;s<e.length&&e[s]!=="]"&&e[s]!=="=";)r+=e[s],s++;for(;s<e.length&&e[s]!=="]";)s++;if(e[s]==="]"&&s++,e[s]!=="=")continue;s++;let n="";if(e[s]==="'"||e[s]==='"'){let i=e[s];for(s++;s<e.length&&e[s]!==i;)e[s]==="\\"&&s+1<e.length&&s++,n+=e[s],s++;e[s]===i&&s++}else for(;s<e.length&&!/\s/.test(e[s]);)n+=e[s],s++;t.push([r,n])}return t}function pn(e){let t=e.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\((.*)\)$/s);if(t)return{name:t[1],isArray:!0,arrayElements:Ce(t[2])};let s=e.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([^\]]+)\]=(.*)$/s);if(s)return{name:s[1],isArray:!1,arrayIndex:s[2],value:s[3]};if(e.includes("=")){let r=e.indexOf("=");return{name:e.slice(0,r),isArray:!1,value:e.slice(r+1)}}return{name:e,isArray:!1}}async function ia(e,t){try{let s=new V,r=Q(s,t);return await B(e,r.expression)}catch{let s=parseInt(t,10);return Number.isNaN(s)?0:s}}async function mn(e,t,s={}){let{name:r,isArray:n,arrayElements:i,value:a,arrayIndex:o}=t,{makeReadonly:l=!1,checkReadonly:c=!0}=s;if(c){let u=ee(e,r);if(u)return u}if(n&&i){for(let u=0;u<i.length;u++)e.state.env.set(`${r}_${u}`,i[u]);e.state.env.set(`${r}__length`,String(i.length))}else if(o!==void 0&&a!==void 0){let u=await ia(e,o);e.state.env.set(`${r}_${u}`,a);let f=parseInt(e.state.env.get(`${r}__length`)??"0",10);u>=f&&e.state.env.set(`${r}__length`,String(u+1))}else a!==void 0&&e.state.env.set(r,a);return l&&le(e,r),null}function We(e,t){e.state.localVarDepth=e.state.localVarDepth||new Map,e.state.localVarDepth.set(t,e.state.callDepth)}function rt(e,t){return e.state.localVarDepth?.get(t)}function qt(e,t){e.state.localVarDepth?.delete(t)}function yn(e,t,s){e.state.localVarStack=e.state.localVarStack||new Map;let r=e.state.localVarStack.get(t)||[];r.push({value:s,scopeIndex:e.state.localScopes.length-1}),e.state.localVarStack.set(t,r)}function Gt(e,t){let s=e.state.localVarStack?.get(t);if(!(!s||s.length===0))return s.pop()}function gn(e,t){if(e.state.localVarStack)for(let[s,r]of e.state.localVarStack.entries()){for(;r.length>0&&r[r.length-1].scopeIndex===t;)r.pop();r.length===0&&e.state.localVarStack.delete(s)}}var Os=new Set([":",".","break","continue","eval","exec","exit","export","readonly","return","set","shift","trap","unset"]);function wn(e){return Os.has(e)}var xs=new Set(["if","then","else","elif","fi","case","esac","for","select","while","until","do","done","in","function","{","}","time","[[","]]","!"]),nt=new Set([":","true","false","cd","export","unset","exit","local","set","break","continue","return","eval","shift","getopts","compgen","complete","compopt","pushd","popd","dirs","source",".","read","mapfile","readarray","declare","typeset","readonly","let","command","shopt","exec","test","[","echo","printf","pwd","alias","unalias","type","hash","ulimit","umask","trap","times","wait","kill","jobs","fg","bg","disown","suspend","fc","history","help","enable","builtin","caller"]);async function Be(e,t,s,r){try{if((await e.fs.stat(t)).isDirectory)return`bash: ${s}: Is a directory
|
|
16
16
|
`;if(r.checkNoclobber&&e.state.options.noclobber&&!r.isClobber&&s!=="/dev/null")return`bash: ${s}: cannot overwrite existing file
|
|
17
|
-
`}catch{}return null}function
|
|
18
|
-
`};s.set(r,await T(e,n.target))}else{let a=await
|
|
17
|
+
`}catch{}return null}function De(e){let s=Math.min(e.length,8192);for(let r=0;r<s;r++)if(e.charCodeAt(r)>127)return"utf8";return"binary"}function aa(e){if(!e.startsWith("__rw__:"))return null;let t=e.slice(7),s=t.indexOf(":");if(s===-1)return null;let r=Number.parseInt(t.slice(0,s),10);if(Number.isNaN(r)||r<0)return null;let n=s+1,i=t.slice(n,n+r),a=n+r+1,o=t.slice(a),l=o.indexOf(":");if(l===-1)return null;let c=Number.parseInt(o.slice(0,l),10);if(Number.isNaN(c)||c<0)return null;let u=o.slice(l+1);return{path:i,position:c,content:u}}async function vn(e,t){let s=new Map;for(let r=0;r<t.length;r++){let n=t[r];if(n.target.type==="HereDoc")continue;if(n.operator===">&"||n.operator==="<&"){if(gs(e,n.target))return{targets:s,error:`bash: $@: ambiguous redirect
|
|
18
|
+
`};s.set(r,await T(e,n.target))}else{let a=await xt(e,n.target);if("error"in a)return{targets:s,error:a.error};s.set(r,a.target)}}return{targets:s}}function oa(e){e.state.nextFd===void 0&&(e.state.nextFd=10);let t=e.state.nextFd,s=e.limits.maxFileDescriptors;if(t>=s)throw new Error(`bash: cannot allocate file descriptor: too many open files (max ${s})`);return e.state.nextFd++,t}async function Kt(e,t){for(let s of t){if(!s.fdVariable)continue;if(e.state.fileDescriptors||(e.state.fileDescriptors=new Map),(s.operator===">&"||s.operator==="<&")&&s.target.type==="Word"&&await T(e,s.target)==="-"){let i=e.state.env.get(s.fdVariable);if(i!==void 0){let a=Number.parseInt(i,10);Number.isNaN(a)||e.state.fileDescriptors.delete(a)}continue}let r=oa(e);if(e.state.env.set(s.fdVariable,String(r)),s.target.type==="Word"){let n=await T(e,s.target);if(s.operator===">&"||s.operator==="<&"){let i=Number.parseInt(n,10);if(!Number.isNaN(i)){let a=e.state.fileDescriptors.get(i);a!==void 0&&(ie(e),e.state.fileDescriptors.set(r,a));continue}}if(s.operator===">"||s.operator===">>"||s.operator===">|"||s.operator==="&>"||s.operator==="&>>"){let i=e.fs.resolvePath(e.state.cwd,n);(s.operator===">"||s.operator===">|"||s.operator==="&>")&&await e.fs.writeFile(i,"","binary"),ie(e),e.state.fileDescriptors.set(r,`__file__:${i}`)}else if(s.operator==="<<<")ie(e),e.state.fileDescriptors.set(r,`${n}
|
|
19
19
|
`);else if(s.operator==="<"||s.operator==="<>")try{let i=e.fs.resolvePath(e.state.cwd,n),a=await e.fs.readFile(i);ie(e),e.state.fileDescriptors.set(r,a)}catch{return k("",`bash: ${n}: No such file or directory
|
|
20
|
-
`,1)}}}return null}async function ke(e,t){for(let s of t){if(s.target.type==="HereDoc")continue;let r=s.operator===">&";if(s.operator!==">"&&s.operator!==">|"&&s.operator!=="&>"&&!r)continue;let n;if(r){if(n=await T(e,s.target),n==="-"||!Number.isNaN(Number.parseInt(n,10))||s.fd!=null)continue}else{let o=await
|
|
20
|
+
`,1)}}}return null}async function ke(e,t){for(let s of t){if(s.target.type==="HereDoc")continue;let r=s.operator===">&";if(s.operator!==">"&&s.operator!==">|"&&s.operator!=="&>"&&!r)continue;let n;if(r){if(n=await T(e,s.target),n==="-"||!Number.isNaN(Number.parseInt(n,10))||s.fd!=null)continue}else{let o=await xt(e,s.target);if("error"in o)return k("",o.error,1);n=o.target}let i=e.fs.resolvePath(e.state.cwd,n),a=s.operator===">|";if(i.includes("\0"))return k("",`bash: ${n}: No such file or directory
|
|
21
21
|
`,1);try{let o=await e.fs.stat(i);if(o.isDirectory)return k("",`bash: ${n}: Is a directory
|
|
22
22
|
`,1);if(e.state.options.noclobber&&!a&&!o.isDirectory&&n!=="/dev/null")return k("",`bash: ${n}: cannot overwrite existing file
|
|
23
23
|
`,1)}catch{}if(n!=="/dev/null"&&n!=="/dev/stdout"&&n!=="/dev/stderr"&&n!=="/dev/full"&&await e.fs.writeFile(i,"","binary"),n==="/dev/full")return k("",`bash: /dev/full: No space left on device
|
|
24
|
-
`,1)}return null}async function Z(e,t,s,r){let{stdout:n,stderr:i,exitCode:a}=t,o=t.stdoutEncoding==="binary"?()=>"binary":u=>
|
|
25
|
-
`,a=1,n="";continue}d=await T(e,f.target)}else{let m=await
|
|
24
|
+
`,1)}return null}async function Z(e,t,s,r){let{stdout:n,stderr:i,exitCode:a}=t,o=t.stdoutEncoding==="binary"?()=>"binary":u=>De(u);for(let u=0;u<s.length;u++){let f=s[u];if(f.target.type==="HereDoc")continue;let d,h=r?.get(u);if(h!==void 0)d=h;else if(f.operator===">&"||f.operator==="<&"){if(gs(e,f.target)){i+=`bash: $@: ambiguous redirect
|
|
25
|
+
`,a=1,n="";continue}d=await T(e,f.target)}else{let m=await xt(e,f.target);if("error"in m){i+=m.error,a=1,n="";continue}d=m.target}if(!f.fdVariable){if(d.includes("\0")){i+=`bash: ${d.replace(/\0/g,"")}: No such file or directory
|
|
26
26
|
`,a=1,n="";continue}switch(f.operator){case">":case">|":{let p=f.fd??1,m=f.operator===">|";if(p===1){if(d==="/dev/stdout")break;if(d==="/dev/stderr"){i+=n,n="";break}if(d==="/dev/full"){i+=`bash: echo: write error: No space left on device
|
|
27
27
|
`,a=1,n="";break}let y=e.fs.resolvePath(e.state.cwd,d),b=await Be(e,y,d,{checkNoclobber:!0,isClobber:m});if(b){i+=b,a=1,n="";break}await e.fs.writeFile(y,n,o(n)),n=""}else if(p===2){if(d==="/dev/stderr")break;if(d==="/dev/stdout"){n+=i,i="";break}if(d==="/dev/full"){i+=`bash: echo: write error: No space left on device
|
|
28
|
-
`,a=1;break}if(d==="/dev/null")i="";else{let y=e.fs.resolvePath(e.state.cwd,d),b=await Be(e,y,d,{checkNoclobber:!0,isClobber:m});if(b){i+=b,a=1;break}await e.fs.writeFile(y,i,
|
|
28
|
+
`,a=1;break}if(d==="/dev/null")i="";else{let y=e.fs.resolvePath(e.state.cwd,d),b=await Be(e,y,d,{checkNoclobber:!0,isClobber:m});if(b){i+=b,a=1;break}await e.fs.writeFile(y,i,De(i)),i=""}}break}case">>":{let p=f.fd??1;if(p===1){if(d==="/dev/stdout")break;if(d==="/dev/stderr"){i+=n,n="";break}if(d==="/dev/full"){i+=`bash: echo: write error: No space left on device
|
|
29
29
|
`,a=1,n="";break}let m=e.fs.resolvePath(e.state.cwd,d),y=await Be(e,m,d,{});if(y){i+=y,a=1,n="";break}await e.fs.appendFile(m,n,o(n)),n=""}else if(p===2){if(d==="/dev/stderr")break;if(d==="/dev/stdout"){n+=i,i="";break}if(d==="/dev/full"){i+=`bash: echo: write error: No space left on device
|
|
30
|
-
`,a=1;break}let m=e.fs.resolvePath(e.state.cwd,d),y=await Be(e,m,d,{});if(y){i+=y,a=1;break}await e.fs.appendFile(m,i,
|
|
31
|
-
`,a=1)}break}if(d==="2"||d==="&2")p===1&&(i+=n,n="");else if(d==="1"||d==="&1")n+=i,i="";else{let m=Number.parseInt(d,10);if(Number.isNaN(m)){if(f.operator===">&"){let y=e.fs.resolvePath(e.state.cwd,d),b=await Be(e,y,d,{checkNoclobber:!0});if(b){i=b,a=1,n="";break}if(f.fd==null){let v=n+i;await e.fs.writeFile(y,v,o(v)),n="",i=""}else p===1?(await e.fs.writeFile(y,n,o(n)),n=""):p===2&&(await e.fs.writeFile(y,i,
|
|
30
|
+
`,a=1;break}let m=e.fs.resolvePath(e.state.cwd,d),y=await Be(e,m,d,{});if(y){i+=y,a=1;break}await e.fs.appendFile(m,i,De(i)),i=""}break}case">&":case"<&":{let p=f.fd??1;if(d==="-")break;if(d.endsWith("-")){let m=d.slice(0,-1),y=Number.parseInt(m,10);if(!Number.isNaN(y)){let b=e.state.fileDescriptors?.get(y);b!==void 0?(e.state.fileDescriptors||(e.state.fileDescriptors=new Map),e.state.fileDescriptors.set(p,b),y>=3&&e.state.fileDescriptors?.delete(y)):y===1||y===2?(e.state.fileDescriptors||(e.state.fileDescriptors=new Map),e.state.fileDescriptors.set(p,`__dupout__:${y}`)):y===0?(e.state.fileDescriptors||(e.state.fileDescriptors=new Map),e.state.fileDescriptors.set(p,`__dupin__:${y}`)):y>=3&&(i+=`bash: ${y}: Bad file descriptor
|
|
31
|
+
`,a=1)}break}if(d==="2"||d==="&2")p===1&&(i+=n,n="");else if(d==="1"||d==="&1")n+=i,i="";else{let m=Number.parseInt(d,10);if(Number.isNaN(m)){if(f.operator===">&"){let y=e.fs.resolvePath(e.state.cwd,d),b=await Be(e,y,d,{checkNoclobber:!0});if(b){i=b,a=1,n="";break}if(f.fd==null){let v=n+i;await e.fs.writeFile(y,v,o(v)),n="",i=""}else p===1?(await e.fs.writeFile(y,n,o(n)),n=""):p===2&&(await e.fs.writeFile(y,i,De(i)),i="")}}else{let y=e.state.fileDescriptors?.get(m);if(y?.startsWith("__file__:")){let b=y.slice(9);p===1?(await e.fs.appendFile(b,n,o(n)),n=""):p===2&&(await e.fs.appendFile(b,i,De(i)),i="")}else if(y?.startsWith("__rw__:")){let b=aa(y);b&&(p===1?(await e.fs.appendFile(b.path,n,o(n)),n=""):p===2&&(await e.fs.appendFile(b.path,i,De(i)),i=""))}else if(y?.startsWith("__dupout__:")){let b=Number.parseInt(y.slice(11),10);if(b!==1)if(b===2)p===1&&(i+=n,n="");else{let v=e.state.fileDescriptors?.get(b);if(v?.startsWith("__file__:")){let A=v.slice(9);p===1?(await e.fs.appendFile(A,n,o(n)),n=""):p===2&&(await e.fs.appendFile(A,i,De(i)),i="")}}}else y?.startsWith("__dupin__:")?(i+=`bash: ${m}: Bad file descriptor
|
|
32
32
|
`,a=1,n=""):m>=3&&(i+=`bash: ${m}: Bad file descriptor
|
|
33
33
|
`,a=1,n="")}}break}case"&>":{if(d==="/dev/full"){i=`bash: echo: write error: No space left on device
|
|
34
34
|
`,a=1,n="";break}let p=e.fs.resolvePath(e.state.cwd,d),m=await Be(e,p,d,{checkNoclobber:!0});if(m){i=m,a=1,n="";break}let y=n+i;await e.fs.writeFile(p,y,o(y)),n="",i="";break}case"&>>":{if(d==="/dev/full"){i=`bash: echo: write error: No space left on device
|
|
35
|
-
`,a=1,n="";break}let p=e.fs.resolvePath(e.state.cwd,d),m=await Be(e,p,d,{});if(m){i=m,a=1,n="";break}let y=n+i;await e.fs.appendFile(p,y,o(y)),n="",i="";break}}}}let l=e.state.fileDescriptors?.get(1);if(l){if(l==="__dupout__:2")i+=n,n="";else if(l.startsWith("__file__:")){let u=l.slice(9);await e.fs.appendFile(u,n,o(n)),n=""}else if(l.startsWith("__file_append__:")){let u=l.slice(16);await e.fs.appendFile(u,n,o(n)),n=""}}let c=e.state.fileDescriptors?.get(2);if(c){if(c==="__dupout__:1")n+=i,i="";else if(c.startsWith("__file__:")){let u=c.slice(9);await e.fs.appendFile(u,i,
|
|
35
|
+
`,a=1,n="";break}let p=e.fs.resolvePath(e.state.cwd,d),m=await Be(e,p,d,{});if(m){i=m,a=1,n="";break}let y=n+i;await e.fs.appendFile(p,y,o(y)),n="",i="";break}}}}let l=e.state.fileDescriptors?.get(1);if(l){if(l==="__dupout__:2")i+=n,n="";else if(l.startsWith("__file__:")){let u=l.slice(9);await e.fs.appendFile(u,n,o(n)),n=""}else if(l.startsWith("__file_append__:")){let u=l.slice(16);await e.fs.appendFile(u,n,o(n)),n=""}}let c=e.state.fileDescriptors?.get(2);if(c){if(c==="__dupout__:1")n+=i,i="";else if(c.startsWith("__file__:")){let u=c.slice(9);await e.fs.appendFile(u,i,De(i)),i=""}else if(c.startsWith("__file_append__:")){let u=c.slice(16);await e.fs.appendFile(u,i,De(i)),i=""}}return k(n,i,a)}function bn(e,t){if(e.state.options.posix&&Os.has(t.name)){let r=`bash: line ${e.state.currentLine}: \`${t.name}': is a special builtin
|
|
36
36
|
`;throw new j(2,"",r)}let s={...t,sourceFile:t.sourceFile??e.state.currentSource??"main"};return e.state.functions.set(t.name,s),L}async function la(e,t){let s="";for(let r of t)if((r.operator==="<<"||r.operator==="<<-")&&r.target.type==="HereDoc"){let n=r.target,i=await T(e,n.content);n.stripTabs&&(i=i.split(`
|
|
37
37
|
`).map(o=>o.replace(/^\t+/,"")).join(`
|
|
38
38
|
`)),(r.fd??0)===0&&(s=i)}else if(r.operator==="<<<"&&r.target.type==="Word")s=`${await T(e,r.target)}
|
|
@@ -47,11 +47,11 @@ import{B as Mr,C as Wr,D as le,E as je,F as ee,G as $e,H as Ot,I as zr,J as T,K
|
|
|
47
47
|
`,2);f=t[g]}else if(w==="-C"){if(g++,g>=t.length)return _(`compgen: -C: option requires an argument
|
|
48
48
|
`,2);d=t[g]}else if(w==="-X"){if(g++,g>=t.length)return _(`compgen: -X: option requires an argument
|
|
49
49
|
`,2);u=t[g]}else if(w==="-G"){if(g++,g>=t.length)return _(`compgen: -G: option requires an argument
|
|
50
|
-
`,2)}else if(w==="--"){h.push(...t.slice(g+1));break}else w.startsWith("-")||h.push(w)}a=h[0]??null;let m=[];if(l){let g=await
|
|
50
|
+
`,2)}else if(w==="--"){h.push(...t.slice(g+1));break}else w.startsWith("-")||h.push(w)}a=h[0]??null;let m=[];if(l){let g=await Ds(e,a);m.push(...g)}if(c){let g=await $n(e,a);m.push(...g)}for(let g of s)if(g==="variable"){let w=fa(e,a);m.push(...w)}else if(g==="export"){let w=da(e,a);m.push(...w)}else if(g==="function"){let w=ha(e,a);m.push(...w)}else if(g==="builtin"){let w=pa(a);m.push(...w)}else if(g==="keyword"){let w=ma(a);m.push(...w)}else if(g==="alias"){let w=ya(e,a);m.push(...w)}else if(g==="shopt"){let w=ga(a);m.push(...w)}else if(g==="helptopic"){let w=wa(a);m.push(...w)}else if(g==="directory"){let w=await Ds(e,a);m.push(...w)}else if(g==="file"){let w=await $n(e,a);m.push(...w)}else if(g==="user"){let w=va(a);m.push(...w)}else if(g==="command"){let w=await ba(e,a);m.push(...w)}if(r!==null)try{let g=await $a(e,r),w=Ea(e,g);for(let $ of w)(a===null||$.startsWith(a))&&m.push($)}catch{return k("","",1)}if(o){let g=await Ds(e,a);for(let w of g)m.includes(w)||m.push(w)}let y="";if(f!==null){let g=e.state.functions.get(f);if(g){let w=new Map;w.set("COMP_WORDS__length",e.state.env.get("COMP_WORDS__length")),e.state.env.set("COMP_WORDS__length","0"),w.set("COMP_CWORD",e.state.env.get("COMP_CWORD")),e.state.env.set("COMP_CWORD","-1"),w.set("COMP_LINE",e.state.env.get("COMP_LINE")),e.state.env.set("COMP_LINE",""),w.set("COMP_POINT",e.state.env.get("COMP_POINT")),e.state.env.set("COMP_POINT","0");let $=new Map;for(let O of e.state.env.keys())(O==="COMPREPLY"||O.startsWith("COMPREPLY_")||O==="COMPREPLY__length")&&($.set(O,e.state.env.get(O)),e.state.env.delete(O));let E=["compgen",h[0]??"",""];try{let O=await Xt(e,g,E,"");if(O.exitCode!==0)return it(e,w),it(e,$),k("",O.stderr,1);y=O.stdout;let N=Sa(e);m.push(...N)}catch{return it(e,w),it(e,$),k("","",1)}it(e,w),it(e,$)}}if(d!==null)try{let g=ve(d),w=await e.executeScript(g);if(w.exitCode!==0)return k("",w.stderr,w.exitCode);if(w.stdout){let $=w.stdout.split(`
|
|
51
51
|
`);for(let E of $)E.length>0&&m.push(E)}}catch(g){if(g.name==="ParseException")return _(`compgen: -C: ${g.message}
|
|
52
52
|
`,2);throw g}let b=m;if(u!==null){let g=u.startsWith("!"),w=g?u.slice(1):u;b=m.filter($=>{let E=st($,w,!1,!0);return g?E:!E})}if(b.length===0&&a!==null)return k(y,"",1);let v=b.map(g=>`${n}${g}${i}`).join(`
|
|
53
53
|
`),A=y+(v?`${v}
|
|
54
|
-
`:"");return F(A)}function fa(e,t){let s=new Set;for(let n of e.state.env.keys()){if(n.includes("_")&&/^[a-zA-Z_][a-zA-Z0-9_]*_\d+$/.test(n)||n.endsWith("__length"))continue;let i=n.split("_")[0];/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(n)?s.add(n):i&&/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(i)&&e.state.env.has(`${i}__length`)&&s.add(i)}let r=Array.from(s);return t!==null&&(r=r.filter(n=>n.startsWith(t))),r.sort()}function da(e,t){let s=e.state.exportedVars??new Set,r=Array.from(s);return t!==null&&(r=r.filter(n=>n.startsWith(t))),r=r.filter(n=>n.includes("_")&&/^[a-zA-Z_][a-zA-Z0-9_]*_\d+$/.test(n)||n.endsWith("__length")?!1:e.state.env.has(n)),r.sort()}function ha(e,t){let s=Array.from(e.state.functions.keys());return t!==null&&(s=s.filter(r=>r.startsWith(t))),s.sort()}function pa(e){let t=[...Ts];return e!==null&&(t=t.filter(s=>s.startsWith(e))),t.sort()}function ma(e){let t=[...En];return e!==null&&(t=t.filter(s=>s.startsWith(e))),t.sort()}function ya(e,t){let s=[];for(let n of e.state.env.keys())if(n.startsWith("BASH_ALIAS_")){let i=n.slice(11);s.push(i)}let r=s;return t!==null&&(r=r.filter(n=>n.startsWith(t))),r.sort()}function ga(e){let t=[...ca];return e!==null&&(t=t.filter(s=>s.startsWith(e))),t.sort()}function wa(e){let t=[...ua];return e!==null&&(t=t.filter(s=>s.startsWith(e))),t.sort()}async function
|
|
54
|
+
`:"");return F(A)}function fa(e,t){let s=new Set;for(let n of e.state.env.keys()){if(n.includes("_")&&/^[a-zA-Z_][a-zA-Z0-9_]*_\d+$/.test(n)||n.endsWith("__length"))continue;let i=n.split("_")[0];/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(n)?s.add(n):i&&/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(i)&&e.state.env.has(`${i}__length`)&&s.add(i)}let r=Array.from(s);return t!==null&&(r=r.filter(n=>n.startsWith(t))),r.sort()}function da(e,t){let s=e.state.exportedVars??new Set,r=Array.from(s);return t!==null&&(r=r.filter(n=>n.startsWith(t))),r=r.filter(n=>n.includes("_")&&/^[a-zA-Z_][a-zA-Z0-9_]*_\d+$/.test(n)||n.endsWith("__length")?!1:e.state.env.has(n)),r.sort()}function ha(e,t){let s=Array.from(e.state.functions.keys());return t!==null&&(s=s.filter(r=>r.startsWith(t))),s.sort()}function pa(e){let t=[...Ts];return e!==null&&(t=t.filter(s=>s.startsWith(e))),t.sort()}function ma(e){let t=[...En];return e!==null&&(t=t.filter(s=>s.startsWith(e))),t.sort()}function ya(e,t){let s=[];for(let n of e.state.env.keys())if(n.startsWith("BASH_ALIAS_")){let i=n.slice(11);s.push(i)}let r=s;return t!==null&&(r=r.filter(n=>n.startsWith(t))),r.sort()}function ga(e){let t=[...ca];return e!==null&&(t=t.filter(s=>s.startsWith(e))),t.sort()}function wa(e){let t=[...ua];return e!==null&&(t=t.filter(s=>s.startsWith(e))),t.sort()}async function Ds(e,t){let s=[];try{let r=e.state.cwd,n=t??"";if(t){let a=t.lastIndexOf("/");if(a!==-1){let o=t.slice(0,a)||"/";n=t.slice(a+1),o.startsWith("/")?r=o:r=`${e.state.cwd}/${o}`}}let i=await e.fs.readdir(r);for(let a of i){let o=`${r}/${a}`;try{if((await e.fs.stat(o)).isDirectory&&(!n||a.startsWith(n)))if(t?.includes("/")){let c=t.lastIndexOf("/"),u=t.slice(0,c+1);s.push(u+a)}else s.push(a)}catch{}}}catch{}return s.sort()}async function $n(e,t){let s=[];try{let r=e.state.cwd,n=t??"";if(t){let a=t.lastIndexOf("/");if(a!==-1){let o=t.slice(0,a)||"/";n=t.slice(a+1),o.startsWith("/")?r=o:r=`${e.state.cwd}/${o}`}}let i=await e.fs.readdir(r);for(let a of i)if(!n||a.startsWith(n))if(t?.includes("/")){let o=t.lastIndexOf("/"),l=t.slice(0,o+1);s.push(l+a)}else s.push(a)}catch{}return s.sort()}function va(e){return["root","nobody"]}async function ba(e,t){let s=new Set;for(let i of Ts)s.add(i);for(let i of e.state.functions.keys())s.add(i);for(let i of e.state.env.keys())i.startsWith("BASH_ALIAS_")&&s.add(i.slice(11));for(let i of En)s.add(i);let r=e.state.env.get("PATH")??"/usr/bin:/bin";for(let i of r.split(":"))if(i)try{let a=await e.fs.readdir(i);for(let o of a)s.add(o)}catch{}let n=Array.from(s);return t!==null&&(n=n.filter(i=>i.startsWith(t))),n.sort()}async function $a(e,t){let r=new V().parseWordFromString(t,!1,!1);return await T(e,r)}function Ea(e,t){let s=e.state.env.get("IFS")??`
|
|
55
55
|
`;if(s.length===0)return[t];let r=new Set(s.split("")),n=[],i="",a=0;for(;a<t.length;){let o=t[a];if(o==="\\"&&a+1<t.length){let l=t[a+1];i+=l,a+=2}else r.has(o)?(i.length>0&&(n.push(i),i=""),a++):(i+=o,a++)}return i.length>0&&n.push(i),n}function it(e,t){for(let[s,r]of t)r===void 0?e.state.env.delete(s):e.state.env.set(s,r)}function Sa(e){let t=[];if(e.state.env.get("COMPREPLY__length")!==void 0){let n=be(e,"COMPREPLY");for(let[,i]of n)t.push(i)}else{let n=e.state.env.get("COMPREPLY");n!==void 0&&t.push(n)}return t}var Aa=["bashdefault","default","dirnames","filenames","noquote","nosort","nospace","plusdirs"];function Ls(e,t){e.state.completionSpecs||(e.state.completionSpecs=new Map);let s=!1,r=!1,n=!1,i,a,o,l=[],c=[],u=[];for(let f=0;f<t.length;f++){let d=t[f];if(d==="-p")s=!0;else if(d==="-r")r=!0;else if(d==="-D")n=!0;else if(d==="-W"){if(f++,f>=t.length)return _(`complete: -W: option requires an argument
|
|
56
56
|
`,2);i=t[f]}else if(d==="-F"){if(f++,f>=t.length)return _(`complete: -F: option requires an argument
|
|
57
57
|
`,2);a=t[f]}else if(d==="-o"){if(f++,f>=t.length)return _(`complete: -o: option requires an argument
|
|
@@ -95,19 +95,19 @@ import{B as Mr,C as Wr,D as le,E as je,F as ee,G as $e,H as Ot,I as zr,J as T,K
|
|
|
95
95
|
`}}return F(t)}function Nn(e){let t="",s=new Set;for(let n of e.state.env.keys()){if(n.startsWith("BASH_"))continue;if(n.endsWith("__length")){let a=n.slice(0,-8);s.add(a);continue}let i=n.lastIndexOf("_");if(i>0){let a=n.slice(0,i),o=n.slice(i+1);if(/^\d+$/.test(o)||e.state.associativeArrays?.has(a)){s.add(a);continue}}s.add(n)}let r=Array.from(s).sort();for(let n of r){if(e.state.associativeArrays?.has(n)||se(e,n).length>0||e.state.env.has(`${n}__length`))continue;let o=e.state.env.get(n);o!==void 0&&(t+=`${n}=${Yt(o)}
|
|
96
96
|
`)}return F(t)}function Bs(e,t){e.state.integerVars??=new Set,e.state.integerVars.add(t)}function pt(e,t){return e.state.integerVars?.has(t)??!1}function Hs(e,t){e.state.lowercaseVars??=new Set,e.state.lowercaseVars.add(t),e.state.uppercaseVars?.delete(t)}function _a(e,t){return e.state.lowercaseVars?.has(t)??!1}function Us(e,t){e.state.uppercaseVars??=new Set,e.state.uppercaseVars.add(t),e.state.lowercaseVars?.delete(t)}function Ca(e,t){return e.state.uppercaseVars?.has(t)??!1}function at(e,t,s){return _a(e,t)?s.toLowerCase():Ca(e,t)?s.toUpperCase():s}async function On(e,t){try{let s=new V,r=Q(s,t),n=await B(e,r.expression);return String(n)}catch{return"0"}}function ka(e){let t=e.match(/^[a-zA-Z_][a-zA-Z0-9_]*/);if(!t)return null;let s=t[0],r=s.length;if(e[r]!=="[")return null;let n=0,i=r+1;for(;r<e.length;r++)if(e[r]==="[")n++;else if(e[r]==="]"&&(n--,n===0))break;if(n!==0)return null;let a=e.slice(i,r);if(r++,e[r]!=="=")return null;r++;let o=e.slice(r);return{name:s,indexExpr:a,value:o}}async function Zs(e,t){let s=!1,r=!1,n=!1,i=!1,a=!1,o=!1,l=!1,c=!1,u=!1,f=!1,d=!1,h=!1,p=!1,m=!1,y=!1,b=[];for(let N=0;N<t.length;N++){let I=t[N];if(I==="-a")s=!0;else if(I==="-A")r=!0;else if(I==="-r")n=!0;else if(I==="-x")i=!0;else if(I==="-p")a=!0;else if(I==="-n")o=!0;else if(I==="+n")l=!0;else if(I==="+a")c=!0;else if(I==="+x")u=!0;else if(I==="--"){b.push(...t.slice(N+1));break}else if(I.startsWith("+")){for(let C of I.slice(1))if(C==="n")l=!0;else if(C==="a")c=!0;else if(C==="x")u=!0;else if(C!=="r"){if(C!=="i"){if(!(C==="f"||C==="F"))return k("",`bash: typeset: +${C}: invalid option
|
|
97
97
|
`,2)}}}else if(I==="-i")f=!0;else if(I==="-l")d=!0;else if(I==="-u")h=!0;else if(I==="-f")p=!0;else if(I==="-F")m=!0;else if(I==="-g")y=!0;else if(I.startsWith("-"))for(let C of I.slice(1))if(C==="a")s=!0;else if(C==="A")r=!0;else if(C==="r")n=!0;else if(C==="x")i=!0;else if(C==="p")a=!0;else if(C==="n")o=!0;else if(C==="i")f=!0;else if(C==="l")d=!0;else if(C==="u")h=!0;else if(C==="f")p=!0;else if(C==="F")m=!0;else if(C==="g")y=!0;else return k("",`bash: typeset: -${C}: invalid option
|
|
98
|
-
`,2);else b.push(I)}let A=e.state.localScopes.length>0&&!y,g=N=>{if(!A)return;let I=e.state.localScopes[e.state.localScopes.length-1];I.has(N)||I.set(N,e.state.env.get(N))},w=N=>{if(!A)return;let I=e.state.localScopes[e.state.localScopes.length-1];I.has(N)||I.set(N,e.state.env.get(N));let C=`${N}_`;for(let
|
|
98
|
+
`,2);else b.push(I)}let A=e.state.localScopes.length>0&&!y,g=N=>{if(!A)return;let I=e.state.localScopes[e.state.localScopes.length-1];I.has(N)||I.set(N,e.state.env.get(N))},w=N=>{if(!A)return;let I=e.state.localScopes[e.state.localScopes.length-1];I.has(N)||I.set(N,e.state.env.get(N));let C=`${N}_`;for(let x of e.state.env.keys())x.startsWith(C)&&!x.includes("__")&&(I.has(x)||I.set(x,e.state.env.get(x)));let P=`${N}__length`;e.state.env.has(P)&&!I.has(P)&&I.set(P,e.state.env.get(P))},$=N=>{A&&We(e,N)};if(m){if(b.length===0){let C=Array.from(e.state.functions.keys()).sort(),P="";for(let x of C)P+=`declare -f ${x}
|
|
99
99
|
`;return F(P)}let N=!0,I="";for(let C of b)e.state.functions.has(C)?I+=`${C}
|
|
100
100
|
`:N=!1;return k(I,"",N?0:1)}if(p){if(b.length===0){let I="",C=Array.from(e.state.functions.keys()).sort();for(let P of C)I+=`${P} ()
|
|
101
101
|
{
|
|
102
102
|
# function body
|
|
103
103
|
}
|
|
104
|
-
`;return F(I)}let N=!0;for(let I of b)e.state.functions.has(I)||(N=!1);return k("","",N?0:1)}if(a&&b.length>0)return _n(e,b);if(a&&b.length===0)return Cn(e,{filterExport:i,filterReadonly:n,filterNameref:o,filterIndexedArray:s,filterAssocArray:r});if(b.length===0&&r&&!a)return kn(e);if(b.length===0&&s&&!a)return Pn(e);if(b.length===0&&!a)return Nn(e);let E="",O=0;for(let N of b){let I=N.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\((.*)\)$/s);if(I&&!c){let S=I[1],
|
|
104
|
+
`;return F(I)}let N=!0;for(let I of b)e.state.functions.has(I)||(N=!1);return k("","",N?0:1)}if(a&&b.length>0)return _n(e,b);if(a&&b.length===0)return Cn(e,{filterExport:i,filterReadonly:n,filterNameref:o,filterIndexedArray:s,filterAssocArray:r});if(b.length===0&&r&&!a)return kn(e);if(b.length===0&&s&&!a)return Pn(e);if(b.length===0&&!a)return Nn(e);let E="",O=0;for(let N of b){let I=N.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\((.*)\)$/s);if(I&&!c){let S=I[1],D=I[2];if(r&&se(e,S).length>0){E+=`bash: declare: ${S}: cannot convert indexed to associative array
|
|
105
105
|
`,O=1;continue}if((s||!r&&!s)&&e.state.associativeArrays?.has(S)){E+=`bash: declare: ${S}: cannot convert associative to indexed array
|
|
106
|
-
`,O=1;continue}if(w(S),r&&(e.state.associativeArrays??=new Set,e.state.associativeArrays.add(S)),Se(e,S),e.state.env.delete(S),e.state.env.delete(`${S}__length`),r&&
|
|
107
|
-
`,O=1;continue}let J=ee(e,
|
|
108
|
-
`,O=1;continue}e.state.env.set(
|
|
106
|
+
`,O=1;continue}if(w(S),r&&(e.state.associativeArrays??=new Set,e.state.associativeArrays.add(S)),Se(e,S),e.state.env.delete(S),e.state.env.delete(`${S}__length`),r&&D.includes("[")){let R=Zt(D);for(let[J,z]of R){let K=G(e,z);e.state.env.set(`${S}_${J}`,K)}}else if(r){let R=Ce(D);for(let J=0;J<R.length;J+=2){let z=R[J],K=J+1<R.length?G(e,R[J+1]):"";e.state.env.set(`${S}_${z}`,K)}}else{let R=Ce(D);if(R.some(z=>/^\[[^\]]+\]=/.test(z))){let z=0;for(let K of R){let re=K.match(/^\[([^\]]+)\]=(.*)$/);if(re){let ce=re[1],qe=re[2],Ti=G(e,qe),lt;if(/^-?\d+$/.test(ce))lt=Number.parseInt(ce,10);else try{let Ii=new V,Ri=Q(Ii,ce);lt=await B(e,Ri.expression)}catch{lt=0}e.state.env.set(`${S}_${lt}`,Ti),z=lt+1}else{let ce=G(e,K);e.state.env.set(`${S}_${z}`,ce),z++}}}else{for(let z=0;z<R.length;z++)e.state.env.set(`${S}_${z}`,R[z]);e.state.env.set(`${S}__length`,String(R.length))}}$(S),n&&le(e,S),i&&$e(e,S);continue}if(l){let S=N.includes("=")?N.slice(0,N.indexOf("=")):N;if(Ir(e,S),!N.includes("="))continue}if(u){let S=N.includes("=")?N.slice(0,N.indexOf("=")):N;if(Ot(e,S),!N.includes("="))continue}let C=ka(N);if(C){let{name:S,indexExpr:D,value:R}=C,J=ee(e,S);if(J)return J;w(S);let z;try{let re=new V,ce=Q(re,D);z=await B(e,ce.expression)}catch{let re=parseInt(D,10);z=Number.isNaN(re)?0:re}e.state.env.set(`${S}_${z}`,R);let K=parseInt(e.state.env.get(`${S}__length`)??"0",10);z>=K&&e.state.env.set(`${S}__length`,String(z+1)),$(S),n&&le(e,S),i&&$e(e,S);continue}let P=N.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=\((.*)\)$/s);if(P&&!c){let S=P[1],D=P[2],R=ee(e,S);if(R)return R;w(S);let J=Ce(D);if(e.state.associativeArrays?.has(S)){let z=Zt(D);for(let[K,re]of z){let ce=G(e,re);e.state.env.set(`${S}_${K}`,ce)}}else{let z=se(e,S),K=0,re=e.state.env.get(S);z.length===0&&re!==void 0?(e.state.env.set(`${S}_0`,re),e.state.env.delete(S),K=1):z.length>0&&(K=Math.max(...z)+1);for(let qe=0;qe<J.length;qe++)e.state.env.set(`${S}_${K+qe}`,G(e,J[qe]));let ce=K+J.length;e.state.env.set(`${S}__length`,String(ce))}$(S),n&&le(e,S),i&&$e(e,S);continue}let x=N.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=(.*)$/);if(x){let S=x[1],D=G(e,x[2]),R=ee(e,S);if(R)return R;g(S),f&&Bs(e,S),d&&Hs(e,S),h&&Us(e,S);let z=se(e,S).length>0||e.state.associativeArrays?.has(S);if(pt(e,S)){let K=e.state.env.get(S)??"0",re=parseInt(K,10)||0,ce=parseInt(await On(e,D),10)||0;D=String(re+ce),e.state.env.set(S,D)}else if(z){D=at(e,S,D);let K=`${S}_0`,re=e.state.env.get(K)??"";e.state.env.set(K,re+D)}else{D=at(e,S,D);let K=e.state.env.get(S)??"";e.state.env.set(S,K+D)}$(S),n&&le(e,S),i&&$e(e,S),e.state.options.allexport&&!u&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(S));continue}if(N.includes("=")){let S=N.indexOf("="),D=N.slice(0,S),R=N.slice(S+1);if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(D)){E+=`bash: typeset: \`${D}': not a valid identifier
|
|
107
|
+
`,O=1;continue}let J=ee(e,D);if(J)return J;if(g(D),o){if(R!==""&&!/^[a-zA-Z_][a-zA-Z0-9_]*(\[.+\])?$/.test(R)){E+=`bash: declare: \`${R}': invalid variable name for name reference
|
|
108
|
+
`,O=1;continue}e.state.env.set(D,R),Oe(e,D),R!==""&&ms(e,R)&&ps(e,D),$(D),n&&le(e,D),i&&$e(e,D);continue}if(f&&Bs(e,D),d&&Hs(e,D),h&&Us(e,D),pt(e,D)&&(R=await On(e,R)),R=at(e,D,R),me(e,D)){let z=Le(e,D);z&&z!==D?e.state.env.set(z,R):e.state.env.set(D,R)}else e.state.env.set(D,R);$(D),n&&le(e,D),i&&$e(e,D),e.state.options.allexport&&!u&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(D))}else{let S=N;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(S)){E+=`bash: typeset: \`${S}': not a valid identifier
|
|
109
109
|
`,O=1;continue}if(s||r?w(S):g(S),o){Oe(e,S);let R=e.state.env.get(S);R!==void 0&&R!==""&&!/^[a-zA-Z_][a-zA-Z0-9_]*(\[.+\])?$/.test(R)?Rr(e,S):R&&ms(e,R)&&ps(e,S),$(S),n&&le(e,S),i&&$e(e,S);continue}if(f&&Bs(e,S),d&&Hs(e,S),h&&Us(e,S),r){if(se(e,S).length>0){E+=`bash: declare: ${S}: cannot convert indexed to associative array
|
|
110
|
-
`,O=1;continue}e.state.associativeArrays??=new Set,e.state.associativeArrays.add(S)}let
|
|
110
|
+
`,O=1;continue}e.state.associativeArrays??=new Set,e.state.associativeArrays.add(S)}let D=Array.from(e.state.env.keys()).some(R=>R.startsWith(`${S}_`)&&!R.startsWith(`${S}__length`));!e.state.env.has(S)&&!D&&(s||r?e.state.env.set(`${S}__length`,"0"):(e.state.declaredVars??=new Set,e.state.declaredVars.add(S))),$(S),n&&le(e,S),i&&$e(e,S)}}return k("",E,O)}async function qs(e,t){let s=!1,r=!1,n=!1,i=[];for(let a=0;a<t.length;a++){let o=t[a];if(o==="-a")s=!0;else if(o==="-A")r=!0;else if(o==="-p")n=!0;else if(o==="--"){i.push(...t.slice(a+1));break}else o.startsWith("-")||i.push(o)}if(i.length===0){let a="",o=Array.from(e.state.readonlyVars||[]).sort();for(let l of o){let c=e.state.env.get(l);if(c!==void 0){let u=c.replace(/\\/g,"\\\\").replace(/"/g,'\\"');a+=`declare -r ${l}="${u}"
|
|
111
111
|
`}}return F(a)}for(let a of i){let o=a.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=\((.*)\)$/s);if(o){let f=o[1],d=o[2],h=ee(e,f);if(h)return h;let p=Ce(d);if(e.state.associativeArrays?.has(f)){let m=Zt(d);for(let[y,b]of m){let v=G(e,b);e.state.env.set(`${f}_${y}`,v)}}else{let m=se(e,f),y=0,b=e.state.env.get(f);m.length===0&&b!==void 0?(e.state.env.set(`${f}_0`,b),e.state.env.delete(f),y=1):m.length>0&&(y=Math.max(...m)+1);for(let A=0;A<p.length;A++)e.state.env.set(`${f}_${y+A}`,G(e,p[A]));let v=y+p.length;e.state.env.set(`${f}__length`,String(v))}le(e,f);continue}let l=a.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=(.*)$/);if(l){let f=l[1],d=G(e,l[2]),h=ee(e,f);if(h)return h;let p=e.state.env.get(f)??"";e.state.env.set(f,p+d),le(e,f);continue}let c=pn(a);if(c.value===void 0&&!c.isArray){le(e,c.name);continue}let u=await mn(e,c,{makeReadonly:!0});if(u)return u}return L}function Gs(e){return e.state.directoryStack??=[],e.state.directoryStack}function mt(e,t){return t&&e===t?"~":t&&e.startsWith(`${t}/`)?`~${e.slice(t.length)}`:e}function Pa(e){let t=e.split("/").filter(r=>r&&r!=="."),s=[];for(let r of t)r===".."?s.pop():s.push(r);return`/${s.join("/")}`}async function Ks(e,t){let s=Gs(e),r;for(let o=0;o<t.length;o++){let l=t[o];if(l==="--"){if(o+1<t.length){if(r!==void 0)return _(`bash: pushd: too many arguments
|
|
112
112
|
`,2);r=t[o+1],o++}}else{if(l.startsWith("-")&&l!=="-")return _(`bash: pushd: ${l}: invalid option
|
|
113
113
|
`,2);if(r!==void 0)return _(`bash: pushd: too many arguments
|
|
@@ -152,7 +152,7 @@ eval: usage: eval [arg ...]
|
|
|
152
152
|
`;for(let[,m]of e.state.hashTable)p+=` 1 ${m}
|
|
153
153
|
`}return F(p)}let u=!1,f="",h=(e.state.env.get("PATH")||"/usr/bin:/bin").split(":");for(let p of l){if(p.includes("/")){f+=`bash: hash: ${p}: cannot use / in name
|
|
154
154
|
`,u=!0;continue}let m=!1;for(let y of h){if(!y)continue;let b=`${y}/${p}`;if(await e.fs.exists(b)){e.state.hashTable.set(p,b),m=!0;break}}m||(f+=`bash: hash: ${p}: not found
|
|
155
|
-
`,u=!0)}return u?_(f,1):L}var
|
|
155
|
+
`,u=!0)}return u?_(f,1):L}var xn=new Map([[":",[": [arguments]",`Null command.
|
|
156
156
|
No effect; the command does nothing.
|
|
157
157
|
Exit Status:
|
|
158
158
|
Always succeeds.`]],[".",[". filename [arguments]",`Execute commands from a file in the current shell.
|
|
@@ -497,15 +497,15 @@ eval: usage: eval [arg ...]
|
|
|
497
497
|
job specification, and reports its termination status.
|
|
498
498
|
Exit Status:
|
|
499
499
|
Returns the status of the last ID; fails if ID is invalid or an invalid
|
|
500
|
-
option is given.`]]]),
|
|
500
|
+
option is given.`]]]),Dn=[...xn.keys()].sort();function tr(e,t){let s=!1,r=[],n=0;for(;n<t.length;){let l=t[n];if(l==="--"){for(n++;n<t.length;)r.push(t[n]),n++;break}if(l.startsWith("-")&&l.length>1){for(let c=1;c<l.length;c++){let u=l[c];if(u==="s")s=!0;else return _(`bash: help: -${u}: invalid option
|
|
501
501
|
`,2)}n++}else r.push(l),n++}if(r.length===0)return Oa();let i="",a=!1,o="";for(let l of r){let c=Na(l);if(c.length===0){o+=`bash: help: no help topics match \`${l}'. Try \`help help' or \`man -k ${l}' or \`info ${l}'.
|
|
502
|
-
`,a=!0;continue}for(let u of c){let f=
|
|
502
|
+
`,a=!0;continue}for(let u of c){let f=xn.get(u);if(!f)continue;let[d,h]=f;s?i+=`${u}: ${d}
|
|
503
503
|
`:i+=`${u}: ${d}
|
|
504
504
|
${h}
|
|
505
|
-
`}}return{exitCode:a?1:0,stdout:i,stderr:o}}function Na(e){let t=e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,"."),s=ct(`^${t}$`);return
|
|
505
|
+
`}}return{exitCode:a?1:0,stdout:i,stderr:o}}function Na(e){let t=e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,"."),s=ct(`^${t}$`);return Dn.filter(r=>s.test(r))}function Oa(){let e=[];e.push("just-bash shell builtins"),e.push("These shell commands are defined internally. Type `help' to see this list."),e.push("Type `help name' to find out more about the function `name'."),e.push("");let t=36,s=Dn.slice(),r=Math.ceil(s.length/2);for(let n=0;n<r;n++){let i=s[n]||"",a=s[n+r]||"",o=i.padEnd(t);e.push(a?`${o}${a}`:i)}return F(`${e.join(`
|
|
506
506
|
`)}
|
|
507
|
-
`)}function
|
|
508
|
-
`);let s=
|
|
507
|
+
`)}function xa(e){let t=[],s="",r=0;for(let n of e){for(let i of n)i==="("?r++:i===")"&&r--;s?s+=` ${n}`:s=n,r===0&&(t.push(s),s="")}return s&&t.push(s),t}async function sr(e,t){if(t.length===0)return _(`bash: let: expression expected
|
|
508
|
+
`);let s=xa(t),r=0;for(let n of s)try{let a=ve(`(( ${n} ))`).statements[0];if(a&&a.pipelines.length>0&&a.pipelines[0].commands.length>0){let o=a.pipelines[0].commands[0];o.type==="ArithmeticCommand"&&(r=await B(e,o.expression.expression))}}catch(i){return _(`bash: let: ${n}: ${i.message}
|
|
509
509
|
`)}return k("","",r===0?1:0)}async function rr(e,t){if(e.state.localScopes.length===0)return _(`bash: local: can only be used in a function
|
|
510
510
|
`);let s=e.state.localScopes[e.state.localScopes.length-1],r="",n=0,i=!1,a=!1,o=!1,l=[];for(let c of t)if(c==="-n")i=!0;else if(c==="-a")a=!0;else if(c==="-p")o=!0;else if(c.startsWith("-")&&!c.includes("="))for(let u of c.slice(1))u==="n"?i=!0:u==="a"?a=!0:u==="p"&&(o=!0);else l.push(c);if(l.length===0){let c="",u=Array.from(s.keys()).filter(f=>!f.includes("_")||!f.match(/_\d+$/)).filter(f=>!f.includes("__length")).sort();for(let f of u){let d=e.state.env.get(f);d!==void 0&&(c+=`${f}=${d}
|
|
511
511
|
`)}return k(c,"",0)}for(let c of l){let u,f,d=c.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\((.*)\)$/s);if(d){u=d[1];let b=d[2];if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(u)){r+=`bash: local: \`${c}': not a valid identifier
|
|
@@ -515,13 +515,13 @@ ${h}
|
|
|
515
515
|
`,n=0,i=0,a=0,o=!1,l="MAPFILE",c=0;for(;c<t.length;){let v=t[c];v==="-d"&&c+1<t.length?(r=t[c+1]===""?"\0":t[c+1]||`
|
|
516
516
|
`,c+=2):v==="-n"&&c+1<t.length?(n=Number.parseInt(t[c+1],10)||0,c+=2):v==="-O"&&c+1<t.length?(i=Number.parseInt(t[c+1],10)||0,c+=2):v==="-s"&&c+1<t.length?(a=Number.parseInt(t[c+1],10)||0,c+=2):v==="-t"?(o=!0,c++):v==="-u"||v==="-C"||v==="-c"?c+=2:(v.startsWith("-")||(l=v),c++)}let u=s;!u&&e.state.groupStdin!==void 0&&(u=e.state.groupStdin);let f=[],d=u,h=0,p=0,m=e.limits?.maxArrayElements??1e5;for(;d.length>0;){let v=d.indexOf(r);if(v===-1){if(d.length>0){if(p<a)p++;else if(n===0||h<n){if(i+h>=m)return k("",`mapfile: array element limit exceeded (${m})
|
|
517
517
|
`,1);let w=d,$=w.indexOf("\0");$!==-1&&(w=w.substring(0,$)),f.push(w),h++}}break}let A=d.substring(0,v),g=A.indexOf("\0");if(g!==-1&&(A=A.substring(0,g)),!o&&r!=="\0"&&(A+=r),d=d.substring(v+r.length),p<a){p++;continue}if(n>0&&h>=n)break;if(i+h>=m)return k("",`mapfile: array element limit exceeded (${m})
|
|
518
|
-
`,1);f.push(A),h++}i===0&&Se(e,l);for(let v=0;v<f.length;v++)e.state.env.set(`${l}_${i+v}`,f[v]);let y=parseInt(e.state.env.get(`${l}__length`)||"0",10),b=i+f.length;return e.state.env.set(`${l}__length`,String(Math.max(y,b))),e.state.groupStdin!==void 0&&!s&&(e.state.groupStdin=""),k("","",0)}function
|
|
519
|
-
`,a="",o=-1,l=-1,c=null,u=-1,f=-1,d=[],h=0,p=!1,m=(C,P)=>{let
|
|
520
|
-
`){P+=2,A=P;continue}if(
|
|
521
|
-
`){C+=2;continue}if(
|
|
518
|
+
`,1);f.push(A),h++}i===0&&Se(e,l);for(let v=0;v<f.length;v++)e.state.env.set(`${l}_${i+v}`,f[v]);let y=parseInt(e.state.env.get(`${l}__length`)||"0",10),b=i+f.length;return e.state.env.set(`${l}__length`,String(Math.max(y,b))),e.state.groupStdin!==void 0&&!s&&(e.state.groupStdin=""),k("","",0)}function Da(e){if(!e.startsWith("__rw__:"))return null;let t=e.slice(7),s=t.indexOf(":");if(s===-1)return null;let r=Number.parseInt(t.slice(0,s),10);if(Number.isNaN(r)||r<0)return null;let n=s+1,i=t.slice(n,n+r),a=n+r+1,o=t.slice(a),l=o.indexOf(":");if(l===-1)return null;let c=Number.parseInt(o.slice(0,l),10);if(Number.isNaN(c)||c<0)return null;let u=o.slice(l+1);return{path:i,position:c,content:u}}function Ta(e,t,s){return`__rw__:${e.length}:${e}:${t}:${s}`}function ir(e,t,s,r=-1){let n=!1,i=`
|
|
519
|
+
`,a="",o=-1,l=-1,c=null,u=-1,f=-1,d=[],h=0,p=!1,m=(C,P)=>{let x=1;for(;x<C.length;){let S=C[x];if(S==="r")n=!0,x++;else if(S==="s")x++;else{if(S==="d")return x+1<C.length?(i=C.substring(x+1),{nextArgIndex:P+1}):P+1<t.length?(i=t[P+1],{nextArgIndex:P+2}):{nextArgIndex:P+1};if(S==="n"){if(x+1<C.length){let D=C.substring(x+1);return o=Number.parseInt(D,10),(Number.isNaN(o)||o<0)&&(p=!0,o=0),{nextArgIndex:P+1}}else if(P+1<t.length)return o=Number.parseInt(t[P+1],10),(Number.isNaN(o)||o<0)&&(p=!0,o=0),{nextArgIndex:P+2};return{nextArgIndex:P+1}}else if(S==="N"){if(x+1<C.length){let D=C.substring(x+1);return l=Number.parseInt(D,10),(Number.isNaN(l)||l<0)&&(p=!0,l=0),{nextArgIndex:P+1}}else if(P+1<t.length)return l=Number.parseInt(t[P+1],10),(Number.isNaN(l)||l<0)&&(p=!0,l=0),{nextArgIndex:P+2};return{nextArgIndex:P+1}}else{if(S==="a")return x+1<C.length?(c=C.substring(x+1),{nextArgIndex:P+1}):P+1<t.length?(c=t[P+1],{nextArgIndex:P+2}):{nextArgIndex:P+1};if(S==="p")return x+1<C.length?(a=C.substring(x+1),{nextArgIndex:P+1}):P+1<t.length?(a=t[P+1],{nextArgIndex:P+2}):{nextArgIndex:P+1};if(S==="u"){if(x+1<C.length){let D=C.substring(x+1);return u=Number.parseInt(D,10),Number.isNaN(u)||u<0?{nextArgIndex:-2}:{nextArgIndex:P+1}}else if(P+1<t.length)return u=Number.parseInt(t[P+1],10),Number.isNaN(u)||u<0?{nextArgIndex:-2}:{nextArgIndex:P+2};return{nextArgIndex:P+1}}else if(S==="t"){if(x+1<C.length){let D=C.substring(x+1);return f=Number.parseFloat(D),Number.isNaN(f)&&(f=0),{nextArgIndex:P+1}}else if(P+1<t.length)return f=Number.parseFloat(t[P+1]),Number.isNaN(f)&&(f=0),{nextArgIndex:P+2};return{nextArgIndex:P+1}}else if(S==="e"||S==="i"||S==="P"){if(S==="i"&&P+1<t.length)return{nextArgIndex:P+2};x++}else x++}}}return{nextArgIndex:P+1}};for(;h<t.length;){let C=t[h];if(C.startsWith("-")&&C.length>1&&C!=="--"){let P=m(C,h);if(P.nextArgIndex===-1)return{stdout:"",stderr:"",exitCode:2};if(P.nextArgIndex===-2)return{stdout:"",stderr:"",exitCode:1};h=P.nextArgIndex}else if(C==="--")for(h++;h<t.length;)d.push(t[h]),h++;else d.push(C),h++}if(p)return k("","",1);if(d.length===0&&c===null&&d.push("REPLY"),f===0){if(c)Se(e,c);else{for(let C of d)e.state.env.set(C,"");d.length===0&&e.state.env.set("REPLY","")}return k("","",0)}if(f<0&&f!==-1)return k("","",1);let y=s;u>=0?e.state.fileDescriptors?y=e.state.fileDescriptors.get(u)||"":y="":!y&&e.state.groupStdin!==void 0&&(y=e.state.groupStdin);let b=i===""?"\0":i,v="",A=0,g=!0,w=C=>{if(u>=0&&e.state.fileDescriptors)e.state.fileDescriptors.set(u,y.substring(C));else if(r>=0&&e.state.fileDescriptors){let P=e.state.fileDescriptors.get(r);if(P?.startsWith("__rw__:")){let x=Da(P);if(x){let S=x.position+C;e.state.fileDescriptors.set(r,Ta(x.path,S,x.content))}}}else e.state.groupStdin!==void 0&&!s&&(e.state.groupStdin=y.substring(C))};if(l>=0){let C=Math.min(l,y.length);v=y.substring(0,C),A=C,g=C>=l,w(A);let P=d[0]||"REPLY";e.state.env.set(P,v);for(let x=1;x<d.length;x++)e.state.env.set(d[x],"");return k("","",g?0:1)}else if(o>=0){let C=0,P=0,x=!1;for(;P<y.length&&C<o;){let S=y[P];if(S===b){A=P+1,x=!0;break}if(!n&&S==="\\"&&P+1<y.length){let D=y[P+1];if(D===b&&b===`
|
|
520
|
+
`){P+=2,A=P;continue}if(D===b){P+=2,C++,v+=D,A=P;continue}v+=D,P+=2,C++,A=P}else v+=S,P++,C++,A=P}g=C>=o||x,w(A)}else{A=0;let C=0;for(;C<y.length;){let P=y[C];if(P===b){A=C+b.length,g=!0;break}if(!n&&P==="\\"&&C+1<y.length){let x=y[C+1];if(x===`
|
|
521
|
+
`){C+=2;continue}if(x===b){v+=x,C+=2;continue}v+=P,v+=x,C+=2;continue}v+=P,C++}if(C>=y.length&&(g=!1,A=C,v.length===0&&y.length===0)){for(let P of d)e.state.env.set(P,"");return c&&Se(e,c),k("","",1)}w(A)}b===`
|
|
522
522
|
`&&v.endsWith(`
|
|
523
|
-
`)&&(v=v.slice(0,-1));let $=C=>n?C:C.replace(/\\(.)/g,"$1");if(d.length===1&&d[0]==="REPLY")return e.state.env.set("REPLY",$(v)),k("","",g?0:1);let E=
|
|
524
|
-
`,1);Se(e,c);for(let
|
|
523
|
+
`)&&(v=v.slice(0,-1));let $=C=>n?C:C.replace(/\\(.)/g,"$1");if(d.length===1&&d[0]==="REPLY")return e.state.env.set("REPLY",$(v)),k("","",g?0:1);let E=Dr(e.state.env);if(c){let{words:C}=hs(v,E,void 0,n),P=e.limits?.maxArrayElements??1e5;if(C.length>P)return k("",`read: array element limit exceeded (${P})
|
|
524
|
+
`,1);Se(e,c);for(let x=0;x<C.length;x++)e.state.env.set(`${c}_${x}`,$(C[x]));return k("","",g?0:1)}let O=d.length,{words:N,wordStarts:I}=hs(v,E,O,n);for(let C=0;C<d.length;C++){let P=d[C];if(C<d.length-1)e.state.env.set(P,$(N[C]??""));else if(C<I.length){let x=v.substring(I[C]);x=Tr(x,E,n),x=$(x),e.state.env.set(P,x)}else e.state.env.set(P,"")}return k("","",g?0:1)}function ar(e,t){if(e.state.callDepth===0&&e.state.sourceDepth===0)return _("bash: return: can only `return' from a function or sourced script\n");let s=e.state.lastExitCode;if(t.length>0){let r=t[0],n=Number.parseInt(r,10);if(r===""||Number.isNaN(n)||!/^-?\d+$/.test(r))return _(`bash: return: ${r}: numeric argument required
|
|
525
525
|
`,2);s=(n%256+256)%256}throw new oe(s)}var es=`set: usage: set [-eux] [+eux] [-o option] [+o option]
|
|
526
526
|
Options:
|
|
527
527
|
-e Exit immediately if a command exits with non-zero status
|
|
@@ -584,7 +584,7 @@ ${es}`;if(e.state.options.posix)throw new we(1,"",n);return _(n)}return or(e,t.s
|
|
|
584
584
|
`;else{let $=e.state.functions.get(m),E=$?Un(m,$):`${m} is a function
|
|
585
585
|
`;u+=E}y=!0}let v=e.state.env.get(`BASH_ALIAS_${m}`);if(v!==void 0&&(o||!y)&&(i||(n?u+=`alias
|
|
586
586
|
`:u+=`${m} is aliased to \`${v}'
|
|
587
|
-
`),y=!0,!o)||
|
|
587
|
+
`),y=!0,!o)||xs.has(m)&&(o||!y)&&(i||(n?u+=`keyword
|
|
588
588
|
`:u+=`${m} is a shell keyword
|
|
589
589
|
`),y=!0,!o))continue;if(!o&&b&&!y){if(!i)if(n)u+=`function
|
|
590
590
|
`;else{let $=e.state.functions.get(m),E=$?Un(m,$):`${m} is a function
|
|
@@ -604,7 +604,7 @@ ${e} ()
|
|
|
604
604
|
}
|
|
605
605
|
`}function yt(e){if(Array.isArray(e))return e.map(t=>yt(t)).join("; ");if(e.type==="Statement"){let t=[];for(let s=0;s<e.pipelines.length;s++){let r=e.pipelines[s];t.push(Za(r)),e.operators[s]&&t.push(e.operators[s])}return t.join(" ")}if(e.type==="SimpleCommand"){let t=e,s=[];t.name&&s.push(Zn(t.name));for(let r of t.args)s.push(Zn(r));return s.join(" ")}return e.type==="Group"?`{ ${e.body.map(r=>yt(r)).join("; ")}; }`:"..."}function Za(e){let t=e.commands.map(s=>yt(s));return(e.negated?"! ":"")+t.join(" | ")}function Zn(e){let t="";for(let s of e.parts)s.type==="Literal"?t+=s.value:s.type==="DoubleQuoted"?t+=`"${s.parts.map(r=>qn(r)).join("")}"`:s.type==="SingleQuoted"?t+=`'${s.value}'`:t+=qn(s);return t}function qn(e){let t=e;return t.type==="Literal"?t.value??"":t.type==="Variable"?`$${t.name}`:""}async function Kn(e,t,s,r){let n="",i="",a=0;for(let o of t){if(!o){a=1;continue}let l=e.state.env.get(`BASH_ALIAS_${o}`);if(l!==void 0)r?n+=`${o} is an alias for "${l}"
|
|
606
606
|
`:n+=`alias ${o}='${l}'
|
|
607
|
-
`;else if(
|
|
607
|
+
`;else if(xs.has(o))r?n+=`${o} is a shell keyword
|
|
608
608
|
`:n+=`${o}
|
|
609
609
|
`;else if(nt.has(o))r?n+=`${o} is a shell builtin
|
|
610
610
|
`:n+=`${o}
|
|
@@ -621,7 +621,7 @@ ${e} ()
|
|
|
621
621
|
`,127):_(`bash: ${t}: command not found
|
|
622
622
|
`,127);if("error"in c)return c.error==="permission_denied"?_(`bash: ${t}: Permission denied
|
|
623
623
|
`,126):_(`bash: ${t}: No such file or directory
|
|
624
|
-
`,127);if("script"in c)return t.includes("/")||(i.state.hashTable||(i.state.hashTable=new Map),i.state.hashTable.set(t,c.path)),await o(c.path,s,r);let{cmd:u,path:f}=c;t.includes("/")||(i.state.hashTable||(i.state.hashTable=new Map),i.state.hashTable.set(t,f));let d=r||i.state.groupStdin||"",h=a(),p={fs:i.fs,cwd:i.state.cwd,env:i.state.env,exportedEnv:h,stdin:d,limits:i.limits,exec:i.execFn,fetch:i.fetch,getRegisteredCommands:()=>Array.from(i.commands.keys()),sleep:i.sleep,trace:i.trace,fileDescriptors:i.state.fileDescriptors,xpgEcho:i.state.shoptOptions.xpg_echo,coverage:i.coverage,signal:i.state.signal,requireDefenseContext:i.requireDefenseContext,jsBootstrapCode:i.jsBootstrapCode,executorInvokeTool:i.executorInvokeTool},m=Hn(p,t);try{let y=()=>Ar(i.requireDefenseContext,"command",`${t} execution`,()=>u.execute(s,m));return u.trusted?await ge.runTrustedAsync(()=>y()):await y()}catch(y){if(y instanceof Y||y instanceof Ge)throw y;return _(`${t}: ${he(Ne(y))}
|
|
624
|
+
`,127);if("script"in c)return t.includes("/")||(i.state.hashTable||(i.state.hashTable=new Map),i.state.hashTable.set(t,c.path)),await o(c.path,s,r);let{cmd:u,path:f}=c;t.includes("/")||(i.state.hashTable||(i.state.hashTable=new Map),i.state.hashTable.set(t,f));let d=r||i.state.groupStdin||"",h=a(),p={fs:i.fs,cwd:i.state.cwd,env:i.state.env,exportedEnv:h,stdin:d,limits:i.limits,exec:i.execFn,fetch:i.fetch,getRegisteredCommands:()=>Array.from(i.commands.keys()),sleep:i.sleep,trace:i.trace,fileDescriptors:i.state.fileDescriptors,xpgEcho:i.state.shoptOptions.xpg_echo,coverage:i.coverage,signal:i.state.signal,requireDefenseContext:i.requireDefenseContext,jsBootstrapCode:i.jsBootstrapCode,executorInvokeTool:i.executorInvokeTool,executorExecFn:i.executorExecFn},m=Hn(p,t);try{let y=()=>Ar(i.requireDefenseContext,"command",`${t} execution`,()=>u.execute(s,m));return u.trusted?await ge.runTrustedAsync(()=>y()):await y()}catch(y){if(y instanceof Y||y instanceof Ge)throw y;return _(`${t}: ${he(Ne(y))}
|
|
625
625
|
`)}}async function pr(e,t){let s=e.state.inCondition;e.state.inCondition=!0;let r="",n="",i=0;try{for(let a of t){let o=await e.executeStatement(a);r+=o.stdout,n+=o.stderr,i=o.exitCode}}finally{e.state.inCondition=s}return{stdout:r,stderr:n,exitCode:i}}function gt(e,t,s,r){if(e instanceof ue)return t+=e.stdout,s+=e.stderr,e.levels>1&&r>1?(e.levels--,e.stdout=t,e.stderr=s,{action:"rethrow",stdout:t,stderr:s,error:e}):{action:"break",stdout:t,stderr:s};if(e instanceof fe)return t+=e.stdout,s+=e.stderr,e.levels>1&&r>1?(e.levels--,e.stdout=t,e.stderr=s,{action:"rethrow",stdout:t,stderr:s,error:e}):{action:"continue",stdout:t,stderr:s};if(e instanceof oe||e instanceof de||e instanceof j||e instanceof Y)return e.prependOutput(t,s),{action:"rethrow",stdout:t,stderr:s,error:e};let n=Ne(e);return{action:"error",stdout:t,stderr:`${s}${n}
|
|
626
626
|
`,exitCode:1}}async function rs(e,t,s="",r=""){let n=s,i=r,a=0;try{for(let o of t){let l=await e.executeStatement(o);n+=l.stdout,i+=l.stderr,a=l.exitCode}}catch(o){if(_t(o)||o instanceof de||o instanceof j||o instanceof Y||o instanceof Te)throw o.prependOutput(n,i),o;return{stdout:n,stderr:`${i}${Ne(o)}
|
|
627
627
|
`,exitCode:1}}return{stdout:n,stderr:i,exitCode:a}}async function Jn(e,t){let s="",r="";for(let n of t.clauses){let i=await pr(e,n.condition);if(s+=i.stdout,r+=i.stderr,i.exitCode===0)return rs(e,n.body,s,r)}return t.elseBody?rs(e,t.elseBody,s,r):k(s,r,0)}async function ei(e,t){let s=await ke(e,t.redirections);if(s)return s;let r="",n="",i=0,a=0;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t.variable))return _(`bash: \`${t.variable}': not a valid identifier
|
|
@@ -661,7 +661,7 @@ sys 0m0.000s
|
|
|
661
661
|
`,1)}e.state.groupStdin=c;let u=k(n,i,a);return Z(e,u,t.redirections)}async function mi(e,t,s,r,n){let i;try{i=await e.fs.readFile(t)}catch{return _(`bash: ${t}: No such file or directory
|
|
662
662
|
`,127)}if(i.startsWith("#!")){let y=i.indexOf(`
|
|
663
663
|
`);y!==-1&&(i=i.slice(y+1))}let a=new Map(e.state.env),o=e.state.cwd,l={...e.state.options},c=e.state.loopDepth,u=e.state.parentHasLoopContext,f=e.state.lastArg,d=e.state.bashPid,h=e.state.groupStdin,p=e.state.currentSource;e.state.parentHasLoopContext=c>0,e.state.loopDepth=0,e.state.bashPid=e.state.nextVirtualPid++,r&&(e.state.groupStdin=r),e.state.currentSource=t,e.state.env.set("0",t),e.state.env.set("#",String(s.length)),e.state.env.set("@",s.join(" ")),e.state.env.set("*",s.join(" "));for(let y=0;y<s.length&&y<9;y++)e.state.env.set(String(y+1),s[y]);for(let y=s.length+1;y<=9;y++)e.state.env.delete(String(y));let m=()=>{e.state.env=a,e.state.cwd=o,e.state.options=l,e.state.loopDepth=c,e.state.parentHasLoopContext=u,e.state.lastArg=f,e.state.bashPid=d,e.state.groupStdin=h,e.state.currentSource=p};try{let b=new V().parse(i),v=await n(b);return m(),v}catch(y){if(m(),y instanceof j||y instanceof Y)throw y;if(y.name==="ParseException")return _(`bash: ${t}: ${y.message}
|
|
664
|
-
`);throw y}}var wt=class{ctx;constructor(t,s){this.ctx={state:s,fs:t.fs,commands:t.commands,limits:t.limits,execFn:t.exec,executeScript:this.executeScript.bind(this),executeStatement:this.executeStatement.bind(this),executeCommand:this.executeCommand.bind(this),fetch:t.fetch,sleep:t.sleep,trace:t.trace,coverage:t.coverage,requireDefenseContext:t.requireDefenseContext??!1,jsBootstrapCode:t.jsBootstrapCode,executorInvokeTool:t.executorInvokeTool}}assertDefenseContext(t){if(!this.ctx.requireDefenseContext||ge.isInSandboxedContext())return;let s=`interpreter ${t} attempted outside defense context`;throw new Ge(s,{timestamp:Date.now(),type:"missing_defense_context",message:s,path:"DefenseInDepthBox.context",stack:new Error().stack,executionId:ge.getCurrentExecutionId()})}buildExportedEnv(){let t=this.ctx.state.exportedVars,s=this.ctx.state.tempExportedVars,r=new Set;if(t)for(let i of t)r.add(i);if(s)for(let i of s)r.add(i);if(r.size===0)return Object.create(null);let n=Object.create(null);for(let i of r){let a=this.ctx.state.env.get(i);a!==void 0&&(n[i]=a)}return n}async executeScript(t){this.assertDefenseContext("execution");let s="",r="",n=0,i=this.ctx.limits.maxOutputSize,a=(o,l)=>{s.length+r.length+o.length+l.length>i&&_e(`total output size exceeded (>${i} bytes), increase executionLimits.maxOutputSize`,"output_size"),s+=o,r+=l};for(let o of t.statements)try{let l=await this.executeStatement(o);a(l.stdout,l.stderr),n=l.exitCode,this.ctx.state.lastExitCode=n,this.ctx.state.env.set("?",String(n))}catch(l){if(l instanceof j)throw l.prependOutput(s,r),l;if(l instanceof we)return a(l.stdout,l.stderr),n=l.exitCode,this.ctx.state.lastExitCode=n,this.ctx.state.env.set("?",String(n)),{stdout:s,stderr:r,exitCode:n,env:Ie(this.ctx.state.env)};if(l instanceof Y)throw l;if(l instanceof de)return a(l.stdout,l.stderr),n=l.exitCode,this.ctx.state.lastExitCode=n,this.ctx.state.env.set("?",String(n)),{stdout:s,stderr:r,exitCode:n,env:Ie(this.ctx.state.env)};if(l instanceof Er)return a(l.stdout,l.stderr),n=1,this.ctx.state.lastExitCode=n,this.ctx.state.env.set("?",String(n)),{stdout:s,stderr:r,exitCode:n,env:Ie(this.ctx.state.env)};if(l instanceof Et)return a(l.stdout,l.stderr),n=1,this.ctx.state.lastExitCode=n,this.ctx.state.env.set("?",String(n)),{stdout:s,stderr:r,exitCode:n,env:Ie(this.ctx.state.env)};if(l instanceof Ve){a(l.stdout,l.stderr),n=1,this.ctx.state.lastExitCode=n,this.ctx.state.env.set("?",String(n));continue}if(l instanceof Sr){a(l.stdout,l.stderr),n=1,this.ctx.state.lastExitCode=n,this.ctx.state.env.set("?",String(n));continue}if(l instanceof ue||l instanceof fe){if(this.ctx.state.loopDepth>0)throw l.prependOutput(s,r),l;a(l.stdout,l.stderr);continue}throw l instanceof oe&&l.prependOutput(s,r),l}return{stdout:s,stderr:r,exitCode:n,env:Ie(this.ctx.state.env)}}async executeUserScript(t,s,r=""){return mi(this.ctx,t,s,r,n=>this.executeScript(n))}async executeStatement(t){if(this.assertDefenseContext("statement"),this.ctx.state.signal?.aborted)throw new At;if(this.ctx.state.commandCount++,this.ctx.state.commandCount>this.ctx.limits.maxCommandCount&&_e(`too many commands executed (>${this.ctx.limits.maxCommandCount}), increase executionLimits.maxCommandCount`,"commands"),t.deferredError)throw new Pt(t.deferredError.message,t.line??1,1);if(this.ctx.state.options.noexec)return L;this.ctx.state.errexitSafe=!1;let s="",r="";this.ctx.state.options.verbose&&!this.ctx.state.suppressVerbose&&t.sourceText&&(r+=`${t.sourceText}
|
|
664
|
+
`);throw y}}var wt=class{ctx;constructor(t,s){this.ctx={state:s,fs:t.fs,commands:t.commands,limits:t.limits,execFn:t.exec,executeScript:this.executeScript.bind(this),executeStatement:this.executeStatement.bind(this),executeCommand:this.executeCommand.bind(this),fetch:t.fetch,sleep:t.sleep,trace:t.trace,coverage:t.coverage,requireDefenseContext:t.requireDefenseContext??!1,jsBootstrapCode:t.jsBootstrapCode,executorInvokeTool:t.executorInvokeTool,executorExecFn:t.executorExecFn}}assertDefenseContext(t){if(!this.ctx.requireDefenseContext||ge.isInSandboxedContext())return;let s=`interpreter ${t} attempted outside defense context`;throw new Ge(s,{timestamp:Date.now(),type:"missing_defense_context",message:s,path:"DefenseInDepthBox.context",stack:new Error().stack,executionId:ge.getCurrentExecutionId()})}buildExportedEnv(){let t=this.ctx.state.exportedVars,s=this.ctx.state.tempExportedVars,r=new Set;if(t)for(let i of t)r.add(i);if(s)for(let i of s)r.add(i);if(r.size===0)return Object.create(null);let n=Object.create(null);for(let i of r){let a=this.ctx.state.env.get(i);a!==void 0&&(n[i]=a)}return n}async executeScript(t){this.assertDefenseContext("execution");let s="",r="",n=0,i=this.ctx.limits.maxOutputSize,a=(o,l)=>{s.length+r.length+o.length+l.length>i&&_e(`total output size exceeded (>${i} bytes), increase executionLimits.maxOutputSize`,"output_size"),s+=o,r+=l};for(let o of t.statements)try{let l=await this.executeStatement(o);a(l.stdout,l.stderr),n=l.exitCode,this.ctx.state.lastExitCode=n,this.ctx.state.env.set("?",String(n))}catch(l){if(l instanceof j)throw l.prependOutput(s,r),l;if(l instanceof we)return a(l.stdout,l.stderr),n=l.exitCode,this.ctx.state.lastExitCode=n,this.ctx.state.env.set("?",String(n)),{stdout:s,stderr:r,exitCode:n,env:Ie(this.ctx.state.env)};if(l instanceof Y)throw l;if(l instanceof de)return a(l.stdout,l.stderr),n=l.exitCode,this.ctx.state.lastExitCode=n,this.ctx.state.env.set("?",String(n)),{stdout:s,stderr:r,exitCode:n,env:Ie(this.ctx.state.env)};if(l instanceof Er)return a(l.stdout,l.stderr),n=1,this.ctx.state.lastExitCode=n,this.ctx.state.env.set("?",String(n)),{stdout:s,stderr:r,exitCode:n,env:Ie(this.ctx.state.env)};if(l instanceof Et)return a(l.stdout,l.stderr),n=1,this.ctx.state.lastExitCode=n,this.ctx.state.env.set("?",String(n)),{stdout:s,stderr:r,exitCode:n,env:Ie(this.ctx.state.env)};if(l instanceof Ve){a(l.stdout,l.stderr),n=1,this.ctx.state.lastExitCode=n,this.ctx.state.env.set("?",String(n));continue}if(l instanceof Sr){a(l.stdout,l.stderr),n=1,this.ctx.state.lastExitCode=n,this.ctx.state.env.set("?",String(n));continue}if(l instanceof ue||l instanceof fe){if(this.ctx.state.loopDepth>0)throw l.prependOutput(s,r),l;a(l.stdout,l.stderr);continue}throw l instanceof oe&&l.prependOutput(s,r),l}return{stdout:s,stderr:r,exitCode:n,env:Ie(this.ctx.state.env)}}async executeUserScript(t,s,r=""){return mi(this.ctx,t,s,r,n=>this.executeScript(n))}async executeStatement(t){if(this.assertDefenseContext("statement"),this.ctx.state.signal?.aborted)throw new At;if(this.ctx.state.commandCount++,this.ctx.state.commandCount>this.ctx.limits.maxCommandCount&&_e(`too many commands executed (>${this.ctx.limits.maxCommandCount}), increase executionLimits.maxCommandCount`,"commands"),t.deferredError)throw new Pt(t.deferredError.message,t.line??1,1);if(this.ctx.state.options.noexec)return L;this.ctx.state.errexitSafe=!1;let s="",r="";this.ctx.state.options.verbose&&!this.ctx.state.suppressVerbose&&t.sourceText&&(r+=`${t.sourceText}
|
|
665
665
|
`);let n=0,i=-1,a=!1;for(let c=0;c<t.pipelines.length;c++){let u=t.pipelines[c],f=c>0?t.operators[c-1]:null;if(f==="&&"&&n!==0||f==="||"&&n===0)continue;let d=await this.executePipeline(u);s+=d.stdout,r+=d.stderr,n=d.exitCode,i=c,a=u.negated,this.ctx.state.lastExitCode=n,this.ctx.state.env.set("?",String(n))}let o=i<t.pipelines.length-1,l=this.ctx.state.errexitSafe;if(this.ctx.state.errexitSafe=o||a||l,this.ctx.state.options.errexit&&n!==0&&i===t.pipelines.length-1&&!a&&!this.ctx.state.inCondition&&!l)throw new de(n,s,r);return k(s,r,n)}async executePipeline(t){return ui(this.ctx,t,(s,r)=>this.executeCommand(s,r))}async executeCommand(t,s){switch(this.assertDefenseContext("command"),this.ctx.coverage?.hit(`bash:cmd:${t.type}`),t.type){case"SimpleCommand":return this.executeSimpleCommand(t,s);case"If":return Jn(this.ctx,t);case"For":return ei(this.ctx,t);case"CStyleFor":return ti(this.ctx,t);case"While":return si(this.ctx,t,s);case"Until":return ri(this.ctx,t);case"Case":return ni(this.ctx,t);case"Subshell":return this.executeSubshell(t,s);case"Group":return this.executeGroup(t,s);case"FunctionDef":return bn(this.ctx,t);case"ArithmeticCommand":return this.executeArithmeticCommand(t);case"ConditionalCommand":return this.executeConditionalCommand(t);default:return L}}async executeSimpleCommand(t,s){try{return await this.executeSimpleCommandInner(t,s)}catch(r){if(r instanceof St)return _(r.stderr);throw r}}async executeSimpleCommandInner(t,s){if(t.line!==void 0&&(this.ctx.state.currentLine=t.line),this.ctx.state.shoptOptions.expand_aliases&&t.name){let g=t,w=100;for(;w>0;){let $=this.expandAlias(g);if($===g)break;g=$,w--}this.aliasExpansionStack.clear(),g!==t&&(t=g)}this.ctx.state.expansionStderr="";let r=await fi(this.ctx,t);if(r.error)return r.error;let n=r.tempAssignments,i=r.xtraceOutput;if(!t.name){if(t.redirections.length>0){let w=await ke(this.ctx,t.redirections);if(w)return w;let $=k("",i,0);return Z(this.ctx,$,t.redirections)}this.ctx.state.lastArg="";let g=(this.ctx.state.expansionStderr||"")+i;return this.ctx.state.expansionStderr="",k("",g,this.ctx.state.lastExitCode)}let a=t.name&&mr(t.name,["local","declare","typeset","export","readonly"]),o=Array.from(n.keys());if(o.length>0&&!a){this.ctx.state.tempExportedVars=this.ctx.state.tempExportedVars||new Set;for(let g of o)this.ctx.state.tempExportedVars.add(g)}let l=await Kt(this.ctx,t.redirections);if(l){for(let[g,w]of n)w===void 0?this.ctx.state.env.delete(g):this.ctx.state.env.set(g,w);return l}let c=-1;for(let g of t.redirections){if((g.operator==="<<"||g.operator==="<<-")&&g.target.type==="HereDoc"){let w=g.target,$=await T(this.ctx,w.content);w.stripTabs&&($=$.split(`
|
|
666
666
|
`).map(O=>O.replace(/^\t+/,"")).join(`
|
|
667
667
|
`));let E=g.fd??0;E!==0?(this.ctx.state.fileDescriptors||(this.ctx.state.fileDescriptors=new Map),ie(this.ctx),this.ctx.state.fileDescriptors.set(E,$)):s=$;continue}if(g.operator==="<<<"&&g.target.type==="Word"){s=`${await T(this.ctx,g.target)}
|
|
@@ -673,9 +673,9 @@ sys 0m0.000s
|
|
|
673
673
|
`,n);return Z(this.ctx,i,t.redirections)}}};var te={maxCallDepth:100,maxCommandCount:1e4,maxLoopIterations:1e4,maxAwkIterations:1e4,maxSedIterations:1e4,maxJqIterations:1e4,maxSqliteTimeoutMs:5e3,maxPythonTimeoutMs:1e4,maxJsTimeoutMs:1e4,maxGlobOperations:1e5,maxStringLength:10485760,maxArrayElements:1e5,maxHeredocSize:10485760,maxSubstitutionDepth:50,maxBraceExpansionResults:1e4,maxOutputSize:10485760,maxFileDescriptors:1024,maxSourceDepth:100};function yi(e){return e?{maxCallDepth:e.maxCallDepth??te.maxCallDepth,maxCommandCount:e.maxCommandCount??te.maxCommandCount,maxLoopIterations:e.maxLoopIterations??te.maxLoopIterations,maxAwkIterations:e.maxAwkIterations??te.maxAwkIterations,maxSedIterations:e.maxSedIterations??te.maxSedIterations,maxJqIterations:e.maxJqIterations??te.maxJqIterations,maxSqliteTimeoutMs:e.maxSqliteTimeoutMs??te.maxSqliteTimeoutMs,maxPythonTimeoutMs:e.maxPythonTimeoutMs??te.maxPythonTimeoutMs,maxJsTimeoutMs:e.maxJsTimeoutMs??te.maxJsTimeoutMs,maxGlobOperations:e.maxGlobOperations??te.maxGlobOperations,maxStringLength:e.maxStringLength??te.maxStringLength,maxArrayElements:e.maxArrayElements??te.maxArrayElements,maxHeredocSize:e.maxHeredocSize??te.maxHeredocSize,maxSubstitutionDepth:e.maxSubstitutionDepth??te.maxSubstitutionDepth,maxBraceExpansionResults:e.maxBraceExpansionResults??te.maxBraceExpansionResults,maxOutputSize:e.maxOutputSize??te.maxOutputSize,maxFileDescriptors:e.maxFileDescriptors??te.maxFileDescriptors,maxSourceDepth:e.maxSourceDepth??te.maxSourceDepth}:{...te}}import{lookup as ho}from"node:dns";function yr(e){try{let t=new URL(e);return{origin:t.origin,pathname:t.pathname,href:t.href}}catch{return null}}function ao(e){let t=yr(e);return t?{origin:t.origin,pathPrefix:t.pathname}:null}function gi(e){if(e.includes("\\"))return!0;let t=e.toLowerCase();return t.includes("%2f")||t.includes("%5c")}function oo(e,t){return t==="/"||t===""?!0:t.endsWith("/")?e.startsWith(t):e===t||e.startsWith(`${t}/`)}function gr(e,t){let s=yr(e);if(!s)return!1;let r=ao(t);return!r||s.origin!==r.origin||r.pathPrefix!=="/"&&r.pathPrefix!==""&&gi(s.pathname)?!1:oo(s.pathname,r.pathPrefix)}function wi(e){return typeof e=="string"?e:e.url}function vi(e,t){return!t||t.length===0?!1:t.some(s=>gr(e,wi(s)))}function wr(e){let t=lo(e);if(t==="localhost"||t.endsWith(".localhost"))return!0;let s=bi(t);if(s)return ns(s);let r=uo(t);return r?fo(r):!1}function lo(e){let t=e.trim().toLowerCase();return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function co(e){if(!e)return null;let t=10,s=e;if(s.startsWith("0x")||s.startsWith("0X")?(t=16,s=s.slice(2)):s.length>1&&s.startsWith("0")&&(t=8),!s||t===16&&!/^[0-9a-fA-F]+$/.test(s)||t===10&&!/^\d+$/.test(s)||t===8&&!/^[0-7]+$/.test(s))return null;let r=Number.parseInt(s,t);return!Number.isFinite(r)||r<0?null:r}function bi(e){let t=e.split(".");if(t.length===0||t.length>4)return null;let s=t.map(l=>co(l));if(s.some(l=>l===null))return null;let r=s;if(t.length===1){let l=r[0];return l>4294967295?null:[l>>>24&255,l>>>16&255,l>>>8&255,l&255]}if(t.length===2){let[l,c]=r;return l>255||c>16777215?null:[l,c>>>16&255,c>>>8&255,c&255]}if(t.length===3){let[l,c,u]=r;return l>255||c>255||u>65535?null:[l,c,u>>>8&255,u&255]}let[n,i,a,o]=r;return n>255||i>255||a>255||o>255?null:[n,i,a,o]}function uo(e){let t=e,s=null;if(t.includes(".")){let m=t.lastIndexOf(":");if(m<0)return null;let y=t.slice(m+1),b=bi(y);if(!b)return null;s=b,t=t.slice(0,m)}let r=t.includes("::")?t.split("::").length-1:0;if(r>1)return null;let[n,i]=t.split("::"),a=n?n.split(":").filter(Boolean):[],o=i?i.split(":").filter(Boolean):[],l=m=>/^[0-9a-f]{1,4}$/i.test(m)?Number.parseInt(m,16):null,c=a.map(l),u=o.map(l);if(c.some(m=>m===null)||u.some(m=>m===null))return null;let f=s?2:0,d=c.length+u.length+f,h=0;if(r===1){if(h=8-d,h<0)return null}else if(d!==8)return null;let p=[...c,...new Array(h).fill(0),...u];return s&&(p.push(s[0]<<8|s[1]),p.push(s[2]<<8|s[3])),p.length===8?p:null}function ns(e){let[t,s]=e;return t===127||t===10||t===172&&s>=16&&s<=31||t===192&&s===168||t===169&&s===254||t===0||t===100&&s>=64&&s<=127||t===198&&(s===18||s===19)||t===192&&s===0&&e[2]===0||t===192&&s===0&&e[2]===2||t===198&&s===51&&e[2]===100||t===203&&s===0&&e[2]===113||t>=240}function fo(e){if(e.every(n=>n===0)||e.slice(0,7).every(n=>n===0)&&e[7]===1||(e[0]&65472)===65152||(e[0]&65024)===64512)return!0;if(e[0]===0&&e[1]===0&&e[2]===0&&e[3]===0&&e[4]===0&&e[5]===65535){let n=[e[6]>>>8&255,e[6]&255,e[7]>>>8&255,e[7]&255];return ns(n)}if(e[0]===8193&&e[1]===3512)return!0;if(e[0]===100&&e[1]===65435&&e[2]===0&&e[3]===0&&e[4]===0&&e[5]===0){let n=[e[6]>>>8&255,e[6]&255,e[7]>>>8&255,e[7]&255];return ns(n)}if(e[0]===100&&e[1]===65435&&e[2]===1)return!0;if(e[0]===8194){let n=[e[1]>>>8&255,e[1]&255,e[2]>>>8&255,e[2]&255];return ns(n)}return!1}function $i(e){let t=[];for(let s of e){if(typeof s!="string"&&(s===null||typeof s!="object"||!("url"in s)||typeof s.url!="string")){t.push('Invalid allow-list entry: must be a string URL or an object with a "url" string property');continue}let r=wi(s);if(!yr(r)){t.push(`Invalid URL in allow-list: "${r}" - must be a valid URL with scheme and host (e.g., "https://example.com")`);continue}let i=new URL(r);if(i.protocol!=="http:"&&i.protocol!=="https:"){t.push(`Only http and https URLs are allowed in allow-list: "${r}"`);continue}if(!i.hostname){t.push(`Allow-list entry must include a hostname: "${r}"`);continue}if(i.pathname!=="/"&&i.pathname!==""&&gi(i.pathname)){t.push(`Allow-list entry contains ambiguous path separators: "${r}"`);continue}(i.search||i.hash)&&t.push(`Query strings and fragments are ignored in allow-list entries: "${r}"`)}return t}var Pe=class extends Error{constructor(t,s){let r=s??"URL not in allow-list";super(`Network access denied: ${r}: ${t}`),this.name="NetworkAccessDeniedError"}},vt=class extends Error{constructor(t){super(`Too many redirects (max: ${t})`),this.name="TooManyRedirectsError"}},bt=class extends Error{constructor(t){super(`Redirect target not in allow-list: ${t}`),this.name="RedirectNotAllowedError"}},is=class extends Error{constructor(t,s){super(`HTTP method '${t}' not allowed. Allowed methods: ${s.join(", ")}`),this.name="MethodNotAllowedError"}},$t=class extends Error{constructor(t){super(`Response body too large (max: ${t} bytes)`),this.name="ResponseTooLargeError"}};function po(e){return new Promise((t,s)=>{ho(e,{all:!0},(r,n)=>{r?s(r):t(n)})})}var mo=20,yo=3e4,go=10485760,wo=["GET","HEAD"],vo=new Set(["GET","HEAD","OPTIONS"]),bo=new Set([301,302,303,307,308]);function vr(e){let t=e.allowedUrlPrefixes??[];if(!e.dangerouslyAllowFullInternetAccess){let h=$i(t);if(h.length>0)throw new Error(`Invalid network allow-list:
|
|
674
674
|
${h.join(`
|
|
675
675
|
`)}`)}let s=[];for(let h of t)typeof h=="object"&&h.transform&&h.transform.length>0&&s.push(h);function r(h){if(s.length===0)return null;let p=null;for(let m of s)if(gr(h,m.url)&&m.transform){p||(p=new Headers);for(let y of m.transform)for(let[b,v]of Object.entries(y.headers))p.set(b,v)}return p}let n=e.maxRedirects??mo,i=e.timeoutMs??yo,a=e.maxResponseSize??go,o=e.dangerouslyAllowFullInternetAccess?["GET","HEAD","POST","PUT","DELETE","PATCH","OPTIONS"]:e.allowedMethods??wo,l=e.denyPrivateRanges??(typeof process<"u"&&process.env?.NODE_ENV==="production"),c=e._dnsResolve??po;async function u(h){if(!e.dangerouslyAllowFullInternetAccess&&!vi(h,t))throw new Pe(h);if(l)try{let p=new URL(h);if(wr(p.hostname))throw new Pe(h,"private/loopback IP address blocked");let m=p.hostname;if(/[a-zA-Z]/.test(m))try{let b=await c(m);for(let{address:v}of b)if(wr(v))throw new Pe(h,"hostname resolves to private/loopback IP address")}catch(b){if(b instanceof Pe)throw b;let v=b?.code;if(!(v==="ENOTFOUND"||v==="ENODATA"))throw new Pe(h,"DNS resolution failed for private IP check")}}catch(p){if(p instanceof Pe)throw p}}function f(h){if(e.dangerouslyAllowFullInternetAccess)return;let p=h.toUpperCase();if(!o.includes(p))throw new is(p,o)}async function d(h,p={}){let m=p.method?.toUpperCase()??"GET";await u(h),f(m);let y=h,b=0,v=p.followRedirects??!0,A=p.timeoutMs!==void 0?Math.min(p.timeoutMs,i):i;for(;;){let g=new AbortController,w=br(()=>g.abort(),A);try{let $=await ge.runTrustedAsync(()=>{let E=r(y),O=$o(p.headers,E),N={method:m,headers:O,signal:g.signal,redirect:"manual"};return p.body&&!vo.has(m)&&(N.body=p.body),fetch(y,N)});if(bo.has($.status)&&v){let E=$.headers.get("location");if(!E)return await Ei($,y,a);let O=new URL(E,y).href;try{await u(O)}catch{throw new bt(O)}if(b++,b>n)throw new vt(n);y=O;continue}return await Ei($,y,a)}finally{$r(w)}}}return d}function $o(e,t){if(!e&&!t)return;if(!t)return e;let s=e instanceof Headers?new Headers(e):new Headers(e);for(let[r,n]of t)s.set(r,n);return s}async function Ei(e,t,s){let r=Object.create(null);if(e.headers.forEach((i,a)=>{r[a.toLowerCase()]=i}),s>0){let i=e.headers.get("content-length");if(i){let a=parseInt(i,10);if(!Number.isNaN(a)&&a>s)throw new $t(s)}}let n;if(s>0&&e.body){let i=e.body.getReader(),a=new TextDecoder,o=[],l=0;for(;;){let{done:c,value:u}=await i.read();if(c)break;if(l+=u.byteLength,l>s)throw i.cancel(),new $t(s);o.push(a.decode(u,{stream:!0}))}o.push(a.decode()),n=o.join("")}else n=await e.text();return{status:e.status,statusText:e.statusText,headers:r,body:n,url:t}}function Si(e){return Ze(e)}function Ze(e){return e.statements.map(Ai).join(`
|
|
676
|
-
`)}function Ai(e){let t=[];for(let r=0;r<e.pipelines.length;r++)t.push(Eo(e.pipelines[r])),r<e.operators.length&&t.push(e.operators[r]);let s=t.join(" ");return e.background&&(s+=" &"),s}function Eo(e){let t=[];e.timed&&t.push(e.timePosix?"time -p":"time"),e.negated&&t.push("!");let s=[];for(let n=0;n<e.commands.length;n++)if(s.push(_i(e.commands[n])),n<e.commands.length-1){let i=e.pipeStderr?.[n];s.push(i?"|&":"|")}return(t.length>0?`${t.join(" ")} `:"")+s.join(" ")}function _i(e){switch(e.type){case"SimpleCommand":return So(e);case"If":return
|
|
676
|
+
`)}function Ai(e){let t=[];for(let r=0;r<e.pipelines.length;r++)t.push(Eo(e.pipelines[r])),r<e.operators.length&&t.push(e.operators[r]);let s=t.join(" ");return e.background&&(s+=" &"),s}function Eo(e){let t=[];e.timed&&t.push(e.timePosix?"time -p":"time"),e.negated&&t.push("!");let s=[];for(let n=0;n<e.commands.length;n++)if(s.push(_i(e.commands[n])),n<e.commands.length-1){let i=e.pipeStderr?.[n];s.push(i?"|&":"|")}return(t.length>0?`${t.join(" ")} `:"")+s.join(" ")}function _i(e){switch(e.type){case"SimpleCommand":return So(e);case"If":return Do(e);case"For":return To(e);case"CStyleFor":return Io(e);case"While":return Ro(e);case"Until":return Lo(e);case"Case":return Fo(e);case"Subshell":return Wo(e);case"Group":return zo(e);case"ArithmeticCommand":return Vo(e);case"ConditionalCommand":return jo(e);case"FunctionDef":return Bo(e);default:{let t=e;throw new Error(`Unsupported command type: ${t.type}`)}}}function So(e){let t=[];for(let s of e.assignments)t.push(Ao(s));e.name&&t.push(ae(e.name));for(let s of e.args)t.push(ae(s));for(let s of e.redirections)t.push(Pi(s));return t.join(" ")}function Ao(e){let t=e.append?"+=":"=";if(e.array){let s=e.array.map(ae).join(" ");return`${e.name}${t}(${s})`}return e.value?`${e.name}${t}${ae(e.value)}`:`${e.name}${t}`}function ae(e){return e.parts.map(t=>as(t,!1)).join("")}function ze(e){return e.parts.map(t=>as(t,!0)).join("")}function as(e,t){switch(e.type){case"Literal":return t?Co(e.value):_o(e.value);case"SingleQuoted":return`'${e.value}'`;case"DoubleQuoted":return`"${e.parts.map(s=>as(s,!0)).join("")}"`;case"Escaped":return`\\${e.value}`;case"ParameterExpansion":return Ci(e);case"CommandSubstitution":return e.legacy?`\`${Ze(e.body)}\``:`$(${Ze(e.body)})`;case"ArithmeticExpansion":return`$((${H(e.expression.expression)}))`;case"ProcessSubstitution":return e.direction==="input"?`<(${Ze(e.body)})`:`>(${Ze(e.body)})`;case"BraceExpansion":return Oo(e);case"TildeExpansion":return e.user!==null?`~${e.user}`:"~";case"Glob":return e.pattern;default:{let s=e;throw new Error(`Unsupported word part type: ${s.type}`)}}}function _o(e){return e.replace(/[\s\\'"`!|&;()<>{}[\]*?~#]/g,"\\$&")}function Co(e){return e.replace(/[$`"\\]/g,"\\$&")}function ko(e,t){return e.parts.map(s=>Po(s,t)).join("")}function Po(e,t){switch(e.type){case"Literal":return t?e.value:e.value.replace(/[$`]/g,"\\$&");case"Escaped":return`\\${e.value}`;case"ParameterExpansion":return Ci(e);case"CommandSubstitution":return e.legacy?`\`${Ze(e.body)}\``:`$(${Ze(e.body)})`;case"ArithmeticExpansion":return`$((${H(e.expression.expression)}))`;default:return as(e,!1)}}function Ci(e){return e.operation?`\${${ki(e.parameter,e.operation)}}`:No(e.parameter)?`\${${e.parameter}}`:`$${e.parameter}`}function No(e){return!(/^[?#@*$!\-0-9]$/.test(e)||/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e))}function ki(e,t){switch(t.type){case"Length":return`#${e}`;case"LengthSliceError":return`#${e}:`;case"BadSubstitution":return t.text;case"DefaultValue":return`${e}${t.checkEmpty?":":""}-${ze(t.word)}`;case"AssignDefault":return`${e}${t.checkEmpty?":":""}=${ze(t.word)}`;case"ErrorIfUnset":return`${e}${t.checkEmpty?":":""}?${t.word?ze(t.word):""}`;case"UseAlternative":return`${e}${t.checkEmpty?":":""}+${ze(t.word)}`;case"Substring":{let s=H(t.offset.expression);return t.length?`${e}:${s}:${H(t.length.expression)}`:`${e}:${s}`}case"PatternRemoval":{let s=t.side==="prefix"?"#":"%",r=t.greedy?`${s}${s}`:s;return`${e}${r}${ze(t.pattern)}`}case"PatternReplacement":{let s="/";t.all?s="//":t.anchor==="start"?s="/#":t.anchor==="end"&&(s="/%");let r=t.replacement?`/${ze(t.replacement)}`:"";return`${e}${s}${ze(t.pattern)}${r}`}case"CaseModification":{let s=t.direction==="upper"?"^":",",r=t.all?`${s}${s}`:s,n=t.pattern?ze(t.pattern):"";return`${e}${r}${n}`}case"Transform":return`${e}@${t.operator}`;case"Indirection":return t.innerOp?`!${ki(e,t.innerOp)}`:`!${e}`;case"ArrayKeys":return`!${t.array}[${t.star?"*":"@"}]`;case"VarNamePrefix":return`!${t.prefix}${t.star?"*":"@"}`;default:{let s=t;throw new Error(`Unsupported parameter operation type: ${s.type}`)}}}function Oo(e){return`{${e.items.map(xo).join(",")}}`}function xo(e){if(e.type==="Word")return ae(e.word);let t=e.startStr??String(e.start),s=e.endStr??String(e.end);return e.step!==void 0?`${t}..${s}..${e.step}`:`${t}..${s}`}function Pi(e){let t=e.fdVariable?`{${e.fdVariable}}`:e.fd!==null?String(e.fd):"";if(e.operator==="<<"||e.operator==="<<-"){let s=e.target,r=s.quoted?`'${s.delimiter}'`:s.delimiter,n=ko(s.content,s.quoted);return`${t}${e.operator}${r}
|
|
677
677
|
${n}${s.delimiter}`}return e.operator==="<<<"?`${t}<<< ${ae(e.target)}`:e.operator==="&>"||e.operator==="&>>"?`${e.operator} ${ae(e.target)}`:`${t}${e.operator} ${ae(e.target)}`}function Ee(e){return e.length===0?"":` ${e.map(Pi).join(" ")}`}function ye(e){return e.map(Ai).join(`
|
|
678
|
-
`)}function
|
|
678
|
+
`)}function Do(e){let t=[];for(let s=0;s<e.clauses.length;s++){let r=e.clauses[s],n=s===0?"if":"elif";t.push(`${n} ${ye(r.condition)}; then
|
|
679
679
|
${ye(r.body)}`)}return e.elseBody&&t.push(`else
|
|
680
680
|
${ye(e.elseBody)}`),`${t.join(`
|
|
681
681
|
`)}
|
|
@@ -693,17 +693,17 @@ ${t}
|
|
|
693
693
|
esac${Ee(e.redirections)}`}function Mo(e){let t=e.patterns.map(ae).join(" | "),s=ye(e.body);return s?`${t})
|
|
694
694
|
${s}
|
|
695
695
|
${e.terminator}`:`${t})
|
|
696
|
-
${e.terminator}`}function Wo(e){return`(${ye(e.body)})${Ee(e.redirections)}`}function zo(e){return`{ ${ye(e.body)}; }${Ee(e.redirections)}`}function Vo(e){return`((${H(e.expression.expression)}))${Ee(e.redirections)}`}function jo(e){return`[[ ${Ue(e.expression)} ]]${Ee(e.redirections)}`}function Bo(e){let t=_i(e.body);return`${e.name}() ${t}${Ee(e.redirections)}`}function H(e){switch(e.type){case"ArithNumber":return String(e.value);case"ArithVariable":return e.hasDollarPrefix?`$${e.name}`:e.name;case"ArithSpecialVar":return`$${e.name}`;case"ArithBinary":return`${H(e.left)} ${e.operator} ${H(e.right)}`;case"ArithUnary":return e.prefix?`${e.operator}${H(e.operand)}`:`${H(e.operand)}${e.operator}`;case"ArithTernary":return`${H(e.condition)} ? ${H(e.consequent)} : ${H(e.alternate)}`;case"ArithAssignment":return`${e.subscript?`${e.variable}[${H(e.subscript)}]`:e.stringKey!==void 0?`${e.variable}[${e.stringKey}]`:e.variable} ${e.operator} ${H(e.value)}`;case"ArithDynamicAssignment":return`${e.subscript?`${H(e.target)}[${H(e.subscript)}]`:H(e.target)} ${e.operator} ${H(e.value)}`;case"ArithDynamicElement":return`${H(e.nameExpr)}[${H(e.subscript)}]`;case"ArithGroup":return`(${H(e.expression)})`;case"ArithNested":return`$((${H(e.expression)}))`;case"ArithCommandSubst":return`$(${e.command})`;case"ArithBracedExpansion":return`\${${e.content}}`;case"ArithArrayElement":return e.stringKey!==void 0?`${e.array}[${e.stringKey}]`:e.index?`${e.array}[${H(e.index)}]`:e.array;case"ArithDynamicBase":return`\${${e.baseExpr}}#${e.value}`;case"ArithDynamicNumber":return`\${${e.prefix}}${e.suffix}`;case"ArithConcat":return e.parts.map(H).join("");case"ArithDoubleSubscript":return`${e.array}[${H(e.index)}]`;case"ArithNumberSubscript":return`${e.number}[${e.errorToken}]`;case"ArithSyntaxError":return e.errorToken;case"ArithSingleQuote":return`'${e.content}'`;default:{let t=e;throw new Error(`Unsupported arithmetic expression type: ${t.type}`)}}}function Ue(e){switch(e.type){case"CondBinary":return`${ae(e.left)} ${e.operator} ${ae(e.right)}`;case"CondUnary":return`${e.operator} ${ae(e.operand)}`;case"CondNot":return`! ${Ue(e.operand)}`;case"CondAnd":return`${Ue(e.left)} && ${Ue(e.right)}`;case"CondOr":return`${Ue(e.left)} || ${Ue(e.right)}`;case"CondGroup":return`( ${Ue(e.expression)} )`;case"CondWord":return ae(e.word);default:{let t=e;throw new Error(`Unsupported conditional expression type: ${t.type}`)}}}var os=class{fs;commands=new Map;useDefaultLayout=!1;limits;secureFetch;sleepFn;traceFn;logger;defenseInDepthConfig;coverageWriter;jsBootstrapCode;executorInvokeTool;executorSetup;executorApproval;executorSDK;executorInitPromise;transformPlugins=[];state;constructor(t={}){let s=t.fs??new ft(t.files);this.fs=s,this.useDefaultLayout=!t.cwd&&!t.files;let r=t.cwd||(this.useDefaultLayout?"/home/user":"/"),n=new Map([["HOME",this.useDefaultLayout?"/home/user":"/"],["PATH","/usr/bin:/bin"],["IFS",`
|
|
696
|
+
${e.terminator}`}function Wo(e){return`(${ye(e.body)})${Ee(e.redirections)}`}function zo(e){return`{ ${ye(e.body)}; }${Ee(e.redirections)}`}function Vo(e){return`((${H(e.expression.expression)}))${Ee(e.redirections)}`}function jo(e){return`[[ ${Ue(e.expression)} ]]${Ee(e.redirections)}`}function Bo(e){let t=_i(e.body);return`${e.name}() ${t}${Ee(e.redirections)}`}function H(e){switch(e.type){case"ArithNumber":return String(e.value);case"ArithVariable":return e.hasDollarPrefix?`$${e.name}`:e.name;case"ArithSpecialVar":return`$${e.name}`;case"ArithBinary":return`${H(e.left)} ${e.operator} ${H(e.right)}`;case"ArithUnary":return e.prefix?`${e.operator}${H(e.operand)}`:`${H(e.operand)}${e.operator}`;case"ArithTernary":return`${H(e.condition)} ? ${H(e.consequent)} : ${H(e.alternate)}`;case"ArithAssignment":return`${e.subscript?`${e.variable}[${H(e.subscript)}]`:e.stringKey!==void 0?`${e.variable}[${e.stringKey}]`:e.variable} ${e.operator} ${H(e.value)}`;case"ArithDynamicAssignment":return`${e.subscript?`${H(e.target)}[${H(e.subscript)}]`:H(e.target)} ${e.operator} ${H(e.value)}`;case"ArithDynamicElement":return`${H(e.nameExpr)}[${H(e.subscript)}]`;case"ArithGroup":return`(${H(e.expression)})`;case"ArithNested":return`$((${H(e.expression)}))`;case"ArithCommandSubst":return`$(${e.command})`;case"ArithBracedExpansion":return`\${${e.content}}`;case"ArithArrayElement":return e.stringKey!==void 0?`${e.array}[${e.stringKey}]`:e.index?`${e.array}[${H(e.index)}]`:e.array;case"ArithDynamicBase":return`\${${e.baseExpr}}#${e.value}`;case"ArithDynamicNumber":return`\${${e.prefix}}${e.suffix}`;case"ArithConcat":return e.parts.map(H).join("");case"ArithDoubleSubscript":return`${e.array}[${H(e.index)}]`;case"ArithNumberSubscript":return`${e.number}[${e.errorToken}]`;case"ArithSyntaxError":return e.errorToken;case"ArithSingleQuote":return`'${e.content}'`;default:{let t=e;throw new Error(`Unsupported arithmetic expression type: ${t.type}`)}}}function Ue(e){switch(e.type){case"CondBinary":return`${ae(e.left)} ${e.operator} ${ae(e.right)}`;case"CondUnary":return`${e.operator} ${ae(e.operand)}`;case"CondNot":return`! ${Ue(e.operand)}`;case"CondAnd":return`${Ue(e.left)} && ${Ue(e.right)}`;case"CondOr":return`${Ue(e.left)} || ${Ue(e.right)}`;case"CondGroup":return`( ${Ue(e.expression)} )`;case"CondWord":return ae(e.word);default:{let t=e;throw new Error(`Unsupported conditional expression type: ${t.type}`)}}}var os=class{fs;commands=new Map;useDefaultLayout=!1;limits;secureFetch;sleepFn;traceFn;logger;defenseInDepthConfig;coverageWriter;jsBootstrapCode;executorInvokeTool;executorSetup;executorApproval;executorSDK;executorInitPromise;executorExecFn;transformPlugins=[];state;constructor(t={}){let s=t.fs??new ft(t.files);this.fs=s,this.useDefaultLayout=!t.cwd&&!t.files;let r=t.cwd||(this.useDefaultLayout?"/home/user":"/"),n=new Map([["HOME",this.useDefaultLayout?"/home/user":"/"],["PATH","/usr/bin:/bin"],["IFS",`
|
|
697
697
|
`],["OSTYPE","linux-gnu"],["MACHTYPE","x86_64-pc-linux-gnu"],["HOSTTYPE","x86_64"],["HOSTNAME","localhost"],["PWD",r],["OLDPWD",r],["OPTIND","1"],...Object.entries(t.env??{})]);if(this.limits=yi({...t.executionLimits,...t.maxCallDepth!==void 0&&{maxCallDepth:t.maxCallDepth},...t.maxCommandCount!==void 0&&{maxCommandCount:t.maxCommandCount},...t.maxLoopIterations!==void 0&&{maxLoopIterations:t.maxLoopIterations}}),t.fetch?this.secureFetch=t.fetch:t.network&&(this.secureFetch=vr(t.network)),this.sleepFn=t.sleep,this.traceFn=t.trace,this.logger=t.logger,this.defenseInDepthConfig=t.defenseInDepth??!0,this.coverageWriter=t.coverage,this.state={env:n,cwd:r,previousDir:"/home/user",functions:new Map,localScopes:[],callDepth:0,sourceDepth:0,commandCount:0,lastExitCode:0,lastArg:"",startTime:Date.now(),lastBackgroundPid:0,virtualPid:t.processInfo?.pid??1,virtualPpid:t.processInfo?.ppid??0,virtualUid:t.processInfo?.uid??1e3,virtualGid:t.processInfo?.gid??1e3,bashPid:t.processInfo?.pid??1,nextVirtualPid:(t.processInfo?.pid??1)+1,currentLine:1,options:{errexit:!1,pipefail:!1,nounset:!1,xtrace:!1,verbose:!1,posix:!1,allexport:!1,noclobber:!1,noglob:!1,noexec:!1,vi:!1,emacs:!1},shoptOptions:{extglob:!1,dotglob:!1,nullglob:!1,failglob:!1,globstar:!1,globskipdots:!0,nocaseglob:!1,nocasematch:!1,expand_aliases:!1,lastpipe:!1,xpg_echo:!1},inCondition:!1,loopDepth:0,exportedVars:new Set(["HOME","PATH","PWD","OLDPWD",...Object.keys(t.env||{})]),readonlyVars:new Set(["SHELLOPTS","BASHOPTS"]),hashTable:new Map},this.state.env.set("SHELLOPTS",$s(this.state.options)),this.state.env.set("BASHOPTS",Es(this.state.shoptOptions)),Xr(s,this.useDefaultLayout,{pid:this.state.virtualPid,ppid:this.state.virtualPpid,uid:this.state.virtualUid,gid:this.state.virtualGid}),r!=="/"&&s instanceof ft)try{s.mkdirSync(r,{recursive:!0})}catch{}for(let i of Hr(t.commands))this.registerCommand(i);if(t.fetch||t.network)for(let i of Ur())this.registerCommand(i);if(t.python)for(let i of Zr())this.registerCommand(i);if(t.javascript||t.executor){for(let a of qr())this.registerCommand(a);let i=typeof t.javascript=="object"?t.javascript:Object.create(null);i.bootstrap&&(this.jsBootstrapCode=i.bootstrap)}if(t.executor?.tools){let i=t.executor.tools;this.executorInvokeTool=async(a,o)=>{if(!Object.hasOwn(i,a))throw new Error(`Unknown tool: ${a}`);let l=i[a],c;try{c=o?JSON.parse(o):void 0}catch{c=void 0}let u=await l.execute(c);return u!==void 0?JSON.stringify(u):""}}if(t.executor?.setup&&(this.executorSetup=t.executor.setup),t.executor?.onToolApproval&&(this.executorApproval=t.executor.onToolApproval),t.customCommands)for(let i of t.customCommands)Gr(i)?this.registerCommand(Kr(i)):this.registerCommand({...i,trusted:i.trusted??!0})}registerCommand(t){this.commands.set(t.name,t);let s=this.fs;if(typeof s.writeFileSync=="function"){let r=`#!/bin/bash
|
|
698
698
|
# Built-in command: ${t.name}
|
|
699
|
-
`;try{s.writeFileSync(`/bin/${t.name}`,r)}catch{}try{s.writeFileSync(`/usr/bin/${t.name}`,r)}catch{}}}logResult(t){return this.logger&&(t.stdout&&this.logger.debug("stdout",{output:t.stdout}),t.stderr&&this.logger.info("stderr",{output:t.stderr}),this.logger.info("exit",{exitCode:t.exitCode})),t.stdout=Oi(t.stdout),t.stderr=Oi(t.stderr),t}async ensureExecutorReady(){if(!(!this.executorSetup||this.executorSDK)){if(this.executorInitPromise){await this.executorInitPromise;return}this.executorInitPromise=(async()=>{let t="./executor-init.js",{initExecutorSDK:s}=await import(t),r=this.executorSetup;if(!r)return;let{sdk:n,
|
|
700
|
-
`,exitCode:1,env:pe(this.state.env,s?.env)};if(!t.trim())return{stdout:"",stderr:"",exitCode:0,env:pe(this.state.env,s?.env)};this.logger?.info("exec",{command:t});let r=s?.cwd??this.state.cwd,n,i=r;if(s?.cwd)if(s.env&&"PWD"in s.env)n=s.env.PWD;else if(s?.env&&!("PWD"in s.env))try{n=await this.fs.realpath(r),i=n}catch{n=r}else n=r;let a=s?.replaceEnv?new Map:new Map(this.state.env);if(s?.env)for(let[f,d]of Object.entries(s.env))a.set(f,d);n!==void 0&&a.set("PWD",n);let o={...this.state,env:a,cwd:i,functions:new Map(this.state.functions),localScopes:[...this.state.localScopes],options:{...this.state.options},hashTable:this.state.hashTable,groupStdin:s?.stdin,signal:s?.signal,extraArgs:s?.args},l=t;s?.rawScript||(l=Ni(t));let c=this.defenseInDepthConfig?ge.getInstance(this.defenseInDepthConfig):null,u=c?.activate();try{let f=async()=>{let d=ve(l,{maxHeredocSize:this.limits.maxHeredocSize}),h;if(this.transformPlugins.length>0){let v=Object.create(null);for(let A of this.transformPlugins){let g=A.transform({ast:d,metadata:v});d=g.ast,g.metadata&&(v=ls(v,g.metadata))}h=v}let p={fs:this.fs,commands:this.commands,limits:this.limits,exec:this.exec.bind(this),fetch:this.secureFetch,sleep:this.sleepFn,trace:this.traceFn,coverage:this.coverageWriter,requireDefenseContext:c?.isEnabled()===!0,jsBootstrapCode:this.jsBootstrapCode,executorInvokeTool:this.executorInvokeTool},b=await new wt(p,o).executeScript(d);return h&&(b.metadata=h),this.logResult(b)};return u?await u.run(f):await f()}catch(f){if(f instanceof j)return this.logResult({stdout:f.stdout,stderr:f.stderr,exitCode:f.exitCode,env:pe(this.state.env,s?.env)});if(f instanceof we)return this.logResult({stdout:f.stdout,stderr:f.stderr,exitCode:f.exitCode,env:pe(this.state.env,s?.env)});if(f instanceof Ve)return this.logResult({stdout:f.stdout,stderr:f.stderr,exitCode:1,env:pe(this.state.env,s?.env)});if(f instanceof At)return this.logResult({stdout:f.stdout,stderr:f.stderr,exitCode:124,env:pe(this.state.env,s?.env)});if(f instanceof Y)return this.logResult({stdout:f.stdout,stderr:he(f.stderr),exitCode:Y.EXIT_CODE,env:pe(this.state.env,s?.env)});if(f instanceof Ge)return this.logResult({stdout:"",stderr:`bash: security violation: ${he(f.message)}
|
|
699
|
+
`;try{s.writeFileSync(`/bin/${t.name}`,r)}catch{}try{s.writeFileSync(`/usr/bin/${t.name}`,r)}catch{}}}logResult(t){return this.logger&&(t.stdout&&this.logger.debug("stdout",{output:t.stdout}),t.stderr&&this.logger.info("stderr",{output:t.stderr}),this.logger.info("exit",{exitCode:t.exitCode})),t.stdout=Oi(t.stdout),t.stderr=Oi(t.stderr),t}async ensureExecutorReady(){if(!(!this.executorSetup||this.executorSDK)){if(this.executorInitPromise){await this.executorInitPromise;return}this.executorInitPromise=(async()=>{let t="./executor-init.js",{initExecutorSDK:s}=await import(t),r=this.executorSetup;if(!r)return;let{sdk:n,executeViaSdk:i}=await s(r,this.executorApproval,this.fs,()=>this.state.cwd,()=>this.state.env,()=>this.limits);this.executorSDK=n,this.executorExecFn=i})(),await this.executorInitPromise}}async exec(t,s){if(await this.ensureExecutorReady(),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.
|
|
700
|
+
`,exitCode:1,env:pe(this.state.env,s?.env)};if(!t.trim())return{stdout:"",stderr:"",exitCode:0,env:pe(this.state.env,s?.env)};this.logger?.info("exec",{command:t});let r=s?.cwd??this.state.cwd,n,i=r;if(s?.cwd)if(s.env&&"PWD"in s.env)n=s.env.PWD;else if(s?.env&&!("PWD"in s.env))try{n=await this.fs.realpath(r),i=n}catch{n=r}else n=r;let a=s?.replaceEnv?new Map:new Map(this.state.env);if(s?.env)for(let[f,d]of Object.entries(s.env))a.set(f,d);n!==void 0&&a.set("PWD",n);let o={...this.state,env:a,cwd:i,functions:new Map(this.state.functions),localScopes:[...this.state.localScopes],options:{...this.state.options},hashTable:this.state.hashTable,groupStdin:s?.stdin,signal:s?.signal,extraArgs:s?.args},l=t;s?.rawScript||(l=Ni(t));let c=this.defenseInDepthConfig?ge.getInstance(this.defenseInDepthConfig):null,u=c?.activate();try{let f=async()=>{let d=ve(l,{maxHeredocSize:this.limits.maxHeredocSize}),h;if(this.transformPlugins.length>0){let v=Object.create(null);for(let A of this.transformPlugins){let g=A.transform({ast:d,metadata:v});d=g.ast,g.metadata&&(v=ls(v,g.metadata))}h=v}let p={fs:this.fs,commands:this.commands,limits:this.limits,exec:this.exec.bind(this),fetch:this.secureFetch,sleep:this.sleepFn,trace:this.traceFn,coverage:this.coverageWriter,requireDefenseContext:c?.isEnabled()===!0,jsBootstrapCode:this.jsBootstrapCode,executorInvokeTool:this.executorInvokeTool,executorExecFn:this.executorExecFn},b=await new wt(p,o).executeScript(d);return h&&(b.metadata=h),this.logResult(b)};return u?await u.run(f):await f()}catch(f){if(f instanceof j)return this.logResult({stdout:f.stdout,stderr:f.stderr,exitCode:f.exitCode,env:pe(this.state.env,s?.env)});if(f instanceof we)return this.logResult({stdout:f.stdout,stderr:f.stderr,exitCode:f.exitCode,env:pe(this.state.env,s?.env)});if(f instanceof Ve)return this.logResult({stdout:f.stdout,stderr:f.stderr,exitCode:1,env:pe(this.state.env,s?.env)});if(f instanceof At)return this.logResult({stdout:f.stdout,stderr:f.stderr,exitCode:124,env:pe(this.state.env,s?.env)});if(f instanceof Y)return this.logResult({stdout:f.stdout,stderr:he(f.stderr),exitCode:Y.EXIT_CODE,env:pe(this.state.env,s?.env)});if(f instanceof Ge)return this.logResult({stdout:"",stderr:`bash: security violation: ${he(f.message)}
|
|
701
701
|
`,exitCode:1,env:pe(this.state.env,s?.env)});if(f.name==="ParseException")return this.logResult({stdout:"",stderr:`bash: syntax error: ${he(f.message)}
|
|
702
|
-
`,exitCode:2,env:pe(this.state.env,s?.env)});if(f instanceof
|
|
702
|
+
`,exitCode:2,env:pe(this.state.env,s?.env)});if(f instanceof xr)return this.logResult({stdout:"",stderr:`bash: ${he(f.message)}
|
|
703
703
|
`,exitCode:2,env:pe(this.state.env,s?.env)});if(f instanceof RangeError)return this.logResult({stdout:"",stderr:`bash: ${he(f.message)}
|
|
704
704
|
`,exitCode:1,env:pe(this.state.env,s?.env)});throw f}finally{u?.deactivate()}}async readFile(t){return this.fs.readFile(this.fs.resolvePath(this.state.cwd,t))}async writeFile(t,s){return this.fs.writeFile(this.fs.resolvePath(this.state.cwd,t),s)}getCwd(){return this.state.cwd}getEnv(){return Ie(this.state.env)}registerTransformPlugin(t){this.transformPlugins.push(t)}transform(t){let s=Ni(t),r=ve(s,{maxHeredocSize:this.limits.maxHeredocSize}),n=Object.create(null);for(let i of this.transformPlugins){let a=i.transform({ast:r,metadata:n});r=a.ast,a.metadata&&(n=ls(n,a.metadata))}return{script:Si(r),ast:r,metadata:n}}};function Ni(e){let t=e.split(`
|
|
705
705
|
`),s=[],r=[];for(let n=0;n<t.length;n++){let i=t[n];if(r.length>0){let l=r[r.length-1];if((l.stripTabs?i.replace(/^\t+/,""):i)===l.delimiter){s.push(i.trimStart()),r.pop();continue}s.push(i);continue}let a=i.trimStart();s.push(a);let o=/<<(-?)\s*(['"]?)([\w-]+)\2/g;for(let l of a.matchAll(o)){let c=l[1]==="-",u=l[3];r.push({delimiter:u,stripTabs:c})}}return s.join(`
|
|
706
|
-
`)}var Ho=new TextDecoder("utf-8",{fatal:!0});function Oi(e){if(!e)return e;let t=!1;for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);if(n>255)return e;n>127&&(t=!0)}if(!t)return e;let s=new Uint8Array(e.length);for(let r=0;r<e.length;r++)s[r]=e.charCodeAt(r);try{return Ho.decode(s)}catch{return e}}import*as U from"node:fs";import*as ne from"node:path";var Uo=["ELOOP","EFBIG","EPERM"],Zo="/home/user/project",ot=class{root;canonicalRoot;mountPoint;readOnly;maxFileReadSize;allowSymlinks;memory=new Map;deleted=new Set;constructor(t){this.root=ne.resolve(t.root);let s=t.mountPoint??Zo;if(this.mountPoint=s==="/"?"/":s.replace(/\/+$/,""),!this.mountPoint.startsWith("/"))throw new Error(`Mount point must be an absolute path: ${s}`);this.readOnly=t.readOnly??!1,this.maxFileReadSize=t.maxFileReadSize??10485760,this.allowSymlinks=t.allowSymlinks??!1,kr(this.root,"OverlayFs"),this.canonicalRoot=U.realpathSync(this.root),this.createMountPointDirs()}assertWritable(t){if(this.readOnly)throw new Error(`EROFS: read-only file system, ${t}`)}createMountPointDirs(){let t=this.mountPoint.split("/").filter(Boolean),s="";for(let r of t)s+=`/${r}`,this.memory.has(s)||this.memory.set(s,{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(t,s){let n=M(t).split("/").filter(Boolean),i="";for(let a of n)i+=`/${a}`,this.memory.has(i)||this.memory.set(i,{type:"directory",mode:493,mtime:new Date})}writeFileSync(t,s){let r=M(t),n=this.getDirname(r);n!=="/"&&this.mkdirSync(n);let i=s instanceof Uint8Array?s:new TextEncoder().encode(s);this.memory.set(r,{type:"file",content:i,mode:420,mtime:new Date})}getDirname(t){let s=t.lastIndexOf("/");return s===0?"/":t.slice(0,s)}getRelativeToMount(t){return this.mountPoint==="/"?t:t===this.mountPoint?"/":t.startsWith(`${this.mountPoint}/`)?t.slice(this.mountPoint.length):null}toRealPath(t){let s=M(t),r=this.getRelativeToMount(s);if(r===null)return null;let n=ne.join(this.root,r),i=ne.resolve(n);return us(i,this.root)?i:null}resolveRealPath_(t){return t?this.allowSymlinks?_r(t,this.canonicalRoot):Cr(t,this.root,this.canonicalRoot):null}resolveRealPathParent_(t){if(!t)return null;let s=ne.dirname(t),r=this.resolveRealPath_(s);return r===null?null:ne.join(r,ne.basename(t))}sanitizeError(t,s,r){Nr(t,s,r,Uo)}ensureParentDirs(t){let s=Ke(t);s!=="/"&&(this.memory.has(s)||(this.ensureParentDirs(s),this.memory.set(s,{type:"directory",mode:493,mtime:new Date})),this.deleted.delete(s))}async existsInOverlay(t){let s=M(t);if(this.deleted.has(s))return!1;if(this.memory.has(s))return!0;let r=this.resolveRealPathParent_(this.toRealPath(s));if(!r)return!1;try{return await U.promises.lstat(r),!0}catch{return!1}}async readFile(t,s){let r=await this.readFileBuffer(t),n=Fe(s);return Tt(r,n)}async readFileBuffer(t,s=new Set){W(t,"open");let r=M(t);if(s.has(r))throw new Error(`ELOOP: too many levels of symbolic links, open '${t}'`);if(s.add(r),this.deleted.has(r))throw new Error(`ENOENT: no such file or directory, open '${t}'`);let n=this.memory.get(r);if(n){if(n.type==="symlink"){let a=this.resolveSymlink(r,n.target);return this.readFileBuffer(a,s)}if(n.type!=="file")throw new Error(`EISDIR: illegal operation on a directory, read '${t}'`);return n.content}let i=this.resolveRealPath_(this.toRealPath(r));if(!i)throw new Error(`ENOENT: no such file or directory, open '${t}'`);try{let a=await U.promises.lstat(i);if(a.isSymbolicLink()){if(!this.allowSymlinks)throw new Error(`ENOENT: no such file or directory, open '${t}'`);let c=await U.promises.readlink(i),u=this.realTargetToVirtual(r,c),f=this.resolveSymlink(r,u);return this.readFileBuffer(f,s)}if(a.isDirectory())throw new Error(`EISDIR: illegal operation on a directory, read '${t}'`);if(this.maxFileReadSize>0&&a.size>this.maxFileReadSize)throw new Error(`EFBIG: file too large, read '${t}' (${a.size} bytes, max ${this.maxFileReadSize})`);let o=this.allowSymlinks?U.constants.O_RDONLY:U.constants.O_RDONLY|U.constants.O_NOFOLLOW,l=await U.promises.open(i,o);try{let c=await l.readFile();return new Uint8Array(c)}finally{await l.close()}}catch(a){let o=a.code;if(o==="ENOENT")throw new Error(`ENOENT: no such file or directory, open '${t}'`);if(o==="ELOOP")throw new Error(`ENOENT: no such file or directory, open '${t}'`);this.sanitizeError(a,t,"open")}}async writeFile(t,s,r){W(t,"write"),this.assertWritable(`write '${t}'`);let n=M(t);this.ensureParentDirs(n);let i=Fe(r),a=Qe(s,i);this.memory.set(n,{type:"file",content:a,mode:420,mtime:new Date}),this.deleted.delete(n)}async appendFile(t,s,r){W(t,"append"),this.assertWritable(`append '${t}'`);let n=M(t),i=Fe(r),a=Qe(s,i),o;try{o=await this.readFileBuffer(n)}catch{o=new Uint8Array(0)}let l=new Uint8Array(o.length+a.length);l.set(o),l.set(a,o.length),this.ensureParentDirs(n),this.memory.set(n,{type:"file",content:l,mode:420,mtime:new Date}),this.deleted.delete(n)}async exists(t){return t.includes("\0")?!1:this.existsInOverlay(t)}async stat(t,s=new Set){W(t,"stat");let r=M(t);if(s.has(r))throw new Error(`ELOOP: too many levels of symbolic links, stat '${t}'`);if(s.add(r),this.deleted.has(r))throw new Error(`ENOENT: no such file or directory, stat '${t}'`);let n=this.memory.get(r);if(n){if(n.type==="symlink"){let o=this.resolveSymlink(r,n.target);return this.stat(o,s)}let a=0;return n.type==="file"&&(a=n.content.length),{isFile:n.type==="file",isDirectory:n.type==="directory",isSymbolicLink:!1,mode:n.mode,size:a,mtime:n.mtime}}let i=this.resolveRealPath_(this.toRealPath(r));if(!i)throw new Error(`ENOENT: no such file or directory, stat '${t}'`);try{let a=await U.promises.lstat(i);if(a.isSymbolicLink()){if(!this.allowSymlinks)throw new Error(`ENOENT: no such file or directory, stat '${t}'`);let o=await U.promises.readlink(i),l=this.realTargetToVirtual(r,o),c=this.resolveSymlink(r,l);return this.stat(c,s)}return{isFile:a.isFile(),isDirectory:a.isDirectory(),isSymbolicLink:!1,mode:a.mode,size:a.size,mtime:a.mtime}}catch(a){if(a.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, stat '${t}'`);this.sanitizeError(a,t,"stat")}}async lstat(t){W(t,"lstat");let s=M(t);if(this.deleted.has(s))throw new Error(`ENOENT: no such file or directory, lstat '${t}'`);let r=this.memory.get(s);if(r){if(r.type==="symlink")return{isFile:!1,isDirectory:!1,isSymbolicLink:!0,mode:r.mode,size:r.target.length,mtime:r.mtime};let i=0;return r.type==="file"&&(i=r.content.length),{isFile:r.type==="file",isDirectory:r.type==="directory",isSymbolicLink:!1,mode:r.mode,size:i,mtime:r.mtime}}let n=this.resolveRealPathParent_(this.toRealPath(s));if(!n)throw new Error(`ENOENT: no such file or directory, lstat '${t}'`);try{let i=await U.promises.lstat(n);return{isFile:i.isFile(),isDirectory:i.isDirectory(),isSymbolicLink:i.isSymbolicLink(),mode:i.mode,size:i.size,mtime:i.mtime}}catch(i){if(i.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, lstat '${t}'`);this.sanitizeError(i,t,"lstat")}}resolveSymlink(t,s){return Xe(t,s)}realTargetToVirtual(t,s){let r=Pr(s,this.canonicalRoot);if(r.withinRoot){if(!ne.isAbsolute(s))return s;let n=r.relativePath;return this.mountPoint==="/"?n:`${this.mountPoint}${n}`}return r.safeName}async mkdir(t,s){W(t,"mkdir"),this.assertWritable(`mkdir '${t}'`);let r=M(t);if(await this.existsInOverlay(r)){if(!s?.recursive)throw new Error(`EEXIST: file already exists, mkdir '${t}'`);return}let i=Ke(r);if(i!=="/"&&!await this.existsInOverlay(i))if(s?.recursive)await this.mkdir(i,{recursive:!0});else throw new Error(`ENOENT: no such file or directory, mkdir '${t}'`);this.memory.set(r,{type:"directory",mode:493,mtime:new Date}),this.deleted.delete(r)}async readdirCore(t,s){if(this.deleted.has(s))throw new Error(`ENOENT: no such file or directory, scandir '${t}'`);let r=new Map,n=new Set,i=s==="/"?"/":`${s}/`;for(let o of this.deleted)if(o.startsWith(i)){let l=o.slice(i.length),c=l.split("/")[0];c&&!l.includes("/",c.length)&&n.add(c)}for(let[o,l]of this.memory)if(o!==s&&o.startsWith(i)){let c=o.slice(i.length),u=c.split("/")[0];u&&!n.has(u)&&!c.includes("/",1)&&r.set(u,{name:u,isFile:l.type==="file",isDirectory:l.type==="directory",isSymbolicLink:l.type==="symlink"})}let a=this.resolveRealPath_(this.toRealPath(s));if(a)try{if(!this.allowSymlinks&&(await U.promises.lstat(a)).isSymbolicLink()){if(!this.memory.has(s))throw new Error(`ENOENT: no such file or directory, scandir '${t}'`);return r}let o=await U.promises.readdir(a,{withFileTypes:!0});for(let l of o)!n.has(l.name)&&!r.has(l.name)&&r.set(l.name,{name:l.name,isFile:l.isFile(),isDirectory:l.isDirectory(),isSymbolicLink:l.isSymbolicLink()})}catch(o){if(o.code==="ENOENT"){if(!this.memory.has(s))throw new Error(`ENOENT: no such file or directory, scandir '${t}'`)}else o.code!=="ENOTDIR"&&this.sanitizeError(o,t,"scandir")}return r}async resolveForReaddir(t,s=!1){let r=M(t),n=new Set,i=s,a=this.memory.get(r);for(;a&&a.type==="symlink";){if(n.has(r))throw new Error(`ELOOP: too many levels of symbolic links, scandir '${t}'`);n.add(r),i=!0,r=this.resolveSymlink(r,a.target),a=this.memory.get(r)}if(a)return{normalized:r,outsideOverlay:!1};if(this.getRelativeToMount(r)===null)return{normalized:r,outsideOverlay:!0};let l=this.resolveRealPath_(this.toRealPath(r));if(!l)return{normalized:r,outsideOverlay:!0};try{if((await U.promises.lstat(l)).isSymbolicLink()){if(!this.allowSymlinks)return{normalized:r,outsideOverlay:!0};let u=await U.promises.readlink(l),f=this.realTargetToVirtual(r,u),d=this.resolveSymlink(r,f);return this.resolveForReaddir(d,!0)}return{normalized:r,outsideOverlay:!1}}catch{return i?{normalized:r,outsideOverlay:!0}:{normalized:r,outsideOverlay:!1}}}async readdir(t){W(t,"scandir");let{normalized:s,outsideOverlay:r}=await this.resolveForReaddir(t);if(r)return[];let n=await this.readdirCore(t,s);return Array.from(n.keys()).sort((i,a)=>i<a?-1:i>a?1:0)}async readdirWithFileTypes(t){W(t,"scandir");let{normalized:s,outsideOverlay:r}=await this.resolveForReaddir(t);if(r)return[];let n=await this.readdirCore(t,s);return Array.from(n.values()).sort((i,a)=>i.name<a.name?-1:i.name>a.name?1:0)}async rm(t,s){W(t,"rm"),this.assertWritable(`rm '${t}'`);let r=M(t);if(!await this.existsInOverlay(r)){if(s?.force)return;throw new Error(`ENOENT: no such file or directory, rm '${t}'`)}try{if((await this.stat(r)).isDirectory){let a=await this.readdir(r);if(a.length>0){if(!s?.recursive)throw new Error(`ENOTEMPTY: directory not empty, rm '${t}'`);for(let o of a){let l=r==="/"?`/${o}`:`${r}/${o}`;await this.rm(l,s)}}}}catch(i){if(i instanceof Error&&(i.message.includes("ENOTEMPTY")||i.message.includes("EISDIR")))throw i}this.memory.delete(r),this.existsOnRealFs(r)&&this.deleted.add(r)}existsOnRealFs(t){let s=this.toRealPath(t),r=this.resolveRealPathParent_(s);if(!r)return!1;try{return U.lstatSync(r),!0}catch{return!1}}async cp(t,s,r){W(t,"cp"),W(s,"cp"),this.assertWritable(`cp '${s}'`);let n=M(t),i=M(s);if(!await this.existsInOverlay(n))throw new Error(`ENOENT: no such file or directory, cp '${t}'`);let o=await this.stat(n);if(o.isFile){let l=await this.readFileBuffer(n);await this.writeFile(i,l)}else if(o.isDirectory){if(!r?.recursive)throw new Error(`EISDIR: is a directory, cp '${t}'`);await this.mkdir(i,{recursive:!0});let l=await this.readdir(n);for(let c of l){let u=n==="/"?`/${c}`:`${n}/${c}`,f=i==="/"?`/${c}`:`${i}/${c}`;await this.cp(u,f,r)}}}async mv(t,s){this.assertWritable(`mv '${s}'`),await this.cp(t,s,{recursive:!0}),await this.rm(t,{recursive:!0})}resolvePath(t,s){return Ct(t,s)}getAllPaths(){let t=new Set(this.memory.keys());for(let s of this.deleted)t.delete(s);return this.scanRealFs("/",t),Array.from(t)}scanRealFs(t,s){if(this.deleted.has(t))return;let r=this.resolveRealPath_(this.toRealPath(t));if(r)try{let n=U.readdirSync(r);for(let i of n){let a=t==="/"?`/${i}`:`${t}/${i}`;if(this.deleted.has(a))continue;s.add(a);let o=ne.join(r,i);U.lstatSync(o).isDirectory()&&this.scanRealFs(a,s)}}catch{}}async chmod(t,s){W(t,"chmod"),this.assertWritable(`chmod '${t}'`);let r=M(t);if(!await this.existsInOverlay(r))throw new Error(`ENOENT: no such file or directory, chmod '${t}'`);let i=this.memory.get(r);if(i){i.mode=s;return}let a=await this.stat(r);if(a.isFile){let o=await this.readFileBuffer(r);this.memory.set(r,{type:"file",content:o,mode:s,mtime:new Date})}else a.isDirectory&&this.memory.set(r,{type:"directory",mode:s,mtime:new Date})}async symlink(t,s){if(!this.allowSymlinks)throw new Error(`EPERM: operation not permitted, symlink '${s}'`);W(s,"symlink"),this.assertWritable(`symlink '${s}'`);let r=M(s);if(await this.existsInOverlay(r))throw new Error(`EEXIST: file already exists, symlink '${s}'`);this.ensureParentDirs(r),this.memory.set(r,{type:"symlink",target:t,mode:511,mtime:new Date}),this.deleted.delete(r)}async link(t,s){W(t,"link"),W(s,"link"),this.assertWritable(`link '${s}'`);let r=M(t),n=M(s);if(!await this.existsInOverlay(r))throw new Error(`ENOENT: no such file or directory, link '${t}'`);let a=await this.stat(r);if(!a.isFile)throw new Error(`EPERM: operation not permitted, link '${t}'`);if(await this.existsInOverlay(n))throw new Error(`EEXIST: file already exists, link '${s}'`);let l=await this.readFileBuffer(r);this.ensureParentDirs(n),this.memory.set(n,{type:"file",content:l,mode:a.mode,mtime:new Date}),this.deleted.delete(n)}async readlink(t){W(t,"readlink");let s=M(t);if(this.deleted.has(s))throw new Error(`ENOENT: no such file or directory, readlink '${t}'`);let r=this.memory.get(s);if(r){if(r.type!=="symlink")throw new Error(`EINVAL: invalid argument, readlink '${t}'`);return r.target}let n=this.resolveRealPathParent_(this.toRealPath(s));if(!n)throw new Error(`ENOENT: no such file or directory, readlink '${t}'`);try{let i=await U.promises.readlink(n);if(!ne.isAbsolute(i)){let a=ne.resolve(ne.dirname(n),i),o;try{o=U.realpathSync(a)}catch{o=a}if(!us(o,this.canonicalRoot))return ne.basename(i)}return this.realTargetToVirtual(s,i)}catch(i){if(i.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, readlink '${t}'`);if(i.code==="EINVAL")throw new Error(`EINVAL: invalid argument, readlink '${t}'`);this.sanitizeError(i,t,"readlink")}}async realpath(t){W(t,"realpath");let s=M(t),r=new Set,n=async o=>{let l=o==="/"?[]:o.slice(1).split("/"),c="";for(let u of l){if(c=`${c}/${u}`,r.has(c))throw new Error(`ELOOP: too many levels of symbolic links, realpath '${t}'`);if(this.deleted.has(c))throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);let f=this.memory.get(c),d=0,h=40;for(;f&&f.type==="symlink"&&d<h;){if(r.add(c),c=this.resolveSymlink(c,f.target),d++,r.has(c))throw new Error(`ELOOP: too many levels of symbolic links, realpath '${t}'`);if(this.deleted.has(c))throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);f=this.memory.get(c)}if(d>=h)throw new Error(`ELOOP: too many levels of symbolic links, realpath '${t}'`);if(!f){let p=this.toRealPath(c),m=this.resolveRealPath_(p);if(m)try{if((await U.promises.lstat(m)).isSymbolicLink()){if(!this.allowSymlinks)throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);let b=await U.promises.readlink(m),v=this.realTargetToVirtual(c,b);return r.add(c),c=this.resolveSymlink(c,v),n(c)}}catch(y){if(y.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);this.sanitizeError(y,t,"realpath")}else if(!this.allowSymlinks){let y=this.resolveRealPathParent_(p);if(y)try{if((await U.promises.lstat(y)).isSymbolicLink())throw new Error(`ENOENT: no such file or directory, realpath '${t}'`)}catch(b){if(b.message?.includes("ENOENT")||b.message?.includes("ELOOP"))throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);this.sanitizeError(b,t,"realpath")}}}}return c||"/"},i=await n(s);if(!await this.existsInOverlay(i))throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);return i}async utimes(t,s,r){W(t,"utimes"),this.assertWritable(`utimes '${t}'`);let n=M(t);if(!await this.existsInOverlay(n))throw new Error(`ENOENT: no such file or directory, utimes '${t}'`);let a=this.memory.get(n);if(a){a.mtime=r;return}let o=await this.stat(n);if(o.isFile){let l=await this.readFileBuffer(n);this.memory.set(n,{type:"file",content:l,mode:o.mode,mtime:r})}else o.isDirectory&&this.memory.set(n,{type:"directory",mode:o.mode,mtime:r})}};function xi(){console.log(`just-bash - A secure bash environment for AI agents
|
|
706
|
+
`)}var Ho=new TextDecoder("utf-8",{fatal:!0});function Oi(e){if(!e)return e;let t=!1;for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);if(n>255)return e;n>127&&(t=!0)}if(!t)return e;let s=new Uint8Array(e.length);for(let r=0;r<e.length;r++)s[r]=e.charCodeAt(r);try{return Ho.decode(s)}catch{return e}}import*as U from"node:fs";import*as ne from"node:path";var Uo=["ELOOP","EFBIG","EPERM"],Zo="/home/user/project",ot=class{root;canonicalRoot;mountPoint;readOnly;maxFileReadSize;allowSymlinks;memory=new Map;deleted=new Set;constructor(t){this.root=ne.resolve(t.root);let s=t.mountPoint??Zo;if(this.mountPoint=s==="/"?"/":s.replace(/\/+$/,""),!this.mountPoint.startsWith("/"))throw new Error(`Mount point must be an absolute path: ${s}`);this.readOnly=t.readOnly??!1,this.maxFileReadSize=t.maxFileReadSize??10485760,this.allowSymlinks=t.allowSymlinks??!1,kr(this.root,"OverlayFs"),this.canonicalRoot=U.realpathSync(this.root),this.createMountPointDirs()}assertWritable(t){if(this.readOnly)throw new Error(`EROFS: read-only file system, ${t}`)}createMountPointDirs(){let t=this.mountPoint.split("/").filter(Boolean),s="";for(let r of t)s+=`/${r}`,this.memory.has(s)||this.memory.set(s,{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(t,s){let n=M(t).split("/").filter(Boolean),i="";for(let a of n)i+=`/${a}`,this.memory.has(i)||this.memory.set(i,{type:"directory",mode:493,mtime:new Date})}writeFileSync(t,s){let r=M(t),n=this.getDirname(r);n!=="/"&&this.mkdirSync(n);let i=s instanceof Uint8Array?s:new TextEncoder().encode(s);this.memory.set(r,{type:"file",content:i,mode:420,mtime:new Date})}getDirname(t){let s=t.lastIndexOf("/");return s===0?"/":t.slice(0,s)}getRelativeToMount(t){return this.mountPoint==="/"?t:t===this.mountPoint?"/":t.startsWith(`${this.mountPoint}/`)?t.slice(this.mountPoint.length):null}toRealPath(t){let s=M(t),r=this.getRelativeToMount(s);if(r===null)return null;let n=ne.join(this.root,r),i=ne.resolve(n);return us(i,this.root)?i:null}resolveRealPath_(t){return t?this.allowSymlinks?_r(t,this.canonicalRoot):Cr(t,this.root,this.canonicalRoot):null}resolveRealPathParent_(t){if(!t)return null;let s=ne.dirname(t),r=this.resolveRealPath_(s);return r===null?null:ne.join(r,ne.basename(t))}sanitizeError(t,s,r){Nr(t,s,r,Uo)}ensureParentDirs(t){let s=Ke(t);s!=="/"&&(this.memory.has(s)||(this.ensureParentDirs(s),this.memory.set(s,{type:"directory",mode:493,mtime:new Date})),this.deleted.delete(s))}async existsInOverlay(t){let s=M(t);if(this.deleted.has(s))return!1;if(this.memory.has(s))return!0;let r=this.resolveRealPathParent_(this.toRealPath(s));if(!r)return!1;try{return await U.promises.lstat(r),!0}catch{return!1}}async readFile(t,s){let r=await this.readFileBuffer(t),n=Fe(s);return Tt(r,n)}async readFileBuffer(t,s=new Set){W(t,"open");let r=M(t);if(s.has(r))throw new Error(`ELOOP: too many levels of symbolic links, open '${t}'`);if(s.add(r),this.deleted.has(r))throw new Error(`ENOENT: no such file or directory, open '${t}'`);let n=this.memory.get(r);if(n){if(n.type==="symlink"){let a=this.resolveSymlink(r,n.target);return this.readFileBuffer(a,s)}if(n.type!=="file")throw new Error(`EISDIR: illegal operation on a directory, read '${t}'`);return n.content}let i=this.resolveRealPath_(this.toRealPath(r));if(!i)throw new Error(`ENOENT: no such file or directory, open '${t}'`);try{let a=await U.promises.lstat(i);if(a.isSymbolicLink()){if(!this.allowSymlinks)throw new Error(`ENOENT: no such file or directory, open '${t}'`);let c=await U.promises.readlink(i),u=this.realTargetToVirtual(r,c),f=this.resolveSymlink(r,u);return this.readFileBuffer(f,s)}if(a.isDirectory())throw new Error(`EISDIR: illegal operation on a directory, read '${t}'`);if(this.maxFileReadSize>0&&a.size>this.maxFileReadSize)throw new Error(`EFBIG: file too large, read '${t}' (${a.size} bytes, max ${this.maxFileReadSize})`);let o=this.allowSymlinks?U.constants.O_RDONLY:U.constants.O_RDONLY|U.constants.O_NOFOLLOW,l=await U.promises.open(i,o);try{let c=await l.readFile();return new Uint8Array(c)}finally{await l.close()}}catch(a){let o=a.code;if(o==="ENOENT")throw new Error(`ENOENT: no such file or directory, open '${t}'`);if(o==="ELOOP")throw new Error(`ENOENT: no such file or directory, open '${t}'`);this.sanitizeError(a,t,"open")}}async writeFile(t,s,r){W(t,"write"),this.assertWritable(`write '${t}'`);let n=M(t);this.ensureParentDirs(n);let i=Fe(r),a=Qe(s,i);this.memory.set(n,{type:"file",content:a,mode:420,mtime:new Date}),this.deleted.delete(n)}async appendFile(t,s,r){W(t,"append"),this.assertWritable(`append '${t}'`);let n=M(t),i=Fe(r),a=Qe(s,i),o;try{o=await this.readFileBuffer(n)}catch{o=new Uint8Array(0)}let l=new Uint8Array(o.length+a.length);l.set(o),l.set(a,o.length),this.ensureParentDirs(n),this.memory.set(n,{type:"file",content:l,mode:420,mtime:new Date}),this.deleted.delete(n)}async exists(t){return t.includes("\0")?!1:this.existsInOverlay(t)}async stat(t,s=new Set){W(t,"stat");let r=M(t);if(s.has(r))throw new Error(`ELOOP: too many levels of symbolic links, stat '${t}'`);if(s.add(r),this.deleted.has(r))throw new Error(`ENOENT: no such file or directory, stat '${t}'`);let n=this.memory.get(r);if(n){if(n.type==="symlink"){let o=this.resolveSymlink(r,n.target);return this.stat(o,s)}let a=0;return n.type==="file"&&(a=n.content.length),{isFile:n.type==="file",isDirectory:n.type==="directory",isSymbolicLink:!1,mode:n.mode,size:a,mtime:n.mtime}}let i=this.resolveRealPath_(this.toRealPath(r));if(!i)throw new Error(`ENOENT: no such file or directory, stat '${t}'`);try{let a=await U.promises.lstat(i);if(a.isSymbolicLink()){if(!this.allowSymlinks)throw new Error(`ENOENT: no such file or directory, stat '${t}'`);let o=await U.promises.readlink(i),l=this.realTargetToVirtual(r,o),c=this.resolveSymlink(r,l);return this.stat(c,s)}return{isFile:a.isFile(),isDirectory:a.isDirectory(),isSymbolicLink:!1,mode:a.mode,size:a.size,mtime:a.mtime}}catch(a){if(a.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, stat '${t}'`);this.sanitizeError(a,t,"stat")}}async lstat(t){W(t,"lstat");let s=M(t);if(this.deleted.has(s))throw new Error(`ENOENT: no such file or directory, lstat '${t}'`);let r=this.memory.get(s);if(r){if(r.type==="symlink")return{isFile:!1,isDirectory:!1,isSymbolicLink:!0,mode:r.mode,size:r.target.length,mtime:r.mtime};let i=0;return r.type==="file"&&(i=r.content.length),{isFile:r.type==="file",isDirectory:r.type==="directory",isSymbolicLink:!1,mode:r.mode,size:i,mtime:r.mtime}}let n=this.resolveRealPathParent_(this.toRealPath(s));if(!n)throw new Error(`ENOENT: no such file or directory, lstat '${t}'`);try{let i=await U.promises.lstat(n);return{isFile:i.isFile(),isDirectory:i.isDirectory(),isSymbolicLink:i.isSymbolicLink(),mode:i.mode,size:i.size,mtime:i.mtime}}catch(i){if(i.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, lstat '${t}'`);this.sanitizeError(i,t,"lstat")}}resolveSymlink(t,s){return Xe(t,s)}realTargetToVirtual(t,s){let r=Pr(s,this.canonicalRoot);if(r.withinRoot){if(!ne.isAbsolute(s))return s;let n=r.relativePath;return this.mountPoint==="/"?n:`${this.mountPoint}${n}`}return r.safeName}async mkdir(t,s){W(t,"mkdir"),this.assertWritable(`mkdir '${t}'`);let r=M(t);if(await this.existsInOverlay(r)){if(!s?.recursive)throw new Error(`EEXIST: file already exists, mkdir '${t}'`);return}let i=Ke(r);if(i!=="/"&&!await this.existsInOverlay(i))if(s?.recursive)await this.mkdir(i,{recursive:!0});else throw new Error(`ENOENT: no such file or directory, mkdir '${t}'`);this.memory.set(r,{type:"directory",mode:493,mtime:new Date}),this.deleted.delete(r)}async readdirCore(t,s){if(this.deleted.has(s))throw new Error(`ENOENT: no such file or directory, scandir '${t}'`);let r=new Map,n=new Set,i=s==="/"?"/":`${s}/`;for(let o of this.deleted)if(o.startsWith(i)){let l=o.slice(i.length),c=l.split("/")[0];c&&!l.includes("/",c.length)&&n.add(c)}for(let[o,l]of this.memory)if(o!==s&&o.startsWith(i)){let c=o.slice(i.length),u=c.split("/")[0];u&&!n.has(u)&&!c.includes("/",1)&&r.set(u,{name:u,isFile:l.type==="file",isDirectory:l.type==="directory",isSymbolicLink:l.type==="symlink"})}let a=this.resolveRealPath_(this.toRealPath(s));if(a)try{if(!this.allowSymlinks&&(await U.promises.lstat(a)).isSymbolicLink()){if(!this.memory.has(s))throw new Error(`ENOENT: no such file or directory, scandir '${t}'`);return r}let o=await U.promises.readdir(a,{withFileTypes:!0});for(let l of o)!n.has(l.name)&&!r.has(l.name)&&r.set(l.name,{name:l.name,isFile:l.isFile(),isDirectory:l.isDirectory(),isSymbolicLink:l.isSymbolicLink()})}catch(o){if(o.code==="ENOENT"){if(!this.memory.has(s))throw new Error(`ENOENT: no such file or directory, scandir '${t}'`)}else o.code!=="ENOTDIR"&&this.sanitizeError(o,t,"scandir")}return r}async resolveForReaddir(t,s=!1){let r=M(t),n=new Set,i=s,a=this.memory.get(r);for(;a&&a.type==="symlink";){if(n.has(r))throw new Error(`ELOOP: too many levels of symbolic links, scandir '${t}'`);n.add(r),i=!0,r=this.resolveSymlink(r,a.target),a=this.memory.get(r)}if(a)return{normalized:r,outsideOverlay:!1};if(this.getRelativeToMount(r)===null)return{normalized:r,outsideOverlay:!0};let l=this.resolveRealPath_(this.toRealPath(r));if(!l)return{normalized:r,outsideOverlay:!0};try{if((await U.promises.lstat(l)).isSymbolicLink()){if(!this.allowSymlinks)return{normalized:r,outsideOverlay:!0};let u=await U.promises.readlink(l),f=this.realTargetToVirtual(r,u),d=this.resolveSymlink(r,f);return this.resolveForReaddir(d,!0)}return{normalized:r,outsideOverlay:!1}}catch{return i?{normalized:r,outsideOverlay:!0}:{normalized:r,outsideOverlay:!1}}}async readdir(t){W(t,"scandir");let{normalized:s,outsideOverlay:r}=await this.resolveForReaddir(t);if(r)return[];let n=await this.readdirCore(t,s);return Array.from(n.keys()).sort((i,a)=>i<a?-1:i>a?1:0)}async readdirWithFileTypes(t){W(t,"scandir");let{normalized:s,outsideOverlay:r}=await this.resolveForReaddir(t);if(r)return[];let n=await this.readdirCore(t,s);return Array.from(n.values()).sort((i,a)=>i.name<a.name?-1:i.name>a.name?1:0)}async rm(t,s){W(t,"rm"),this.assertWritable(`rm '${t}'`);let r=M(t);if(!await this.existsInOverlay(r)){if(s?.force)return;throw new Error(`ENOENT: no such file or directory, rm '${t}'`)}try{if((await this.stat(r)).isDirectory){let a=await this.readdir(r);if(a.length>0){if(!s?.recursive)throw new Error(`ENOTEMPTY: directory not empty, rm '${t}'`);for(let o of a){let l=r==="/"?`/${o}`:`${r}/${o}`;await this.rm(l,s)}}}}catch(i){if(i instanceof Error&&(i.message.includes("ENOTEMPTY")||i.message.includes("EISDIR")))throw i}this.memory.delete(r),this.existsOnRealFs(r)&&this.deleted.add(r)}existsOnRealFs(t){let s=this.toRealPath(t),r=this.resolveRealPathParent_(s);if(!r)return!1;try{return U.lstatSync(r),!0}catch{return!1}}async cp(t,s,r){W(t,"cp"),W(s,"cp"),this.assertWritable(`cp '${s}'`);let n=M(t),i=M(s);if(!await this.existsInOverlay(n))throw new Error(`ENOENT: no such file or directory, cp '${t}'`);let o=await this.stat(n);if(o.isFile){let l=await this.readFileBuffer(n);await this.writeFile(i,l)}else if(o.isDirectory){if(!r?.recursive)throw new Error(`EISDIR: is a directory, cp '${t}'`);await this.mkdir(i,{recursive:!0});let l=await this.readdir(n);for(let c of l){let u=n==="/"?`/${c}`:`${n}/${c}`,f=i==="/"?`/${c}`:`${i}/${c}`;await this.cp(u,f,r)}}}async mv(t,s){this.assertWritable(`mv '${s}'`),await this.cp(t,s,{recursive:!0}),await this.rm(t,{recursive:!0})}resolvePath(t,s){return Ct(t,s)}getAllPaths(){let t=new Set(this.memory.keys());for(let s of this.deleted)t.delete(s);return this.scanRealFs("/",t),Array.from(t)}scanRealFs(t,s){if(this.deleted.has(t))return;let r=this.resolveRealPath_(this.toRealPath(t));if(r)try{let n=U.readdirSync(r);for(let i of n){let a=t==="/"?`/${i}`:`${t}/${i}`;if(this.deleted.has(a))continue;s.add(a);let o=ne.join(r,i);U.lstatSync(o).isDirectory()&&this.scanRealFs(a,s)}}catch{}}async chmod(t,s){W(t,"chmod"),this.assertWritable(`chmod '${t}'`);let r=M(t);if(!await this.existsInOverlay(r))throw new Error(`ENOENT: no such file or directory, chmod '${t}'`);let i=this.memory.get(r);if(i){i.mode=s;return}let a=await this.stat(r);if(a.isFile){let o=await this.readFileBuffer(r);this.memory.set(r,{type:"file",content:o,mode:s,mtime:new Date})}else a.isDirectory&&this.memory.set(r,{type:"directory",mode:s,mtime:new Date})}async symlink(t,s){if(!this.allowSymlinks)throw new Error(`EPERM: operation not permitted, symlink '${s}'`);W(s,"symlink"),this.assertWritable(`symlink '${s}'`);let r=M(s);if(await this.existsInOverlay(r))throw new Error(`EEXIST: file already exists, symlink '${s}'`);this.ensureParentDirs(r),this.memory.set(r,{type:"symlink",target:t,mode:511,mtime:new Date}),this.deleted.delete(r)}async link(t,s){W(t,"link"),W(s,"link"),this.assertWritable(`link '${s}'`);let r=M(t),n=M(s);if(!await this.existsInOverlay(r))throw new Error(`ENOENT: no such file or directory, link '${t}'`);let a=await this.stat(r);if(!a.isFile)throw new Error(`EPERM: operation not permitted, link '${t}'`);if(await this.existsInOverlay(n))throw new Error(`EEXIST: file already exists, link '${s}'`);let l=await this.readFileBuffer(r);this.ensureParentDirs(n),this.memory.set(n,{type:"file",content:l,mode:a.mode,mtime:new Date}),this.deleted.delete(n)}async readlink(t){W(t,"readlink");let s=M(t);if(this.deleted.has(s))throw new Error(`ENOENT: no such file or directory, readlink '${t}'`);let r=this.memory.get(s);if(r){if(r.type!=="symlink")throw new Error(`EINVAL: invalid argument, readlink '${t}'`);return r.target}let n=this.resolveRealPathParent_(this.toRealPath(s));if(!n)throw new Error(`ENOENT: no such file or directory, readlink '${t}'`);try{let i=await U.promises.readlink(n);if(!ne.isAbsolute(i)){let a=ne.resolve(ne.dirname(n),i),o;try{o=U.realpathSync(a)}catch{o=a}if(!us(o,this.canonicalRoot))return ne.basename(i)}return this.realTargetToVirtual(s,i)}catch(i){if(i.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, readlink '${t}'`);if(i.code==="EINVAL")throw new Error(`EINVAL: invalid argument, readlink '${t}'`);this.sanitizeError(i,t,"readlink")}}async realpath(t){W(t,"realpath");let s=M(t),r=new Set,n=async o=>{let l=o==="/"?[]:o.slice(1).split("/"),c="";for(let u of l){if(c=`${c}/${u}`,r.has(c))throw new Error(`ELOOP: too many levels of symbolic links, realpath '${t}'`);if(this.deleted.has(c))throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);let f=this.memory.get(c),d=0,h=40;for(;f&&f.type==="symlink"&&d<h;){if(r.add(c),c=this.resolveSymlink(c,f.target),d++,r.has(c))throw new Error(`ELOOP: too many levels of symbolic links, realpath '${t}'`);if(this.deleted.has(c))throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);f=this.memory.get(c)}if(d>=h)throw new Error(`ELOOP: too many levels of symbolic links, realpath '${t}'`);if(!f){let p=this.toRealPath(c),m=this.resolveRealPath_(p);if(m)try{if((await U.promises.lstat(m)).isSymbolicLink()){if(!this.allowSymlinks)throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);let b=await U.promises.readlink(m),v=this.realTargetToVirtual(c,b);return r.add(c),c=this.resolveSymlink(c,v),n(c)}}catch(y){if(y.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);this.sanitizeError(y,t,"realpath")}else if(!this.allowSymlinks){let y=this.resolveRealPathParent_(p);if(y)try{if((await U.promises.lstat(y)).isSymbolicLink())throw new Error(`ENOENT: no such file or directory, realpath '${t}'`)}catch(b){if(b.message?.includes("ENOENT")||b.message?.includes("ELOOP"))throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);this.sanitizeError(b,t,"realpath")}}}}return c||"/"},i=await n(s);if(!await this.existsInOverlay(i))throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);return i}async utimes(t,s,r){W(t,"utimes"),this.assertWritable(`utimes '${t}'`);let n=M(t);if(!await this.existsInOverlay(n))throw new Error(`ENOENT: no such file or directory, utimes '${t}'`);let a=this.memory.get(n);if(a){a.mtime=r;return}let o=await this.stat(n);if(o.isFile){let l=await this.readFileBuffer(n);this.memory.set(n,{type:"file",content:l,mode:o.mode,mtime:r})}else o.isDirectory&&this.memory.set(n,{type:"directory",mode:o.mode,mtime:r})}};function Di(){console.log(`just-bash - A secure bash environment for AI agents
|
|
707
707
|
|
|
708
708
|
Usage:
|
|
709
709
|
just-bash [options] [script-file]
|
|
@@ -750,5 +750,5 @@ Examples:
|
|
|
750
750
|
|
|
751
751
|
# Allow write operations (writes stay in memory)
|
|
752
752
|
just-bash -c 'echo test > /tmp/file.txt && cat /tmp/file.txt' --allow-write
|
|
753
|
-
`)}function qo(){console.log("just-bash 1.0.0")}function Go(e){let t={root:process.cwd(),cwd:"/",cwdOverridden:!1,errexit:!1,allowWrite:!1,python:!1,javascript:!1,json:!1,help:!1,version:!1},s=0;for(;s<e.length;){let r=e[s];if(r==="-h"||r==="--help")t.help=!0,s++;else if(r==="-v"||r==="--version")t.version=!0,s++;else if(r==="-c")s+1>=e.length&&(console.error("Error: -c requires a script argument"),process.exit(1)),t.script=e[s+1],s+=2;else if(r==="-e"||r==="--errexit")t.errexit=!0,s++;else if(r==="--root")s+1>=e.length&&(console.error("Error: --root requires a path argument"),process.exit(1)),t.root=
|
|
753
|
+
`)}function qo(){console.log("just-bash 1.0.0")}function Go(e){let t={root:process.cwd(),cwd:"/",cwdOverridden:!1,errexit:!1,allowWrite:!1,python:!1,javascript:!1,json:!1,help:!1,version:!1},s=0;for(;s<e.length;){let r=e[s];if(r==="-h"||r==="--help")t.help=!0,s++;else if(r==="-v"||r==="--version")t.version=!0,s++;else if(r==="-c")s+1>=e.length&&(console.error("Error: -c requires a script argument"),process.exit(1)),t.script=e[s+1],s+=2;else if(r==="-e"||r==="--errexit")t.errexit=!0,s++;else if(r==="--root")s+1>=e.length&&(console.error("Error: --root requires a path argument"),process.exit(1)),t.root=xi(e[s+1]),s+=2;else if(r==="--cwd")s+1>=e.length&&(console.error("Error: --cwd requires a path argument"),process.exit(1)),t.cwd=e[s+1],t.cwdOverridden=!0,s+=2;else if(r==="--json")t.json=!0,s++;else if(r==="--allow-write")t.allowWrite=!0,s++;else if(r==="--python")t.python=!0,s++;else if(r==="--javascript")t.javascript=!0,s++;else if(r.startsWith("-"))if(r.length>2&&!r.startsWith("--")){let n=r.slice(1);for(let i of n)if(i==="e")t.errexit=!0;else if(i==="h")t.help=!0;else if(i==="v")t.version=!0;else if(i==="c"){s+1>=e.length&&(console.error("Error: -c requires a script argument"),process.exit(1)),t.script=e[s+1],s++;break}else console.error(`Error: Unknown option: -${i}`),process.exit(1);s++}else console.error(`Error: Unknown option: ${r}`),process.exit(1);else!t.scriptFile&&!t.script?t.scriptFile=r:t.scriptFile&&t.root===process.cwd()&&(t.root=xi(r)),s++}return t}function Ko(e){if(!e||e==="/")return"/";let t=e.endsWith("/")&&e!=="/"?e.slice(0,-1):e;t.startsWith("/")||(t=`/${t}`);let s=t.split("/").filter(n=>n&&n!=="."),r=[];for(let n of s)n===".."?r.pop():r.push(n);return`/${r.join("/")}`||"/"}async function Xo(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf-8")}async function Yo(){let e=process.argv.slice(2),t=Go(e);t.help&&(Di(),process.exit(0)),t.version&&(qo(),process.exit(0));let s;if(t.script)s=t.script;else if(t.scriptFile){let o=new ot({root:t.root}),l=o.getMountPoint();try{let c=t.scriptFile.startsWith("/")?t.scriptFile:`${l}/${t.scriptFile}`;s=await o.readFile(c,"utf-8")}catch(c){console.error(`Error: Cannot read script file: ${t.scriptFile}`),console.error(he(c instanceof Error?c.message:String(c))),process.exit(1)}}else process.stdin.isTTY?(Di(),process.exit(1)):s=await Xo();s.trim()||(t.json&&console.log(JSON.stringify({stdout:"",stderr:"",exitCode:0})),process.exit(0));let r=new ot({root:t.root,readOnly:!t.allowWrite}),n=r.getMountPoint(),i=t.cwdOverridden?Ko(t.cwd):n,a=new os({fs:r,cwd:i,python:t.python,javascript:t.javascript});t.errexit&&(s=`set -e
|
|
754
754
|
${s}`);try{let o=await a.exec(s);t.json?console.log(JSON.stringify({stdout:o.stdout,stderr:o.stderr,exitCode:o.exitCode})):(o.stdout&&process.stdout.write(o.stdout),o.stderr&&process.stderr.write(o.stderr)),process.exit(o.exitCode)}catch(o){let l=he(o instanceof Error?o.message:String(o));t.json?console.log(JSON.stringify({stdout:"",stderr:l,exitCode:1})):console.error(l),process.exit(1)}}Yo().catch(e=>{console.error("Fatal error:",he(e instanceof Error?e.message:String(e))),process.exit(1)});
|