just-binary 3.3.0 → 3.3.1

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.
@@ -1,149 +1,151 @@
1
1
  #!/usr/bin/env node
2
- import{$ as yr,A as Fs,B as Kt,C as ar,D as Vs,E as lr,F as ve,G as Be,H as cr,I as ur,J as zs,K as js,L as Me,M as fr,N as dr,O as Ne,P as Bs,R as hr,S as pr,T as be,U as et,V as ue,W as Oe,X as Xt,Y as mr,Z as z,_ as gr,a as rr,aa as We,b as Ls,ba as wr,c as ir,ca as vr,d as or,da as it,e as Zt,ea as Q,f as le,g as Z,h as Ie,i as Jt,j as Qe,k as Ms,l as Ws,m as Re,n as Pt,o as _t,p as U,q as Pe,r as K,s as xt,t as X,u as ee,v as qe,w as te,x as he,y as Le,z as Ze}from"./chunks/chunk-73X3QWRT.js";import{a as kt}from"./chunks/chunk-JGKR7YR7.js";import{a as nr}from"./chunks/chunk-RUESYAVK.js";import{a as Ge,b as ke}from"./chunks/chunk-CAXM2HMK.js";import{a as Ct}from"./chunks/chunk-N7YAMUQG.js";import{a as $e,b as Ae,c as ye,d as Ce,e as er,f as q,g as Xe,h as At,i as Gt,j as tr,k as oe,l as sr,m as pe,n as Ye,o as ze,p as qt,q as we}from"./chunks/chunk-A257OMG4.js";import"./chunks/chunk-OBH7XN5N.js";import{a as je}from"./chunks/chunk-4VDEBYW7.js";import{a as St,b as E,d as de,e as Et,f as V,g as ie,h as Rs,i as rt,j as $t}from"./chunks/chunk-6VQWCKYE.js";import{a as Ut,g as L,h as F,i as H,j as Qn,k as bt,l as T,m as y}from"./chunks/chunk-463VWH7H.js";import{resolve as Yi}from"node:path";var ot=[{name:"echo",load:async()=>(await import("./chunks/echo-DHVSEP57.js")).echoCommand},{name:"cat",load:async()=>(await import("./chunks/cat-UO3ZDQHP.js")).catCommand},{name:"printf",load:async()=>(await import("./chunks/printf-CVEJOTYB.js")).printfCommand},{name:"ls",load:async()=>(await import("./chunks/ls-LBW3TTPI.js")).lsCommand},{name:"mkdir",load:async()=>(await import("./chunks/mkdir-UUOVKGHS.js")).mkdirCommand},{name:"rmdir",load:async()=>(await import("./chunks/rmdir-NJCSEPRP.js")).rmdirCommand},{name:"touch",load:async()=>(await import("./chunks/touch-4ZSEFYEW.js")).touchCommand},{name:"rm",load:async()=>(await import("./chunks/rm-UMIY7ESO.js")).rmCommand},{name:"cp",load:async()=>(await import("./chunks/cp-YSXTOMBS.js")).cpCommand},{name:"mv",load:async()=>(await import("./chunks/mv-7VY5OVAU.js")).mvCommand},{name:"ln",load:async()=>(await import("./chunks/ln-2OLFXJYU.js")).lnCommand},{name:"chmod",load:async()=>(await import("./chunks/chmod-GYXHDITN.js")).chmodCommand},{name:"pwd",load:async()=>(await import("./chunks/pwd-6OLMY3MQ.js")).pwdCommand},{name:"readlink",load:async()=>(await import("./chunks/readlink-T4CDCG4Z.js")).readlinkCommand},{name:"head",load:async()=>(await import("./chunks/head-HT46A7YT.js")).headCommand},{name:"tail",load:async()=>(await import("./chunks/tail-LOVA3SKT.js")).tailCommand},{name:"wc",load:async()=>(await import("./chunks/wc-TDIG4RIU.js")).wcCommand},{name:"stat",load:async()=>(await import("./chunks/stat-J5TUE4U5.js")).statCommand},{name:"grep",load:async()=>(await import("./chunks/grep-RG26XCUN.js")).grepCommand},{name:"fgrep",load:async()=>(await import("./chunks/grep-RG26XCUN.js")).fgrepCommand},{name:"egrep",load:async()=>(await import("./chunks/grep-RG26XCUN.js")).egrepCommand},{name:"rg",load:async()=>(await import("./chunks/rg-PQP4HTR3.js")).rgCommand},{name:"sed",load:async()=>(await import("./chunks/sed-BZW7POX3.js")).sedCommand},{name:"awk",load:async()=>(await import("./chunks/awk2-FB5MXVFV.js")).awkCommand2},{name:"sort",load:async()=>(await import("./chunks/sort-TO3IPXI2.js")).sortCommand},{name:"uniq",load:async()=>(await import("./chunks/uniq-I2KNCRR6.js")).uniqCommand},{name:"comm",load:async()=>(await import("./chunks/comm-WKYJTISA.js")).commCommand},{name:"cut",load:async()=>(await import("./chunks/cut-2MSOLU4C.js")).cutCommand},{name:"paste",load:async()=>(await import("./chunks/paste-Q23K6FU7.js")).pasteCommand},{name:"tr",load:async()=>(await import("./chunks/tr-ARR7JBLN.js")).trCommand},{name:"rev",load:async()=>(await import("./chunks/rev-O3PQMT23.js")).rev},{name:"nl",load:async()=>(await import("./chunks/nl-34JIXDXD.js")).nl},{name:"fold",load:async()=>(await import("./chunks/fold-OVU7UR2E.js")).fold},{name:"expand",load:async()=>(await import("./chunks/expand-L4NT2YFK.js")).expand},{name:"unexpand",load:async()=>(await import("./chunks/unexpand-B4WHWJHL.js")).unexpand},{name:"strings",load:async()=>(await import("./chunks/strings-TDUSHGAB.js")).strings},{name:"split",load:async()=>(await import("./chunks/split-JXCUP73P.js")).split},{name:"column",load:async()=>(await import("./chunks/column-UCIEGSHJ.js")).column},{name:"join",load:async()=>(await import("./chunks/join-6M3ARIFB.js")).join},{name:"tee",load:async()=>(await import("./chunks/tee-SREYEKO6.js")).teeCommand},{name:"find",load:async()=>(await import("./chunks/find-B6JV4QSG.js")).findCommand},{name:"basename",load:async()=>(await import("./chunks/basename-ZFBDKUVW.js")).basenameCommand},{name:"dirname",load:async()=>(await import("./chunks/dirname-XXQNLCA4.js")).dirnameCommand},{name:"tree",load:async()=>(await import("./chunks/tree-7Y7H64VI.js")).treeCommand},{name:"du",load:async()=>(await import("./chunks/du-IKBAW7PG.js")).duCommand},{name:"env",load:async()=>(await import("./chunks/env-A43LGO53.js")).envCommand},{name:"printenv",load:async()=>(await import("./chunks/env-A43LGO53.js")).printenvCommand},{name:"alias",load:async()=>(await import("./chunks/alias-MILMQPGR.js")).aliasCommand},{name:"unalias",load:async()=>(await import("./chunks/alias-MILMQPGR.js")).unaliasCommand},{name:"history",load:async()=>(await import("./chunks/history-WO6CMWMT.js")).historyCommand},{name:"xargs",load:async()=>(await import("./chunks/xargs-6K57XYD6.js")).xargsCommand},{name:"true",load:async()=>(await import("./chunks/true-CKHNKYAT.js")).trueCommand},{name:"false",load:async()=>(await import("./chunks/true-CKHNKYAT.js")).falseCommand},{name:"clear",load:async()=>(await import("./chunks/clear-FZZM6QD2.js")).clearCommand},{name:"yes",load:async()=>(await import("./chunks/yes-7ZGUE2PX.js")).yesCommand},{name:"bash",load:async()=>(await import("./chunks/bash-FQY3C37R.js")).bashCommand},{name:"sh",load:async()=>(await import("./chunks/bash-FQY3C37R.js")).shCommand},{name:"jq",load:async()=>(await import("./chunks/jq-HP7VLWBL.js")).jqCommand},{name:"base64",load:async()=>(await import("./chunks/base64-NGAPXZAM.js")).base64Command},{name:"diff",load:async()=>(await import("./chunks/diff-4PEKV4XS.js")).diffCommand},{name:"date",load:async()=>(await import("./chunks/date-5LA42436.js")).dateCommand},{name:"sleep",load:async()=>(await import("./chunks/sleep-HDMKKRCV.js")).sleepCommand},{name:"timeout",load:async()=>(await import("./chunks/timeout-XBYZ5LW5.js")).timeoutCommand},{name:"time",load:async()=>(await import("./chunks/time-GS6SIFPK.js")).timeCommand},{name:"seq",load:async()=>(await import("./chunks/seq-3FRPQG5E.js")).seqCommand},{name:"expr",load:async()=>(await import("./chunks/expr-BGBONRHV.js")).exprCommand},{name:"md5sum",load:async()=>(await import("./chunks/md5sum-GAWU76ZU.js")).md5sumCommand},{name:"sha1sum",load:async()=>(await import("./chunks/sha1sum-AOZWHFTU.js")).sha1sumCommand},{name:"sha256sum",load:async()=>(await import("./chunks/sha256sum-EXJTAPU4.js")).sha256sumCommand},{name:"file",load:async()=>(await import("./chunks/file-DZRWWDPH.js")).fileCommand},{name:"html-to-markdown",load:async()=>(await import("./chunks/html-to-markdown-34LV4LFQ.js")).htmlToMarkdownCommand},{name:"help",load:async()=>(await import("./chunks/help-AOETY73Q.js")).helpCommand},{name:"which",load:async()=>(await import("./chunks/which-QMZ276XE.js")).whichCommand},{name:"tac",load:async()=>(await import("./chunks/tac-QXOHN3J4.js")).tac},{name:"hostname",load:async()=>(await import("./chunks/hostname-4O6NEPL2.js")).hostname},{name:"whoami",load:async()=>(await import("./chunks/whoami-XYB47VCX.js")).whoami},{name:"od",load:async()=>(await import("./chunks/od-IGVFBAFH.js")).od},{name:"gzip",load:async()=>(await import("./chunks/gzip-XZZL25AV.js")).gzipCommand},{name:"gunzip",load:async()=>(await import("./chunks/gzip-XZZL25AV.js")).gunzipCommand},{name:"zcat",load:async()=>(await import("./chunks/gzip-XZZL25AV.js")).zcatCommand}];(typeof __BROWSER__>"u"||!__BROWSER__)&&(ot.push({name:"tar",load:async()=>(await import("./chunks/tar-BAKR5OJO.js")).tarCommand}),ot.push({name:"yq",load:async()=>(await import("./chunks/yq-ZHYSTGN3.js")).yqCommand}),ot.push({name:"xan",load:async()=>(await import("./chunks/xan-STBKXZ5W.js")).xanCommand}),ot.push({name:"sqlite3",load:async()=>(await import("./chunks/sqlite3-K7LHCU76.js")).sqlite3Command}));var Hs=[];(typeof __BROWSER__>"u"||!__BROWSER__)&&(Hs.push({name:"python3",load:async()=>(await import("./chunks/python3-VZL5HRHR.js")).python3Command}),Hs.push({name:"python",load:async()=>(await import("./chunks/python3-VZL5HRHR.js")).pythonCommand}));var no=[{name:"curl",load:async()=>(await import("./chunks/curl-YFYJ2XNC.js")).curlCommand}],br=new Map;function Us(e){return{name:e.name,async execute(t,s){let n=br.get(e.name);if(n||(n=await e.load(),br.set(e.name,n)),s.coverage&&(typeof __BROWSER__>"u"||!__BROWSER__)){let{emitFlagCoverage:r}=await import("./chunks/flag-coverage-FTS7XXHM.js"),{decodeArgs:i}=await import("./chunks/bytes-C34BYEMS.js");r(s.coverage,e.name,i(t))}return n.execute(t,s)}}}function Sr(e){return(e?ot.filter(s=>e.includes(s.name)):ot).map(Us)}function Er(){return no.map(Us)}function $r(){return Hs.map(Us)}function Ar(e){return"load"in e&&typeof e.load=="function"}function Cr(e){let t=null;return{name:e.name,async execute(s,n){return t||(t=await e.load()),t.execute(s,n)}}}var ro=new TextEncoder;function io(e){return typeof e=="object"&&e!==null&&typeof e.getReader=="function"}function oo(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 n=0;n<e.length;n+=2)s[n/2]=parseInt(e.slice(n,n+2),16);return s}if(t==="binary"||t==="latin1"){if(e.length<=65536)return Uint8Array.from(e,r=>r.charCodeAt(0));let n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r);return n}return ro.encode(e)}function Pr(e){if(e.length===0)return[];if(e.length<=St)return[e];let t=[];for(let s=0;s<e.length;s+=St)t.push(e.subarray(s,Math.min(s+St,e.length)));return t}function at(e,t){let s=oo(e,t);return{chunks:Pr(s),size:s.length}}async function lt(e,t){if(io(e)){let s=[],n=0;for await(let r of $t(e))if(r.length<=St)s.push(r),n+=r.length;else for(let i of Pr(r))s.push(i),n+=i.length;return{chunks:s,size:n}}return at(e,t)}function Yt(e,t){if(t==="base64")return btoa(nr(kr(e)));if(t==="hex"){let r="";for(let i of e)for(let a=0;a<i.length;a++)r+=i[a].toString(16).padStart(2,"0");return r}if(t==="binary"||t==="latin1"){if(typeof Buffer<"u")return Buffer.from(kr(e)).toString(t);let r=65536,i="";for(let a of e)if(a.length<=r)i+=String.fromCharCode(...a);else for(let o=0;o<a.length;o+=r){let l=a.subarray(o,o+r);i+=String.fromCharCode(...l)}return i}let s=new TextDecoder,n="";for(let r of e)r.length>0&&(n+=s.decode(r,{stream:!0}));return n+=s.decode(),n}function kr(e){let t=0;for(let r of e)t+=r.length;if(t===0)return new Uint8Array(0);if(e.length===1)return e[0];let s=new Uint8Array(t),n=0;for(let r of e)s.set(r,n),n+=r.length;return s}function He(e){if(e!=null)return typeof e=="string"?e:e.encoding??void 0}function Qt(e,t){if(!Number.isFinite(e)||!Number.isInteger(e)||e<0)throw new Error(`EINVAL: invalid offset (must be a non-negative integer): ${e}`);if(!Number.isFinite(t)||!Number.isInteger(t)||t<0)throw new Error(`EINVAL: invalid length (must be a non-negative integer): ${t}`)}function es(e,t,s,n){if(s>=t||n===0)return new Uint8Array(0);let r=Math.min(s+n,t),i=r-s,a=new Uint8Array(i),o=0,l=0;for(let u of e){if(o>=i)break;let c=l+u.length;if(c>s&&l<r){let f=Math.max(0,s-l),d=Math.min(u.length,r-l),p=u.subarray(f,d);a.set(p,o),o+=p.length}l=c}return a}function ao(e){return typeof e=="object"&&e!==null&&!(e instanceof Uint8Array)&&!(e instanceof ReadableStream)&&"content"in e}function ce(e,t){if(e.includes("\0"))throw new Error(`ENOENT: path contains null byte, ${t} '${e}'`)}var Tt=class{data=new Map;constructor(t){if(this.data.set("/",{type:"directory",mode:493,mtime:new Date}),t)for(let[s,n]of Object.entries(t))if(ao(n)){if(n.content instanceof ReadableStream)throw new Error("InMemoryFs: streams not supported in InitialFiles; use writeFile() after construction");this.writeFileSync(s,n.content,void 0,{mode:n.mode,mtime:n.mtime})}else{if(n instanceof ReadableStream)throw new Error("InMemoryFs: streams not supported in InitialFiles; use writeFile() after construction");this.writeFileSync(s,n)}}normalizePath(t){if(!t||t==="/")return"/";let s=t.endsWith("/")&&t!=="/"?t.slice(0,-1):t;s.startsWith("/")||(s=`/${s}`);let n=s.split("/").filter(i=>i&&i!=="."),r=[];for(let i of n)i===".."?r.pop():r.push(i);return`/${r.join("/")}`||"/"}dirname(t){let s=this.normalizePath(t);if(s==="/")return"/";let n=s.lastIndexOf("/");return n===0?"/":s.slice(0,n)}ensureParentDirs(t){let s=this.dirname(t);s!=="/"&&(this.data.has(s)||(this.ensureParentDirs(s),this.data.set(s,{type:"directory",mode:493,mtime:new Date})))}writeFileSync(t,s,n,r){ce(t,"write");let i=this.normalizePath(t);this.ensureParentDirs(i);let a=He(n),{chunks:o,size:l}=at(s,a);this.data.set(i,{type:"file",chunks:o,size:l,mode:r?.mode??420,mtime:r?.mtime??new Date})}async readFile(t){ce(t,"open");let s=this.resolvePathWithSymlinks(t),n=this.data.get(s);if(!n)throw new Error(`ENOENT: no such file or directory, open '${t}'`);if(n.type!=="file")throw new Error(`EISDIR: illegal operation on a directory, read '${t}'`);return Et(n.chunks)}async readRange(t,s,n){Qt(s,n),ce(t,"open");let r=this.resolvePathWithSymlinks(t),i=this.data.get(r);if(!i)throw new Error(`ENOENT: no such file or directory, open '${t}'`);if(i.type!=="file")throw new Error(`EISDIR: illegal operation on a directory, read '${t}'`);return es(i.chunks,i.size,s,n)}async readFileText(t,s){ce(t,"open");let n=this.resolvePathWithSymlinks(t),r=this.data.get(n);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}'`);let i=He(s);return Yt(r.chunks,i)}async writeFile(t,s,n){ce(t,"write");let r=this.normalizePath(t);this.ensureParentDirs(r);let i=He(n),{chunks:a,size:o}=await lt(s,i);this.data.set(r,{type:"file",chunks:a,size:o,mode:420,mtime:new Date})}async appendFile(t,s,n){ce(t,"append");let r=this.normalizePath(t),i=this.data.get(r);if(i&&i.type==="directory")throw new Error(`EISDIR: illegal operation on a directory, write '${t}'`);let a=He(n),{chunks:o,size:l}=await lt(s,a);i?.type==="file"?this.data.set(r,{type:"file",chunks:[...i.chunks,...o],size:i.size+l,mode:i.mode,mtime:new Date}):(this.ensureParentDirs(r),this.data.set(r,{type:"file",chunks:o,size:l,mode:420,mtime:new Date}))}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){ce(t,"stat");let s=this.resolvePathWithSymlinks(t),n=this.data.get(s);if(!n)throw new Error(`ENOENT: no such file or directory, stat '${t}'`);let r=0;return n.type==="file"&&(r=n.size),{isFile:n.type==="file",isDirectory:n.type==="directory",isSymbolicLink:!1,mode:n.mode,size:r,mtime:n.mtime||new Date}}async lstat(t){ce(t,"lstat");let s=this.resolveIntermediateSymlinks(t),n=this.data.get(s);if(!n)throw new Error(`ENOENT: no such file or directory, lstat '${t}'`);if(n.type==="symlink")return{isFile:!1,isDirectory:!1,isSymbolicLink:!0,mode:n.mode,size:n.target.length,mtime:n.mtime||new Date};let r=0;return n.type==="file"&&(r=n.size),{isFile:n.type==="file",isDirectory:n.type==="directory",isSymbolicLink:!1,mode:n.mode,size:r,mtime:n.mtime||new Date}}resolveSymlink(t,s){if(s.startsWith("/"))return this.normalizePath(s);let n=this.dirname(t);return this.normalizePath(n==="/"?`/${s}`:`${n}/${s}`)}resolveIntermediateSymlinks(t){let s=this.normalizePath(t);if(s==="/")return"/";let n=s.slice(1).split("/");if(n.length<=1)return s;let r="",i=new Set;for(let a=0;a<n.length-1;a++){let o=n[a];r=`${r}/${o}`;let l=this.data.get(r),u=0,c=40;for(;l&&l.type==="symlink"&&u<c;){if(i.has(r))throw new Error(`ELOOP: too many levels of symbolic links, lstat '${t}'`);i.add(r),r=this.resolveSymlink(r,l.target),l=this.data.get(r),u++}if(u>=c)throw new Error(`ELOOP: too many levels of symbolic links, lstat '${t}'`)}return`${r}/${n[n.length-1]}`}resolvePathWithSymlinks(t){let s=this.normalizePath(t);if(s==="/")return"/";let n=s.slice(1).split("/"),r="",i=new Set;for(let a of n){r=`${r}/${a}`;let o=this.data.get(r),l=0,u=40;for(;o&&o.type==="symlink"&&l<u;){if(i.has(r))throw new Error(`ELOOP: too many levels of symbolic links, open '${t}'`);i.add(r),r=this.resolveSymlink(r,o.target),o=this.data.get(r),l++}if(l>=u)throw new Error(`ELOOP: too many levels of symbolic links, open '${t}'`)}return r}async mkdir(t,s){this.mkdirSync(t,s)}mkdirSync(t,s){ce(t,"mkdir");let n=this.normalizePath(t);if(this.data.has(n)){if(this.data.get(n)?.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 r=this.dirname(n);if(r!=="/"&&!this.data.has(r))if(s?.recursive)this.mkdirSync(r,{recursive:!0});else throw new Error(`ENOENT: no such file or directory, mkdir '${t}'`);this.data.set(n,{type:"directory",mode:493,mtime:new Date})}async readdir(t){return(await this.readdirWithFileTypes(t)).map(n=>n.name)}async readdirWithFileTypes(t){ce(t,"scandir");let s=this.normalizePath(t),n=this.data.get(s);if(!n)throw new Error(`ENOENT: no such file or directory, scandir '${t}'`);let r=new Set;for(;n&&n.type==="symlink";){if(r.has(s))throw new Error(`ELOOP: too many levels of symbolic links, scandir '${t}'`);r.add(s),s=this.resolveSymlink(s,n.target),n=this.data.get(s)}if(!n)throw new Error(`ENOENT: no such file or directory, scandir '${t}'`);if(n.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 u=o.slice(i.length),c=u.split("/")[0];c&&!u.includes("/",c.length)&&!a.has(c)&&a.set(c,{name:c,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){ce(t,"rm");let n=this.normalizePath(t),r=this.data.get(n);if(!r){if(s?.force)return;throw new Error(`ENOENT: no such file or directory, rm '${t}'`)}if(r.type==="directory"){let i=await this.readdir(n);if(i.length>0){if(!s?.recursive)throw new Error(`ENOTEMPTY: directory not empty, rm '${t}'`);for(let a of i){let o=n==="/"?`/${a}`:`${n}/${a}`;await this.rm(o,s)}}}this.data.delete(n)}async cp(t,s,n){ce(t,"cp"),ce(s,"cp");let r=this.normalizePath(t),i=this.normalizePath(s),a=this.data.get(r);if(!a)throw new Error(`ENOENT: no such file or directory, cp '${t}'`);if(a.type==="file")this.ensureParentDirs(i),this.data.set(i,{type:"file",chunks:[...a.chunks],size:a.size,mode:a.mode,mtime:a.mtime});else if(a.type==="directory"){if(!n?.recursive)throw new Error(`EISDIR: is a directory, cp '${t}'`);await this.mkdir(i,{recursive:!0});let o=await this.readdir(r);for(let l of o){let u=r==="/"?`/${l}`:`${r}/${l}`,c=i==="/"?`/${l}`:`${i}/${l}`;await this.cp(u,c,n)}}}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){if(s.startsWith("/"))return this.normalizePath(s);let n=t==="/"?`/${s}`:`${t}/${s}`;return this.normalizePath(n)}async chmod(t,s){ce(t,"chmod");let n=this.normalizePath(t),r=this.data.get(n);if(!r)throw new Error(`ENOENT: no such file or directory, chmod '${t}'`);r.mode=s}async symlink(t,s){ce(s,"symlink");let n=this.normalizePath(s);if(this.data.has(n))throw new Error(`EEXIST: file already exists, symlink '${s}'`);this.ensureParentDirs(n),this.data.set(n,{type:"symlink",target:t,mode:511,mtime:new Date})}async link(t,s){ce(t,"link"),ce(s,"link");let n=this.normalizePath(t),r=this.normalizePath(s),i=this.data.get(n);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(r))throw new Error(`EEXIST: file already exists, link '${s}'`);this.ensureParentDirs(r),this.data.set(r,{type:"file",chunks:[...i.chunks],size:i.size,mode:i.mode,mtime:i.mtime})}async readlink(t){ce(t,"readlink");let s=this.normalizePath(t),n=this.data.get(s);if(!n)throw new Error(`ENOENT: no such file or directory, readlink '${t}'`);if(n.type!=="symlink")throw new Error(`EINVAL: invalid argument, readlink '${t}'`);return n.target}async realpath(t){ce(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,n){ce(t,"utimes");let r=this.normalizePath(t),i=this.resolvePathWithSymlinks(r),a=this.data.get(i);if(!a)throw new Error(`ENOENT: no such file or directory, utimes '${t}'`);a.mtime=n}};function lo(e){let t=e;return typeof t.mkdirSync=="function"&&typeof t.writeFileSync=="function"}function co(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 uo(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 fo(e){e.mkdirSync("/proc/self/fd",{recursive:!0}),e.writeFileSync("/proc/version",`${rr}
2
+ import{$ as yr,A as Fs,B as Kt,C as ar,D as Vs,E as lr,F as ve,G as Be,H as cr,I as ur,J as zs,K as js,L as Me,M as fr,N as dr,O as xe,P as Bs,R as hr,S as pr,T as be,U as et,V as ue,W as Oe,X as Yt,Y as mr,Z as z,_ as gr,a as rr,aa as We,b as Ls,ba as wr,c as ir,ca as vr,d as or,da as it,e as Jt,ea as Q,f as le,g as Z,h as De,i as Xt,j as Qe,k as Ms,l as Ws,m as Re,n as Pt,o as _t,p as H,q as Pe,r as K,s as Tt,t as Y,u as ee,v as qe,w as te,x as he,y as Le,z as Ze}from"./chunks/chunk-73X3QWRT.js";import{a as kt}from"./chunks/chunk-JGKR7YR7.js";import{a as nr}from"./chunks/chunk-RUESYAVK.js";import{a as Ge,b as ke}from"./chunks/chunk-CAXM2HMK.js";import{a as Ct}from"./chunks/chunk-N7YAMUQG.js";import{a as $e,b as Ae,c as ye,d as Ce,e as er,f as q,g as Ke,h as At,i as qt,j as tr,k as oe,l as sr,m as pe,n as Ye,o as ze,p as Zt,q as we}from"./chunks/chunk-A257OMG4.js";import"./chunks/chunk-OBH7XN5N.js";import{a as je}from"./chunks/chunk-4VDEBYW7.js";import{a as St,b as A,d as de,e as Et,f as V,g as ie,h as Rs,i as rt,j as $t}from"./chunks/chunk-6VQWCKYE.js";import{a as Gt,g as R,h as F,i as U,j as Qn,k as bt,l as x,m as y}from"./chunks/chunk-463VWH7H.js";import{resolve as Yi}from"node:path";var ot=[{name:"echo",load:async()=>(await import("./chunks/echo-DHVSEP57.js")).echoCommand},{name:"cat",load:async()=>(await import("./chunks/cat-UO3ZDQHP.js")).catCommand},{name:"printf",load:async()=>(await import("./chunks/printf-CVEJOTYB.js")).printfCommand},{name:"ls",load:async()=>(await import("./chunks/ls-LBW3TTPI.js")).lsCommand},{name:"mkdir",load:async()=>(await import("./chunks/mkdir-UUOVKGHS.js")).mkdirCommand},{name:"rmdir",load:async()=>(await import("./chunks/rmdir-NJCSEPRP.js")).rmdirCommand},{name:"touch",load:async()=>(await import("./chunks/touch-4ZSEFYEW.js")).touchCommand},{name:"rm",load:async()=>(await import("./chunks/rm-UMIY7ESO.js")).rmCommand},{name:"cp",load:async()=>(await import("./chunks/cp-YSXTOMBS.js")).cpCommand},{name:"mv",load:async()=>(await import("./chunks/mv-7VY5OVAU.js")).mvCommand},{name:"ln",load:async()=>(await import("./chunks/ln-2OLFXJYU.js")).lnCommand},{name:"chmod",load:async()=>(await import("./chunks/chmod-GYXHDITN.js")).chmodCommand},{name:"pwd",load:async()=>(await import("./chunks/pwd-6OLMY3MQ.js")).pwdCommand},{name:"readlink",load:async()=>(await import("./chunks/readlink-T4CDCG4Z.js")).readlinkCommand},{name:"head",load:async()=>(await import("./chunks/head-HT46A7YT.js")).headCommand},{name:"tail",load:async()=>(await import("./chunks/tail-LOVA3SKT.js")).tailCommand},{name:"wc",load:async()=>(await import("./chunks/wc-TDIG4RIU.js")).wcCommand},{name:"stat",load:async()=>(await import("./chunks/stat-J5TUE4U5.js")).statCommand},{name:"grep",load:async()=>(await import("./chunks/grep-RG26XCUN.js")).grepCommand},{name:"fgrep",load:async()=>(await import("./chunks/grep-RG26XCUN.js")).fgrepCommand},{name:"egrep",load:async()=>(await import("./chunks/grep-RG26XCUN.js")).egrepCommand},{name:"rg",load:async()=>(await import("./chunks/rg-PQP4HTR3.js")).rgCommand},{name:"sed",load:async()=>(await import("./chunks/sed-BZW7POX3.js")).sedCommand},{name:"awk",load:async()=>(await import("./chunks/awk2-FB5MXVFV.js")).awkCommand2},{name:"sort",load:async()=>(await import("./chunks/sort-TO3IPXI2.js")).sortCommand},{name:"uniq",load:async()=>(await import("./chunks/uniq-I2KNCRR6.js")).uniqCommand},{name:"comm",load:async()=>(await import("./chunks/comm-WKYJTISA.js")).commCommand},{name:"cut",load:async()=>(await import("./chunks/cut-2MSOLU4C.js")).cutCommand},{name:"paste",load:async()=>(await import("./chunks/paste-Q23K6FU7.js")).pasteCommand},{name:"tr",load:async()=>(await import("./chunks/tr-ARR7JBLN.js")).trCommand},{name:"rev",load:async()=>(await import("./chunks/rev-O3PQMT23.js")).rev},{name:"nl",load:async()=>(await import("./chunks/nl-34JIXDXD.js")).nl},{name:"fold",load:async()=>(await import("./chunks/fold-OVU7UR2E.js")).fold},{name:"expand",load:async()=>(await import("./chunks/expand-L4NT2YFK.js")).expand},{name:"unexpand",load:async()=>(await import("./chunks/unexpand-B4WHWJHL.js")).unexpand},{name:"strings",load:async()=>(await import("./chunks/strings-TDUSHGAB.js")).strings},{name:"split",load:async()=>(await import("./chunks/split-JXCUP73P.js")).split},{name:"column",load:async()=>(await import("./chunks/column-UCIEGSHJ.js")).column},{name:"join",load:async()=>(await import("./chunks/join-6M3ARIFB.js")).join},{name:"tee",load:async()=>(await import("./chunks/tee-SREYEKO6.js")).teeCommand},{name:"find",load:async()=>(await import("./chunks/find-B6JV4QSG.js")).findCommand},{name:"basename",load:async()=>(await import("./chunks/basename-ZFBDKUVW.js")).basenameCommand},{name:"dirname",load:async()=>(await import("./chunks/dirname-XXQNLCA4.js")).dirnameCommand},{name:"tree",load:async()=>(await import("./chunks/tree-7Y7H64VI.js")).treeCommand},{name:"du",load:async()=>(await import("./chunks/du-IKBAW7PG.js")).duCommand},{name:"env",load:async()=>(await import("./chunks/env-A43LGO53.js")).envCommand},{name:"printenv",load:async()=>(await import("./chunks/env-A43LGO53.js")).printenvCommand},{name:"alias",load:async()=>(await import("./chunks/alias-MILMQPGR.js")).aliasCommand},{name:"unalias",load:async()=>(await import("./chunks/alias-MILMQPGR.js")).unaliasCommand},{name:"history",load:async()=>(await import("./chunks/history-WO6CMWMT.js")).historyCommand},{name:"xargs",load:async()=>(await import("./chunks/xargs-6K57XYD6.js")).xargsCommand},{name:"true",load:async()=>(await import("./chunks/true-CKHNKYAT.js")).trueCommand},{name:"false",load:async()=>(await import("./chunks/true-CKHNKYAT.js")).falseCommand},{name:"clear",load:async()=>(await import("./chunks/clear-FZZM6QD2.js")).clearCommand},{name:"yes",load:async()=>(await import("./chunks/yes-7ZGUE2PX.js")).yesCommand},{name:"bash",load:async()=>(await import("./chunks/bash-FQY3C37R.js")).bashCommand},{name:"sh",load:async()=>(await import("./chunks/bash-FQY3C37R.js")).shCommand},{name:"jq",load:async()=>(await import("./chunks/jq-HP7VLWBL.js")).jqCommand},{name:"base64",load:async()=>(await import("./chunks/base64-NGAPXZAM.js")).base64Command},{name:"diff",load:async()=>(await import("./chunks/diff-4PEKV4XS.js")).diffCommand},{name:"date",load:async()=>(await import("./chunks/date-5LA42436.js")).dateCommand},{name:"sleep",load:async()=>(await import("./chunks/sleep-HDMKKRCV.js")).sleepCommand},{name:"timeout",load:async()=>(await import("./chunks/timeout-XBYZ5LW5.js")).timeoutCommand},{name:"time",load:async()=>(await import("./chunks/time-GS6SIFPK.js")).timeCommand},{name:"seq",load:async()=>(await import("./chunks/seq-3FRPQG5E.js")).seqCommand},{name:"expr",load:async()=>(await import("./chunks/expr-BGBONRHV.js")).exprCommand},{name:"md5sum",load:async()=>(await import("./chunks/md5sum-GAWU76ZU.js")).md5sumCommand},{name:"sha1sum",load:async()=>(await import("./chunks/sha1sum-AOZWHFTU.js")).sha1sumCommand},{name:"sha256sum",load:async()=>(await import("./chunks/sha256sum-EXJTAPU4.js")).sha256sumCommand},{name:"file",load:async()=>(await import("./chunks/file-DZRWWDPH.js")).fileCommand},{name:"html-to-markdown",load:async()=>(await import("./chunks/html-to-markdown-34LV4LFQ.js")).htmlToMarkdownCommand},{name:"help",load:async()=>(await import("./chunks/help-AOETY73Q.js")).helpCommand},{name:"which",load:async()=>(await import("./chunks/which-QMZ276XE.js")).whichCommand},{name:"tac",load:async()=>(await import("./chunks/tac-QXOHN3J4.js")).tac},{name:"hostname",load:async()=>(await import("./chunks/hostname-4O6NEPL2.js")).hostname},{name:"whoami",load:async()=>(await import("./chunks/whoami-XYB47VCX.js")).whoami},{name:"od",load:async()=>(await import("./chunks/od-IGVFBAFH.js")).od},{name:"gzip",load:async()=>(await import("./chunks/gzip-XZZL25AV.js")).gzipCommand},{name:"gunzip",load:async()=>(await import("./chunks/gzip-XZZL25AV.js")).gunzipCommand},{name:"zcat",load:async()=>(await import("./chunks/gzip-XZZL25AV.js")).zcatCommand}];(typeof __BROWSER__>"u"||!__BROWSER__)&&(ot.push({name:"tar",load:async()=>(await import("./chunks/tar-BAKR5OJO.js")).tarCommand}),ot.push({name:"yq",load:async()=>(await import("./chunks/yq-ZHYSTGN3.js")).yqCommand}),ot.push({name:"xan",load:async()=>(await import("./chunks/xan-STBKXZ5W.js")).xanCommand}),ot.push({name:"sqlite3",load:async()=>(await import("./chunks/sqlite3-K7LHCU76.js")).sqlite3Command}));var Us=[];(typeof __BROWSER__>"u"||!__BROWSER__)&&(Us.push({name:"python3",load:async()=>(await import("./chunks/python3-VZL5HRHR.js")).python3Command}),Us.push({name:"python",load:async()=>(await import("./chunks/python3-VZL5HRHR.js")).pythonCommand}));var no=[{name:"curl",load:async()=>(await import("./chunks/curl-YFYJ2XNC.js")).curlCommand}],br=new Map;function Hs(e){return{name:e.name,async execute(t,s){let n=br.get(e.name);if(n||(n=await e.load(),br.set(e.name,n)),s.coverage&&(typeof __BROWSER__>"u"||!__BROWSER__)){let{emitFlagCoverage:r}=await import("./chunks/flag-coverage-FTS7XXHM.js"),{decodeArgs:i}=await import("./chunks/bytes-C34BYEMS.js");r(s.coverage,e.name,i(t))}return n.execute(t,s)}}}function Sr(e){return(e?ot.filter(s=>e.includes(s.name)):ot).map(Hs)}function Er(){return no.map(Hs)}function $r(){return Us.map(Hs)}function Ar(e){return"load"in e&&typeof e.load=="function"}function Cr(e){let t=null;return{name:e.name,async execute(s,n){return t||(t=await e.load()),t.execute(s,n)}}}var ro=new TextEncoder;function io(e){return typeof e=="object"&&e!==null&&typeof e.getReader=="function"}function oo(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 n=0;n<e.length;n+=2)s[n/2]=parseInt(e.slice(n,n+2),16);return s}if(t==="binary"||t==="latin1"){if(e.length<=65536)return Uint8Array.from(e,r=>r.charCodeAt(0));let n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r);return n}return ro.encode(e)}function Pr(e){if(e.length===0)return[];if(e.length<=St)return[e];let t=[];for(let s=0;s<e.length;s+=St)t.push(e.subarray(s,Math.min(s+St,e.length)));return t}function at(e,t){let s=oo(e,t);return{chunks:Pr(s),size:s.length}}async function lt(e,t){if(io(e)){let s=[],n=0;for await(let r of $t(e))if(r.length<=St)s.push(r),n+=r.length;else for(let i of Pr(r))s.push(i),n+=i.length;return{chunks:s,size:n}}return at(e,t)}function Qt(e,t){if(t==="base64")return btoa(nr(kr(e)));if(t==="hex"){let r="";for(let i of e)for(let a=0;a<i.length;a++)r+=i[a].toString(16).padStart(2,"0");return r}if(t==="binary"||t==="latin1"){if(typeof Buffer<"u")return Buffer.from(kr(e)).toString(t);let r=65536,i="";for(let a of e)if(a.length<=r)i+=String.fromCharCode(...a);else for(let o=0;o<a.length;o+=r){let l=a.subarray(o,o+r);i+=String.fromCharCode(...l)}return i}let s=new TextDecoder,n="";for(let r of e)r.length>0&&(n+=s.decode(r,{stream:!0}));return n+=s.decode(),n}function kr(e){let t=0;for(let r of e)t+=r.length;if(t===0)return new Uint8Array(0);if(e.length===1)return e[0];let s=new Uint8Array(t),n=0;for(let r of e)s.set(r,n),n+=r.length;return s}function Ue(e){if(e!=null)return typeof e=="string"?e:e.encoding??void 0}function es(e,t){if(!Number.isFinite(e)||!Number.isInteger(e)||e<0)throw new Error(`EINVAL: invalid offset (must be a non-negative integer): ${e}`);if(!Number.isFinite(t)||!Number.isInteger(t)||t<0)throw new Error(`EINVAL: invalid length (must be a non-negative integer): ${t}`)}function ts(e,t,s,n){if(s>=t||n===0)return new Uint8Array(0);let r=Math.min(s+n,t),i=r-s,a=new Uint8Array(i),o=0,l=0;for(let c of e){if(o>=i)break;let u=l+c.length;if(u>s&&l<r){let f=Math.max(0,s-l),d=Math.min(c.length,r-l),p=c.subarray(f,d);a.set(p,o),o+=p.length}l=u}return a}function ao(e){return typeof e=="object"&&e!==null&&!(e instanceof Uint8Array)&&!(e instanceof ReadableStream)&&"content"in e}function ce(e,t){if(e.includes("\0"))throw new Error(`ENOENT: path contains null byte, ${t} '${e}'`)}var Nt=class{data=new Map;constructor(t){if(this.data.set("/",{type:"directory",mode:493,mtime:new Date}),t)for(let[s,n]of Object.entries(t))if(ao(n)){if(n.content instanceof ReadableStream)throw new Error("InMemoryFs: streams not supported in InitialFiles; use writeFile() after construction");this.writeFileSync(s,n.content,void 0,{mode:n.mode,mtime:n.mtime})}else{if(n instanceof ReadableStream)throw new Error("InMemoryFs: streams not supported in InitialFiles; use writeFile() after construction");this.writeFileSync(s,n)}}normalizePath(t){if(!t||t==="/")return"/";let s=t.endsWith("/")&&t!=="/"?t.slice(0,-1):t;s.startsWith("/")||(s=`/${s}`);let n=s.split("/").filter(i=>i&&i!=="."),r=[];for(let i of n)i===".."?r.pop():r.push(i);return`/${r.join("/")}`||"/"}dirname(t){let s=this.normalizePath(t);if(s==="/")return"/";let n=s.lastIndexOf("/");return n===0?"/":s.slice(0,n)}ensureParentDirs(t){let s=this.dirname(t);s!=="/"&&(this.data.has(s)||(this.ensureParentDirs(s),this.data.set(s,{type:"directory",mode:493,mtime:new Date})))}writeFileSync(t,s,n,r){ce(t,"write");let i=this.normalizePath(t);this.ensureParentDirs(i);let a=Ue(n),{chunks:o,size:l}=at(s,a);this.data.set(i,{type:"file",chunks:o,size:l,mode:r?.mode??420,mtime:r?.mtime??new Date})}async readFile(t){ce(t,"open");let s=this.resolvePathWithSymlinks(t),n=this.data.get(s);if(!n)throw new Error(`ENOENT: no such file or directory, open '${t}'`);if(n.type!=="file")throw new Error(`EISDIR: illegal operation on a directory, read '${t}'`);return Et(n.chunks)}async readRange(t,s,n){es(s,n),ce(t,"open");let r=this.resolvePathWithSymlinks(t),i=this.data.get(r);if(!i)throw new Error(`ENOENT: no such file or directory, open '${t}'`);if(i.type!=="file")throw new Error(`EISDIR: illegal operation on a directory, read '${t}'`);return ts(i.chunks,i.size,s,n)}async readFileText(t,s){ce(t,"open");let n=this.resolvePathWithSymlinks(t),r=this.data.get(n);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}'`);let i=Ue(s);return Qt(r.chunks,i)}async writeFile(t,s,n){ce(t,"write");let r=this.normalizePath(t);this.ensureParentDirs(r);let i=Ue(n),{chunks:a,size:o}=await lt(s,i);this.data.set(r,{type:"file",chunks:a,size:o,mode:420,mtime:new Date})}async appendFile(t,s,n){ce(t,"append");let r=this.normalizePath(t),i=this.data.get(r);if(i&&i.type==="directory")throw new Error(`EISDIR: illegal operation on a directory, write '${t}'`);let a=Ue(n),{chunks:o,size:l}=await lt(s,a);i?.type==="file"?this.data.set(r,{type:"file",chunks:[...i.chunks,...o],size:i.size+l,mode:i.mode,mtime:new Date}):(this.ensureParentDirs(r),this.data.set(r,{type:"file",chunks:o,size:l,mode:420,mtime:new Date}))}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){ce(t,"stat");let s=this.resolvePathWithSymlinks(t),n=this.data.get(s);if(!n)throw new Error(`ENOENT: no such file or directory, stat '${t}'`);let r=0;return n.type==="file"&&(r=n.size),{isFile:n.type==="file",isDirectory:n.type==="directory",isSymbolicLink:!1,mode:n.mode,size:r,mtime:n.mtime||new Date}}async lstat(t){ce(t,"lstat");let s=this.resolveIntermediateSymlinks(t),n=this.data.get(s);if(!n)throw new Error(`ENOENT: no such file or directory, lstat '${t}'`);if(n.type==="symlink")return{isFile:!1,isDirectory:!1,isSymbolicLink:!0,mode:n.mode,size:n.target.length,mtime:n.mtime||new Date};let r=0;return n.type==="file"&&(r=n.size),{isFile:n.type==="file",isDirectory:n.type==="directory",isSymbolicLink:!1,mode:n.mode,size:r,mtime:n.mtime||new Date}}resolveSymlink(t,s){if(s.startsWith("/"))return this.normalizePath(s);let n=this.dirname(t);return this.normalizePath(n==="/"?`/${s}`:`${n}/${s}`)}resolveIntermediateSymlinks(t){let s=this.normalizePath(t);if(s==="/")return"/";let n=s.slice(1).split("/");if(n.length<=1)return s;let r="",i=new Set;for(let a=0;a<n.length-1;a++){let o=n[a];r=`${r}/${o}`;let l=this.data.get(r),c=0,u=40;for(;l&&l.type==="symlink"&&c<u;){if(i.has(r))throw new Error(`ELOOP: too many levels of symbolic links, lstat '${t}'`);i.add(r),r=this.resolveSymlink(r,l.target),l=this.data.get(r),c++}if(c>=u)throw new Error(`ELOOP: too many levels of symbolic links, lstat '${t}'`)}return`${r}/${n[n.length-1]}`}resolvePathWithSymlinks(t){let s=this.normalizePath(t);if(s==="/")return"/";let n=s.slice(1).split("/"),r="",i=new Set;for(let a of n){r=`${r}/${a}`;let o=this.data.get(r),l=0,c=40;for(;o&&o.type==="symlink"&&l<c;){if(i.has(r))throw new Error(`ELOOP: too many levels of symbolic links, open '${t}'`);i.add(r),r=this.resolveSymlink(r,o.target),o=this.data.get(r),l++}if(l>=c)throw new Error(`ELOOP: too many levels of symbolic links, open '${t}'`)}return r}async mkdir(t,s){this.mkdirSync(t,s)}mkdirSync(t,s){ce(t,"mkdir");let n=this.normalizePath(t);if(this.data.has(n)){if(this.data.get(n)?.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 r=this.dirname(n);if(r!=="/"&&!this.data.has(r))if(s?.recursive)this.mkdirSync(r,{recursive:!0});else throw new Error(`ENOENT: no such file or directory, mkdir '${t}'`);this.data.set(n,{type:"directory",mode:493,mtime:new Date})}async readdir(t){return(await this.readdirWithFileTypes(t)).map(n=>n.name)}async readdirWithFileTypes(t){ce(t,"scandir");let s=this.normalizePath(t),n=this.data.get(s);if(!n)throw new Error(`ENOENT: no such file or directory, scandir '${t}'`);let r=new Set;for(;n&&n.type==="symlink";){if(r.has(s))throw new Error(`ELOOP: too many levels of symbolic links, scandir '${t}'`);r.add(s),s=this.resolveSymlink(s,n.target),n=this.data.get(s)}if(!n)throw new Error(`ENOENT: no such file or directory, scandir '${t}'`);if(n.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){ce(t,"rm");let n=this.normalizePath(t),r=this.data.get(n);if(!r){if(s?.force)return;throw new Error(`ENOENT: no such file or directory, rm '${t}'`)}if(r.type==="directory"){let i=await this.readdir(n);if(i.length>0){if(!s?.recursive)throw new Error(`ENOTEMPTY: directory not empty, rm '${t}'`);for(let a of i){let o=n==="/"?`/${a}`:`${n}/${a}`;await this.rm(o,s)}}}this.data.delete(n)}async cp(t,s,n){ce(t,"cp"),ce(s,"cp");let r=this.normalizePath(t),i=this.normalizePath(s),a=this.data.get(r);if(!a)throw new Error(`ENOENT: no such file or directory, cp '${t}'`);if(a.type==="file")this.ensureParentDirs(i),this.data.set(i,{type:"file",chunks:[...a.chunks],size:a.size,mode:a.mode,mtime:a.mtime});else if(a.type==="directory"){if(!n?.recursive)throw new Error(`EISDIR: is a directory, cp '${t}'`);await this.mkdir(i,{recursive:!0});let o=await this.readdir(r);for(let l of o){let c=r==="/"?`/${l}`:`${r}/${l}`,u=i==="/"?`/${l}`:`${i}/${l}`;await this.cp(c,u,n)}}}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){if(s.startsWith("/"))return this.normalizePath(s);let n=t==="/"?`/${s}`:`${t}/${s}`;return this.normalizePath(n)}async chmod(t,s){ce(t,"chmod");let n=this.normalizePath(t),r=this.data.get(n);if(!r)throw new Error(`ENOENT: no such file or directory, chmod '${t}'`);r.mode=s}async symlink(t,s){ce(s,"symlink");let n=this.normalizePath(s);if(this.data.has(n))throw new Error(`EEXIST: file already exists, symlink '${s}'`);this.ensureParentDirs(n),this.data.set(n,{type:"symlink",target:t,mode:511,mtime:new Date})}async link(t,s){ce(t,"link"),ce(s,"link");let n=this.normalizePath(t),r=this.normalizePath(s),i=this.data.get(n);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(r))throw new Error(`EEXIST: file already exists, link '${s}'`);this.ensureParentDirs(r),this.data.set(r,{type:"file",chunks:[...i.chunks],size:i.size,mode:i.mode,mtime:i.mtime})}async readlink(t){ce(t,"readlink");let s=this.normalizePath(t),n=this.data.get(s);if(!n)throw new Error(`ENOENT: no such file or directory, readlink '${t}'`);if(n.type!=="symlink")throw new Error(`EINVAL: invalid argument, readlink '${t}'`);return n.target}async realpath(t){ce(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,n){ce(t,"utimes");let r=this.normalizePath(t),i=this.resolvePathWithSymlinks(r),a=this.data.get(i);if(!a)throw new Error(`ENOENT: no such file or directory, utimes '${t}'`);a.mtime=n}};function lo(e){let t=e;return typeof t.mkdirSync=="function"&&typeof t.writeFileSync=="function"}function co(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 uo(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 fo(e){e.mkdirSync("/proc/self/fd",{recursive:!0}),e.writeFileSync("/proc/version",`${rr}
3
3
  `),e.writeFileSync("/proc/self/exe","/bin/bash"),e.writeFileSync("/proc/self/cmdline","bash\0"),e.writeFileSync("/proc/self/comm",`bash
4
- `),e.writeFileSync("/proc/self/status",ir()),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 _r(e,t){lo(e)&&(co(e,t),uo(e),fo(e))}var ho=["allexport","errexit","noglob","noclobber","noexec","nounset","pipefail","posix","verbose","xtrace"],po=["braceexpand","hashall","interactive-comments"];function Gs(e){let t=[],s=[...po.map(n=>({name:n,enabled:!0})),...ho.map(n=>({name:n,enabled:e[n]}))].sort((n,r)=>n.name.localeCompare(r.name));for(let n of s)n.enabled&&t.push(n.name);return t.join(":")}function ct(e){y(e.state.env,"SHELLOPTS",Gs(e.state.options))}var mo=["dotglob","expand_aliases","extglob","failglob","globskipdots","globstar","lastpipe","nocaseglob","nocasematch","nullglob","xpg_echo"];function qs(e){let t=[];for(let s of mo)e[s]&&t.push(s);return t.join(":")}function Zs(e){y(e.state.env,"BASHOPTS",qs(e.state.shoptOptions))}var go="BASH_ALIAS_";function xr(e){return e.parts.length!==1?!1:e.parts[0].type==="Literal"}function Tr(e){if(e.parts.length!==1)return null;let t=e.parts[0];return t.type==="Literal"?t.value:null}function Nr(e,t){let s=e.env.get(`${go}${t}`);return s!==void 0?H(s):void 0}function Js(e,t,s){if(!t.name||!xr(t.name))return t;let n=Tr(t.name);if(!n)return t;let r=Nr(e,n);if(!r||s.has(n))return t;try{s.add(n);let i=new Z,a=r,o=r.endsWith(" ");if(!o)for(let f of t.args){let d=Dr(f);a+=` ${d}`}let l;try{l=i.parse(a)}catch(f){if(f instanceof Zt)throw f;return t}if(l.statements.length!==1||l.statements[0].pipelines.length!==1||l.statements[0].pipelines[0].commands.length!==1)return Or(t,r);let u=l.statements[0].pipelines[0].commands[0];if(u.type!=="SimpleCommand")return Or(t,r);let c={...u,assignments:[...t.assignments,...u.assignments],redirections:[...u.redirections,...t.redirections],line:t.line};if(o&&t.args.length>0&&(c={...c,args:[...c.args,...t.args]},c.args.length>0)){let f=c.args[0];if(xr(f)){let d=Tr(f);if(d&&Nr(e,d)){let p={type:"SimpleCommand",name:f,args:c.args.slice(1),assignments:[],redirections:[]},m=Js(e,p,s);m!==p&&(c={...c,name:m.name,args:[...m.args]})}}}return c}catch(i){throw s.delete(n),i}}function Or(e,t){let s=t;for(let a of e.args){let o=Dr(a);s+=` ${o}`}let n=new Z,r=n.parseWordFromString("eval",!1,!1),i=n.parseWordFromString(`'${s.replace(/'/g,"'\\''")}'`,!1,!1);return{type:"SimpleCommand",name:r,args:[i],assignments:e.assignments,redirections:e.redirections,line:e.line}}function Dr(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(n=>n.type==="Literal"?n.value:`$${n.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 Ir(e,t){let s=t.parts.map(c=>c.type==="Literal"?c.value:"\0").join(""),n=s.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\(/);if(!n||!s.endsWith(")"))return null;let r=n[1],i=[],a=!1,o="",l=!1;for(let c of t.parts)if(c.type==="Literal"){let f=c.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 p of d)/^\s+$/.test(p)?(o||l)&&(i.push(o),o="",l=!1):p&&(o+=p)}}else if(a)if(c.type==="BraceExpansion")if(/^\[.+\]=/.test(o))o+=Kt({type:"Word",parts:[c]});else{(o||l)&&(i.push(o),o="",l=!1);let d=await We(e,{type:"Word",parts:[c]});i.push(...d.values)}else{(c.type==="SingleQuoted"||c.type==="DoubleQuoted"||c.type==="Escaped")&&(l=!0);let f=await z(e,{type:"Word",parts:[c]});o+=f}(o||l)&&i.push(o);let u=i.map(c=>/^\[.+\]=/.test(c)?c:c===""?"''":/[\s"'\\$`!*?[\]{}|&;<>()]/.test(c)&&!c.startsWith("'")&&!c.startsWith('"')?`'${c.replace(/'/g,"'\\''")}'`:c);return`${r}=(${u.join(" ")})`}async function Rr(e,t){let s=-1,n=-1,r=!1;for(let h=0;h<t.parts.length;h++){let b=t.parts[h];if(b.type==="Literal"){let S=b.value.indexOf("+=");if(S!==-1){let g=b.value.slice(0,S);if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(g)){s=h,n=S,r=!0;break}if(/^[a-zA-Z_][a-zA-Z0-9_]*\[[^\]]+\]$/.test(g)){s=h,n=S,r=!0;break}}let $=b.value.indexOf("=");if($!==-1&&($===0||b.value[$-1]!=="+")){let g=b.value.slice(0,$);if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(g)||/^[a-zA-Z_][a-zA-Z0-9_]*\[[^\]]+\]$/.test(g)){s=h,n=$;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=r?2:1,l=a.value.slice(0,n),u=a.value.slice(n+o),c=t.parts.slice(s+1),f="";for(let h of i)f+=await z(e,{type:"Word",parts:[h]});f+=l;let d={type:"Word",parts:u!==""?[{type:"Literal",value:u},...c]:c},p=d.parts.length>0?await z(e,d):"";return`${f}${r?"+=":"="}${p}`}var yo=["tar","yq","xan","sqlite3","python3","python"];function Lr(e){return yo.includes(e)}function B(){return{stdout:E(),stderr:E(),exitCode:0}}var ut={get stdout(){return E()},get stderr(){return E()},exitCode:0};function _e(e=E()){return{stdout:e,stderr:E(),exitCode:0}}function G(e){return{stdout:V(e),stderr:E(),exitCode:0}}function A(e,t=1){return{stdout:E(),stderr:V(e),exitCode:t}}function W(e,t,s){return{stdout:e instanceof Uint8Array?de(e):e,stderr:t instanceof Uint8Array?de(t):t,exitCode:s}}function ae(e){return{stdout:E(),stderr:E(),exitCode:e?0:1}}function De(e,t){throw new oe(e,t)}async function Ks(e,t){if(e.state.loopDepth===0){if(e.state.parentHasLoopContext)throw new ze;return B()}if(t.length>1)throw await U(e,2,`bash: break: too many arguments
5
- `,!0),new q(1);let s=1;if(t.length>0){let n=Number.parseInt(t[0],10);if(Number.isNaN(n)||n<1)throw await U(e,2,`bash: break: ${t[0]}: numeric argument required
6
- `,!0),new q(128);s=n}throw new $e(s)}async function Xs(e,t){let s,n=!1,r=!1,i=0;for(;i<t.length;)if(t[i]==="--"){i++;break}else if(t[i]==="-L")r=!1,i++;else if(t[i]==="-P")r=!0,i++;else if(t[i].startsWith("-")&&t[i]!=="-")i++;else break;let a=t.slice(i);if(a.length===0?s=T(e.state.env,"HOME","/"):a[0]==="~"?s=T(e.state.env,"HOME","/"):a[0]==="-"?(s=e.state.previousDir,n=!0):s=a[0],!s.startsWith("/")&&!s.startsWith("./")&&!s.startsWith("../")&&s!=="."&&s!==".."){let f=e.state.env.get("CDPATH");if(f){let d=H(f??L).split(":").filter(p=>p);for(let p of d){let m=p.startsWith("/")?`${p}/${s}`:`${e.state.cwd}/${p}/${s}`;try{if((await e.fs.stat(m)).isDirectory){s=m,n=!0;break}}catch{}}}}let l=(s.startsWith("/")?s:`${e.state.cwd}/${s}`).split("/").filter(f=>f&&f!=="."),u="";for(let f of l)if(f==="..")u=u.split("/").slice(0,-1).join("/")||"/";else{u=u?`${u}/${f}`:`/${f}`;try{if(!(await e.fs.stat(u)).isDirectory)return A(`bash: cd: ${s}: Not a directory
7
- `)}catch{return A(`bash: cd: ${s}: No such file or directory
8
- `)}}let c=u||"/";if(r)try{c=await e.fs.realpath(c)}catch{}return e.state.previousDir=e.state.cwd,e.state.cwd=c,y(e.state.env,"PWD",e.state.cwd),y(e.state.env,"OLDPWD",e.state.previousDir),n?G(`${c}
9
- `):_e()}function Ys(e,t){return e.fs.resolvePath(e.state.cwd,t)}var wo=["-e","-a","-f","-d","-r","-w","-x","-s","-L","-h","-k","-g","-u","-G","-O","-b","-c","-p","-S","-t","-N"];function ts(e){return wo.includes(e)}async function ss(e,t,s){let n=Ys(e,s);switch(t){case"-e":case"-a":return e.fs.exists(n);case"-f":return await e.fs.exists(n)?(await e.fs.stat(n)).isFile:!1;case"-d":return await e.fs.exists(n)?(await e.fs.stat(n)).isDirectory:!1;case"-r":return await e.fs.exists(n)?((await e.fs.stat(n)).mode&256)!==0:!1;case"-w":return await e.fs.exists(n)?((await e.fs.stat(n)).mode&128)!==0:!1;case"-x":return await e.fs.exists(n)?((await e.fs.stat(n)).mode&64)!==0:!1;case"-s":return await e.fs.exists(n)?(await e.fs.stat(n)).size>0:!1;case"-L":case"-h":try{return(await e.fs.lstat(n)).isSymbolicLink}catch{return!1}case"-k":return await e.fs.exists(n)?((await e.fs.stat(n)).mode&512)!==0:!1;case"-g":return await e.fs.exists(n)?((await e.fs.stat(n)).mode&1024)!==0:!1;case"-u":return await e.fs.exists(n)?((await e.fs.stat(n)).mode&2048)!==0:!1;case"-G":case"-O":return e.fs.exists(n);case"-b":return!1;case"-c":return["/dev/null","/dev/zero","/dev/random","/dev/urandom","/dev/tty","/dev/stdin","/dev/stdout","/dev/stderr"].some(i=>n===i||n.endsWith(i));case"-p":return!1;case"-S":return!1;case"-t":return!1;case"-N":return e.fs.exists(n);default:return!1}}var vo=["-nt","-ot","-ef"];function ns(e){return vo.includes(e)}async function rs(e,t,s,n){let r=Ys(e,s),i=Ys(e,n);switch(t){case"-nt":try{let a=await e.fs.stat(r),o=await e.fs.stat(i);return a.mtime>o.mtime}catch{return!1}case"-ot":try{let a=await e.fs.stat(r),o=await e.fs.stat(i);return a.mtime<o.mtime}catch{return!1}case"-ef":try{if(!await e.fs.exists(r)||!await e.fs.exists(i))return!1;let a=e.fs.resolvePath(e.state.cwd,r),o=e.fs.resolvePath(e.state.cwd,i);return a===o}catch{return!1}default:return!1}}var bo=new Set(["-eq","-ne","-lt","-le","-gt","-ge"]);function is(e){return bo.has(e)}function os(e,t,s){switch(e){case"-eq":return t===s;case"-ne":return t!==s;case"-lt":return t<s;case"-le":return t<=s;case"-gt":return t>s;case"-ge":return t>=s}}function Nt(e){return e==="="||e==="=="||e==="!="}function as(e,t,s,n=!1,r=!1,i=!1){if(n){let o=ft(t,s,r,i);return e==="!="?!o:o}if(r){let o=t.toLowerCase()===s.toLowerCase();return e==="!="?!o:o}let a=t===s;return e==="!="?!a:a}var So=new Set(["-z","-n"]);function ls(e){return So.has(e)}function cs(e,t){switch(e){case"-z":return t==="";case"-n":return t!==""}}async function us(e,t){let s=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(s){let n=s[1],r=s[2];if(e.state.associativeArrays?.has(n)){let o=r;return(o.startsWith("'")&&o.endsWith("'")||o.startsWith('"')&&o.endsWith('"'))&&(o=o.slice(1,-1)),o=o.replace(/\$([a-zA-Z_][a-zA-Z0-9_]*)/g,(l,u)=>T(e.state.env,u)),e.state.env.has(`${n}_${o}`)}let a;try{let o=new Z,l=le(o,r);a=await Q(e,l.expression)}catch{if(/^-?\d+$/.test(r))a=Number.parseInt(r,10);else{let o=T(e.state.env,r);a=o?Number.parseInt(o,10):0}}if(a<0){let o=he(e,n),l=e.state.currentLine;if(o.length===0)return await U(e,2,`bash: line ${l}: ${n}: bad array subscript
10
- `),!1;if(a=Math.max(...o)+1+a,a<0)return await U(e,2,`bash: line ${l}: ${n}: bad array subscript
11
- `),!1}return e.state.env.has(`${n}_${a}`)}return e.state.env.has(t)?!0:e.state.associativeArrays?.has(t)?Ze(e,t).length>0:he(e,t).length>0}async function Je(e,t){switch(t.type){case"CondBinary":{let s=await z(e,t.left),n=t.right.parts.length>0&&t.right.parts.every(i=>i.type==="SingleQuoted"||i.type==="DoubleQuoted"||i.type==="Escaped"&&t.operator!=="=~"),r;if(t.operator==="=~")if(n){let i=await z(e,t.right);r=pr(i)}else r=await gr(e,t.right);else Nt(t.operator)&&!n?r=await yr(e,t.right):r=await z(e,t.right);if(Nt(t.operator)){let i=e.state.shoptOptions.nocasematch;return as(t.operator,s,r,!n,i,!0)}if(is(t.operator))return os(t.operator,await Wr(e,s),await Wr(e,r));if(ns(t.operator))return rs(e,t.operator,s,r);switch(t.operator){case"=~":try{let i=e.state.shoptOptions.nocasematch,a=Co(r),l=Ct(a,i?"i":"").match(s);if(Le(e,"BASH_REMATCH"),l)for(let u=0;u<l.length;u++)y(e.state.env,`BASH_REMATCH_${u}`,l[u]||"");return l!==null}catch{throw new Error("syntax error in regular expression")}case"<":return s<r;case">":return s>r;default:return!1}}case"CondUnary":{let s=await z(e,t.operand);return ts(t.operator)?ss(e,t.operator,s):ls(t.operator)?cs(t.operator,s):t.operator==="-v"?await us(e,s):t.operator==="-o"?en(e,s):!1}case"CondNot":return e.state.shoptOptions.extglob&&t.operand.type==="CondGroup"&&t.operand.expression.type==="CondWord"?`!(${await z(e,t.operand.expression.word)})`!=="":!await Je(e,t.operand);case"CondAnd":return await Je(e,t.left)?await Je(e,t.right):!1;case"CondOr":return await Je(e,t.left)?!0:await Je(e,t.right);case"CondGroup":return await Je(e,t.expression);case"CondWord":return await z(e,t.word)!=="";default:return!1}}async function Ot(e,t){if(t.length===0)return W(L,L,1);if(t.length===1)return ae(!!t[0]);if(t.length===2){let n=t[0],r=t[1];return n==="("?A(`test: '(' without matching ')'
12
- `,2):ts(n)?ae(await ss(e,n,r)):ls(n)?ae(cs(n,r)):n==="!"?ae(!r):n==="-v"?ae(await us(e,r)):n==="-o"?ae(en(e,r)):n==="="||n==="=="||n==="!="||n==="<"||n===">"||n==="-eq"||n==="-ne"||n==="-lt"||n==="-le"||n==="-gt"||n==="-ge"||n==="-nt"||n==="-ot"||n==="-ef"?A(`test: ${n}: unary operator expected
13
- `,2):W(L,L,1)}if(t.length===3){let n=t[0],r=t[1],i=t[2];if(Nt(r))return ae(as(r,n,i));if(is(r)){let a=fs(n),o=fs(i);return!a.valid||!o.valid?W(L,L,2):ae(os(r,a.value,o.value))}if(ns(r))return ae(await rs(e,r,n,i));switch(r){case"-a":return ae(n!==""&&i!=="");case"-o":return ae(n!==""||i!=="");case">":return ae(n>i);case"<":return ae(n<i)}if(n==="!"){let a=await Ot(e,[r,i]);return W(L,a.stderr,a.exitCode===0?1:a.exitCode===1?0:a.exitCode)}if(n==="("&&i===")")return ae(r!=="")}if(t.length===4){if(t[0]==="!"){let n=await Ot(e,t.slice(1));return W(L,n.stderr,n.exitCode===0?1:n.exitCode===1?0:n.exitCode)}if(t[0]==="("&&t[3]===")")return Ot(e,[t[1],t[2]])}let s=await Vr(e,t,0);return s.pos<t.length?A(`test: too many arguments
14
- `,2):ae(s.value)}async function Vr(e,t,s){return Eo(e,t,s)}async function Eo(e,t,s){let{value:n,pos:r}=await Mr(e,t,s);for(;t[r]==="-o";){let i=await Mr(e,t,r+1);n=n||i.value,r=i.pos}return{value:n,pos:r}}async function Mr(e,t,s){let{value:n,pos:r}=await Qs(e,t,s);for(;t[r]==="-a";){let i=await Qs(e,t,r+1);n=n&&i.value,r=i.pos}return{value:n,pos:r}}async function Qs(e,t,s){if(t[s]==="!"){let{value:n,pos:r}=await Qs(e,t,s+1);return{value:!n,pos:r}}return $o(e,t,s)}async function $o(e,t,s){let n=t[s];if(n==="("){let{value:i,pos:a}=await Vr(e,t,s+1);return{value:i,pos:t[a]===")"?a+1:a}}let r=t[s+1];if(Nt(r)){let i=n,a=t[s+2]??"";return{value:as(r,i,a),pos:s+3}}if(is(r)){let i=fs(n),a=fs(t[s+2]??"0");return!i.valid||!a.valid?{value:!1,pos:s+3}:{value:os(r,i.value,a.value),pos:s+3}}if(ns(r)){let i=n,a=t[s+2]??"";return{value:await rs(e,r,i,a),pos:s+3}}if(ts(n)){let i=t[s+1]??"";return{value:await ss(e,n,i),pos:s+2}}if(ls(n)){let i=t[s+1]??"";return{value:cs(n,i),pos:s+2}}if(n==="-v"){let i=t[s+1]??"";return{value:await us(e,i),pos:s+2}}if(n==="-o"){let i=t[s+1]??"";return{value:en(e,i),pos:s+2}}return{value:n!==void 0&&n!=="",pos:s+1}}function ft(e,t,s=!1,n=!1){let r=`^${zr(t,n)}$`;return Ct(r,s?"is":"s").test(e)}function zr(e,t){let s="";for(let n=0;n<e.length;n++){let r=e[n];if(t&&(r==="@"||r==="*"||r==="+"||r==="?"||r==="!")&&n+1<e.length&&e[n+1]==="("){let i=jr(e,n+1);if(i!==-1){let a=e.slice(n+2,i),o=Br(a),l=o.map(c=>zr(c,t)),u=l.length>0?l.join("|"):"(?:)";if(r==="@")s+=`(?:${u})`;else if(r==="*")s+=`(?:${u})*`;else if(r==="+")s+=`(?:${u})+`;else if(r==="?")s+=`(?:${u})?`;else if(r==="!")if(i<e.length-1){let f=o.map(p=>Hr(p,t));if(f.every(p=>p!==null)&&f.every(p=>p===f[0])&&f[0]!==null){let p=f[0];if(p===0)s+="(?:.+)";else{let m=[];p>0&&m.push(`.{0,${p-1}}`),m.push(`.{${p+1},}`),m.push(`(?!(?:${u})).{${p}}`),s+=`(?:${m.join("|")})`}}else s+=`(?:(?!(?:${u})).)*?`}else s+=`(?!(?:${u})$).*`;n=i;continue}}if(r==="\\")if(n+1<e.length){let i=e[n+1];/[\\^$.|+(){}[\]*?]/.test(i)?s+=`\\${i}`:s+=i,n++}else s+="\\\\";else if(r==="*")s+=".*";else if(r==="?")s+=".";else if(r==="["){let i=e.indexOf("]",n+1);i!==-1?(s+=e.slice(n,i+1),n=i):s+="\\["}else/[\\^$.|+(){}]/.test(r)?s+=`\\${r}`:s+=r}return s}function jr(e,t){let s=1,n=t+1;for(;n<e.length&&s>0;){let r=e[n];if(r==="\\"){n+=2;continue}if(r==="(")s++;else if(r===")"&&(s--,s===0))return n;n++}return-1}function Br(e){let t=[],s="",n=0,r=0;for(;r<e.length;){let i=e[r];if(i==="\\"){s+=i,r+1<e.length?(s+=e[r+1],r+=2):r++;continue}i==="("?(n++,s+=i):i===")"?(n--,s+=i):i==="|"&&n===0?(t.push(s),s=""):s+=i,r++}return t.push(s),t}function Hr(e,t){let s=0,n=0;for(;n<e.length;){let r=e[n];if(t&&(r==="@"||r==="*"||r==="+"||r==="?"||r==="!")&&n+1<e.length&&e[n+1]==="("){let i=jr(e,n+1);if(i!==-1){if(r==="@"){let a=e.slice(n+2,i),l=Br(a).map(u=>Hr(u,t));if(l.every(u=>u!==null)&&l.every(u=>u===l[0])){s+=l[0],n=i+1;continue}return null}return null}}if(r==="*")return null;if(r==="?"){s+=1,n++;continue}if(r==="["){let i=e.indexOf("]",n+1);if(i!==-1){s+=1,n=i+1;continue}s+=1,n++;continue}if(r==="\\"){s+=1,n+=2;continue}s+=1,n++}return s}function en(e,t){let n=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 n?n():!1}async function Wr(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 Fr(t);try{let s=new Z,n=le(s,t);return await Q(e,n.expression)}catch{return Fr(t)}}function Ao(e,t){let s=0;for(let n of e){let r;if(n>="0"&&n<="9")r=n.charCodeAt(0)-48;else if(n>="a"&&n<="z")r=n.charCodeAt(0)-97+10;else if(n>="A"&&n<="Z")r=n.charCodeAt(0)-65+36;else if(n==="@")r=62;else if(n==="_")r=63;else return Number.NaN;if(r>=t)return Number.NaN;s=s*t+r}return s}function Fr(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,n=e.match(/^(\d+)#([a-zA-Z0-9@_]+)$/);if(n){let r=Number.parseInt(n[1],10);r>=2&&r<=64?s=Ao(n[2],r):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 fs(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 Co(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 n=ko(e,s);t+=n.converted,s=n.endIndex}else t+=e[s],s++;return t}function ko(e,t){let s=t+1,n="[";s<e.length&&(e[s]==="^"||e[s]==="!")&&(n+="^",s++);let r=!1;s<e.length&&e[s]==="]"&&(r=!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 u=e.indexOf(":]",s+2);if(u!==-1){let c=e.slice(s+2,u);a+=Po(c),s=u+2;continue}}if(l==="["&&s+1<e.length){let u=e[s+1];if(u==="."||u==="="){let c=`${u}]`,f=e.indexOf(c,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?(r&&(n+="\\]"),i&&(n+="\\["),n+=a,n+="]",{converted:n,endIndex:s}):{converted:"\\[",endIndex:t+1}}function Po(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 Fe(e){let t=[],s="",n=!1,r=!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==="'"&&!r){n||(a=!0),n=!n;continue}if(o==='"'&&!n){r||(a=!0),r=!r;continue}if((o===" "||o===" "||o===`
15
- `)&&!n&&!r){a&&(t.push(s),s="",a=!1);continue}s+=o,a=!0}return a&&t.push(s),t}function ds(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 n="";if(e[s]==="'"||e[s]==='"'){let i=e[s];for(s++;s<e.length&&e[s]!==i;)n+=e[s],s++;e[s]===i&&s++}else for(;s<e.length&&e[s]!=="]"&&e[s]!=="=";)n+=e[s],s++;for(;s<e.length&&e[s]!=="]";)s++;if(e[s]==="]"&&s++,e[s]!=="=")continue;s++;let r="";if(e[s]==="'"||e[s]==='"'){let i=e[s];for(s++;s<e.length&&e[s]!==i;)e[s]==="\\"&&s+1<e.length&&s++,r+=e[s],s++;e[s]===i&&s++}else for(;s<e.length&&!/\s/.test(e[s]);)r+=e[s],s++;t.push([n,r])}return t}function Ur(e){let t=e.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\((.*)\)$/s);if(t)return{name:t[1],isArray:!0,arrayElements:Fe(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 n=e.indexOf("=");return{name:e.slice(0,n),isArray:!1,value:e.slice(n+1)}}return{name:e,isArray:!1}}async function _o(e,t){try{let s=new Z,n=le(s,t);return await Q(e,n.expression)}catch{let s=parseInt(t,10);return Number.isNaN(s)?0:s}}async function Gr(e,t,s={}){let{name:n,isArray:r,arrayElements:i,value:a,arrayIndex:o}=t,{makeReadonly:l=!1,checkReadonly:u=!0}=s;if(u){let c=await ue(e,n);if(c)return c}if(r&&i){for(let c=0;c<i.length;c++)y(e.state.env,`${n}_${c}`,i[c]);y(e.state.env,`${n}__length`,String(i.length))}else if(o!==void 0&&a!==void 0){let c=await _o(e,o);y(e.state.env,`${n}_${c}`,a);let f=parseInt(T(e.state.env,`${n}__length`,"0"),10);c>=f&&y(e.state.env,`${n}__length`,String(c+1))}else a!==void 0&&y(e.state.env,n,a);return l&&be(e,n),null}function Ke(e,t){e.state.localVarDepth=e.state.localVarDepth||new Map,e.state.localVarDepth.set(t,e.state.callDepth)}function dt(e,t){return e.state.localVarDepth?.get(t)}function hs(e,t){e.state.localVarDepth?.delete(t)}function qr(e,t,s){e.state.localVarStack=e.state.localVarStack||new Map;let n=e.state.localVarStack.get(t)||[];n.push({value:s,scopeIndex:e.state.localScopes.length-1}),e.state.localVarStack.set(t,n)}function ps(e,t){let s=e.state.localVarStack?.get(t);if(!(!s||s.length===0))return s.pop()}function Zr(e,t){if(e.state.localVarStack)for(let[s,n]of e.state.localVarStack.entries()){for(;n.length>0&&n[n.length-1].scopeIndex===t;)n.pop();n.length===0&&e.state.localVarStack.delete(s)}}var tn=new Set([":",".","break","continue","eval","exec","exit","export","readonly","return","set","shift","trap","unset"]);function Jr(e){return tn.has(e)}var sn=new Set(["if","then","else","elif","fi","case","esac","for","select","while","until","do","done","in","function","{","}","time","[[","]]","!"]),Ue=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"]);function Dt(e,t){if(e.parts.length!==1)return!1;let s=e.parts[0];return s.type!=="Literal"?!1:t.includes(s.value)}function ms(e){if(!e.startsWith("__rw__:"))return null;let t=e.slice(7),s=t.indexOf(":");if(s===-1)return null;let n=Number.parseInt(t.slice(0,s),10);if(Number.isNaN(n)||n<0)return null;let r=s+1,i=t.slice(r,r+n),a=r+n+1,o=t.slice(a),l=o.indexOf(":");if(l===-1)return null;let u=Number.parseInt(o.slice(0,l),10);if(Number.isNaN(u)||u<0)return null;let c=o.slice(l+1);return{path:i,position:u,content:c}}async function Kr(e,t,s,n){try{if((await e.fs.stat(t)).isDirectory)return`bash: ${s}: Is a directory
4
+ `),e.writeFileSync("/proc/self/status",ir()),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 _r(e,t){lo(e)&&(co(e,t),uo(e),fo(e))}var ho=["allexport","errexit","noglob","noclobber","noexec","nounset","pipefail","posix","verbose","xtrace"],po=["braceexpand","hashall","interactive-comments"];function Gs(e){let t=[],s=[...po.map(n=>({name:n,enabled:!0})),...ho.map(n=>({name:n,enabled:e[n]}))].sort((n,r)=>n.name.localeCompare(r.name));for(let n of s)n.enabled&&t.push(n.name);return t.join(":")}function ct(e){y(e.state.env,"SHELLOPTS",Gs(e.state.options))}var mo=["dotglob","expand_aliases","extglob","failglob","globskipdots","globstar","lastpipe","nocaseglob","nocasematch","nullglob","xpg_echo"];function qs(e){let t=[];for(let s of mo)e[s]&&t.push(s);return t.join(":")}function Zs(e){y(e.state.env,"BASHOPTS",qs(e.state.shoptOptions))}var go="BASH_ALIAS_";function Tr(e){return e.parts.length!==1?!1:e.parts[0].type==="Literal"}function Nr(e){if(e.parts.length!==1)return null;let t=e.parts[0];return t.type==="Literal"?t.value:null}function xr(e,t){let s=e.env.get(`${go}${t}`);return s!==void 0?U(s):void 0}function Js(e,t,s){if(!t.name||!Tr(t.name))return t;let n=Nr(t.name);if(!n)return t;let r=xr(e,n);if(!r||s.has(n))return t;try{s.add(n);let i=new Z,a=r,o=r.endsWith(" ");if(!o)for(let f of t.args){let d=Ir(f);a+=` ${d}`}let l;try{l=i.parse(a)}catch(f){if(f instanceof Jt)throw f;return t}if(l.statements.length!==1||l.statements[0].pipelines.length!==1||l.statements[0].pipelines[0].commands.length!==1)return Or(t,r);let c=l.statements[0].pipelines[0].commands[0];if(c.type!=="SimpleCommand")return Or(t,r);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(Tr(f)){let d=Nr(f);if(d&&xr(e,d)){let p={type:"SimpleCommand",name:f,args:u.args.slice(1),assignments:[],redirections:[]},m=Js(e,p,s);m!==p&&(u={...u,name:m.name,args:[...m.args]})}}}return u}catch(i){throw s.delete(n),i}}function Or(e,t){let s=t;for(let a of e.args){let o=Ir(a);s+=` ${o}`}let n=new Z,r=n.parseWordFromString("eval",!1,!1),i=n.parseWordFromString(`'${s.replace(/'/g,"'\\''")}'`,!1,!1);return{type:"SimpleCommand",name:r,args:[i],assignments:e.assignments,redirections:e.redirections,line:e.line}}function Ir(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(n=>n.type==="Literal"?n.value:`$${n.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 Dr(e,t){let s=t.parts.map(u=>u.type==="Literal"?u.value:"\0").join(""),n=s.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\(/);if(!n||!s.endsWith(")"))return null;let r=n[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 p of d)/^\s+$/.test(p)?(o||l)&&(i.push(o),o="",l=!1):p&&(o+=p)}}else if(a)if(u.type==="BraceExpansion")if(/^\[.+\]=/.test(o))o+=Kt({type:"Word",parts:[u]});else{(o||l)&&(i.push(o),o="",l=!1);let d=await We(e,{type:"Word",parts:[u]});i.push(...d.values)}else{(u.type==="SingleQuoted"||u.type==="DoubleQuoted"||u.type==="Escaped")&&(l=!0);let f=await z(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`${r}=(${c.join(" ")})`}async function Rr(e,t){let s=-1,n=-1,r=!1;for(let h=0;h<t.parts.length;h++){let v=t.parts[h];if(v.type==="Literal"){let S=v.value.indexOf("+=");if(S!==-1){let b=v.value.slice(0,S);if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(b)){s=h,n=S,r=!0;break}if(/^[a-zA-Z_][a-zA-Z0-9_]*\[[^\]]+\]$/.test(b)){s=h,n=S,r=!0;break}}let E=v.value.indexOf("=");if(E!==-1&&(E===0||v.value[E-1]!=="+")){let b=v.value.slice(0,E);if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(b)||/^[a-zA-Z_][a-zA-Z0-9_]*\[[^\]]+\]$/.test(b)){s=h,n=E;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=r?2:1,l=a.value.slice(0,n),c=a.value.slice(n+o),u=t.parts.slice(s+1),f="";for(let h of i)f+=await z(e,{type:"Word",parts:[h]});f+=l;let d={type:"Word",parts:c!==""?[{type:"Literal",value:c},...u]:u},p=d.parts.length>0?await z(e,d):"";return`${f}${r?"+=":"="}${p}`}var yo=["tar","yq","xan","sqlite3","python3","python"];function Lr(e){return yo.includes(e)}function B(){return{stdout:A(),stderr:A(),exitCode:0}}var ut={get stdout(){return A()},get stderr(){return A()},exitCode:0};function _e(e=A()){return{stdout:e,stderr:A(),exitCode:0}}function G(e){return{stdout:V(e),stderr:A(),exitCode:0}}function C(e,t=1){return{stdout:A(),stderr:V(e),exitCode:t}}function W(e,t,s){return{stdout:e instanceof Uint8Array?de(e):e,stderr:t instanceof Uint8Array?de(t):t,exitCode:s}}function ae(e){return{stdout:A(),stderr:A(),exitCode:e?0:1}}function Ie(e,t){throw new oe(e,t)}async function Xs(e,t){if(e.state.loopDepth===0){if(e.state.parentHasLoopContext)throw new ze;return B()}if(t.length>1)throw await H(e,2,`bash: break: too many arguments
5
+ `,!0),new q(1);let s=1;if(t.length>0){let n=Number.parseInt(t[0],10);if(Number.isNaN(n)||n<1)throw await H(e,2,`bash: break: ${t[0]}: numeric argument required
6
+ `,!0),new q(128);s=n}throw new $e(s)}async function Ks(e,t){let s,n=!1,r=!1,i=0;for(;i<t.length;)if(t[i]==="--"){i++;break}else if(t[i]==="-L")r=!1,i++;else if(t[i]==="-P")r=!0,i++;else if(t[i].startsWith("-")&&t[i]!=="-")i++;else break;let a=t.slice(i);if(a.length===0?s=x(e.state.env,"HOME","/"):a[0]==="~"?s=x(e.state.env,"HOME","/"):a[0]==="-"?(s=e.state.previousDir,n=!0):s=a[0],!s.startsWith("/")&&!s.startsWith("./")&&!s.startsWith("../")&&s!=="."&&s!==".."){let f=e.state.env.get("CDPATH");if(f){let d=U(f??R).split(":").filter(p=>p);for(let p of d){let m=p.startsWith("/")?`${p}/${s}`:`${e.state.cwd}/${p}/${s}`;try{if((await e.fs.stat(m)).isDirectory){s=m,n=!0;break}}catch{}}}}let l=(s.startsWith("/")?s:`${e.state.cwd}/${s}`).split("/").filter(f=>f&&f!=="."),c="";for(let f of l)if(f==="..")c=c.split("/").slice(0,-1).join("/")||"/";else{c=c?`${c}/${f}`:`/${f}`;try{if(!(await e.fs.stat(c)).isDirectory)return C(`bash: cd: ${s}: Not a directory
7
+ `)}catch{return C(`bash: cd: ${s}: No such file or directory
8
+ `)}}let u=c||"/";if(r)try{u=await e.fs.realpath(u)}catch{}return e.state.previousDir=e.state.cwd,e.state.cwd=u,y(e.state.env,"PWD",e.state.cwd),y(e.state.env,"OLDPWD",e.state.previousDir),n?G(`${u}
9
+ `):_e()}function Ys(e,t){return e.fs.resolvePath(e.state.cwd,t)}var wo=["-e","-a","-f","-d","-r","-w","-x","-s","-L","-h","-k","-g","-u","-G","-O","-b","-c","-p","-S","-t","-N"];function ss(e){return wo.includes(e)}async function ns(e,t,s){let n=Ys(e,s);switch(t){case"-e":case"-a":return e.fs.exists(n);case"-f":return await e.fs.exists(n)?(await e.fs.stat(n)).isFile:!1;case"-d":return await e.fs.exists(n)?(await e.fs.stat(n)).isDirectory:!1;case"-r":return await e.fs.exists(n)?((await e.fs.stat(n)).mode&256)!==0:!1;case"-w":return await e.fs.exists(n)?((await e.fs.stat(n)).mode&128)!==0:!1;case"-x":return await e.fs.exists(n)?((await e.fs.stat(n)).mode&64)!==0:!1;case"-s":return await e.fs.exists(n)?(await e.fs.stat(n)).size>0:!1;case"-L":case"-h":try{return(await e.fs.lstat(n)).isSymbolicLink}catch{return!1}case"-k":return await e.fs.exists(n)?((await e.fs.stat(n)).mode&512)!==0:!1;case"-g":return await e.fs.exists(n)?((await e.fs.stat(n)).mode&1024)!==0:!1;case"-u":return await e.fs.exists(n)?((await e.fs.stat(n)).mode&2048)!==0:!1;case"-G":case"-O":return e.fs.exists(n);case"-b":return!1;case"-c":return["/dev/null","/dev/zero","/dev/random","/dev/urandom","/dev/tty","/dev/stdin","/dev/stdout","/dev/stderr"].some(i=>n===i||n.endsWith(i));case"-p":return!1;case"-S":return!1;case"-t":return!1;case"-N":return e.fs.exists(n);default:return!1}}var vo=["-nt","-ot","-ef"];function rs(e){return vo.includes(e)}async function is(e,t,s,n){let r=Ys(e,s),i=Ys(e,n);switch(t){case"-nt":try{let a=await e.fs.stat(r),o=await e.fs.stat(i);return a.mtime>o.mtime}catch{return!1}case"-ot":try{let a=await e.fs.stat(r),o=await e.fs.stat(i);return a.mtime<o.mtime}catch{return!1}case"-ef":try{if(!await e.fs.exists(r)||!await e.fs.exists(i))return!1;let a=e.fs.resolvePath(e.state.cwd,r),o=e.fs.resolvePath(e.state.cwd,i);return a===o}catch{return!1}default:return!1}}var bo=new Set(["-eq","-ne","-lt","-le","-gt","-ge"]);function os(e){return bo.has(e)}function as(e,t,s){switch(e){case"-eq":return t===s;case"-ne":return t!==s;case"-lt":return t<s;case"-le":return t<=s;case"-gt":return t>s;case"-ge":return t>=s}}function xt(e){return e==="="||e==="=="||e==="!="}function ls(e,t,s,n=!1,r=!1,i=!1){if(n){let o=ft(t,s,r,i);return e==="!="?!o:o}if(r){let o=t.toLowerCase()===s.toLowerCase();return e==="!="?!o:o}let a=t===s;return e==="!="?!a:a}var So=new Set(["-z","-n"]);function cs(e){return So.has(e)}function us(e,t){switch(e){case"-z":return t==="";case"-n":return t!==""}}async function fs(e,t){let s=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(s){let n=s[1],r=s[2];if(e.state.associativeArrays?.has(n)){let o=r;return(o.startsWith("'")&&o.endsWith("'")||o.startsWith('"')&&o.endsWith('"'))&&(o=o.slice(1,-1)),o=o.replace(/\$([a-zA-Z_][a-zA-Z0-9_]*)/g,(l,c)=>x(e.state.env,c)),e.state.env.has(`${n}_${o}`)}let a;try{let o=new Z,l=le(o,r);a=await Q(e,l.expression)}catch{if(/^-?\d+$/.test(r))a=Number.parseInt(r,10);else{let o=x(e.state.env,r);a=o?Number.parseInt(o,10):0}}if(a<0){let o=he(e,n),l=e.state.currentLine;if(o.length===0)return await H(e,2,`bash: line ${l}: ${n}: bad array subscript
10
+ `),!1;if(a=Math.max(...o)+1+a,a<0)return await H(e,2,`bash: line ${l}: ${n}: bad array subscript
11
+ `),!1}return e.state.env.has(`${n}_${a}`)}return e.state.env.has(t)?!0:e.state.associativeArrays?.has(t)?Ze(e,t).length>0:he(e,t).length>0}async function Je(e,t){switch(t.type){case"CondBinary":{let s=await z(e,t.left),n=t.right.parts.length>0&&t.right.parts.every(i=>i.type==="SingleQuoted"||i.type==="DoubleQuoted"||i.type==="Escaped"&&t.operator!=="=~"),r;if(t.operator==="=~")if(n){let i=await z(e,t.right);r=pr(i)}else r=await gr(e,t.right);else xt(t.operator)&&!n?r=await yr(e,t.right):r=await z(e,t.right);if(xt(t.operator)){let i=e.state.shoptOptions.nocasematch;return ls(t.operator,s,r,!n,i,!0)}if(os(t.operator))return as(t.operator,await Wr(e,s),await Wr(e,r));if(rs(t.operator))return is(e,t.operator,s,r);switch(t.operator){case"=~":try{let i=e.state.shoptOptions.nocasematch,a=Co(r),l=Ct(a,i?"i":"").match(s);if(Le(e,"BASH_REMATCH"),l)for(let c=0;c<l.length;c++)y(e.state.env,`BASH_REMATCH_${c}`,l[c]||"");return l!==null}catch{throw new Error("syntax error in regular expression")}case"<":return s<r;case">":return s>r;default:return!1}}case"CondUnary":{let s=await z(e,t.operand);return ss(t.operator)?ns(e,t.operator,s):cs(t.operator)?us(t.operator,s):t.operator==="-v"?await fs(e,s):t.operator==="-o"?en(e,s):!1}case"CondNot":return e.state.shoptOptions.extglob&&t.operand.type==="CondGroup"&&t.operand.expression.type==="CondWord"?`!(${await z(e,t.operand.expression.word)})`!=="":!await Je(e,t.operand);case"CondAnd":return await Je(e,t.left)?await Je(e,t.right):!1;case"CondOr":return await Je(e,t.left)?!0:await Je(e,t.right);case"CondGroup":return await Je(e,t.expression);case"CondWord":return await z(e,t.word)!=="";default:return!1}}async function Ot(e,t){if(t.length===0)return W(R,R,1);if(t.length===1)return ae(!!t[0]);if(t.length===2){let n=t[0],r=t[1];return n==="("?C(`test: '(' without matching ')'
12
+ `,2):ss(n)?ae(await ns(e,n,r)):cs(n)?ae(us(n,r)):n==="!"?ae(!r):n==="-v"?ae(await fs(e,r)):n==="-o"?ae(en(e,r)):n==="="||n==="=="||n==="!="||n==="<"||n===">"||n==="-eq"||n==="-ne"||n==="-lt"||n==="-le"||n==="-gt"||n==="-ge"||n==="-nt"||n==="-ot"||n==="-ef"?C(`test: ${n}: unary operator expected
13
+ `,2):W(R,R,1)}if(t.length===3){let n=t[0],r=t[1],i=t[2];if(xt(r))return ae(ls(r,n,i));if(os(r)){let a=ds(n),o=ds(i);return!a.valid||!o.valid?W(R,R,2):ae(as(r,a.value,o.value))}if(rs(r))return ae(await is(e,r,n,i));switch(r){case"-a":return ae(n!==""&&i!=="");case"-o":return ae(n!==""||i!=="");case">":return ae(n>i);case"<":return ae(n<i)}if(n==="!"){let a=await Ot(e,[r,i]);return W(R,a.stderr,a.exitCode===0?1:a.exitCode===1?0:a.exitCode)}if(n==="("&&i===")")return ae(r!=="")}if(t.length===4){if(t[0]==="!"){let n=await Ot(e,t.slice(1));return W(R,n.stderr,n.exitCode===0?1:n.exitCode===1?0:n.exitCode)}if(t[0]==="("&&t[3]===")")return Ot(e,[t[1],t[2]])}let s=await Vr(e,t,0);return s.pos<t.length?C(`test: too many arguments
14
+ `,2):ae(s.value)}async function Vr(e,t,s){return Eo(e,t,s)}async function Eo(e,t,s){let{value:n,pos:r}=await Mr(e,t,s);for(;t[r]==="-o";){let i=await Mr(e,t,r+1);n=n||i.value,r=i.pos}return{value:n,pos:r}}async function Mr(e,t,s){let{value:n,pos:r}=await Qs(e,t,s);for(;t[r]==="-a";){let i=await Qs(e,t,r+1);n=n&&i.value,r=i.pos}return{value:n,pos:r}}async function Qs(e,t,s){if(t[s]==="!"){let{value:n,pos:r}=await Qs(e,t,s+1);return{value:!n,pos:r}}return $o(e,t,s)}async function $o(e,t,s){let n=t[s];if(n==="("){let{value:i,pos:a}=await Vr(e,t,s+1);return{value:i,pos:t[a]===")"?a+1:a}}let r=t[s+1];if(xt(r)){let i=n,a=t[s+2]??"";return{value:ls(r,i,a),pos:s+3}}if(os(r)){let i=ds(n),a=ds(t[s+2]??"0");return!i.valid||!a.valid?{value:!1,pos:s+3}:{value:as(r,i.value,a.value),pos:s+3}}if(rs(r)){let i=n,a=t[s+2]??"";return{value:await is(e,r,i,a),pos:s+3}}if(ss(n)){let i=t[s+1]??"";return{value:await ns(e,n,i),pos:s+2}}if(cs(n)){let i=t[s+1]??"";return{value:us(n,i),pos:s+2}}if(n==="-v"){let i=t[s+1]??"";return{value:await fs(e,i),pos:s+2}}if(n==="-o"){let i=t[s+1]??"";return{value:en(e,i),pos:s+2}}return{value:n!==void 0&&n!=="",pos:s+1}}function ft(e,t,s=!1,n=!1){let r=`^${zr(t,n)}$`;return Ct(r,s?"is":"s").test(e)}function zr(e,t){let s="";for(let n=0;n<e.length;n++){let r=e[n];if(t&&(r==="@"||r==="*"||r==="+"||r==="?"||r==="!")&&n+1<e.length&&e[n+1]==="("){let i=jr(e,n+1);if(i!==-1){let a=e.slice(n+2,i),o=Br(a),l=o.map(u=>zr(u,t)),c=l.length>0?l.join("|"):"(?:)";if(r==="@")s+=`(?:${c})`;else if(r==="*")s+=`(?:${c})*`;else if(r==="+")s+=`(?:${c})+`;else if(r==="?")s+=`(?:${c})?`;else if(r==="!")if(i<e.length-1){let f=o.map(p=>Ur(p,t));if(f.every(p=>p!==null)&&f.every(p=>p===f[0])&&f[0]!==null){let p=f[0];if(p===0)s+="(?:.+)";else{let m=[];p>0&&m.push(`.{0,${p-1}}`),m.push(`.{${p+1},}`),m.push(`(?!(?:${c})).{${p}}`),s+=`(?:${m.join("|")})`}}else s+=`(?:(?!(?:${c})).)*?`}else s+=`(?!(?:${c})$).*`;n=i;continue}}if(r==="\\")if(n+1<e.length){let i=e[n+1];/[\\^$.|+(){}[\]*?]/.test(i)?s+=`\\${i}`:s+=i,n++}else s+="\\\\";else if(r==="*")s+=".*";else if(r==="?")s+=".";else if(r==="["){let i=e.indexOf("]",n+1);i!==-1?(s+=e.slice(n,i+1),n=i):s+="\\["}else/[\\^$.|+(){}]/.test(r)?s+=`\\${r}`:s+=r}return s}function jr(e,t){let s=1,n=t+1;for(;n<e.length&&s>0;){let r=e[n];if(r==="\\"){n+=2;continue}if(r==="(")s++;else if(r===")"&&(s--,s===0))return n;n++}return-1}function Br(e){let t=[],s="",n=0,r=0;for(;r<e.length;){let i=e[r];if(i==="\\"){s+=i,r+1<e.length?(s+=e[r+1],r+=2):r++;continue}i==="("?(n++,s+=i):i===")"?(n--,s+=i):i==="|"&&n===0?(t.push(s),s=""):s+=i,r++}return t.push(s),t}function Ur(e,t){let s=0,n=0;for(;n<e.length;){let r=e[n];if(t&&(r==="@"||r==="*"||r==="+"||r==="?"||r==="!")&&n+1<e.length&&e[n+1]==="("){let i=jr(e,n+1);if(i!==-1){if(r==="@"){let a=e.slice(n+2,i),l=Br(a).map(c=>Ur(c,t));if(l.every(c=>c!==null)&&l.every(c=>c===l[0])){s+=l[0],n=i+1;continue}return null}return null}}if(r==="*")return null;if(r==="?"){s+=1,n++;continue}if(r==="["){let i=e.indexOf("]",n+1);if(i!==-1){s+=1,n=i+1;continue}s+=1,n++;continue}if(r==="\\"){s+=1,n+=2;continue}s+=1,n++}return s}function en(e,t){let n=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 n?n():!1}async function Wr(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 Fr(t);try{let s=new Z,n=le(s,t);return await Q(e,n.expression)}catch{return Fr(t)}}function Ao(e,t){let s=0;for(let n of e){let r;if(n>="0"&&n<="9")r=n.charCodeAt(0)-48;else if(n>="a"&&n<="z")r=n.charCodeAt(0)-97+10;else if(n>="A"&&n<="Z")r=n.charCodeAt(0)-65+36;else if(n==="@")r=62;else if(n==="_")r=63;else return Number.NaN;if(r>=t)return Number.NaN;s=s*t+r}return s}function Fr(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,n=e.match(/^(\d+)#([a-zA-Z0-9@_]+)$/);if(n){let r=Number.parseInt(n[1],10);r>=2&&r<=64?s=Ao(n[2],r):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 ds(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 Co(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 n=ko(e,s);t+=n.converted,s=n.endIndex}else t+=e[s],s++;return t}function ko(e,t){let s=t+1,n="[";s<e.length&&(e[s]==="^"||e[s]==="!")&&(n+="^",s++);let r=!1;s<e.length&&e[s]==="]"&&(r=!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+=Po(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?(r&&(n+="\\]"),i&&(n+="\\["),n+=a,n+="]",{converted:n,endIndex:s}):{converted:"\\[",endIndex:t+1}}function Po(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 Fe(e){let t=[],s="",n=!1,r=!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==="'"&&!r){n||(a=!0),n=!n;continue}if(o==='"'&&!n){r||(a=!0),r=!r;continue}if((o===" "||o===" "||o===`
15
+ `)&&!n&&!r){a&&(t.push(s),s="",a=!1);continue}s+=o,a=!0}return a&&t.push(s),t}function hs(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 n="";if(e[s]==="'"||e[s]==='"'){let i=e[s];for(s++;s<e.length&&e[s]!==i;)n+=e[s],s++;e[s]===i&&s++}else for(;s<e.length&&e[s]!=="]"&&e[s]!=="=";)n+=e[s],s++;for(;s<e.length&&e[s]!=="]";)s++;if(e[s]==="]"&&s++,e[s]!=="=")continue;s++;let r="";if(e[s]==="'"||e[s]==='"'){let i=e[s];for(s++;s<e.length&&e[s]!==i;)e[s]==="\\"&&s+1<e.length&&s++,r+=e[s],s++;e[s]===i&&s++}else for(;s<e.length&&!/\s/.test(e[s]);)r+=e[s],s++;t.push([n,r])}return t}function Hr(e){let t=e.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\((.*)\)$/s);if(t)return{name:t[1],isArray:!0,arrayElements:Fe(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 n=e.indexOf("=");return{name:e.slice(0,n),isArray:!1,value:e.slice(n+1)}}return{name:e,isArray:!1}}async function _o(e,t){try{let s=new Z,n=le(s,t);return await Q(e,n.expression)}catch{let s=parseInt(t,10);return Number.isNaN(s)?0:s}}async function Gr(e,t,s={}){let{name:n,isArray:r,arrayElements:i,value:a,arrayIndex:o}=t,{makeReadonly:l=!1,checkReadonly:c=!0}=s;if(c){let u=await ue(e,n);if(u)return u}if(r&&i){for(let u=0;u<i.length;u++)y(e.state.env,`${n}_${u}`,i[u]);y(e.state.env,`${n}__length`,String(i.length))}else if(o!==void 0&&a!==void 0){let u=await _o(e,o);y(e.state.env,`${n}_${u}`,a);let f=parseInt(x(e.state.env,`${n}__length`,"0"),10);u>=f&&y(e.state.env,`${n}__length`,String(u+1))}else a!==void 0&&y(e.state.env,n,a);return l&&be(e,n),null}function Xe(e,t){e.state.localVarDepth=e.state.localVarDepth||new Map,e.state.localVarDepth.set(t,e.state.callDepth)}function dt(e,t){return e.state.localVarDepth?.get(t)}function ps(e,t){e.state.localVarDepth?.delete(t)}function qr(e,t,s){e.state.localVarStack=e.state.localVarStack||new Map;let n=e.state.localVarStack.get(t)||[];n.push({value:s,scopeIndex:e.state.localScopes.length-1}),e.state.localVarStack.set(t,n)}function ms(e,t){let s=e.state.localVarStack?.get(t);if(!(!s||s.length===0))return s.pop()}function Zr(e,t){if(e.state.localVarStack)for(let[s,n]of e.state.localVarStack.entries()){for(;n.length>0&&n[n.length-1].scopeIndex===t;)n.pop();n.length===0&&e.state.localVarStack.delete(s)}}var tn=new Set([":",".","break","continue","eval","exec","exit","export","readonly","return","set","shift","trap","unset"]);function Jr(e){return tn.has(e)}var sn=new Set(["if","then","else","elif","fi","case","esac","for","select","while","until","do","done","in","function","{","}","time","[[","]]","!"]),He=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"]);function It(e,t){if(e.parts.length!==1)return!1;let s=e.parts[0];return s.type!=="Literal"?!1:t.includes(s.value)}function gs(e){if(!e.startsWith("__rw__:"))return null;let t=e.slice(7),s=t.indexOf(":");if(s===-1)return null;let n=Number.parseInt(t.slice(0,s),10);if(Number.isNaN(n)||n<0)return null;let r=s+1,i=t.slice(r,r+n),a=r+n+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 Xr(e,t,s,n){try{if((await e.fs.stat(t)).isDirectory)return`bash: ${s}: Is a directory
16
16
  `;if(n.checkNoclobber&&e.state.options.noclobber&&!n.isClobber&&s!=="/dev/null")return`bash: ${s}: cannot overwrite existing file
17
- `}catch{}return null}async function gs(e,t){if(t.target.type==="HereDoc")throw new Error("Here-document targets are not words");return t.operator===">&"||t.operator==="<&"?wr(e,t.target)?{error:`bash: $@: ambiguous redirect
17
+ `}catch{}return null}async function ys(e,t){if(t.target.type==="HereDoc")throw new Error("Here-document targets are not words");return t.operator===">&"||t.operator==="<&"?wr(e,t.target)?{error:`bash: $@: ambiguous redirect
18
18
  `}:{target:await z(e,t.target)}:vr(e,t.target)}function nn(e){return e.includes("\0")?`bash: ${e.replace(/\0/g,"")}: No such file or directory
19
19
  `:null}function Ve(e){return`bash: ${e}: Bad file descriptor
20
- `}function rn(e,t=()=>!1){for(e.state.nextFd===void 0&&(e.state.nextFd=10);t(e.state.nextFd);)e.state.nextFd++;return e.state.nextFd++}async function ht(e,t,s){for(let n of t){if(!n.fdVariable)continue;e.state.fileDescriptors||(e.state.fileDescriptors=new Map);let r;if((n.operator===">&"||n.operator==="<&")&&n.target.type==="Word"&&(r=await z(e,n.target),r==="-")){if(e.state.env.has(n.fdVariable)){let a=Number.parseInt(T(e.state.env,n.fdVariable),10);Number.isNaN(a)||e.state.fileDescriptors.delete(a)}continue}let i=rn(e,s);if(y(e.state.env,n.fdVariable,String(i)),n.target.type==="Word"){let a=r??await z(e,n.target);if(n.operator===">&"||n.operator==="<&"){let o=Number.parseInt(a,10);if(!Number.isNaN(o)){let l=e.state.fileDescriptors.get(o);if(l!==void 0)e.state.fileDescriptors.set(i,l);else return W(E(),V(Ve(o)),1);continue}}if(n.operator===">"||n.operator===">>"||n.operator===">|"||n.operator==="&>"||n.operator==="&>>"){let o=e.fs.resolvePath(e.state.cwd,a);(n.operator===">"||n.operator===">|"||n.operator==="&>")&&await e.fs.writeFile(o,""),e.state.fileDescriptors.set(i,`__file__:${o}`)}else if(n.operator==="<<<")e.state.fileDescriptors.set(i,`${a}
21
- `);else if(n.operator==="<"||n.operator==="<>")try{let o=e.fs.resolvePath(e.state.cwd,a),l=await e.fs.readFileText(o);e.state.fileDescriptors.set(i,l)}catch{return W(E(),V(`bash: ${a}: No such file or directory
22
- `),1)}}}return null}var xo={write(){}},To={write(){let e=new Error(`bash: echo: write error: No space left on device
23
- `);return e.code="ENOSPC",Promise.reject(e)}};function No(e){return e.target.type==="HereDoc"||e.operator==="<"||e.operator==="<>"||e.operator==="<<<"||e.operator==="<<"||e.operator==="<<-"}function on(e,t){return{...e,target:{type:"Word",parts:[{type:"Literal",value:t}]}}}function ws(e,t){let s=Promise.resolve();return{write(n){let r=s.then(()=>e.fs.appendFile(t,n));return s=r.catch(()=>{}),r}}}function Yr(e,t,s,n=new Set){let r=t.bindings.get(s),i=r?.sink;if(i)return i;if(n.has(s))return;n.add(s);let a=r?.descriptor,o;if(a?.startsWith("__file__:"))o=ws(e,a.slice(9));else if(a?.startsWith("__file_append__:"))o=ws(e,a.slice(16));else if(a?.startsWith("__rw__:")){let l=ms(a);l&&(o=ws(e,l.path))}else if(a?.startsWith("__dupout__:")){let l=Number.parseInt(a.slice(11),10);Number.isNaN(l)||(o=Yr(e,t,l,n))}return o&&t.bindings.set(s,{...r,sink:o}),o}async function Xr(e,t,s,n,r=!1){if(s==="/dev/null")return{sink:xo,descriptor:"__file__:/dev/null"};if(s==="/dev/full")return{sink:To,descriptor:"__file__:/dev/full"};if(s==="/dev/stdout"||s==="/dev/stderr"){let o=s==="/dev/stdout"?1:2,l=t.bindings.get(o),u=l?.sink;return u?{sink:u,descriptor:l.descriptor??`__dupout__:${o}`}:{error:Ve(o)}}let i=e.fs.resolvePath(e.state.cwd,s),a=await Kr(e,i,s,{checkNoclobber:n==="truncate",isClobber:r});return a?{error:a}:(n==="truncate"?await e.fs.writeFile(i,""):await e.fs.appendFile(i,new Uint8Array),{sink:ws(e,i),descriptor:n==="append"?`__file_append__:${i}`:`__file__:${i}`})}function tt(e,t,s){e.state.fileDescriptors||(e.state.fileDescriptors=new Map),e.state.fileDescriptors.set(t,s)}function Oo(e,t){return e.bindings.get(t)?.descriptor??`__dupout__:${t}`}function an(e,t,s,n,r){if(!(!r&&!t.fdVariable)){if(t.fdVariable&&n.startsWith("__file_append__:")){tt(e,s,`__file__:${n.slice(16)}`);return}tt(e,s,n)}}function ys(e,t,s,n,r,i=!0){let a=e.state.fileDescriptors?.get(s),o=r?.startsWith("__file_append__:")?`__file__:${r.slice(16)}`:r;(n||t.fdVariable)&&i&&a!==void 0&&a===o&&e.state.fileDescriptors?.delete(s)}function xe(e,t,s){return{channels:e,legacyRedirections:t,error:A(s)}}async function Te(e,t,s,n={}){let r={bindings:new Map(t.bindings),parent:t,overrides:new Set};for(let[o,l]of e.state.fileDescriptors??[]){let u=r.bindings.get(o);u?.descriptor===void 0&&r.bindings.set(o,{...u,descriptor:l})}let i=[],a=n.persistent===!0;for(let o of s){let l;if(o.operator==="<&"&&o.target.type==="Word"){let S=await gs(e,o);if("error"in S)return xe(r,i,S.error);l=S.target;let $=l.startsWith("&")?l.slice(1):l,g=/^\d+-?$/.test($);if(l!=="-"&&!g)return xe(r,i,`bash: ${l}: ambiguous redirect
24
- `);if(!o.fdVariable&&(o.fd??0)===0){i.push(on(o,l));continue}}if(o.operator==="<"&&!o.fdVariable&&o.target.type==="Word"){let S=await gs(e,o);if("error"in S)return xe(r,i,S.error);let $=nn(S.target);if($)return xe(r,i,$);try{let g=e.fs.resolvePath(e.state.cwd,S.target);await e.fs.readFile(g)}catch{return xe(r,i,`bash: ${S.target}: No such file or directory
25
- `)}i.push(on(o,S.target));continue}if(No(o)){if(o.fdVariable&&o.target.type==="Word"){let S=await ht(e,[o],v=>Ws(r,v));if(S)return{channels:r,legacyRedirections:i,error:S};let $=Number.parseInt(T(e.state.env,o.fdVariable),10),g=e.state.fileDescriptors?.get($);if(!Number.isNaN($)&&g!==void 0){let v=r.bindings.get($);r.bindings.set($,{...v,descriptor:g})}}else i.push(o);continue}let u;if(l!==void 0)u=l;else{let S=await gs(e,o);if("error"in S)return xe(r,i,S.error);u=S.target}let c=nn(u);if(c)return xe(r,i,c);if((o.operator===">&"||o.operator==="<&")&&u==="-"&&o.fdVariable){if(e.state.env.has(o.fdVariable)){let S=Number.parseInt(T(e.state.env,o.fdVariable),10);if(!Number.isNaN(S)){let $=r.bindings.get(S)?.descriptor,g=_t(r,S);ys(e,o,S,a,$,g)}}continue}let f=o.fdVariable?rn(e,S=>Ws(r,S)):o.fd??(o.operator==="<&"?0:1);if(o.fdVariable&&y(e.state.env,o.fdVariable,String(f)),!Number.isInteger(f)||f<0)return xe(r,i,Ve(f));if(o.operator===">"||o.operator===">|"||o.operator===">>"||o.operator==="&>"||o.operator==="&>>"){let S=o.operator===">>"||o.operator==="&>>",$=await Xr(e,r,u,S?"append":"truncate",o.operator===">|");if("error"in $)return xe(r,i,$.error);o.operator==="&>"||o.operator==="&>>"?(r.bindings.set(1,{sink:$.sink,descriptor:$.descriptor}),r.bindings.set(2,{sink:$.sink,descriptor:$.descriptor}),r.overrides?.add(1),r.overrides?.add(2),a&&(tt(e,1,$.descriptor),tt(e,2,$.descriptor))):(o.fdVariable?Pt(r,f,$.sink,$.descriptor):(r.bindings.set(f,{sink:$.sink,descriptor:$.descriptor}),r.overrides?.add(f)),an(e,o,f,$.descriptor,a));continue}if(o.operator!==">&"&&o.operator!=="<&"){i.push(o);continue}if(u==="-"){let S=r.bindings.get(f)?.descriptor;r.overrides?.add(f),r.bindings.set(f,{descriptor:Jt}),ys(e,o,f,a,S);continue}let d=u.endsWith("-"),p=d?u.slice(0,-1):u,m=p.startsWith("&")?p.slice(1):p,h=/^\d+$/.test(m)?Number.parseInt(m,10):Number.NaN;if(!Number.isNaN(h)){let S=Yr(e,r,h);if(!S){let g=r.bindings.get(h)?.descriptor;if(g===Jt)return xe(r,i,Ve(h));if(o.operator==="<&"&&o.fdVariable&&g!==void 0){if(r.bindings.set(f,{descriptor:g}),tt(e,f,g),d){let v=_t(r,h);ys(e,o,h,a,g,v)}continue}if(o.operator==="<&"&&!o.fdVariable){i.push(on(o,u));continue}return xe(r,i,Ve(h))}let $=Oo(r,h);if(o.fdVariable?Pt(r,f,S,$):r.bindings.set(f,{sink:S,descriptor:$}),an(e,o,f,$,a),d){let g=!0;o.fdVariable?g=_t(r,h):(r.overrides?.add(h),r.bindings.set(h,{descriptor:Jt}),n.persistMovedSource&&r.parent&&(g=_t(r.parent,h))),ys(e,o,h,a||n.persistMovedSource===!0,$,g)}o.fdVariable||r.overrides?.add(f);continue}if(o.operator==="<&")return xe(r,i,`bash: ${u}: ambiguous redirect
26
- `);let b=await Xr(e,r,u,"truncate");if("error"in b)return xe(r,i,b.error);o.fd==null&&!o.fdVariable?(r.bindings.set(1,{sink:b.sink,descriptor:b.descriptor}),r.bindings.set(2,{sink:b.sink,descriptor:b.descriptor}),r.overrides?.add(1),r.overrides?.add(2),a&&(tt(e,1,b.descriptor),tt(e,2,b.descriptor))):(o.fdVariable?Pt(r,f,b.sink,b.descriptor):(r.bindings.set(f,{sink:b.sink,descriptor:b.descriptor}),r.overrides?.add(f)),an(e,o,f,b.descriptor,a))}return{channels:r,legacyRedirections:i}}async function Qr(e,t){let s=e.outputChannels,n=await Te(e,s,t,{persistent:!0});if(n.error)return n;for(let r of n.channels.overrides??[]){let i=n.channels.bindings.get(r);i?.descriptor!==void 0&&Pt(s,r,i.sink,i.descriptor)}return{...n,channels:s}}async function ei(e,t){if(e.state.options.posix&&tn.has(t.name)){let n=`bash: line ${e.state.currentLine}: \`${t.name}': is a special builtin
27
- `;throw await U(e,2,n,!0),new q(2)}let s={...t,sourceFile:t.sourceFile??e.state.currentSource??"main"};return e.state.functions.set(t.name,s),B()}async function Do(e,t){let s=E(),n=!1;for(let r of t)if(!r.fdVariable){if((r.operator==="<<"||r.operator==="<<-")&&r.target.type==="HereDoc"){let i=r.target,a=await z(e,i.content);i.stripTabs&&(a=a.split(`
20
+ `}async function Dt(e,t){try{if((await e.fs.stat(e.fs.resolvePath(e.state.cwd,t))).isDirectory)return`bash: ${t}: Is a directory
21
+ `}catch{}return`bash: ${t}: No such file or directory
22
+ `}function rn(e,t=()=>!1){for(e.state.nextFd===void 0&&(e.state.nextFd=10);t(e.state.nextFd);)e.state.nextFd++;return e.state.nextFd++}async function ht(e,t,s){for(let n of t){if(!n.fdVariable)continue;e.state.fileDescriptors||(e.state.fileDescriptors=new Map);let r;if((n.operator===">&"||n.operator==="<&")&&n.target.type==="Word"&&(r=await z(e,n.target),r==="-")){if(e.state.env.has(n.fdVariable)){let a=Number.parseInt(x(e.state.env,n.fdVariable),10);Number.isNaN(a)||e.state.fileDescriptors.delete(a)}continue}let i=rn(e,s);if(y(e.state.env,n.fdVariable,String(i)),n.target.type==="Word"){let a=r??await z(e,n.target);if(n.operator===">&"||n.operator==="<&"){let o=Number.parseInt(a,10);if(!Number.isNaN(o)){let l=e.state.fileDescriptors.get(o);if(l!==void 0)e.state.fileDescriptors.set(i,l);else return W(A(),V(Ve(o)),1);continue}}if(n.operator===">"||n.operator===">>"||n.operator===">|"||n.operator==="&>"||n.operator==="&>>"){let o=e.fs.resolvePath(e.state.cwd,a);(n.operator===">"||n.operator===">|"||n.operator==="&>")&&await e.fs.writeFile(o,""),e.state.fileDescriptors.set(i,`__file__:${o}`)}else if(n.operator==="<<<")e.state.fileDescriptors.set(i,`${a}
23
+ `);else if(n.operator==="<"||n.operator==="<>")try{let o=e.fs.resolvePath(e.state.cwd,a),l=await e.fs.readFileText(o);e.state.fileDescriptors.set(i,l)}catch{return W(A(),V(`bash: ${a}: No such file or directory
24
+ `),1)}}}return null}var To={write(){}},No={write(){let e=new Error(`bash: echo: write error: No space left on device
25
+ `);return e.code="ENOSPC",Promise.reject(e)}};function xo(e){return e.target.type==="HereDoc"||e.operator==="<"||e.operator==="<>"||e.operator==="<<<"||e.operator==="<<"||e.operator==="<<-"}function on(e,t){return{...e,target:{type:"Word",parts:[{type:"Literal",value:t}]}}}function vs(e,t){let s=Promise.resolve();return{write(n){let r=s.then(()=>e.fs.appendFile(t,n));return s=r.catch(()=>{}),r}}}function Yr(e,t,s,n=new Set){let r=t.bindings.get(s),i=r?.sink;if(i)return i;if(n.has(s))return;n.add(s);let a=r?.descriptor,o;if(a?.startsWith("__file__:"))o=vs(e,a.slice(9));else if(a?.startsWith("__file_append__:"))o=vs(e,a.slice(16));else if(a?.startsWith("__rw__:")){let l=gs(a);l&&(o=vs(e,l.path))}else if(a?.startsWith("__dupout__:")){let l=Number.parseInt(a.slice(11),10);Number.isNaN(l)||(o=Yr(e,t,l,n))}return o&&t.bindings.set(s,{...r,sink:o}),o}async function Kr(e,t,s,n,r=!1){if(s==="/dev/null")return{sink:To,descriptor:"__file__:/dev/null"};if(s==="/dev/full")return{sink:No,descriptor:"__file__:/dev/full"};if(s==="/dev/stdout"||s==="/dev/stderr"){let o=s==="/dev/stdout"?1:2,l=t.bindings.get(o),c=l?.sink;return c?{sink:c,descriptor:l.descriptor??`__dupout__:${o}`}:{error:Ve(o)}}let i=e.fs.resolvePath(e.state.cwd,s),a=await Xr(e,i,s,{checkNoclobber:n==="truncate",isClobber:r});return a?{error:a}:(n==="truncate"?await e.fs.writeFile(i,""):await e.fs.appendFile(i,new Uint8Array),{sink:vs(e,i),descriptor:n==="append"?`__file_append__:${i}`:`__file__:${i}`})}function tt(e,t,s){e.state.fileDescriptors||(e.state.fileDescriptors=new Map),e.state.fileDescriptors.set(t,s)}function Oo(e,t){return e.bindings.get(t)?.descriptor??`__dupout__:${t}`}function an(e,t,s,n,r){if(!(!r&&!t.fdVariable)){if(t.fdVariable&&n.startsWith("__file_append__:")){tt(e,s,`__file__:${n.slice(16)}`);return}tt(e,s,n)}}function ws(e,t,s,n,r,i=!0){let a=e.state.fileDescriptors?.get(s),o=r?.startsWith("__file_append__:")?`__file__:${r.slice(16)}`:r;(n||t.fdVariable)&&i&&a!==void 0&&a===o&&e.state.fileDescriptors?.delete(s)}function Te(e,t,s){return{channels:e,legacyRedirections:t,error:C(s)}}async function Ne(e,t,s,n={}){let r={bindings:new Map(t.bindings),parent:t,overrides:new Set};for(let[o,l]of e.state.fileDescriptors??[]){let c=r.bindings.get(o);c?.descriptor===void 0&&r.bindings.set(o,{...c,descriptor:l})}let i=[],a=n.persistent===!0;for(let o of s){let l;if(o.operator==="<&"&&o.target.type==="Word"){let S=await ys(e,o);if("error"in S)return Te(r,i,S.error);l=S.target;let E=l.startsWith("&")?l.slice(1):l,b=/^\d+-?$/.test(E);if(l!=="-"&&!b)return Te(r,i,`bash: ${l}: ambiguous redirect
26
+ `);if(!o.fdVariable&&(o.fd??0)===0){i.push(on(o,l));continue}}if(o.operator==="<"&&!o.fdVariable&&o.target.type==="Word"){let S=await ys(e,o);if("error"in S)return Te(r,i,S.error);let E=nn(S.target);if(E)return Te(r,i,E);try{let b=e.fs.resolvePath(e.state.cwd,S.target),g=await e.fs.stat(b)}catch{return Te(r,i,`bash: ${S.target}: No such file or directory
27
+ `)}i.push(on(o,S.target));continue}if(xo(o)){if(o.fdVariable&&o.target.type==="Word"){let S=await ht(e,[o],g=>Ws(r,g));if(S)return{channels:r,legacyRedirections:i,error:S};let E=Number.parseInt(x(e.state.env,o.fdVariable),10),b=e.state.fileDescriptors?.get(E);if(!Number.isNaN(E)&&b!==void 0){let g=r.bindings.get(E);r.bindings.set(E,{...g,descriptor:b})}}else i.push(o);continue}let c;if(l!==void 0)c=l;else{let S=await ys(e,o);if("error"in S)return Te(r,i,S.error);c=S.target}let u=nn(c);if(u)return Te(r,i,u);if((o.operator===">&"||o.operator==="<&")&&c==="-"&&o.fdVariable){if(e.state.env.has(o.fdVariable)){let S=Number.parseInt(x(e.state.env,o.fdVariable),10);if(!Number.isNaN(S)){let E=r.bindings.get(S)?.descriptor,b=_t(r,S);ws(e,o,S,a,E,b)}}continue}let f=o.fdVariable?rn(e,S=>Ws(r,S)):o.fd??(o.operator==="<&"?0:1);if(o.fdVariable&&y(e.state.env,o.fdVariable,String(f)),!Number.isInteger(f)||f<0)return Te(r,i,Ve(f));if(o.operator===">"||o.operator===">|"||o.operator===">>"||o.operator==="&>"||o.operator==="&>>"){let S=o.operator===">>"||o.operator==="&>>",E=await Kr(e,r,c,S?"append":"truncate",o.operator===">|");if("error"in E)return Te(r,i,E.error);o.operator==="&>"||o.operator==="&>>"?(r.bindings.set(1,{sink:E.sink,descriptor:E.descriptor}),r.bindings.set(2,{sink:E.sink,descriptor:E.descriptor}),r.overrides?.add(1),r.overrides?.add(2),a&&(tt(e,1,E.descriptor),tt(e,2,E.descriptor))):(o.fdVariable?Pt(r,f,E.sink,E.descriptor):(r.bindings.set(f,{sink:E.sink,descriptor:E.descriptor}),r.overrides?.add(f)),an(e,o,f,E.descriptor,a));continue}if(o.operator!==">&"&&o.operator!=="<&"){i.push(o);continue}if(c==="-"){let S=r.bindings.get(f)?.descriptor;r.overrides?.add(f),r.bindings.set(f,{descriptor:Xt}),ws(e,o,f,a,S);continue}let d=c.endsWith("-"),p=d?c.slice(0,-1):c,m=p.startsWith("&")?p.slice(1):p,h=/^\d+$/.test(m)?Number.parseInt(m,10):Number.NaN;if(!Number.isNaN(h)){let S=Yr(e,r,h);if(!S){let b=r.bindings.get(h)?.descriptor;if(b===Xt)return Te(r,i,Ve(h));if(o.operator==="<&"&&o.fdVariable&&b!==void 0){if(r.bindings.set(f,{descriptor:b}),tt(e,f,b),d){let g=_t(r,h);ws(e,o,h,a,b,g)}continue}if(o.operator==="<&"&&!o.fdVariable){i.push(on(o,c));continue}return Te(r,i,Ve(h))}let E=Oo(r,h);if(o.fdVariable?Pt(r,f,S,E):r.bindings.set(f,{sink:S,descriptor:E}),an(e,o,f,E,a),d){let b=!0;o.fdVariable?b=_t(r,h):(r.overrides?.add(h),r.bindings.set(h,{descriptor:Xt}),n.persistMovedSource&&r.parent&&(b=_t(r.parent,h))),ws(e,o,h,a||n.persistMovedSource===!0,E,b)}o.fdVariable||r.overrides?.add(f);continue}if(o.operator==="<&")return Te(r,i,`bash: ${c}: ambiguous redirect
28
+ `);let v=await Kr(e,r,c,"truncate");if("error"in v)return Te(r,i,v.error);o.fd==null&&!o.fdVariable?(r.bindings.set(1,{sink:v.sink,descriptor:v.descriptor}),r.bindings.set(2,{sink:v.sink,descriptor:v.descriptor}),r.overrides?.add(1),r.overrides?.add(2),a&&(tt(e,1,v.descriptor),tt(e,2,v.descriptor))):(o.fdVariable?Pt(r,f,v.sink,v.descriptor):(r.bindings.set(f,{sink:v.sink,descriptor:v.descriptor}),r.overrides?.add(f)),an(e,o,f,v.descriptor,a))}return{channels:r,legacyRedirections:i}}async function Qr(e,t){let s=e.outputChannels,n=await Ne(e,s,t,{persistent:!0});if(n.error)return n;for(let r of n.channels.overrides??[]){let i=n.channels.bindings.get(r);i?.descriptor!==void 0&&Pt(s,r,i.sink,i.descriptor)}return{...n,channels:s}}async function ei(e,t){if(e.state.options.posix&&tn.has(t.name)){let n=`bash: line ${e.state.currentLine}: \`${t.name}': is a special builtin
29
+ `;throw await H(e,2,n,!0),new q(2)}let s={...t,sourceFile:t.sourceFile??e.state.currentSource??"main"};return e.state.functions.set(t.name,s),B()}async function Io(e,t){let s=A(),n=!1;for(let r of t)if(!r.fdVariable){if((r.operator==="<<"||r.operator==="<<-")&&r.target.type==="HereDoc"){let i=r.target,a=await z(e,i.content);i.stripTabs&&(a=a.split(`
28
30
  `).map(l=>l.replace(/^\t+/,"")).join(`
29
31
  `)),(r.fd??0)===0&&(s=V(a),n=!0)}else if(r.operator==="<<<"&&r.target.type==="Word")s=V(`${await z(e,r.target)}
30
- `),n=!0;else if(r.operator==="<"&&r.target.type==="Word"){let i=await z(e,r.target),a=e.fs.resolvePath(e.state.cwd,i);try{s=await e.fs.readFile(a),n=!0}catch{}}}return s}async function vs(e,t,s,n=E(),r){e.state.callDepth++,e.state.callDepth>e.limits.maxCallDepth&&(e.state.callDepth--,De(`${t.name}: maximum recursion depth (${e.limits.maxCallDepth}) exceeded, increase executionLimits.maxCallDepth`,"recursion")),e.state.funcNameStack||(e.state.funcNameStack=[]),e.state.callLineStack||(e.state.callLineStack=[]),e.state.sourceStack||(e.state.sourceStack=[]),e.state.funcNameStack.unshift(t.name),e.state.callLineStack.unshift(r??e.state.currentLine),e.state.sourceStack.unshift(t.sourceFile??"main"),e.state.localScopes.push(new Map),e.state.localExportedVars||(e.state.localExportedVars=[]),e.state.localExportedVars.push(new Set);let i=new Map;for(let o=0;o<s.length;o++)i.set(String(o+1),T(e.state.env,String(o+1))),y(e.state.env,String(o+1),s[o]);i.set("@",T(e.state.env,"@")),i.set("#",T(e.state.env,"#")),y(e.state.env,"@",s.join(" ")),y(e.state.env,"#",String(s.length));let a=()=>{let o=e.state.localScopes.length-1,l=e.state.localScopes.pop();if(l)for(let[u,c]of l)c===void 0?e.state.env.delete(u):e.state.env.set(u,c);if(Zr(e,o),e.state.fullyUnsetLocals)for(let[u,c]of e.state.fullyUnsetLocals.entries())c===o&&e.state.fullyUnsetLocals.delete(u);if(e.state.localExportedVars&&e.state.localExportedVars.length>0){let u=e.state.localExportedVars.pop();if(u)for(let c of u)e.state.exportedVars?.delete(c)}for(let[u,c]of i)c===void 0?e.state.env.delete(u):y(e.state.env,u,c);e.state.funcNameStack?.shift(),e.state.callLineStack?.shift(),e.state.sourceStack?.shift(),e.state.callDepth--};try{let o=await Te(e,e.outputChannels,t.redirections);return o.error?await K(e,o.channels,()=>te(e,()=>Promise.resolve(o.error))):await K(e,o.channels,async()=>{try{let l=await ht(e,o.legacyRedirections);if(l)return await te(e,()=>Promise.resolve(l));let u=await ie(n),c=u.length>0?de(u):await Do(e,o.legacyRedirections),f=await e.executeCommand(t.body,c);return await te(e,()=>Promise.resolve(f))}catch(l){let{writeFailure:u}=await qe(e,l);if(u)return u;if(l instanceof ye)return W(E(),E(),l.exitCode);throw l}})}catch(o){throw await ee(e,o),o}finally{a()}}var si=["!","[[","]]","case","do","done","elif","else","esac","fi","for","function","if","in","then","time","until","while","{","}"],cn=[".",":","[","alias","bg","bind","break","builtin","caller","cd","command","compgen","complete","compopt","continue","declare","dirs","disown","echo","enable","eval","exec","exit","export","false","fc","fg","getopts","hash","help","history","jobs","kill","let","local","logout","mapfile","popd","printf","pushd","pwd","read","readarray","readonly","return","set","shift","shopt","source","suspend","test","times","trap","true","type","typeset","ulimit","umask","unalias","unset","wait"],Io=["autocd","assoc_expand_once","cdable_vars","cdspell","checkhash","checkjobs","checkwinsize","cmdhist","compat31","compat32","compat40","compat41","compat42","compat43","compat44","complete_fullquote","direxpand","dirspell","dotglob","execfail","expand_aliases","extdebug","extglob","extquote","failglob","force_fignore","globasciiranges","globstar","gnu_errfmt","histappend","histreedit","histverify","hostcomplete","huponexit","inherit_errexit","interactive_comments","lastpipe","lithist","localvar_inherit","localvar_unset","login_shell","mailwarn","no_empty_cmd_completion","nocaseglob","nocasematch","nullglob","progcomp","progcomp_alias","promptvars","restricted_shell","shift_verbose","sourcepath","xpg_echo"],Ro=cn;async function un(e,t){let s=[],n=null,r="",i="",a=null,o=!1,l=!1,u=!1,c=null,f=null,d=null,p=[],m=["alias","arrayvar","binding","builtin","command","directory","disabled","enabled","export","file","function","group","helptopic","hostname","job","keyword","running","service","setopt","shopt","signal","stopped","user","variable"];for(let v=0;v<t.length;v++){let C=t[v];if(C==="-v")s.push("variable");else if(C==="-e")s.push("export");else if(C==="-f")s.push("file");else if(C==="-d")s.push("directory");else if(C==="-k")s.push("keyword");else if(C==="-A"){if(v++,v>=t.length)return A(`compgen: -A: option requires an argument
31
- `,2);let N=t[v];if(!m.includes(N))return A(`compgen: ${N}: invalid action name
32
- `,2);s.push(N)}else if(C==="-W"){if(v++,v>=t.length)return A(`compgen: -W: option requires an argument
33
- `,2);n=t[v]}else if(C==="-P"){if(v++,v>=t.length)return A(`compgen: -P: option requires an argument
34
- `,2);r=t[v]}else if(C==="-S"){if(v++,v>=t.length)return A(`compgen: -S: option requires an argument
35
- `,2);i=t[v]}else if(C==="-o"){if(v++,v>=t.length)return A(`compgen: -o: option requires an argument
36
- `,2);let N=t[v];if(N==="plusdirs")o=!0;else if(N==="dirnames")l=!0;else if(N==="default")u=!0;else if(!(N==="filenames"||N==="nospace"||N==="bashdefault"||N==="noquote"))return A(`compgen: ${N}: invalid option name
37
- `,2)}else if(C==="-F"){if(v++,v>=t.length)return A(`compgen: -F: option requires an argument
38
- `,2);f=t[v]}else if(C==="-C"){if(v++,v>=t.length)return A(`compgen: -C: option requires an argument
39
- `,2);d=t[v]}else if(C==="-X"){if(v++,v>=t.length)return A(`compgen: -X: option requires an argument
40
- `,2);c=t[v]}else if(C==="-G"){if(v++,v>=t.length)return A(`compgen: -G: option requires an argument
41
- `,2)}else if(C==="--"){p.push(...t.slice(v+1));break}else C.startsWith("-")||p.push(C)}a=p[0]??null;let h=[];if(l){let v=await ln(e,a);h.push(...v)}if(u){let v=await ti(e,a);h.push(...v)}for(let v of s)if(v==="variable"){let C=Lo(e,a);h.push(...C)}else if(v==="export"){let C=Mo(e,a);h.push(...C)}else if(v==="function"){let C=Wo(e,a);h.push(...C)}else if(v==="builtin"){let C=Fo(a);h.push(...C)}else if(v==="keyword"){let C=Vo(a);h.push(...C)}else if(v==="alias"){let C=zo(e,a);h.push(...C)}else if(v==="shopt"){let C=jo(a);h.push(...C)}else if(v==="helptopic"){let C=Bo(a);h.push(...C)}else if(v==="directory"){let C=await ln(e,a);h.push(...C)}else if(v==="file"){let C=await ti(e,a);h.push(...C)}else if(v==="user"){let C=Ho(a);h.push(...C)}else if(v==="command"){let C=await Uo(e,a);h.push(...C)}if(n!==null)try{let v=await Go(e,n),C=qo(e,v);for(let N of C)(a===null||N.startsWith(a))&&h.push(N)}catch{return W(L,L,1)}if(o){let v=await ln(e,a);for(let C of v)h.includes(C)||h.push(C)}let b="";if(f!==null){let v=e.state.functions.get(f);if(v){let C=new Map;C.set("COMP_WORDS__length",T(e.state.env,"COMP_WORDS__length")),y(e.state.env,"COMP_WORDS__length","0"),C.set("COMP_CWORD",T(e.state.env,"COMP_CWORD")),y(e.state.env,"COMP_CWORD","-1"),C.set("COMP_LINE",T(e.state.env,"COMP_LINE")),y(e.state.env,"COMP_LINE",""),C.set("COMP_POINT",T(e.state.env,"COMP_POINT")),y(e.state.env,"COMP_POINT","0");let N=new Map;for(let P of e.state.env.keys())(P==="COMPREPLY"||P.startsWith("COMPREPLY_")||P==="COMPREPLY__length")&&(N.set(P,T(e.state.env,P)),e.state.env.delete(P));let I=["compgen",p[0]??"",""];try{let P=Pe(),k=Pe(),O=await K(e,{bindings:new Map([[1,{sink:P}],[2,{sink:k}]])},()=>vs(e,v,I,E()));if(await xt(e,O.stderr,k),O.exitCode!==0)return pt(e,C),pt(e,N),W(L,k.stream(),1);await xt(e,O.stdout,P),b=H(await ie(P.stream()));let R=Zo(e);h.push(...R)}catch{return pt(e,C),pt(e,N),W(L,L,1)}pt(e,C),pt(e,N)}}if(d!==null)try{let v=Ie(d),C=Pe(),N=Pe(),I=await K(e,{bindings:new Map([[1,{sink:C}],[2,{sink:N}]])},()=>e.executeScript(v));if(await xt(e,I.stderr,N),I.exitCode!==0)return W(L,N.stream(),I.exitCode);await xt(e,I.stdout,C);let P=await ie(C.stream());if(P.length>0){let k=H(P).split(`
42
- `);for(let O of k)O.length>0&&h.push(O)}}catch(v){if(v.name==="ParseException")return A(`compgen: -C: ${v.message}
43
- `,2);throw v}let S=h;if(c!==null){let v=c.startsWith("!"),C=v?c.slice(1):c;S=h.filter(N=>{let I=ft(N,C,!1,!0);return v?I:!I})}if(S.length===0&&a!==null)return W(F(b),L,1);let $=S.map(v=>`${r}${v}${i}`).join(`
44
- `),g=b+($?`${$}
45
- `:"");return G(g)}function Lo(e,t){let s=new Set;for(let r of e.state.env.keys()){if(r.includes("_")&&/^[a-zA-Z_][a-zA-Z0-9_]*_\d+$/.test(r)||r.endsWith("__length"))continue;let i=r.split("_")[0];/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(r)?s.add(r):i&&/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(i)&&e.state.env.has(`${i}__length`)&&s.add(i)}let n=Array.from(s);return t!==null&&(n=n.filter(r=>r.startsWith(t))),n.sort()}function Mo(e,t){let s=e.state.exportedVars??new Set,n=Array.from(s);return t!==null&&(n=n.filter(r=>r.startsWith(t))),n=n.filter(r=>r.includes("_")&&/^[a-zA-Z_][a-zA-Z0-9_]*_\d+$/.test(r)||r.endsWith("__length")?!1:e.state.env.has(r)),n.sort()}function Wo(e,t){let s=Array.from(e.state.functions.keys());return t!==null&&(s=s.filter(n=>n.startsWith(t))),s.sort()}function Fo(e){let t=[...cn];return e!==null&&(t=t.filter(s=>s.startsWith(e))),t.sort()}function Vo(e){let t=[...si];return e!==null&&(t=t.filter(s=>s.startsWith(e))),t.sort()}function zo(e,t){let s=[];for(let r of e.state.env.keys())if(r.startsWith("BASH_ALIAS_")){let i=r.slice(11);s.push(i)}let n=s;return t!==null&&(n=n.filter(r=>r.startsWith(t))),n.sort()}function jo(e){let t=[...Io];return e!==null&&(t=t.filter(s=>s.startsWith(e))),t.sort()}function Bo(e){let t=[...Ro];return e!==null&&(t=t.filter(s=>s.startsWith(e))),t.sort()}async function ln(e,t){let s=[];try{let n=e.state.cwd,r=t??"";if(t){let a=t.lastIndexOf("/");if(a!==-1){let o=t.slice(0,a)||"/";r=t.slice(a+1),o.startsWith("/")?n=o:n=`${e.state.cwd}/${o}`}}let i=await e.fs.readdir(n);for(let a of i){let o=`${n}/${a}`;try{if((await e.fs.stat(o)).isDirectory&&(!r||a.startsWith(r)))if(t?.includes("/")){let u=t.lastIndexOf("/"),c=t.slice(0,u+1);s.push(c+a)}else s.push(a)}catch{}}}catch{}return s.sort()}async function ti(e,t){let s=[];try{let n=e.state.cwd,r=t??"";if(t){let a=t.lastIndexOf("/");if(a!==-1){let o=t.slice(0,a)||"/";r=t.slice(a+1),o.startsWith("/")?n=o:n=`${e.state.cwd}/${o}`}}let i=await e.fs.readdir(n);for(let a of i)if(!r||a.startsWith(r))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 Ho(e){return["root","nobody"]}async function Uo(e,t){let s=new Set;for(let i of cn)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 si)s.add(i);let n=T(e.state.env,"PATH","/usr/bin:/bin");for(let i of n.split(":"))if(i)try{let a=await e.fs.readdir(i);for(let o of a)s.add(o)}catch{}let r=Array.from(s);return t!==null&&(r=r.filter(i=>i.startsWith(t))),r.sort()}async function Go(e,t){let n=new Z().parseWordFromString(t,!1,!1);return await z(e,n)}function qo(e,t){let s=T(e.state.env,"IFS",`
46
- `);if(s.length===0)return[t];let n=new Set(s.split("")),r=[],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 n.has(o)?(i.length>0&&(r.push(i),i=""),a++):(i+=o,a++)}return i.length>0&&r.push(i),r}function pt(e,t){for(let[s,n]of t)n===void 0?e.state.env.delete(s):y(e.state.env,s,n)}function Zo(e){let t=[];if(e.state.env.get("COMPREPLY__length")!==void 0){let r=Ne(e,"COMPREPLY");for(let[,i]of r)t.push(i)}else e.state.env.has("COMPREPLY")&&t.push(T(e.state.env,"COMPREPLY"));return t}var Jo=["bashdefault","default","dirnames","filenames","noquote","nosort","nospace","plusdirs"];function dn(e,t){e.state.completionSpecs||(e.state.completionSpecs=new Map);let s=!1,n=!1,r=!1,i,a,o,l=[],u=[],c=[];for(let f=0;f<t.length;f++){let d=t[f];if(d==="-p")s=!0;else if(d==="-r")n=!0;else if(d==="-D")r=!0;else if(d==="-W"){if(f++,f>=t.length)return A(`complete: -W: option requires an argument
47
- `,2);i=t[f]}else if(d==="-F"){if(f++,f>=t.length)return A(`complete: -F: option requires an argument
48
- `,2);a=t[f]}else if(d==="-o"){if(f++,f>=t.length)return A(`complete: -o: option requires an argument
49
- `,2);let p=t[f];if(!Jo.includes(p))return A(`complete: ${p}: invalid option name
50
- `,2);l.push(p)}else if(d==="-A"){if(f++,f>=t.length)return A(`complete: -A: option requires an argument
51
- `,2);u.push(t[f])}else if(d==="-C"){if(f++,f>=t.length)return A(`complete: -C: option requires an argument
52
- `,2);o=t[f]}else if(d==="-G"){if(f++,f>=t.length)return A(`complete: -G: option requires an argument
53
- `,2)}else if(d==="-P"){if(f++,f>=t.length)return A(`complete: -P: option requires an argument
54
- `,2)}else if(d==="-S"){if(f++,f>=t.length)return A(`complete: -S: option requires an argument
55
- `,2)}else if(d==="-X"){if(f++,f>=t.length)return A(`complete: -X: option requires an argument
56
- `,2)}else if(d==="--"){c.push(...t.slice(f+1));break}else d.startsWith("-")||c.push(d)}if(n){if(c.length===0)return e.state.completionSpecs.clear(),_e();for(let f of c)e.state.completionSpecs.delete(f);return _e()}if(s)return c.length===0?fn(e):fn(e,c);if(t.length===0||c.length===0&&!i&&!a&&!o&&l.length===0&&u.length===0&&!r)return fn(e);if(a&&c.length===0&&!r)return A(`complete: -F: option requires a command name
57
- `,2);if(r){let f={isDefault:!0};return i!==void 0&&(f.wordlist=i),a!==void 0&&(f.function=a),o!==void 0&&(f.command=o),l.length>0&&(f.options=l),u.length>0&&(f.actions=u),e.state.completionSpecs.set("__default__",f),_e()}for(let f of c){let d=Object.create(null);i!==void 0&&(d.wordlist=i),a!==void 0&&(d.function=a),o!==void 0&&(d.command=o),l.length>0&&(d.options=l),u.length>0&&(d.actions=u),e.state.completionSpecs.set(f,d)}return _e()}function fn(e,t){let s=e.state.completionSpecs;if(!s||s.size===0){if(t&&t.length>0){let i="";for(let a of t)i+=`complete: ${a}: no completion specification
58
- `;return W(L,F(i),1)}return _e()}let n=[],r=t||Array.from(s.keys());for(let i of r){if(i==="__default__")continue;let a=s.get(i);if(!a){if(t)return W(F(n.join(`
32
+ `),n=!0;else if(r.operator==="<"&&r.target.type==="Word"){let i=await z(e,r.target),a=e.fs.resolvePath(e.state.cwd,i);try{s=await e.fs.readFile(a),n=!0}catch{}}}return s}async function bs(e,t,s,n=A(),r){e.state.callDepth++,e.state.callDepth>e.limits.maxCallDepth&&(e.state.callDepth--,Ie(`${t.name}: maximum recursion depth (${e.limits.maxCallDepth}) exceeded, increase executionLimits.maxCallDepth`,"recursion")),e.state.funcNameStack||(e.state.funcNameStack=[]),e.state.callLineStack||(e.state.callLineStack=[]),e.state.sourceStack||(e.state.sourceStack=[]),e.state.funcNameStack.unshift(t.name),e.state.callLineStack.unshift(r??e.state.currentLine),e.state.sourceStack.unshift(t.sourceFile??"main"),e.state.localScopes.push(new Map),e.state.localExportedVars||(e.state.localExportedVars=[]),e.state.localExportedVars.push(new Set);let i=new Map;for(let o=0;o<s.length;o++)i.set(String(o+1),x(e.state.env,String(o+1))),y(e.state.env,String(o+1),s[o]);i.set("@",x(e.state.env,"@")),i.set("#",x(e.state.env,"#")),y(e.state.env,"@",s.join(" ")),y(e.state.env,"#",String(s.length));let a=()=>{let o=e.state.localScopes.length-1,l=e.state.localScopes.pop();if(l)for(let[c,u]of l)u===void 0?e.state.env.delete(c):e.state.env.set(c,u);if(Zr(e,o),e.state.fullyUnsetLocals)for(let[c,u]of e.state.fullyUnsetLocals.entries())u===o&&e.state.fullyUnsetLocals.delete(c);if(e.state.localExportedVars&&e.state.localExportedVars.length>0){let c=e.state.localExportedVars.pop();if(c)for(let u of c)e.state.exportedVars?.delete(u)}for(let[c,u]of i)u===void 0?e.state.env.delete(c):y(e.state.env,c,u);e.state.funcNameStack?.shift(),e.state.callLineStack?.shift(),e.state.sourceStack?.shift(),e.state.callDepth--};try{let o=await Ne(e,e.outputChannels,t.redirections);return o.error?await K(e,o.channels,()=>te(e,()=>Promise.resolve(o.error))):await K(e,o.channels,async()=>{try{let l=await ht(e,o.legacyRedirections);if(l)return await te(e,()=>Promise.resolve(l));let c=await ie(n),u=c.length>0?de(c):await Io(e,o.legacyRedirections),f=await e.executeCommand(t.body,u);return await te(e,()=>Promise.resolve(f))}catch(l){let{writeFailure:c}=await qe(e,l);if(c)return c;if(l instanceof ye)return W(A(),A(),l.exitCode);throw l}})}catch(o){throw await ee(e,o),o}finally{a()}}var si=["!","[[","]]","case","do","done","elif","else","esac","fi","for","function","if","in","then","time","until","while","{","}"],cn=[".",":","[","alias","bg","bind","break","builtin","caller","cd","command","compgen","complete","compopt","continue","declare","dirs","disown","echo","enable","eval","exec","exit","export","false","fc","fg","getopts","hash","help","history","jobs","kill","let","local","logout","mapfile","popd","printf","pushd","pwd","read","readarray","readonly","return","set","shift","shopt","source","suspend","test","times","trap","true","type","typeset","ulimit","umask","unalias","unset","wait"],Do=["autocd","assoc_expand_once","cdable_vars","cdspell","checkhash","checkjobs","checkwinsize","cmdhist","compat31","compat32","compat40","compat41","compat42","compat43","compat44","complete_fullquote","direxpand","dirspell","dotglob","execfail","expand_aliases","extdebug","extglob","extquote","failglob","force_fignore","globasciiranges","globstar","gnu_errfmt","histappend","histreedit","histverify","hostcomplete","huponexit","inherit_errexit","interactive_comments","lastpipe","lithist","localvar_inherit","localvar_unset","login_shell","mailwarn","no_empty_cmd_completion","nocaseglob","nocasematch","nullglob","progcomp","progcomp_alias","promptvars","restricted_shell","shift_verbose","sourcepath","xpg_echo"],Ro=cn;async function un(e,t){let s=[],n=null,r="",i="",a=null,o=!1,l=!1,c=!1,u=null,f=null,d=null,p=[],m=["alias","arrayvar","binding","builtin","command","directory","disabled","enabled","export","file","function","group","helptopic","hostname","job","keyword","running","service","setopt","shopt","signal","stopped","user","variable"];for(let g=0;g<t.length;g++){let P=t[g];if(P==="-v")s.push("variable");else if(P==="-e")s.push("export");else if(P==="-f")s.push("file");else if(P==="-d")s.push("directory");else if(P==="-k")s.push("keyword");else if(P==="-A"){if(g++,g>=t.length)return C(`compgen: -A: option requires an argument
33
+ `,2);let N=t[g];if(!m.includes(N))return C(`compgen: ${N}: invalid action name
34
+ `,2);s.push(N)}else if(P==="-W"){if(g++,g>=t.length)return C(`compgen: -W: option requires an argument
35
+ `,2);n=t[g]}else if(P==="-P"){if(g++,g>=t.length)return C(`compgen: -P: option requires an argument
36
+ `,2);r=t[g]}else if(P==="-S"){if(g++,g>=t.length)return C(`compgen: -S: option requires an argument
37
+ `,2);i=t[g]}else if(P==="-o"){if(g++,g>=t.length)return C(`compgen: -o: option requires an argument
38
+ `,2);let N=t[g];if(N==="plusdirs")o=!0;else if(N==="dirnames")l=!0;else if(N==="default")c=!0;else if(!(N==="filenames"||N==="nospace"||N==="bashdefault"||N==="noquote"))return C(`compgen: ${N}: invalid option name
39
+ `,2)}else if(P==="-F"){if(g++,g>=t.length)return C(`compgen: -F: option requires an argument
40
+ `,2);f=t[g]}else if(P==="-C"){if(g++,g>=t.length)return C(`compgen: -C: option requires an argument
41
+ `,2);d=t[g]}else if(P==="-X"){if(g++,g>=t.length)return C(`compgen: -X: option requires an argument
42
+ `,2);u=t[g]}else if(P==="-G"){if(g++,g>=t.length)return C(`compgen: -G: option requires an argument
43
+ `,2)}else if(P==="--"){p.push(...t.slice(g+1));break}else P.startsWith("-")||p.push(P)}a=p[0]??null;let h=[];if(l){let g=await ln(e,a);h.push(...g)}if(c){let g=await ti(e,a);h.push(...g)}for(let g of s)if(g==="variable"){let P=Lo(e,a);h.push(...P)}else if(g==="export"){let P=Mo(e,a);h.push(...P)}else if(g==="function"){let P=Wo(e,a);h.push(...P)}else if(g==="builtin"){let P=Fo(a);h.push(...P)}else if(g==="keyword"){let P=Vo(a);h.push(...P)}else if(g==="alias"){let P=zo(e,a);h.push(...P)}else if(g==="shopt"){let P=jo(a);h.push(...P)}else if(g==="helptopic"){let P=Bo(a);h.push(...P)}else if(g==="directory"){let P=await ln(e,a);h.push(...P)}else if(g==="file"){let P=await ti(e,a);h.push(...P)}else if(g==="user"){let P=Uo(a);h.push(...P)}else if(g==="command"){let P=await Ho(e,a);h.push(...P)}if(n!==null)try{let g=await Go(e,n),P=qo(e,g);for(let N of P)(a===null||N.startsWith(a))&&h.push(N)}catch{return W(R,R,1)}if(o){let g=await ln(e,a);for(let P of g)h.includes(P)||h.push(P)}let v="";if(f!==null){let g=e.state.functions.get(f);if(g){let P=new Map;P.set("COMP_WORDS__length",x(e.state.env,"COMP_WORDS__length")),y(e.state.env,"COMP_WORDS__length","0"),P.set("COMP_CWORD",x(e.state.env,"COMP_CWORD")),y(e.state.env,"COMP_CWORD","-1"),P.set("COMP_LINE",x(e.state.env,"COMP_LINE")),y(e.state.env,"COMP_LINE",""),P.set("COMP_POINT",x(e.state.env,"COMP_POINT")),y(e.state.env,"COMP_POINT","0");let N=new Map;for(let $ of e.state.env.keys())($==="COMPREPLY"||$.startsWith("COMPREPLY_")||$==="COMPREPLY__length")&&(N.set($,x(e.state.env,$)),e.state.env.delete($));let M=["compgen",p[0]??"",""];try{let $=Pe(),k=Pe(),O=await K(e,{bindings:new Map([[1,{sink:$}],[2,{sink:k}]])},()=>bs(e,g,M,A()));if(await Tt(e,O.stderr,k),O.exitCode!==0)return pt(e,P),pt(e,N),W(R,k.stream(),1);await Tt(e,O.stdout,$),v=U(await ie($.stream()));let D=Zo(e);h.push(...D)}catch{return pt(e,P),pt(e,N),W(R,R,1)}pt(e,P),pt(e,N)}}if(d!==null)try{let g=De(d),P=Pe(),N=Pe(),M=await K(e,{bindings:new Map([[1,{sink:P}],[2,{sink:N}]])},()=>e.executeScript(g));if(await Tt(e,M.stderr,N),M.exitCode!==0)return W(R,N.stream(),M.exitCode);await Tt(e,M.stdout,P);let $=await ie(P.stream());if($.length>0){let k=U($).split(`
44
+ `);for(let O of k)O.length>0&&h.push(O)}}catch(g){if(g.name==="ParseException")return C(`compgen: -C: ${g.message}
45
+ `,2);throw g}let S=h;if(u!==null){let g=u.startsWith("!"),P=g?u.slice(1):u;S=h.filter(N=>{let M=ft(N,P,!1,!0);return g?M:!M})}if(S.length===0&&a!==null)return W(F(v),R,1);let E=S.map(g=>`${r}${g}${i}`).join(`
46
+ `),b=v+(E?`${E}
47
+ `:"");return G(b)}function Lo(e,t){let s=new Set;for(let r of e.state.env.keys()){if(r.includes("_")&&/^[a-zA-Z_][a-zA-Z0-9_]*_\d+$/.test(r)||r.endsWith("__length"))continue;let i=r.split("_")[0];/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(r)?s.add(r):i&&/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(i)&&e.state.env.has(`${i}__length`)&&s.add(i)}let n=Array.from(s);return t!==null&&(n=n.filter(r=>r.startsWith(t))),n.sort()}function Mo(e,t){let s=e.state.exportedVars??new Set,n=Array.from(s);return t!==null&&(n=n.filter(r=>r.startsWith(t))),n=n.filter(r=>r.includes("_")&&/^[a-zA-Z_][a-zA-Z0-9_]*_\d+$/.test(r)||r.endsWith("__length")?!1:e.state.env.has(r)),n.sort()}function Wo(e,t){let s=Array.from(e.state.functions.keys());return t!==null&&(s=s.filter(n=>n.startsWith(t))),s.sort()}function Fo(e){let t=[...cn];return e!==null&&(t=t.filter(s=>s.startsWith(e))),t.sort()}function Vo(e){let t=[...si];return e!==null&&(t=t.filter(s=>s.startsWith(e))),t.sort()}function zo(e,t){let s=[];for(let r of e.state.env.keys())if(r.startsWith("BASH_ALIAS_")){let i=r.slice(11);s.push(i)}let n=s;return t!==null&&(n=n.filter(r=>r.startsWith(t))),n.sort()}function jo(e){let t=[...Do];return e!==null&&(t=t.filter(s=>s.startsWith(e))),t.sort()}function Bo(e){let t=[...Ro];return e!==null&&(t=t.filter(s=>s.startsWith(e))),t.sort()}async function ln(e,t){let s=[];try{let n=e.state.cwd,r=t??"";if(t){let a=t.lastIndexOf("/");if(a!==-1){let o=t.slice(0,a)||"/";r=t.slice(a+1),o.startsWith("/")?n=o:n=`${e.state.cwd}/${o}`}}let i=await e.fs.readdir(n);for(let a of i){let o=`${n}/${a}`;try{if((await e.fs.stat(o)).isDirectory&&(!r||a.startsWith(r)))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 ti(e,t){let s=[];try{let n=e.state.cwd,r=t??"";if(t){let a=t.lastIndexOf("/");if(a!==-1){let o=t.slice(0,a)||"/";r=t.slice(a+1),o.startsWith("/")?n=o:n=`${e.state.cwd}/${o}`}}let i=await e.fs.readdir(n);for(let a of i)if(!r||a.startsWith(r))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 Uo(e){return["root","nobody"]}async function Ho(e,t){let s=new Set;for(let i of cn)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 si)s.add(i);let n=x(e.state.env,"PATH","/usr/bin:/bin");for(let i of n.split(":"))if(i)try{let a=await e.fs.readdir(i);for(let o of a)s.add(o)}catch{}let r=Array.from(s);return t!==null&&(r=r.filter(i=>i.startsWith(t))),r.sort()}async function Go(e,t){let n=new Z().parseWordFromString(t,!1,!1);return await z(e,n)}function qo(e,t){let s=x(e.state.env,"IFS",`
48
+ `);if(s.length===0)return[t];let n=new Set(s.split("")),r=[],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 n.has(o)?(i.length>0&&(r.push(i),i=""),a++):(i+=o,a++)}return i.length>0&&r.push(i),r}function pt(e,t){for(let[s,n]of t)n===void 0?e.state.env.delete(s):y(e.state.env,s,n)}function Zo(e){let t=[];if(e.state.env.get("COMPREPLY__length")!==void 0){let r=xe(e,"COMPREPLY");for(let[,i]of r)t.push(i)}else e.state.env.has("COMPREPLY")&&t.push(x(e.state.env,"COMPREPLY"));return t}var Jo=["bashdefault","default","dirnames","filenames","noquote","nosort","nospace","plusdirs"];function dn(e,t){e.state.completionSpecs||(e.state.completionSpecs=new Map);let s=!1,n=!1,r=!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")n=!0;else if(d==="-D")r=!0;else if(d==="-W"){if(f++,f>=t.length)return C(`complete: -W: option requires an argument
49
+ `,2);i=t[f]}else if(d==="-F"){if(f++,f>=t.length)return C(`complete: -F: option requires an argument
50
+ `,2);a=t[f]}else if(d==="-o"){if(f++,f>=t.length)return C(`complete: -o: option requires an argument
51
+ `,2);let p=t[f];if(!Jo.includes(p))return C(`complete: ${p}: invalid option name
52
+ `,2);l.push(p)}else if(d==="-A"){if(f++,f>=t.length)return C(`complete: -A: option requires an argument
53
+ `,2);c.push(t[f])}else if(d==="-C"){if(f++,f>=t.length)return C(`complete: -C: option requires an argument
54
+ `,2);o=t[f]}else if(d==="-G"){if(f++,f>=t.length)return C(`complete: -G: option requires an argument
55
+ `,2)}else if(d==="-P"){if(f++,f>=t.length)return C(`complete: -P: option requires an argument
56
+ `,2)}else if(d==="-S"){if(f++,f>=t.length)return C(`complete: -S: option requires an argument
57
+ `,2)}else if(d==="-X"){if(f++,f>=t.length)return C(`complete: -X: option requires an argument
58
+ `,2)}else if(d==="--"){u.push(...t.slice(f+1));break}else d.startsWith("-")||u.push(d)}if(n){if(u.length===0)return e.state.completionSpecs.clear(),_e();for(let f of u)e.state.completionSpecs.delete(f);return _e()}if(s)return u.length===0?fn(e):fn(e,u);if(t.length===0||u.length===0&&!i&&!a&&!o&&l.length===0&&c.length===0&&!r)return fn(e);if(a&&u.length===0&&!r)return C(`complete: -F: option requires a command name
59
+ `,2);if(r){let f={isDefault:!0};return i!==void 0&&(f.wordlist=i),a!==void 0&&(f.function=a),o!==void 0&&(f.command=o),l.length>0&&(f.options=l),c.length>0&&(f.actions=c),e.state.completionSpecs.set("__default__",f),_e()}for(let f of u){let d=Object.create(null);i!==void 0&&(d.wordlist=i),a!==void 0&&(d.function=a),o!==void 0&&(d.command=o),l.length>0&&(d.options=l),c.length>0&&(d.actions=c),e.state.completionSpecs.set(f,d)}return _e()}function fn(e,t){let s=e.state.completionSpecs;if(!s||s.size===0){if(t&&t.length>0){let i="";for(let a of t)i+=`complete: ${a}: no completion specification
60
+ `;return W(R,F(i),1)}return _e()}let n=[],r=t||Array.from(s.keys());for(let i of r){if(i==="__default__")continue;let a=s.get(i);if(!a){if(t)return W(F(n.join(`
59
61
  `)+(n.length>0?`
60
62
  `:"")),F(`complete: ${i}: no completion specification
61
63
  `),1);continue}let o="complete";if(a.options)for(let l of a.options)o+=` -o ${l}`;if(a.actions)for(let l of a.actions)o+=` -A ${l}`;a.wordlist!==void 0&&(a.wordlist.includes(" ")||a.wordlist.includes("'")?o+=` -W '${a.wordlist}'`:o+=` -W ${a.wordlist}`),a.function!==void 0&&(o+=` -F ${a.function}`),a.isDefault&&(o+=" -D"),o+=` ${i}`,n.push(o)}return n.length===0?_e():G(`${n.join(`
62
64
  `)}
63
- `)}var ni=["bashdefault","default","dirnames","filenames","noquote","nosort","nospace","plusdirs"];function hn(e,t){e.state.completionSpecs||(e.state.completionSpecs=new Map);let s=!1,n=!1,r=[],i=[],a=[];for(let o=0;o<t.length;o++){let l=t[o];if(l==="-D")s=!0;else if(l==="-E")n=!0;else if(l==="-o"){if(o++,o>=t.length)return A(`compopt: -o: option requires an argument
64
- `,2);let u=t[o];if(!ni.includes(u))return A(`compopt: ${u}: invalid option name
65
- `,2);r.push(u)}else if(l==="+o"){if(o++,o>=t.length)return A(`compopt: +o: option requires an argument
66
- `,2);let u=t[o];if(!ni.includes(u))return A(`compopt: ${u}: invalid option name
67
- `,2);i.push(u)}else if(l==="--"){a.push(...t.slice(o+1));break}else!l.startsWith("-")&&!l.startsWith("+")&&a.push(l)}if(s){let o=e.state.completionSpecs.get("__default__")??{isDefault:!0},l=new Set(o.options??[]);for(let u of r)l.add(u);for(let u of i)l.delete(u);return o.options=l.size>0?Array.from(l):void 0,e.state.completionSpecs.set("__default__",o),_e()}if(n){let o=e.state.completionSpecs.get("__empty__")??{},l=new Set(o.options??[]);for(let u of r)l.add(u);for(let u of i)l.delete(u);return o.options=l.size>0?Array.from(l):void 0,e.state.completionSpecs.set("__empty__",o),_e()}if(a.length>0){for(let o of a){let l=e.state.completionSpecs.get(o)??{},u=new Set(l.options??[]);for(let c of r)u.add(c);for(let c of i)u.delete(c);l.options=u.size>0?Array.from(u):void 0,e.state.completionSpecs.set(o,l)}return _e()}return A(`compopt: not currently executing completion function
68
- `,1)}async function pn(e,t){if(e.state.loopDepth===0){if(e.state.parentHasLoopContext)throw new ze;return B()}if(t.length>1)throw await U(e,2,`bash: continue: too many arguments
69
- `,!0),new q(1);let s=1;if(t.length>0){let n=Number.parseInt(t[0],10);if(Number.isNaN(n)||n<1)throw await U(e,2,`bash: continue: ${t[0]}: numeric argument required
70
- `,!0),new q(1);s=n}throw new Ae(s)}function se(e,t){let s=T(e.state.env,"HOME","/home/user");return t.split(":").map(i=>i==="~"?s:i==="~root"?"/root":i.startsWith("~/")?s+i.slice(1):i.startsWith("~root/")?`/root${i.slice(5)}`:i).join(":")}function mn(e){for(let t=0;t<e.length;t++){let s=e.charCodeAt(t);if(s<32||s===127)return!0}return!1}function gn(e){let t="$'";for(let s=0;s<e.length;s++){let n=e[s],r=e.charCodeAt(s);r===7?t+="\\a":r===8?t+="\\b":r===9?t+="\\t":r===10?t+="\\n":r===11?t+="\\v":r===12?t+="\\f":r===13?t+="\\r":r===27?t+="\\e":r===39?t+="\\'":r===92?t+="\\\\":r<32||r===127?t+=`\\${r.toString(8).padStart(3,"0")}`:t+=n}return t+="'",t}function bs(e){return mn(e)?gn(e):/^[a-zA-Z0-9_/.:\-@%+,=]*$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}function st(e){return mn(e)?gn(e):`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function yn(e){return mn(e)?gn(e):`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function ri(e,t){let s="";return e.state.integerVars?.has(t)&&(s+="i"),e.state.lowercaseVars?.has(t)&&(s+="l"),ve(e,t)&&(s+="n"),e.state.readonlyVars?.has(t)&&(s+="r"),e.state.uppercaseVars?.has(t)&&(s+="u"),e.state.exportedVars?.has(t)&&(s+="x"),s===""?"--":`-${s}`}function wn(e){return e===""?"''":/[\s'\\]/.test(e)?`'${e.replace(/'/g,"'\\''")}'`:e}function ii(e,t){let s="",n="",r=!1;for(let i of t){let a=ri(e,i);if(e.state.associativeArrays?.has(i)){let u=Ze(e,i);if(u.length===0)s+=`declare -A ${i}=()
71
- `;else{let c=u.map(f=>{let d=T(e.state.env,`${i}_${f}`,""),p=wn(d);return`['${f}']=${p}`});s+=`declare -A ${i}=(${c.join(" ")})
72
- `}continue}let l=he(e,i);if(l.length>0){let u=l.map(c=>{let f=T(e.state.env,`${i}_${c}`,"");return`[${c}]=${st(f)}`});s+=`declare -a ${i}=(${u.join(" ")})
65
+ `)}var ni=["bashdefault","default","dirnames","filenames","noquote","nosort","nospace","plusdirs"];function hn(e,t){e.state.completionSpecs||(e.state.completionSpecs=new Map);let s=!1,n=!1,r=[],i=[],a=[];for(let o=0;o<t.length;o++){let l=t[o];if(l==="-D")s=!0;else if(l==="-E")n=!0;else if(l==="-o"){if(o++,o>=t.length)return C(`compopt: -o: option requires an argument
66
+ `,2);let c=t[o];if(!ni.includes(c))return C(`compopt: ${c}: invalid option name
67
+ `,2);r.push(c)}else if(l==="+o"){if(o++,o>=t.length)return C(`compopt: +o: option requires an argument
68
+ `,2);let c=t[o];if(!ni.includes(c))return C(`compopt: ${c}: invalid option name
69
+ `,2);i.push(c)}else if(l==="--"){a.push(...t.slice(o+1));break}else!l.startsWith("-")&&!l.startsWith("+")&&a.push(l)}if(s){let o=e.state.completionSpecs.get("__default__")??{isDefault:!0},l=new Set(o.options??[]);for(let c of r)l.add(c);for(let c of i)l.delete(c);return o.options=l.size>0?Array.from(l):void 0,e.state.completionSpecs.set("__default__",o),_e()}if(n){let o=e.state.completionSpecs.get("__empty__")??{},l=new Set(o.options??[]);for(let c of r)l.add(c);for(let c of i)l.delete(c);return o.options=l.size>0?Array.from(l):void 0,e.state.completionSpecs.set("__empty__",o),_e()}if(a.length>0){for(let o of a){let l=e.state.completionSpecs.get(o)??{},c=new Set(l.options??[]);for(let u of r)c.add(u);for(let u of i)c.delete(u);l.options=c.size>0?Array.from(c):void 0,e.state.completionSpecs.set(o,l)}return _e()}return C(`compopt: not currently executing completion function
70
+ `,1)}async function pn(e,t){if(e.state.loopDepth===0){if(e.state.parentHasLoopContext)throw new ze;return B()}if(t.length>1)throw await H(e,2,`bash: continue: too many arguments
71
+ `,!0),new q(1);let s=1;if(t.length>0){let n=Number.parseInt(t[0],10);if(Number.isNaN(n)||n<1)throw await H(e,2,`bash: continue: ${t[0]}: numeric argument required
72
+ `,!0),new q(1);s=n}throw new Ae(s)}function se(e,t){let s=x(e.state.env,"HOME","/home/user");return t.split(":").map(i=>i==="~"?s:i==="~root"?"/root":i.startsWith("~/")?s+i.slice(1):i.startsWith("~root/")?`/root${i.slice(5)}`:i).join(":")}function mn(e){for(let t=0;t<e.length;t++){let s=e.charCodeAt(t);if(s<32||s===127)return!0}return!1}function gn(e){let t="$'";for(let s=0;s<e.length;s++){let n=e[s],r=e.charCodeAt(s);r===7?t+="\\a":r===8?t+="\\b":r===9?t+="\\t":r===10?t+="\\n":r===11?t+="\\v":r===12?t+="\\f":r===13?t+="\\r":r===27?t+="\\e":r===39?t+="\\'":r===92?t+="\\\\":r<32||r===127?t+=`\\${r.toString(8).padStart(3,"0")}`:t+=n}return t+="'",t}function Ss(e){return mn(e)?gn(e):/^[a-zA-Z0-9_/.:\-@%+,=]*$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}function st(e){return mn(e)?gn(e):`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function yn(e){return mn(e)?gn(e):`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function ri(e,t){let s="";return e.state.integerVars?.has(t)&&(s+="i"),e.state.lowercaseVars?.has(t)&&(s+="l"),ve(e,t)&&(s+="n"),e.state.readonlyVars?.has(t)&&(s+="r"),e.state.uppercaseVars?.has(t)&&(s+="u"),e.state.exportedVars?.has(t)&&(s+="x"),s===""?"--":`-${s}`}function wn(e){return e===""?"''":/[\s'\\]/.test(e)?`'${e.replace(/'/g,"'\\''")}'`:e}function ii(e,t){let s="",n="",r=!1;for(let i of t){let a=ri(e,i);if(e.state.associativeArrays?.has(i)){let c=Ze(e,i);if(c.length===0)s+=`declare -A ${i}=()
73
+ `;else{let u=c.map(f=>{let d=x(e.state.env,`${i}_${f}`,""),p=wn(d);return`['${f}']=${p}`});s+=`declare -A ${i}=(${u.join(" ")})
74
+ `}continue}let l=he(e,i);if(l.length>0){let c=l.map(u=>{let f=x(e.state.env,`${i}_${u}`,"");return`[${u}]=${st(f)}`});s+=`declare -a ${i}=(${c.join(" ")})
73
75
  `;continue}if(e.state.env.has(`${i}__length`)){s+=`declare -a ${i}=()
74
- `;continue}if(e.state.env.has(i)){let u=T(e.state.env,i);s+=`declare ${a} ${i}=${yn(u)}
75
- `}else{let u=e.state.declaredVars?.has(i),c=e.state.localVarDepth?.has(i);u||c?s+=`declare ${a} ${i}
76
+ `;continue}if(e.state.env.has(i)){let c=x(e.state.env,i);s+=`declare ${a} ${i}=${yn(c)}
77
+ `}else{let c=e.state.declaredVars?.has(i),u=e.state.localVarDepth?.has(i);c||u?s+=`declare ${a} ${i}
76
78
  `:(n+=`bash: declare: ${i}: not found
77
- `,r=!0)}}return W(F(s),F(n),r?1:0)}function oi(e,t){let{filterExport:s,filterReadonly:n,filterNameref:r,filterIndexedArray:i,filterAssocArray:a}=t,o=s||n||r||i||a,l="",u=new Set;for(let f of e.state.env.keys()){if(f.startsWith("BASH_"))continue;if(f.endsWith("__length")){let p=f.slice(0,-8);u.add(p);continue}let d=f.lastIndexOf("_");if(d>0){let p=f.slice(0,d),m=f.slice(d+1);if(/^\d+$/.test(m)||e.state.associativeArrays?.has(p)){u.add(p);continue}}u.add(f)}if(e.state.localVarDepth)for(let f of e.state.localVarDepth.keys())u.add(f);if(e.state.associativeArrays)for(let f of e.state.associativeArrays)u.add(f);let c=Array.from(u).sort();for(let f of c){let d=ri(e,f),p=e.state.associativeArrays?.has(f),m=he(e,f),h=!p&&(m.length>0||e.state.env.has(`${f}__length`));if(!(o&&(a&&!p||i&&!h||s&&!e.state.exportedVars?.has(f)||n&&!e.state.readonlyVars?.has(f)||r&&!ve(e,f)))){if(p){let b=Ze(e,f);if(b.length===0)l+=`declare -A ${f}=()
78
- `;else{let S=b.map($=>{let g=T(e.state.env,`${f}_${$}`,""),v=wn(g);return`['${$}']=${v}`});l+=`declare -A ${f}=(${S.join(" ")})
79
- `}continue}if(m.length>0){let b=m.map(S=>{let $=T(e.state.env,`${f}_${S}`,"");return`[${S}]=${st($)}`});l+=`declare -a ${f}=(${b.join(" ")})
79
+ `,r=!0)}}return W(F(s),F(n),r?1:0)}function oi(e,t){let{filterExport:s,filterReadonly:n,filterNameref:r,filterIndexedArray:i,filterAssocArray:a}=t,o=s||n||r||i||a,l="",c=new Set;for(let f of e.state.env.keys()){if(f.startsWith("BASH_"))continue;if(f.endsWith("__length")){let p=f.slice(0,-8);c.add(p);continue}let d=f.lastIndexOf("_");if(d>0){let p=f.slice(0,d),m=f.slice(d+1);if(/^\d+$/.test(m)||e.state.associativeArrays?.has(p)){c.add(p);continue}}c.add(f)}if(e.state.localVarDepth)for(let f of e.state.localVarDepth.keys())c.add(f);if(e.state.associativeArrays)for(let f of e.state.associativeArrays)c.add(f);let u=Array.from(c).sort();for(let f of u){let d=ri(e,f),p=e.state.associativeArrays?.has(f),m=he(e,f),h=!p&&(m.length>0||e.state.env.has(`${f}__length`));if(!(o&&(a&&!p||i&&!h||s&&!e.state.exportedVars?.has(f)||n&&!e.state.readonlyVars?.has(f)||r&&!ve(e,f)))){if(p){let v=Ze(e,f);if(v.length===0)l+=`declare -A ${f}=()
80
+ `;else{let S=v.map(E=>{let b=x(e.state.env,`${f}_${E}`,""),g=wn(b);return`['${E}']=${g}`});l+=`declare -A ${f}=(${S.join(" ")})
81
+ `}continue}if(m.length>0){let v=m.map(S=>{let E=x(e.state.env,`${f}_${S}`,"");return`[${S}]=${st(E)}`});l+=`declare -a ${f}=(${v.join(" ")})
80
82
  `;continue}if(e.state.env.has(`${f}__length`)){l+=`declare -a ${f}=()
81
- `;continue}if(e.state.env.has(f)){let b=T(e.state.env,f);l+=`declare ${d} ${f}=${yn(b)}
83
+ `;continue}if(e.state.env.has(f)){let v=x(e.state.env,f);l+=`declare ${d} ${f}=${yn(v)}
82
84
  `}}}return G(l)}function ai(e){let t="",s=Array.from(e.state.associativeArrays??[]).sort();for(let n of s){let r=Ze(e,n);if(r.length===0)t+=`declare -A ${n}=()
83
- `;else{let i=r.map(a=>{let o=T(e.state.env,`${n}_${a}`,""),l=wn(o);return`['${a}']=${l}`});t+=`declare -A ${n}=(${i.join(" ")})
85
+ `;else{let i=r.map(a=>{let o=x(e.state.env,`${n}_${a}`,""),l=wn(o);return`['${a}']=${l}`});t+=`declare -A ${n}=(${i.join(" ")})
84
86
  `}}return G(t)}function li(e){let t="",s=new Set;for(let r of e.state.env.keys()){if(r.startsWith("BASH_"))continue;if(r.endsWith("__length")){let a=r.slice(0,-8);e.state.associativeArrays?.has(a)||s.add(a);continue}let i=r.lastIndexOf("_");if(i>0){let a=r.slice(0,i),o=r.slice(i+1);/^\d+$/.test(o)&&(e.state.associativeArrays?.has(a)||s.add(a))}}let n=Array.from(s).sort();for(let r of n){let i=he(e,r);if(i.length===0)t+=`declare -a ${r}=()
85
- `;else{let a=i.map(o=>{let l=T(e.state.env,`${r}_${o}`,"");return`[${o}]=${st(l)}`});t+=`declare -a ${r}=(${a.join(" ")})
86
- `}}return G(t)}function ci(e){let t="",s=new Set;for(let r of e.state.env.keys()){if(r.startsWith("BASH_"))continue;if(r.endsWith("__length")){let a=r.slice(0,-8);s.add(a);continue}let i=r.lastIndexOf("_");if(i>0){let a=r.slice(0,i),o=r.slice(i+1);if(/^\d+$/.test(o)||e.state.associativeArrays?.has(a)){s.add(a);continue}}s.add(r)}let n=Array.from(s).sort();for(let r of n)e.state.associativeArrays?.has(r)||he(e,r).length>0||e.state.env.has(`${r}__length`)||e.state.env.has(r)&&(t+=`${r}=${bs(T(e.state.env,r))}
87
- `);return G(t)}function vn(e,t){e.state.integerVars??=new Set,e.state.integerVars.add(t)}function It(e,t){return e.state.integerVars?.has(t)??!1}function bn(e,t){e.state.lowercaseVars??=new Set,e.state.lowercaseVars.add(t),e.state.uppercaseVars?.delete(t)}function Ko(e,t){return e.state.lowercaseVars?.has(t)??!1}function Sn(e,t){e.state.uppercaseVars??=new Set,e.state.uppercaseVars.add(t),e.state.lowercaseVars?.delete(t)}function Xo(e,t){return e.state.uppercaseVars?.has(t)??!1}function mt(e,t,s){return Ko(e,t)?s.toLowerCase():Xo(e,t)?s.toUpperCase():s}async function ui(e,t){try{let s=new Z,n=le(s,t),r=await Q(e,n.expression);return String(r)}catch{return"0"}}function Yo(e){let t=e.match(/^[a-zA-Z_][a-zA-Z0-9_]*/);if(!t)return null;let s=t[0],n=s.length;if(e[n]!=="[")return null;let r=0,i=n+1;for(;n<e.length;n++)if(e[n]==="[")r++;else if(e[n]==="]"&&(r--,r===0))break;if(r!==0)return null;let a=e.slice(i,n);if(n++,e[n]!=="=")return null;n++;let o=e.slice(n);return{name:s,indexExpr:a,value:o}}async function En(e,t){let s=!1,n=!1,r=!1,i=!1,a=!1,o=!1,l=!1,u=!1,c=!1,f=!1,d=!1,p=!1,m=!1,h=!1,b=!1,S=[];for(let k=0;k<t.length;k++){let O=t[k];if(O==="-a")s=!0;else if(O==="-A")n=!0;else if(O==="-r")r=!0;else if(O==="-x")i=!0;else if(O==="-p")a=!0;else if(O==="-n")o=!0;else if(O==="+n")l=!0;else if(O==="+a")u=!0;else if(O==="+x")c=!0;else if(O==="--"){S.push(...t.slice(k+1));break}else if(O.startsWith("+")){for(let R of O.slice(1))if(R==="n")l=!0;else if(R==="a")u=!0;else if(R==="x")c=!0;else if(R!=="r"){if(R!=="i"){if(!(R==="f"||R==="F"))return W(L,F(`bash: typeset: +${R}: invalid option
88
- `),2)}}}else if(O==="-i")f=!0;else if(O==="-l")d=!0;else if(O==="-u")p=!0;else if(O==="-f")m=!0;else if(O==="-F")h=!0;else if(O==="-g")b=!0;else if(O.startsWith("-"))for(let R of O.slice(1))if(R==="a")s=!0;else if(R==="A")n=!0;else if(R==="r")r=!0;else if(R==="x")i=!0;else if(R==="p")a=!0;else if(R==="n")o=!0;else if(R==="i")f=!0;else if(R==="l")d=!0;else if(R==="u")p=!0;else if(R==="f")m=!0;else if(R==="F")h=!0;else if(R==="g")b=!0;else return W(L,F(`bash: typeset: -${R}: invalid option
89
- `),2);else S.push(O)}let g=e.state.localScopes.length>0&&!b,v=k=>{if(!g)return;let O=e.state.localScopes[e.state.localScopes.length-1];O.has(k)||O.set(k,e.state.env.get(k))},C=k=>{if(!g)return;let O=e.state.localScopes[e.state.localScopes.length-1];O.has(k)||O.set(k,e.state.env.get(k));let R=`${k}_`;for(let x of e.state.env.keys())x.startsWith(R)&&!x.includes("__")&&(O.has(x)||O.set(x,e.state.env.get(x)));let _=`${k}__length`;e.state.env.has(_)&&!O.has(_)&&O.set(_,e.state.env.get(_))},N=k=>{g&&Ke(e,k)};if(h){if(S.length===0){let R=Array.from(e.state.functions.keys()).sort(),_="";for(let x of R)_+=`declare -f ${x}
90
- `;return G(_)}let k=!0,O="";for(let R of S)e.state.functions.has(R)?O+=`${R}
91
- `:k=!1;return W(F(O),L,k?0:1)}if(m){if(S.length===0){let O="",R=Array.from(e.state.functions.keys()).sort();for(let _ of R)O+=`${_} ()
87
+ `;else{let a=i.map(o=>{let l=x(e.state.env,`${r}_${o}`,"");return`[${o}]=${st(l)}`});t+=`declare -a ${r}=(${a.join(" ")})
88
+ `}}return G(t)}function ci(e){let t="",s=new Set;for(let r of e.state.env.keys()){if(r.startsWith("BASH_"))continue;if(r.endsWith("__length")){let a=r.slice(0,-8);s.add(a);continue}let i=r.lastIndexOf("_");if(i>0){let a=r.slice(0,i),o=r.slice(i+1);if(/^\d+$/.test(o)||e.state.associativeArrays?.has(a)){s.add(a);continue}}s.add(r)}let n=Array.from(s).sort();for(let r of n)e.state.associativeArrays?.has(r)||he(e,r).length>0||e.state.env.has(`${r}__length`)||e.state.env.has(r)&&(t+=`${r}=${Ss(x(e.state.env,r))}
89
+ `);return G(t)}function vn(e,t){e.state.integerVars??=new Set,e.state.integerVars.add(t)}function Rt(e,t){return e.state.integerVars?.has(t)??!1}function bn(e,t){e.state.lowercaseVars??=new Set,e.state.lowercaseVars.add(t),e.state.uppercaseVars?.delete(t)}function Xo(e,t){return e.state.lowercaseVars?.has(t)??!1}function Sn(e,t){e.state.uppercaseVars??=new Set,e.state.uppercaseVars.add(t),e.state.lowercaseVars?.delete(t)}function Ko(e,t){return e.state.uppercaseVars?.has(t)??!1}function mt(e,t,s){return Xo(e,t)?s.toLowerCase():Ko(e,t)?s.toUpperCase():s}async function ui(e,t){try{let s=new Z,n=le(s,t),r=await Q(e,n.expression);return String(r)}catch{return"0"}}function Yo(e){let t=e.match(/^[a-zA-Z_][a-zA-Z0-9_]*/);if(!t)return null;let s=t[0],n=s.length;if(e[n]!=="[")return null;let r=0,i=n+1;for(;n<e.length;n++)if(e[n]==="[")r++;else if(e[n]==="]"&&(r--,r===0))break;if(r!==0)return null;let a=e.slice(i,n);if(n++,e[n]!=="=")return null;n++;let o=e.slice(n);return{name:s,indexExpr:a,value:o}}async function En(e,t){let s=!1,n=!1,r=!1,i=!1,a=!1,o=!1,l=!1,c=!1,u=!1,f=!1,d=!1,p=!1,m=!1,h=!1,v=!1,S=[];for(let k=0;k<t.length;k++){let O=t[k];if(O==="-a")s=!0;else if(O==="-A")n=!0;else if(O==="-r")r=!0;else if(O==="-x")i=!0;else if(O==="-p")a=!0;else if(O==="-n")o=!0;else if(O==="+n")l=!0;else if(O==="+a")c=!0;else if(O==="+x")u=!0;else if(O==="--"){S.push(...t.slice(k+1));break}else if(O.startsWith("+")){for(let D of O.slice(1))if(D==="n")l=!0;else if(D==="a")c=!0;else if(D==="x")u=!0;else if(D!=="r"){if(D!=="i"){if(!(D==="f"||D==="F"))return W(R,F(`bash: typeset: +${D}: invalid option
90
+ `),2)}}}else if(O==="-i")f=!0;else if(O==="-l")d=!0;else if(O==="-u")p=!0;else if(O==="-f")m=!0;else if(O==="-F")h=!0;else if(O==="-g")v=!0;else if(O.startsWith("-"))for(let D of O.slice(1))if(D==="a")s=!0;else if(D==="A")n=!0;else if(D==="r")r=!0;else if(D==="x")i=!0;else if(D==="p")a=!0;else if(D==="n")o=!0;else if(D==="i")f=!0;else if(D==="l")d=!0;else if(D==="u")p=!0;else if(D==="f")m=!0;else if(D==="F")h=!0;else if(D==="g")v=!0;else return W(R,F(`bash: typeset: -${D}: invalid option
91
+ `),2);else S.push(O)}let b=e.state.localScopes.length>0&&!v,g=k=>{if(!b)return;let O=e.state.localScopes[e.state.localScopes.length-1];O.has(k)||O.set(k,e.state.env.get(k))},P=k=>{if(!b)return;let O=e.state.localScopes[e.state.localScopes.length-1];O.has(k)||O.set(k,e.state.env.get(k));let D=`${k}_`;for(let T of e.state.env.keys())T.startsWith(D)&&!T.includes("__")&&(O.has(T)||O.set(T,e.state.env.get(T)));let _=`${k}__length`;e.state.env.has(_)&&!O.has(_)&&O.set(_,e.state.env.get(_))},N=k=>{b&&Xe(e,k)};if(h){if(S.length===0){let D=Array.from(e.state.functions.keys()).sort(),_="";for(let T of D)_+=`declare -f ${T}
92
+ `;return G(_)}let k=!0,O="";for(let D of S)e.state.functions.has(D)?O+=`${D}
93
+ `:k=!1;return W(F(O),R,k?0:1)}if(m){if(S.length===0){let O="",D=Array.from(e.state.functions.keys()).sort();for(let _ of D)O+=`${_} ()
92
94
  {
93
95
  # function body
94
96
  }
95
- `;return G(O)}let k=!0;for(let O of S)e.state.functions.has(O)||(k=!1);return W(L,L,k?0:1)}if(a&&S.length>0)return ii(e,S);if(a&&S.length===0)return oi(e,{filterExport:i,filterReadonly:r,filterNameref:o,filterIndexedArray:s,filterAssocArray:n});if(S.length===0&&n&&!a)return ai(e);if(S.length===0&&s&&!a)return li(e);if(S.length===0&&!a)return ci(e);let I="",P=0;for(let k of S){let O=k.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\((.*)\)$/s);if(O&&!u){let w=O[1],D=O[2];if(n&&he(e,w).length>0){I+=`bash: declare: ${w}: cannot convert indexed to associative array
96
- `,P=1;continue}if((s||!n&&!s)&&e.state.associativeArrays?.has(w)){I+=`bash: declare: ${w}: cannot convert associative to indexed array
97
- `,P=1;continue}if(C(w),n&&(e.state.associativeArrays??=new Set,e.state.associativeArrays.add(w)),Le(e,w),e.state.env.delete(w),e.state.env.delete(`${w}__length`),n&&D.includes("[")){let M=ds(D);for(let[J,j]of M){let Y=se(e,j);y(e.state.env,`${w}_${J}`,Y)}}else if(n){let M=Fe(D);for(let J=0;J<M.length;J+=2){let j=M[J],Y=J+1<M.length?se(e,M[J+1]):"";y(e.state.env,`${w}_${j}`,Y)}}else{let M=Fe(D);if(M.some(j=>/^\[[^\]]+\]=/.test(j))){let j=0;for(let Y of M){let re=Y.match(/^\[([^\]]+)\]=(.*)$/);if(re){let Ee=re[1],nt=re[2],eo=se(e,nt),vt;if(/^-?\d+$/.test(Ee))vt=Number.parseInt(Ee,10);else try{let to=new Z,so=le(to,Ee);vt=await Q(e,so.expression)}catch{vt=0}y(e.state.env,`${w}_${vt}`,eo),j=vt+1}else{let Ee=se(e,Y);y(e.state.env,`${w}_${j}`,Ee),j++}}}else{for(let j=0;j<M.length;j++)y(e.state.env,`${w}_${j}`,M[j]);y(e.state.env,`${w}__length`,String(M.length))}}N(w),r&&be(e,w),i&&Oe(e,w);continue}if(l){let w=k.includes("=")?k.slice(0,k.indexOf("=")):k;if(cr(e,w),!k.includes("="))continue}if(c){let w=k.includes("=")?k.slice(0,k.indexOf("=")):k;if(Xt(e,w),!k.includes("="))continue}let R=Yo(k);if(R){let{name:w,indexExpr:D,value:M}=R,J=await ue(e,w);if(J)return J;C(w);let j;try{let re=new Z,Ee=le(re,D);j=await Q(e,Ee.expression)}catch{let re=parseInt(D,10);j=Number.isNaN(re)?0:re}y(e.state.env,`${w}_${j}`,M);let Y=parseInt(T(e.state.env,`${w}__length`,"0"),10);j>=Y&&y(e.state.env,`${w}__length`,String(j+1)),N(w),r&&be(e,w),i&&Oe(e,w);continue}let _=k.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=\((.*)\)$/s);if(_&&!u){let w=_[1],D=_[2],M=await ue(e,w);if(M)return M;C(w);let J=Fe(D);if(e.state.associativeArrays?.has(w)){let j=ds(D);for(let[Y,re]of j){let Ee=se(e,re);y(e.state.env,`${w}_${Y}`,Ee)}}else{let j=he(e,w),Y=0,re=e.state.env.get(w);j.length===0&&re!==void 0?(e.state.env.set(`${w}_0`,re),e.state.env.delete(w),Y=1):j.length>0&&(Y=Math.max(...j)+1);for(let nt=0;nt<J.length;nt++)y(e.state.env,`${w}_${Y+nt}`,se(e,J[nt]));let Ee=Y+J.length;y(e.state.env,`${w}__length`,String(Ee))}N(w),r&&be(e,w),i&&Oe(e,w);continue}let x=k.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=(.*)$/);if(x){let w=x[1],D=se(e,x[2]),M=await ue(e,w);if(M)return M;v(w),f&&vn(e,w),d&&bn(e,w),p&&Sn(e,w);let j=he(e,w).length>0||e.state.associativeArrays?.has(w);if(It(e,w)){let Y=T(e.state.env,w,"0"),re=parseInt(Y,10)||0,Ee=parseInt(await ui(e,D),10)||0;D=String(re+Ee),y(e.state.env,w,D)}else if(j){D=mt(e,w,D);let Y=`${w}_0`,re=T(e.state.env,Y);y(e.state.env,Y,re+D)}else{D=mt(e,w,D);let Y=T(e.state.env,w);y(e.state.env,w,Y+D)}N(w),r&&be(e,w),i&&Oe(e,w),e.state.options.allexport&&!c&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(w));continue}if(k.includes("=")){let w=k.indexOf("="),D=k.slice(0,w),M=k.slice(w+1);if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(D)){I+=`bash: typeset: \`${D}': not a valid identifier
98
- `,P=1;continue}let J=await ue(e,D);if(J)return J;if(v(D),o){if(M!==""&&!/^[a-zA-Z_][a-zA-Z0-9_]*(\[.+\])?$/.test(M)){I+=`bash: declare: \`${M}': invalid variable name for name reference
99
- `,P=1;continue}y(e.state.env,D,M),Be(e,D),M!==""&&js(e,M)&&zs(e,D),N(D),r&&be(e,D),i&&Oe(e,D);continue}if(f&&vn(e,D),d&&bn(e,D),p&&Sn(e,D),It(e,D)&&(M=await ui(e,M)),M=mt(e,D,M),ve(e,D)){let j=Me(e,D);j&&j!==D?y(e.state.env,j,M):y(e.state.env,D,M)}else y(e.state.env,D,M);N(D),r&&be(e,D),i&&Oe(e,D),e.state.options.allexport&&!c&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(D))}else{let w=k;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(w)){I+=`bash: typeset: \`${w}': not a valid identifier
100
- `,P=1;continue}if(s||n?C(w):v(w),o){Be(e,w);let M=T(e.state.env,w);M!==""&&!/^[a-zA-Z_][a-zA-Z0-9_]*(\[.+\])?$/.test(M)?ur(e,w):M&&js(e,M)&&zs(e,w),N(w),r&&be(e,w),i&&Oe(e,w);continue}if(f&&vn(e,w),d&&bn(e,w),p&&Sn(e,w),n){if(he(e,w).length>0){I+=`bash: declare: ${w}: cannot convert indexed to associative array
101
- `,P=1;continue}e.state.associativeArrays??=new Set,e.state.associativeArrays.add(w)}let D=Array.from(e.state.env.keys()).some(M=>M.startsWith(`${w}_`)&&!M.startsWith(`${w}__length`));!e.state.env.has(w)&&!D&&(s||n?y(e.state.env,`${w}__length`,"0"):(e.state.declaredVars??=new Set,e.state.declaredVars.add(w))),N(w),r&&be(e,w),i&&Oe(e,w)}}return W(L,F(I),P)}async function $n(e,t){let s=!1,n=!1,r=!1,i=[];for(let a=0;a<t.length;a++){let o=t[a];if(o==="-a")s=!0;else if(o==="-A")n=!0;else if(o==="-p")r=!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 u=e.state.env.get(l);if(u!==void 0){let c=H(u??L).replace(/\\/g,"\\\\").replace(/"/g,'\\"');a+=`declare -r ${l}="${c}"
102
- `}}return G(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],p=await ue(e,f);if(p)return p;let m=Fe(d);if(e.state.associativeArrays?.has(f)){let h=ds(d);for(let[b,S]of h){let $=se(e,S);y(e.state.env,`${f}_${b}`,$)}}else{let h=he(e,f),b=0,S=e.state.env.get(f);h.length===0&&S!==void 0?(e.state.env.set(`${f}_0`,S),e.state.env.delete(f),b=1):h.length>0&&(b=Math.max(...h)+1);for(let g=0;g<m.length;g++)y(e.state.env,`${f}_${b+g}`,se(e,m[g]));let $=b+m.length;y(e.state.env,`${f}__length`,String($))}be(e,f);continue}let l=a.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=(.*)$/);if(l){let f=l[1],d=se(e,l[2]),p=await ue(e,f);if(p)return p;let m=T(e.state.env,f);y(e.state.env,f,m+d),be(e,f);continue}let u=Ur(a);if(u.value===void 0&&!u.isArray){be(e,u.name);continue}let c=await Gr(e,u,{makeReadonly:!0});if(c)return c}return ut}function An(e){return e.state.directoryStack??=[],e.state.directoryStack}function Rt(e,t){return t&&e===t?"~":t&&e.startsWith(`${t}/`)?`~${e.slice(t.length)}`:e}function Qo(e){let t=e.split("/").filter(n=>n&&n!=="."),s=[];for(let n of t)n===".."?s.pop():s.push(n);return`/${s.join("/")}`}async function Cn(e,t){let s=An(e),n;for(let o=0;o<t.length;o++){let l=t[o];if(l==="--"){if(o+1<t.length){if(n!==void 0)return A(`bash: pushd: too many arguments
103
- `,2);n=t[o+1],o++}}else{if(l.startsWith("-")&&l!=="-")return A(`bash: pushd: ${l}: invalid option
104
- `,2);if(n!==void 0)return A(`bash: pushd: too many arguments
105
- `,2);n=l}}if(n===void 0){if(s.length<2)return A(`bash: pushd: no other directory
106
- `,1);let o=s[0];s[0]=s[1],s[1]=o,n=s[0]}let r;if(n.startsWith("/"))r=n;else if(n===".."){let o=e.state.cwd.split("/").filter(l=>l);o.pop(),r=`/${o.join("/")}`}else n==="."?r=e.state.cwd:n.startsWith("~")?r=T(e.state.env,"HOME","/")+n.slice(1):r=`${e.state.cwd}/${n}`;r=Qo(r);try{if(!(await e.fs.stat(r)).isDirectory)return A(`bash: pushd: ${n}: Not a directory
107
- `,1)}catch{return A(`bash: pushd: ${n}: No such file or directory
108
- `,1)}s.unshift(e.state.cwd),e.state.previousDir=e.state.cwd,e.state.cwd=r,y(e.state.env,"PWD",r),y(e.state.env,"OLDPWD",e.state.previousDir);let i=T(e.state.env,"HOME",""),a=`${[r,...s].map(o=>Rt(o,i)).join(" ")}
109
- `;return G(a)}function kn(e,t){let s=An(e);for(let a of t)if(a!=="--")return a.startsWith("-")&&a!=="-"?A(`bash: popd: ${a}: invalid option
110
- `,2):A(`bash: popd: too many arguments
111
- `,2);if(s.length===0)return A(`bash: popd: directory stack empty
112
- `,1);let n=s.shift();if(!n)return A(`bash: popd: directory stack empty
113
- `,1);e.state.previousDir=e.state.cwd,e.state.cwd=n,y(e.state.env,"PWD",n),y(e.state.env,"OLDPWD",e.state.previousDir);let r=T(e.state.env,"HOME",""),i=`${[n,...s].map(a=>Rt(a,r)).join(" ")}
114
- `;return G(i)}function Pn(e,t){let s=An(e),n=!1,r=!1,i=!1,a=!1;for(let c of t)if(c!=="--")if(c.startsWith("-"))for(let f of c.slice(1))if(f==="c")n=!0;else if(f==="l")r=!0;else if(f==="p")i=!0;else if(f==="v")i=!0,a=!0;else return A(`bash: dirs: -${f}: invalid option
115
- `,2);else return A(`bash: dirs: too many arguments
116
- `,1);if(n)return e.state.directoryStack=[],ut;let o=[e.state.cwd,...s],l=T(e.state.env,"HOME",""),u;return a?(u=o.map((c,f)=>{let d=r?c:Rt(c,l);return` ${f} ${d}`}).join(`
117
- `),u+=`
118
- `):i?u=o.map(c=>r?c:Rt(c,l)).join(`
97
+ `;return G(O)}let k=!0;for(let O of S)e.state.functions.has(O)||(k=!1);return W(R,R,k?0:1)}if(a&&S.length>0)return ii(e,S);if(a&&S.length===0)return oi(e,{filterExport:i,filterReadonly:r,filterNameref:o,filterIndexedArray:s,filterAssocArray:n});if(S.length===0&&n&&!a)return ai(e);if(S.length===0&&s&&!a)return li(e);if(S.length===0&&!a)return ci(e);let M="",$=0;for(let k of S){let O=k.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\((.*)\)$/s);if(O&&!c){let w=O[1],I=O[2];if(n&&he(e,w).length>0){M+=`bash: declare: ${w}: cannot convert indexed to associative array
98
+ `,$=1;continue}if((s||!n&&!s)&&e.state.associativeArrays?.has(w)){M+=`bash: declare: ${w}: cannot convert associative to indexed array
99
+ `,$=1;continue}if(P(w),n&&(e.state.associativeArrays??=new Set,e.state.associativeArrays.add(w)),Le(e,w),e.state.env.delete(w),e.state.env.delete(`${w}__length`),n&&I.includes("[")){let L=hs(I);for(let[J,j]of L){let X=se(e,j);y(e.state.env,`${w}_${J}`,X)}}else if(n){let L=Fe(I);for(let J=0;J<L.length;J+=2){let j=L[J],X=J+1<L.length?se(e,L[J+1]):"";y(e.state.env,`${w}_${j}`,X)}}else{let L=Fe(I);if(L.some(j=>/^\[[^\]]+\]=/.test(j))){let j=0;for(let X of L){let re=X.match(/^\[([^\]]+)\]=(.*)$/);if(re){let Ee=re[1],nt=re[2],eo=se(e,nt),vt;if(/^-?\d+$/.test(Ee))vt=Number.parseInt(Ee,10);else try{let to=new Z,so=le(to,Ee);vt=await Q(e,so.expression)}catch{vt=0}y(e.state.env,`${w}_${vt}`,eo),j=vt+1}else{let Ee=se(e,X);y(e.state.env,`${w}_${j}`,Ee),j++}}}else{for(let j=0;j<L.length;j++)y(e.state.env,`${w}_${j}`,L[j]);y(e.state.env,`${w}__length`,String(L.length))}}N(w),r&&be(e,w),i&&Oe(e,w);continue}if(l){let w=k.includes("=")?k.slice(0,k.indexOf("=")):k;if(cr(e,w),!k.includes("="))continue}if(u){let w=k.includes("=")?k.slice(0,k.indexOf("=")):k;if(Yt(e,w),!k.includes("="))continue}let D=Yo(k);if(D){let{name:w,indexExpr:I,value:L}=D,J=await ue(e,w);if(J)return J;P(w);let j;try{let re=new Z,Ee=le(re,I);j=await Q(e,Ee.expression)}catch{let re=parseInt(I,10);j=Number.isNaN(re)?0:re}y(e.state.env,`${w}_${j}`,L);let X=parseInt(x(e.state.env,`${w}__length`,"0"),10);j>=X&&y(e.state.env,`${w}__length`,String(j+1)),N(w),r&&be(e,w),i&&Oe(e,w);continue}let _=k.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=\((.*)\)$/s);if(_&&!c){let w=_[1],I=_[2],L=await ue(e,w);if(L)return L;P(w);let J=Fe(I);if(e.state.associativeArrays?.has(w)){let j=hs(I);for(let[X,re]of j){let Ee=se(e,re);y(e.state.env,`${w}_${X}`,Ee)}}else{let j=he(e,w),X=0,re=e.state.env.get(w);j.length===0&&re!==void 0?(e.state.env.set(`${w}_0`,re),e.state.env.delete(w),X=1):j.length>0&&(X=Math.max(...j)+1);for(let nt=0;nt<J.length;nt++)y(e.state.env,`${w}_${X+nt}`,se(e,J[nt]));let Ee=X+J.length;y(e.state.env,`${w}__length`,String(Ee))}N(w),r&&be(e,w),i&&Oe(e,w);continue}let T=k.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=(.*)$/);if(T){let w=T[1],I=se(e,T[2]),L=await ue(e,w);if(L)return L;g(w),f&&vn(e,w),d&&bn(e,w),p&&Sn(e,w);let j=he(e,w).length>0||e.state.associativeArrays?.has(w);if(Rt(e,w)){let X=x(e.state.env,w,"0"),re=parseInt(X,10)||0,Ee=parseInt(await ui(e,I),10)||0;I=String(re+Ee),y(e.state.env,w,I)}else if(j){I=mt(e,w,I);let X=`${w}_0`,re=x(e.state.env,X);y(e.state.env,X,re+I)}else{I=mt(e,w,I);let X=x(e.state.env,w);y(e.state.env,w,X+I)}N(w),r&&be(e,w),i&&Oe(e,w),e.state.options.allexport&&!u&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(w));continue}if(k.includes("=")){let w=k.indexOf("="),I=k.slice(0,w),L=k.slice(w+1);if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(I)){M+=`bash: typeset: \`${I}': not a valid identifier
100
+ `,$=1;continue}let J=await ue(e,I);if(J)return J;if(g(I),o){if(L!==""&&!/^[a-zA-Z_][a-zA-Z0-9_]*(\[.+\])?$/.test(L)){M+=`bash: declare: \`${L}': invalid variable name for name reference
101
+ `,$=1;continue}y(e.state.env,I,L),Be(e,I),L!==""&&js(e,L)&&zs(e,I),N(I),r&&be(e,I),i&&Oe(e,I);continue}if(f&&vn(e,I),d&&bn(e,I),p&&Sn(e,I),Rt(e,I)&&(L=await ui(e,L)),L=mt(e,I,L),ve(e,I)){let j=Me(e,I);j&&j!==I?y(e.state.env,j,L):y(e.state.env,I,L)}else y(e.state.env,I,L);N(I),r&&be(e,I),i&&Oe(e,I),e.state.options.allexport&&!u&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(I))}else{let w=k;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(w)){M+=`bash: typeset: \`${w}': not a valid identifier
102
+ `,$=1;continue}if(s||n?P(w):g(w),o){Be(e,w);let L=x(e.state.env,w);L!==""&&!/^[a-zA-Z_][a-zA-Z0-9_]*(\[.+\])?$/.test(L)?ur(e,w):L&&js(e,L)&&zs(e,w),N(w),r&&be(e,w),i&&Oe(e,w);continue}if(f&&vn(e,w),d&&bn(e,w),p&&Sn(e,w),n){if(he(e,w).length>0){M+=`bash: declare: ${w}: cannot convert indexed to associative array
103
+ `,$=1;continue}e.state.associativeArrays??=new Set,e.state.associativeArrays.add(w)}let I=Array.from(e.state.env.keys()).some(L=>L.startsWith(`${w}_`)&&!L.startsWith(`${w}__length`));!e.state.env.has(w)&&!I&&(s||n?y(e.state.env,`${w}__length`,"0"):(e.state.declaredVars??=new Set,e.state.declaredVars.add(w))),N(w),r&&be(e,w),i&&Oe(e,w)}}return W(R,F(M),$)}async function $n(e,t){let s=!1,n=!1,r=!1,i=[];for(let a=0;a<t.length;a++){let o=t[a];if(o==="-a")s=!0;else if(o==="-A")n=!0;else if(o==="-p")r=!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=U(c??R).replace(/\\/g,"\\\\").replace(/"/g,'\\"');a+=`declare -r ${l}="${u}"
104
+ `}}return G(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],p=await ue(e,f);if(p)return p;let m=Fe(d);if(e.state.associativeArrays?.has(f)){let h=hs(d);for(let[v,S]of h){let E=se(e,S);y(e.state.env,`${f}_${v}`,E)}}else{let h=he(e,f),v=0,S=e.state.env.get(f);h.length===0&&S!==void 0?(e.state.env.set(`${f}_0`,S),e.state.env.delete(f),v=1):h.length>0&&(v=Math.max(...h)+1);for(let b=0;b<m.length;b++)y(e.state.env,`${f}_${v+b}`,se(e,m[b]));let E=v+m.length;y(e.state.env,`${f}__length`,String(E))}be(e,f);continue}let l=a.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=(.*)$/);if(l){let f=l[1],d=se(e,l[2]),p=await ue(e,f);if(p)return p;let m=x(e.state.env,f);y(e.state.env,f,m+d),be(e,f);continue}let c=Hr(a);if(c.value===void 0&&!c.isArray){be(e,c.name);continue}let u=await Gr(e,c,{makeReadonly:!0});if(u)return u}return ut}function An(e){return e.state.directoryStack??=[],e.state.directoryStack}function Lt(e,t){return t&&e===t?"~":t&&e.startsWith(`${t}/`)?`~${e.slice(t.length)}`:e}function Qo(e){let t=e.split("/").filter(n=>n&&n!=="."),s=[];for(let n of t)n===".."?s.pop():s.push(n);return`/${s.join("/")}`}async function Cn(e,t){let s=An(e),n;for(let o=0;o<t.length;o++){let l=t[o];if(l==="--"){if(o+1<t.length){if(n!==void 0)return C(`bash: pushd: too many arguments
105
+ `,2);n=t[o+1],o++}}else{if(l.startsWith("-")&&l!=="-")return C(`bash: pushd: ${l}: invalid option
106
+ `,2);if(n!==void 0)return C(`bash: pushd: too many arguments
107
+ `,2);n=l}}if(n===void 0){if(s.length<2)return C(`bash: pushd: no other directory
108
+ `,1);let o=s[0];s[0]=s[1],s[1]=o,n=s[0]}let r;if(n.startsWith("/"))r=n;else if(n===".."){let o=e.state.cwd.split("/").filter(l=>l);o.pop(),r=`/${o.join("/")}`}else n==="."?r=e.state.cwd:n.startsWith("~")?r=x(e.state.env,"HOME","/")+n.slice(1):r=`${e.state.cwd}/${n}`;r=Qo(r);try{if(!(await e.fs.stat(r)).isDirectory)return C(`bash: pushd: ${n}: Not a directory
109
+ `,1)}catch{return C(`bash: pushd: ${n}: No such file or directory
110
+ `,1)}s.unshift(e.state.cwd),e.state.previousDir=e.state.cwd,e.state.cwd=r,y(e.state.env,"PWD",r),y(e.state.env,"OLDPWD",e.state.previousDir);let i=x(e.state.env,"HOME",""),a=`${[r,...s].map(o=>Lt(o,i)).join(" ")}
111
+ `;return G(a)}function kn(e,t){let s=An(e);for(let a of t)if(a!=="--")return a.startsWith("-")&&a!=="-"?C(`bash: popd: ${a}: invalid option
112
+ `,2):C(`bash: popd: too many arguments
113
+ `,2);if(s.length===0)return C(`bash: popd: directory stack empty
114
+ `,1);let n=s.shift();if(!n)return C(`bash: popd: directory stack empty
115
+ `,1);e.state.previousDir=e.state.cwd,e.state.cwd=n,y(e.state.env,"PWD",n),y(e.state.env,"OLDPWD",e.state.previousDir);let r=x(e.state.env,"HOME",""),i=`${[n,...s].map(a=>Lt(a,r)).join(" ")}
116
+ `;return G(i)}function Pn(e,t){let s=An(e),n=!1,r=!1,i=!1,a=!1;for(let u of t)if(u!=="--")if(u.startsWith("-"))for(let f of u.slice(1))if(f==="c")n=!0;else if(f==="l")r=!0;else if(f==="p")i=!0;else if(f==="v")i=!0,a=!0;else return C(`bash: dirs: -${f}: invalid option
117
+ `,2);else return C(`bash: dirs: too many arguments
118
+ `,1);if(n)return e.state.directoryStack=[],ut;let o=[e.state.cwd,...s],l=x(e.state.env,"HOME",""),c;return a?(c=o.map((u,f)=>{let d=r?u:Lt(u,l);return` ${f} ${d}`}).join(`
119
+ `),c+=`
120
+ `):i?c=o.map(u=>r?u:Lt(u,l)).join(`
119
121
  `)+`
120
- `:u=o.map(c=>r?c:Rt(c,l)).join(" ")+`
121
- `,G(u)}async function Ss(e,t,s){let n=t;if(n.length>0){let o=n[0];if(o==="--")n=n.slice(1);else if(o.startsWith("-")&&o!=="-"&&o.length>1)return A(`bash: eval: ${o}: invalid option
122
+ `:c=o.map(u=>r?u:Lt(u,l)).join(" ")+`
123
+ `,G(c)}async function Es(e,t,s){let n=t;if(n.length>0){let o=n[0];if(o==="--")n=n.slice(1);else if(o.startsWith("-")&&o!=="-"&&o.length>1)return C(`bash: eval: ${o}: invalid option
122
124
  eval: usage: eval [arg ...]
123
- `,2)}if(n.length===0)return B();let r=n.join(" ");if(r.trim()==="")return B();let i=e.state.groupStdin,a=s??e.state.groupStdin;a!==void 0&&(e.state.groupStdin=a);try{let o=Ie(r),l=await e.executeScript(o);return await X(e,l)}catch(o){if(await ee(e,o),o instanceof $e||o instanceof Ae||o instanceof ye||o instanceof q)throw o;if(o.name==="ParseException")return A(`bash: eval: ${o.message}
125
+ `,2)}if(n.length===0)return B();let r=n.join(" ");if(r.trim()==="")return B();let i=e.state.groupStdin,a=s??e.state.groupStdin;a!==void 0&&(e.state.groupStdin=a);try{let o=De(r),l=await e.executeScript(o);return await Y(e,l)}catch(o){if(await ee(e,o),o instanceof $e||o instanceof Ae||o instanceof ye||o instanceof q)throw o;if(o.name==="ParseException")return C(`bash: eval: ${o.message}
124
126
  `);throw o}finally{e.state.groupStdin=i}}async function _n(e,t){let s,n;if(t.length===0)s=e.state.lastExitCode;else{let r=t[0],i=Number.parseInt(r,10);r===""||Number.isNaN(i)||!/^-?\d+$/.test(r)?(n=`bash: exit: ${r}: numeric argument required
125
- `,s=2):s=(i%256+256)%256}throw n&&await U(e,2,n,!0),new q(s)}function xn(e,t){let s=!1,n=[];for(let a of t)a==="-n"?s=!0:a==="-p"||a==="--"||n.push(a);if(n.length===0&&!s){let a="",o=e.state.exportedVars??new Set,l=Array.from(o).sort();for(let u of l){let c=e.state.env.get(u);if(c!==void 0){let f=H(c??L).replace(/\\/g,"\\\\").replace(/"/g,'\\"');a+=`declare -x ${u}="${f}"
126
- `}}return G(a)}if(s){for(let a of n){let o,l;if(a.includes("=")){let u=a.indexOf("=");o=a.slice(0,u),l=se(e,a.slice(u+1)),y(e.state.env,o,l)}else o=a;Xt(e,o)}return ut}let r="",i=0;for(let a of n){let o,l,u=!1,c=a.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=(.*)$/);if(c)o=c[1],l=se(e,c[2]),u=!0;else if(a.includes("=")){let f=a.indexOf("=");o=a.slice(0,f),l=se(e,a.slice(f+1))}else o=a;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(o)){r+=`bash: export: \`${a}': not a valid identifier
127
- `,i=1;continue}if(l!==void 0)if(u){let f=T(e.state.env,o);y(e.state.env,o,f+l)}else y(e.state.env,o,l);else e.state.env.has(o)||y(e.state.env,o,"");Oe(e,o)}return W(L,F(r),i)}function Es(e,t){if(t.length<2)return A(`bash: getopts: usage: getopts optstring name [arg ...]
128
- `);let s=t[0],n=t[1],r=!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(n),i=s.startsWith(":"),a=i?s.slice(1):s,o;if(t.length>2)o=t.slice(2);else{let h=Number.parseInt(T(e.state.env,"#","0"),10);o=[];for(let b=1;b<=h;b++)o.push(T(e.state.env,String(b))||"")}let l=Number.parseInt(T(e.state.env,"OPTIND","1"),10);l<1&&(l=1);let u=Number.parseInt(T(e.state.env,"__GETOPTS_CHARINDEX","0"),10);if(y(e.state.env,"OPTARG",""),l>o.length)return r||y(e.state.env,n,"?"),y(e.state.env,"OPTIND",String(o.length+1)),y(e.state.env,"__GETOPTS_CHARINDEX","0"),{exitCode:r?2:1,stdout:E(),stderr:E()};let c=o[l-1];if(!c||c==="-"||!c.startsWith("-"))return r||y(e.state.env,n,"?"),{exitCode:r?2:1,stdout:E(),stderr:E()};if(c==="--")return y(e.state.env,"OPTIND",String(l+1)),y(e.state.env,"__GETOPTS_CHARINDEX","0"),r||y(e.state.env,n,"?"),{exitCode:r?2:1,stdout:E(),stderr:E()};let f=u===0?1:u,d=c[f];if(!d)return y(e.state.env,"OPTIND",String(l+1)),y(e.state.env,"__GETOPTS_CHARINDEX","0"),Es(e,t);let p=a.indexOf(d);if(p===-1){let h="";return i?y(e.state.env,"OPTARG",d):h=`bash: illegal option -- ${d}
129
- `,r||y(e.state.env,n,"?"),f+1<c.length?(y(e.state.env,"__GETOPTS_CHARINDEX",String(f+1)),y(e.state.env,"OPTIND",String(l))):(y(e.state.env,"OPTIND",String(l+1)),y(e.state.env,"__GETOPTS_CHARINDEX","0")),{exitCode:r?2:0,stdout:E(),stderr:V(h)}}if(p+1<a.length&&a[p+1]===":")if(f+1<c.length)y(e.state.env,"OPTARG",c.slice(f+1)),y(e.state.env,"OPTIND",String(l+1)),y(e.state.env,"__GETOPTS_CHARINDEX","0");else{if(l>=o.length){let h="";return i?(y(e.state.env,"OPTARG",d),r||y(e.state.env,n,":")):(h=`bash: option requires an argument -- ${d}
130
- `,r||y(e.state.env,n,"?")),y(e.state.env,"OPTIND",String(l+1)),y(e.state.env,"__GETOPTS_CHARINDEX","0"),{exitCode:r?2:0,stdout:E(),stderr:V(h)}}y(e.state.env,"OPTARG",o[l]),y(e.state.env,"OPTIND",String(l+2)),y(e.state.env,"__GETOPTS_CHARINDEX","0")}else f+1<c.length?(y(e.state.env,"__GETOPTS_CHARINDEX",String(f+1)),y(e.state.env,"OPTIND",String(l))):(y(e.state.env,"OPTIND",String(l+1)),y(e.state.env,"__GETOPTS_CHARINDEX","0"));return r||y(e.state.env,n,d),{exitCode:r?2:0,stdout:E(),stderr:E()}}async function Tn(e,t){e.state.hashTable||(e.state.hashTable=new Map);let s=!1,n=!1,r=!1,i=!1,a=!1,o="",l=[],u=0;for(;u<t.length;){let m=t[u];if(m==="--"){u++,l.push(...t.slice(u));break}if(m==="-r")s=!0,u++;else if(m==="-d")n=!0,u++;else if(m==="-l")r=!0,u++;else if(m==="-t")a=!0,u++;else if(m==="-p"){if(i=!0,u++,u>=t.length)return A(`bash: hash: -p: option requires an argument
131
- `,1);o=t[u],u++}else if(m.startsWith("-")&&m.length>1){for(let h of m.slice(1))if(h==="r")s=!0;else if(h==="d")n=!0;else if(h==="l")r=!0;else if(h==="t")a=!0;else return h==="p"?A(`bash: hash: -p: option requires an argument
132
- `,1):A(`bash: hash: -${h}: invalid option
133
- `,1);u++}else l.push(m),u++}if(s)return e.state.hashTable.clear(),B();if(n){if(l.length===0)return A(`bash: hash: -d: option requires an argument
134
- `,1);let m=!1,h="";for(let b of l)e.state.hashTable.has(b)?e.state.hashTable.delete(b):(h+=`bash: hash: ${b}: not found
135
- `,m=!0);return m?A(h,1):B()}if(a){if(l.length===0)return A(`bash: hash: -t: option requires an argument
136
- `,1);let m="",h=!1,b="";for(let S of l){let $=e.state.hashTable.get(S);$?l.length>1?m+=`${S} ${$}
137
- `:m+=`${$}
138
- `:(b+=`bash: hash: ${S}: not found
139
- `,h=!0)}return h?{exitCode:1,stdout:V(m),stderr:V(b)}:G(m)}if(i){if(l.length===0)return A(`bash: hash: usage: hash [-lr] [-p pathname] [-dt] [name ...]
127
+ `,s=2):s=(i%256+256)%256}throw n&&await H(e,2,n,!0),new q(s)}function Tn(e,t){let s=!1,n=[];for(let a of t)a==="-n"?s=!0:a==="-p"||a==="--"||n.push(a);if(n.length===0&&!s){let a="",o=e.state.exportedVars??new Set,l=Array.from(o).sort();for(let c of l){let u=e.state.env.get(c);if(u!==void 0){let f=U(u??R).replace(/\\/g,"\\\\").replace(/"/g,'\\"');a+=`declare -x ${c}="${f}"
128
+ `}}return G(a)}if(s){for(let a of n){let o,l;if(a.includes("=")){let c=a.indexOf("=");o=a.slice(0,c),l=se(e,a.slice(c+1)),y(e.state.env,o,l)}else o=a;Yt(e,o)}return ut}let r="",i=0;for(let a of n){let o,l,c=!1,u=a.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=(.*)$/);if(u)o=u[1],l=se(e,u[2]),c=!0;else if(a.includes("=")){let f=a.indexOf("=");o=a.slice(0,f),l=se(e,a.slice(f+1))}else o=a;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(o)){r+=`bash: export: \`${a}': not a valid identifier
129
+ `,i=1;continue}if(l!==void 0)if(c){let f=x(e.state.env,o);y(e.state.env,o,f+l)}else y(e.state.env,o,l);else e.state.env.has(o)||y(e.state.env,o,"");Oe(e,o)}return W(R,F(r),i)}function $s(e,t){if(t.length<2)return C(`bash: getopts: usage: getopts optstring name [arg ...]
130
+ `);let s=t[0],n=t[1],r=!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(n),i=s.startsWith(":"),a=i?s.slice(1):s,o;if(t.length>2)o=t.slice(2);else{let h=Number.parseInt(x(e.state.env,"#","0"),10);o=[];for(let v=1;v<=h;v++)o.push(x(e.state.env,String(v))||"")}let l=Number.parseInt(x(e.state.env,"OPTIND","1"),10);l<1&&(l=1);let c=Number.parseInt(x(e.state.env,"__GETOPTS_CHARINDEX","0"),10);if(y(e.state.env,"OPTARG",""),l>o.length)return r||y(e.state.env,n,"?"),y(e.state.env,"OPTIND",String(o.length+1)),y(e.state.env,"__GETOPTS_CHARINDEX","0"),{exitCode:r?2:1,stdout:A(),stderr:A()};let u=o[l-1];if(!u||u==="-"||!u.startsWith("-"))return r||y(e.state.env,n,"?"),{exitCode:r?2:1,stdout:A(),stderr:A()};if(u==="--")return y(e.state.env,"OPTIND",String(l+1)),y(e.state.env,"__GETOPTS_CHARINDEX","0"),r||y(e.state.env,n,"?"),{exitCode:r?2:1,stdout:A(),stderr:A()};let f=c===0?1:c,d=u[f];if(!d)return y(e.state.env,"OPTIND",String(l+1)),y(e.state.env,"__GETOPTS_CHARINDEX","0"),$s(e,t);let p=a.indexOf(d);if(p===-1){let h="";return i?y(e.state.env,"OPTARG",d):h=`bash: illegal option -- ${d}
131
+ `,r||y(e.state.env,n,"?"),f+1<u.length?(y(e.state.env,"__GETOPTS_CHARINDEX",String(f+1)),y(e.state.env,"OPTIND",String(l))):(y(e.state.env,"OPTIND",String(l+1)),y(e.state.env,"__GETOPTS_CHARINDEX","0")),{exitCode:r?2:0,stdout:A(),stderr:V(h)}}if(p+1<a.length&&a[p+1]===":")if(f+1<u.length)y(e.state.env,"OPTARG",u.slice(f+1)),y(e.state.env,"OPTIND",String(l+1)),y(e.state.env,"__GETOPTS_CHARINDEX","0");else{if(l>=o.length){let h="";return i?(y(e.state.env,"OPTARG",d),r||y(e.state.env,n,":")):(h=`bash: option requires an argument -- ${d}
132
+ `,r||y(e.state.env,n,"?")),y(e.state.env,"OPTIND",String(l+1)),y(e.state.env,"__GETOPTS_CHARINDEX","0"),{exitCode:r?2:0,stdout:A(),stderr:V(h)}}y(e.state.env,"OPTARG",o[l]),y(e.state.env,"OPTIND",String(l+2)),y(e.state.env,"__GETOPTS_CHARINDEX","0")}else f+1<u.length?(y(e.state.env,"__GETOPTS_CHARINDEX",String(f+1)),y(e.state.env,"OPTIND",String(l))):(y(e.state.env,"OPTIND",String(l+1)),y(e.state.env,"__GETOPTS_CHARINDEX","0"));return r||y(e.state.env,n,d),{exitCode:r?2:0,stdout:A(),stderr:A()}}async function Nn(e,t){e.state.hashTable||(e.state.hashTable=new Map);let s=!1,n=!1,r=!1,i=!1,a=!1,o="",l=[],c=0;for(;c<t.length;){let m=t[c];if(m==="--"){c++,l.push(...t.slice(c));break}if(m==="-r")s=!0,c++;else if(m==="-d")n=!0,c++;else if(m==="-l")r=!0,c++;else if(m==="-t")a=!0,c++;else if(m==="-p"){if(i=!0,c++,c>=t.length)return C(`bash: hash: -p: option requires an argument
133
+ `,1);o=t[c],c++}else if(m.startsWith("-")&&m.length>1){for(let h of m.slice(1))if(h==="r")s=!0;else if(h==="d")n=!0;else if(h==="l")r=!0;else if(h==="t")a=!0;else return h==="p"?C(`bash: hash: -p: option requires an argument
134
+ `,1):C(`bash: hash: -${h}: invalid option
135
+ `,1);c++}else l.push(m),c++}if(s)return e.state.hashTable.clear(),B();if(n){if(l.length===0)return C(`bash: hash: -d: option requires an argument
136
+ `,1);let m=!1,h="";for(let v of l)e.state.hashTable.has(v)?e.state.hashTable.delete(v):(h+=`bash: hash: ${v}: not found
137
+ `,m=!0);return m?C(h,1):B()}if(a){if(l.length===0)return C(`bash: hash: -t: option requires an argument
138
+ `,1);let m="",h=!1,v="";for(let S of l){let E=e.state.hashTable.get(S);E?l.length>1?m+=`${S} ${E}
139
+ `:m+=`${E}
140
+ `:(v+=`bash: hash: ${S}: not found
141
+ `,h=!0)}return h?{exitCode:1,stdout:V(m),stderr:V(v)}:G(m)}if(i){if(l.length===0)return C(`bash: hash: usage: hash [-lr] [-p pathname] [-dt] [name ...]
140
142
  `,1);let m=l[0];return e.state.hashTable.set(m,o),B()}if(l.length===0){if(e.state.hashTable.size===0)return G(`hash: hash table empty
141
- `);let m="";if(r)for(let[h,b]of e.state.hashTable)m+=`builtin hash -p ${b} ${h}
143
+ `);let m="";if(r)for(let[h,v]of e.state.hashTable)m+=`builtin hash -p ${v} ${h}
142
144
  `;else{m=`hits command
143
145
  `;for(let[,h]of e.state.hashTable)m+=` 1 ${h}
144
- `}return G(m)}let c=!1,f="",p=T(e.state.env,"PATH","/usr/bin:/bin").split(":");for(let m of l){if(m.includes("/")){f+=`bash: hash: ${m}: cannot use / in name
145
- `,c=!0;continue}let h=!1;for(let b of p){if(!b)continue;let S=`${b}/${m}`;if(await e.fs.exists(S)){e.state.hashTable.set(m,S),h=!0;break}}h||(f+=`bash: hash: ${m}: not found
146
- `,c=!0)}return c?A(f,1):B()}var fi=new Map([[":",[": [arguments]",`Null command.
146
+ `}return G(m)}let u=!1,f="",p=x(e.state.env,"PATH","/usr/bin:/bin").split(":");for(let m of l){if(m.includes("/")){f+=`bash: hash: ${m}: cannot use / in name
147
+ `,u=!0;continue}let h=!1;for(let v of p){if(!v)continue;let S=`${v}/${m}`;if(await e.fs.exists(S)){e.state.hashTable.set(m,S),h=!0;break}}h||(f+=`bash: hash: ${m}: not found
148
+ `,u=!0)}return u?C(f,1):B()}var fi=new Map([[":",[": [arguments]",`Null command.
147
149
  No effect; the command does nothing.
148
150
  Exit Status:
149
151
  Always succeeds.`]],[".",[". filename [arguments]",`Execute commands from a file in the current shell.
@@ -488,46 +490,47 @@ eval: usage: eval [arg ...]
488
490
  job specification. With no ID, waits for all known jobs.
489
491
  Exit Status:
490
492
  Returns the status of the last ID; fails if ID is invalid or an invalid
491
- option is given.`]]]),di=[...fi.keys()].sort();function Nn(e,t){let s=!1,n=[],r=0;for(;r<t.length;){let l=t[r];if(l==="--"){for(r++;r<t.length;)n.push(t[r]),r++;break}if(l.startsWith("-")&&l.length>1){for(let u=1;u<l.length;u++){let c=l[u];if(c==="s")s=!0;else return A(`bash: help: -${c}: invalid option
492
- `,2)}r++}else n.push(l),r++}if(n.length===0)return ta();let i="",a=!1,o="";for(let l of n){let u=ea(l);if(u.length===0){o+=`bash: help: no help topics match \`${l}'. Try \`help help' or \`man -k ${l}' or \`info ${l}'.
493
- `,a=!0;continue}for(let c of u){let f=fi.get(c);if(!f)continue;let[d,p]=f;s?i+=`${c}: ${d}
494
- `:i+=`${c}: ${d}
493
+ option is given.`]]]),di=[...fi.keys()].sort();function xn(e,t){let s=!1,n=[],r=0;for(;r<t.length;){let l=t[r];if(l==="--"){for(r++;r<t.length;)n.push(t[r]),r++;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 C(`bash: help: -${u}: invalid option
494
+ `,2)}r++}else n.push(l),r++}if(n.length===0)return ta();let i="",a=!1,o="";for(let l of n){let c=ea(l);if(c.length===0){o+=`bash: help: no help topics match \`${l}'. Try \`help help' or \`man -k ${l}' or \`info ${l}'.
495
+ `,a=!0;continue}for(let u of c){let f=fi.get(u);if(!f)continue;let[d,p]=f;s?i+=`${u}: ${d}
496
+ `:i+=`${u}: ${d}
495
497
  ${p}
496
498
  `}}return{exitCode:a?1:0,stdout:V(i),stderr:V(o)}}function ea(e){let t=e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,"."),s=Ct(`^${t}$`);return di.filter(n=>s.test(n))}function ta(){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=di.slice(),n=Math.ceil(s.length/2);for(let r=0;r<n;r++){let i=s[r]||"",a=s[r+n]||"",o=i.padEnd(t);e.push(a?`${o}${a}`:i)}return G(`${e.join(`
497
499
  `)}
498
500
  `)}var sa=`jobs: usage: jobs [-lnprs] [jobspec ...] or jobs -x command [args]
499
- `;function na(e){return{stdout:E(),stderr:V(`bash: jobs: ${e}: invalid option
500
- ${sa}`),exitCode:2}}async function On(e,t,s){if(t[0]==="-x"){let f=t[1];if(!f)return{stdout:E(),stderr:E(),exitCode:0};if(!s)return{stdout:E(),stderr:V(`bash: jobs: -x: command execution unavailable
501
- `),exitCode:1};let d=[];for(let p of t.slice(2)){if(!p.startsWith("%")){d.push(p);continue}let m=e.processes.resolveJobSpec(p);if(m===void 0)return{stdout:E(),stderr:V(`bash: ${p}: no such job
502
- `),exitCode:1};d.push(String(m))}return s(f,d)}let n={long:!1,pidsOnly:!1,runningOnly:!1,stoppedOnly:!1,changedOnly:!1},r=0;for(;r<t.length;r++){let f=t[r];if(f==="--"){r++;break}if(!f.startsWith("-")||f==="-")break;for(let d of f.slice(1))if(d==="l")n.long=!0;else if(d==="n")n.changedOnly=!0;else if(d==="p")n.pidsOnly=!0;else if(d==="r")n.runningOnly=!0;else if(d==="s")n.stoppedOnly=!0;else return na(`-${d}`)}let i=t.slice(r),a=i.length===0?void 0:new Set(i.map(f=>e.processes.resolveJobSpec(f)).filter(f=>f!==void 0)),o="",l="",u=0;for(let f of i)e.processes.resolveJobSpec(f)===void 0&&(l+=`bash: jobs: ${f}: no such job
503
- `,u=1);let c=e.processes.listJobs(a,{changedOnly:n.changedOnly,runningOnly:n.runningOnly,stoppedOnly:n.stoppedOnly});for(let f of c){if(n.pidsOnly){o+=`${f.pid}
504
- `;continue}let d=f.state==="running"?"Running ":"Done ",p=n.long?`[${f.jobNumber}]${f.marker} ${f.pid} `:`[${f.jobNumber}]${f.marker} `;o+=`${p}${d}${f.command}
505
- `}return{stdout:V(o),stderr:V(l),exitCode:u}}var hi=`kill: usage: kill [-s sigspec | -n signum | -sigspec] pid | jobspec ... or kill -l [sigspec]
506
- `,$s=typeof process<"u"&&process.platform==="darwin",Dn=[{name:"HUP",number:1,delivery:"SIGTERM"},{name:"INT",number:2,delivery:"SIGINT"},{name:"QUIT",number:3,delivery:"SIGTERM"},{name:"KILL",number:9,delivery:"SIGKILL"},{name:"TERM",number:15,delivery:"SIGTERM"},{name:"USR1",number:$s?30:10,delivery:"SIGTERM"},{name:"USR2",number:$s?31:12,delivery:"SIGTERM"},{name:"STOP",number:$s?17:19,delivery:"SIGSTOP"},{name:"CONT",number:$s?19:18,delivery:"SIGCONT"}];function As(e){let t=e.toUpperCase().replace(/^SIG/,"");if(/^\d+$/.test(t)){let s=Number.parseInt(t,10);return Dn.find(n=>n.number===s)}return Dn.find(s=>s.name===t)}function In(e){return{stdout:E(),stderr:V(`bash: kill: ${e.replace(/^-/,"")}: invalid signal specification
507
- `),exitCode:1}}function ra(e){if(e.length===0)return{stdout:V(`${Dn.map(s=>`${s.number}) SIG${s.name}`).join(" ")}
508
- `),stderr:E(),exitCode:0};let t="";for(let s of e){let n=/^\d+$/.test(s)?String(Number.parseInt(s,10)-(Number(s)>128?128:0)):s,r=As(n);if(!r)return In(s);t+=/^\d+$/.test(s)?`${r.name}
501
+ `;function na(e){return{stdout:A(),stderr:V(`bash: jobs: ${e}: invalid option
502
+ ${sa}`),exitCode:2}}async function On(e,t,s){if(t[0]==="-x"){let d=t[1];if(!d)return{stdout:A(),stderr:A(),exitCode:0};if(!s)return{stdout:A(),stderr:V(`bash: jobs: -x: command execution unavailable
503
+ `),exitCode:1};let p=[];for(let m of t.slice(2)){if(!m.startsWith("%")){p.push(m);continue}let h=e.processes.resolveJobSpec(m);p.push(h===void 0?m:String(h))}return s(d,p)}let n={long:!1,pidsOnly:!1,runningOnly:!1,stoppedOnly:!1,changedOnly:!1},r=0;for(;r<t.length;r++){let d=t[r];if(d==="--"){r++;break}if(!d.startsWith("-")||d==="-")break;for(let p of d.slice(1))if(p==="l")n.long=!0;else if(p==="n")n.changedOnly=!0;else if(p==="p")n.pidsOnly=!0;else if(p==="r")n.runningOnly=!0;else if(p==="s")n.stoppedOnly=!0;else return na(`-${p}`)}let i=t.slice(r),a=d=>{let p=e.processes.resolveJobSpec(d);return p!==void 0&&e.processes.get(p)?p:void 0},o=i.length===0?void 0:new Set(i.map(a).filter(d=>d!==void 0)),l="",c="",u=0;for(let d of i)a(d)===void 0&&(c+=`bash: jobs: ${d}: no such job
504
+ `,u=1);let f=e.processes.listJobs(o,{changedOnly:n.changedOnly,runningOnly:n.runningOnly,stoppedOnly:n.stoppedOnly});for(let d of f){if(n.pidsOnly){l+=`${d.pid}
505
+ `;continue}let p=d.state==="running"?"Running ":"Done ",m=n.long?`[${d.jobNumber}]${d.marker} ${d.pid} `:`[${d.jobNumber}]${d.marker} `;l+=`${m}${p}${d.command}
506
+ `}return{stdout:V(l),stderr:V(c),exitCode:u}}var hi=`kill: usage: kill [-s sigspec | -n signum | -sigspec] pid | jobspec ... or kill -l [sigspec]
507
+ `,ra=typeof process<"u"&&process.platform==="darwin",ia=ra?["HUP","INT","QUIT","ILL","TRAP","ABRT","EMT","FPE","KILL","BUS","SEGV","SYS","PIPE","ALRM","TERM","URG","STOP","TSTP","CONT","CHLD","TTIN","TTOU","IO","XCPU","XFSZ","VTALRM","PROF","WINCH","INFO","USR1","USR2"]:["HUP","INT","QUIT","ILL","TRAP","ABRT","BUS","FPE","KILL","USR1","SEGV","USR2","PIPE","ALRM","TERM","STKFLT","CHLD","CONT","STOP","TSTP","TTIN","TTOU","URG","XCPU","XFSZ","VTALRM","PROF","WINCH","IO","PWR","SYS"],oa=new Set(["STOP","TSTP","TTIN","TTOU","CONT","CHLD","URG","WINCH","INFO"]);function aa(e){if(!oa.has(e))return e==="KILL"?"SIGKILL":e==="INT"?"SIGINT":"SIGTERM"}var In=ia.map((e,t)=>({name:e,number:t+1,delivery:aa(e)})),la={name:"0",number:0};function As(e){let t=e.toUpperCase().replace(/^SIG/,"");if(/^\d+$/.test(t)){let s=Number.parseInt(t,10);return s===0?la:In.find(n=>n.number===s)}return In.find(s=>s.name===t)}function Dn(e){return{stdout:A(),stderr:V(`bash: kill: ${e.replace(/^-/,"")}: invalid signal specification
508
+ `),exitCode:1}}function ca(e){if(e.length===0){let s="";for(let n of In)s+=`${String(n.number).padStart(2)}) SIG${n.name} `,n.number%4===0&&(s=`${s.slice(0,-1)}
509
+ `);return{stdout:V(s.endsWith(`
510
+ `)?s:`${s}
511
+ `),stderr:A(),exitCode:0}}let t="";for(let s of e){let n=/^\d+$/.test(s)?String(Number.parseInt(s,10)-(Number(s)>128?128:0)):s,r=As(n);if(!r)return Dn(s);t+=/^\d+$/.test(s)?`${r.name}
509
512
  `:`${r.number}
510
- `}return{stdout:V(t),stderr:E(),exitCode:0}}function Rn(e,t){let s=As("TERM"),n=0;if(t[0]==="-l")return ra(t.slice(1));if(t[0]==="-s"||t[0]==="-n"){let o=t[1];if(!o)return{stdout:E(),stderr:V(hi),exitCode:2};let l=As(o);if(!l)return In(o);s=l,n=2}else if(t[0]?.startsWith("-")&&t[0]!=="--"){let o=t[0].slice(1),l=As(o);if(!l)return In(o);s=l,n=1}else t[0]==="--"&&(n=1);let r=t.slice(n);if(r.length===0)return{stdout:E(),stderr:V(hi),exitCode:2};let i="",a=0;for(let o of r){let l;if(o.startsWith("%")){if(l=e.processes.resolveJobSpec(o),l===void 0){i+=`bash: kill: ${o}: no such job
511
- `,a=1;continue}}else if(/^\d+$/.test(o)){let u=Number(o);Number.isSafeInteger(u)&&u>0&&(l=u)}if(l===void 0){i+=`bash: kill: ${o}: arguments must be process or job IDs
512
- `,a=1;continue}e.processes.kill(l,s.delivery,s.number)||(i+=`bash: kill: (${l}) - No such process
513
- `,a=1)}return{stdout:E(),stderr:V(i),exitCode:a}}function ia(e){let t=[],s="",n=0;for(let r of e){for(let i of r)i==="("?n++:i===")"&&n--;s?s+=` ${r}`:s=r,n===0&&(t.push(s),s="")}return s&&t.push(s),t}async function Ln(e,t){if(t.length===0)return A(`bash: let: expression expected
514
- `);let s=ia(t),n=0;for(let r of s)try{let a=Ie(`(( ${r} ))`).statements[0];if(a&&a.pipelines.length>0&&a.pipelines[0].commands.length>0){let o=a.pipelines[0].commands[0];o.type==="ArithmeticCommand"&&(n=await Q(e,o.expression.expression))}}catch(i){return A(`bash: let: ${r}: ${i.message}
515
- `)}return W(L,L,n===0?1:0)}async function Mn(e,t){if(e.state.localScopes.length===0)return A(`bash: local: can only be used in a function
516
- `);let s=e.state.localScopes[e.state.localScopes.length-1],n="",r=0,i=!1,a=!1,o=!1,l=[];for(let u of t)if(u==="-n")i=!0;else if(u==="-a")a=!0;else if(u==="-p")o=!0;else if(u.startsWith("-")&&!u.includes("="))for(let c of u.slice(1))c==="n"?i=!0:c==="a"?a=!0:c==="p"&&(o=!0);else l.push(u);if(l.length===0){let u="",c=Array.from(s.keys()).filter(f=>!f.includes("_")||!f.match(/_\d+$/)).filter(f=>!f.includes("__length")).sort();for(let f of c){let d=e.state.env.get(f);if(d!==void 0){let p=H(d);u+=`${f}=${p}
517
- `}}return W(F(u),L,0)}for(let u of l){let c,f,d=u.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\((.*)\)$/s);if(d){c=d[1];let S=d[2];if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(c)){n+=`bash: local: \`${u}': not a valid identifier
518
- `,r=1;continue}if(await ue(e,c,"bash"),!s.has(c)){s.set(c,e.state.env.get(c));let v=`${c}_`;for(let C of e.state.env.keys())C.startsWith(v)&&!C.includes("__")&&(s.has(C)||s.set(C,e.state.env.get(C)))}let $=`${c}_`;for(let v of e.state.env.keys())v.startsWith($)&&!v.includes("__")&&e.state.env.delete(v);let g=Fe(S);for(let v=0;v<g.length;v++)y(e.state.env,`${c}_${v}`,g[v]);y(e.state.env,`${c}__length`,String(g.length)),Ke(e,c),i&&Be(e,c);continue}let p=u.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=\((.*)\)$/s);if(p){c=p[1];let S=p[2];if(await ue(e,c,"bash"),!s.has(c)){s.set(c,e.state.env.get(c));let I=`${c}_`;for(let k of e.state.env.keys())k.startsWith(I)&&!k.includes("__")&&(s.has(k)||s.set(k,e.state.env.get(k)));let P=`${c}__length`;e.state.env.has(P)&&!s.has(P)&&s.set(P,e.state.env.get(P))}let $=Fe(S),g=he(e,c),v=0,C=e.state.env.get(c);g.length===0&&C!==void 0?(e.state.env.set(`${c}_0`,C),e.state.env.delete(c),v=1):g.length>0&&(v=Math.max(...g)+1);for(let I=0;I<$.length;I++)y(e.state.env,`${c}_${v+I}`,se(e,$[I]));let N=v+$.length;y(e.state.env,`${c}__length`,String(N)),Ke(e,c),i&&Be(e,c);continue}let m=u.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=(.*)$/);if(m){c=m[1];let S=se(e,m[2]);await ue(e,c,"bash"),s.has(c)||s.set(c,e.state.env.get(c));let $=T(e.state.env,c);y(e.state.env,c,$+S),Ke(e,c),i&&Be(e,c);continue}let h=u.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([^\]]+)\]=(.*)$/s);if(h){c=h[1];let S=h[2],$=se(e,h[3]);if(await ue(e,c,"bash"),!s.has(c)){s.set(c,e.state.env.get(c));let C=`${c}_`;for(let I of e.state.env.keys())I.startsWith(C)&&!I.includes("__")&&(s.has(I)||s.set(I,e.state.env.get(I)));let N=`${c}__length`;e.state.env.has(N)&&!s.has(N)&&s.set(N,e.state.env.get(N))}let g;try{let C=new Z,N=le(C,S);g=await Q(e,N.expression)}catch{let C=parseInt(S,10);g=Number.isNaN(C)?0:C}y(e.state.env,`${c}_${g}`,$);let v=parseInt(T(e.state.env,`${c}__length`,"0"),10);g>=v&&y(e.state.env,`${c}__length`,String(g+1)),Ke(e,c),i&&Be(e,c);continue}if(u.includes("=")){let S=u.indexOf("=");c=u.slice(0,S),f=se(e,u.slice(S+1))}else c=u;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(c)){n+=`bash: local: \`${u}': not a valid identifier
519
- `,r=1;continue}let b=s.has(c);if(f!==void 0){let S=e.state.env.get(c);if(e.state.tempEnvBindings){let $=e.state.accessedTempEnvVars?.has(c),g=e.state.mutatedTempEnvVars?.has(c);if(!$&&!g)for(let v=e.state.tempEnvBindings.length-1;v>=0;v--){let C=e.state.tempEnvBindings[v];if(C.has(c)){S=C.get(c);break}}}qr(e,c,S)}if(!b){let S=e.state.env.get(c);if(e.state.tempEnvBindings)for(let $=e.state.tempEnvBindings.length-1;$>=0;$--){let g=e.state.tempEnvBindings[$];if(g.has(c)){S=g.get(c);break}}if(s.set(c,S),a){let $=`${c}_`;for(let v of e.state.env.keys())v.startsWith($)&&!v.includes("__")&&(s.has(v)||s.set(v,e.state.env.get(v)));let g=`${c}__length`;e.state.env.has(g)&&!s.has(g)&&s.set(g,e.state.env.get(g))}}if(a&&f===void 0){let S=`${c}_`;for(let $ of e.state.env.keys())$.startsWith(S)&&!$.includes("__")&&e.state.env.delete($);y(e.state.env,`${c}__length`,"0")}else if(f!==void 0){if(await ue(e,c,"bash"),i&&f!==""&&!/^[a-zA-Z_][a-zA-Z0-9_]*(\[.+\])?$/.test(f)){n+=`bash: local: \`${f}': invalid variable name for name reference
520
- `,r=1;continue}y(e.state.env,c,f),e.state.options.allexport&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(c))}else{let S=e.state.tempEnvBindings?.some($=>$.has(c));!b&&!S&&e.state.env.delete(c)}Ke(e,c),i&&Be(e,c)}return W(L,F(n),r)}async function Wn(e,t,s){let n=H(s),r=`
521
- `,i=0,a=0,o=0,l=!1,u="MAPFILE",c=0;for(;c<t.length;){let g=t[c];g==="-d"&&c+1<t.length?(r=t[c+1]===""?"\0":t[c+1]||`
522
- `,c+=2):g==="-n"&&c+1<t.length?(i=Number.parseInt(t[c+1],10)||0,c+=2):g==="-O"&&c+1<t.length?(a=Number.parseInt(t[c+1],10)||0,c+=2):g==="-s"&&c+1<t.length?(o=Number.parseInt(t[c+1],10)||0,c+=2):g==="-t"?(l=!0,c++):g==="-u"||g==="-C"||g==="-c"?c+=2:(g.startsWith("-")||(u=g),c++)}let f=n;!f&&e.state.groupStdin!==void 0&&(f=H(await ie(e.state.groupStdin)));let d=[],p=f,m=0,h=0,b=e.limits?.maxArrayElements??1e5;for(;p.length>0;){let g=p.indexOf(r);if(g===-1){if(p.length>0){if(h<o)h++;else if(i===0||m<i){if(a+m>=b)return W(L,F(`mapfile: array element limit exceeded (${b})
523
- `),1);let N=p,I=N.indexOf("\0");I!==-1&&(N=N.substring(0,I)),d.push(N),m++}}break}let v=p.substring(0,g),C=v.indexOf("\0");if(C!==-1&&(v=v.substring(0,C)),!l&&r!=="\0"&&(v+=r),p=p.substring(g+r.length),h<o){h++;continue}if(i>0&&m>=i)break;if(a+m>=b)return W(L,F(`mapfile: array element limit exceeded (${b})
524
- `),1);d.push(v),m++}a===0&&Le(e,u);for(let g=0;g<d.length;g++)y(e.state.env,`${u}_${a+g}`,d[g]);let S=parseInt(T(e.state.env,`${u}__length`,"0"),10),$=a+d.length;return y(e.state.env,`${u}__length`,String(Math.max(S,$))),e.state.groupStdin!==void 0&&!n&&(e.state.groupStdin=E()),W(L,L,0)}function oa(e){if(!e.startsWith("__rw__:"))return null;let t=e.slice(7),s=t.indexOf(":");if(s===-1)return null;let n=Number.parseInt(t.slice(0,s),10);if(Number.isNaN(n)||n<0)return null;let r=s+1,i=t.slice(r,r+n),a=r+n+1,o=t.slice(a),l=o.indexOf(":");if(l===-1)return null;let u=Number.parseInt(o.slice(0,l),10);if(Number.isNaN(u)||u<0)return null;let c=o.slice(l+1);return{path:i,position:u,content:c}}function aa(e,t,s){return`__rw__:${e.length}:${e}:${t}:${s}`}async function Fn(e,t,s,n=-1){let r=H(s),i=!1,a=`
525
- `,o="",l=-1,u=-1,c=null,f=-1,d=-1,p=[],m=0,h=!1,b=(_,x)=>{let w=1;for(;w<_.length;){let D=_[w];if(D==="r")i=!0,w++;else if(D==="s")w++;else{if(D==="d")return w+1<_.length?(a=_.substring(w+1),{nextArgIndex:x+1}):x+1<t.length?(a=t[x+1],{nextArgIndex:x+2}):{nextArgIndex:x+1};if(D==="n"){if(w+1<_.length){let M=_.substring(w+1);return l=Number.parseInt(M,10),(Number.isNaN(l)||l<0)&&(h=!0,l=0),{nextArgIndex:x+1}}else if(x+1<t.length)return l=Number.parseInt(t[x+1],10),(Number.isNaN(l)||l<0)&&(h=!0,l=0),{nextArgIndex:x+2};return{nextArgIndex:x+1}}else if(D==="N"){if(w+1<_.length){let M=_.substring(w+1);return u=Number.parseInt(M,10),(Number.isNaN(u)||u<0)&&(h=!0,u=0),{nextArgIndex:x+1}}else if(x+1<t.length)return u=Number.parseInt(t[x+1],10),(Number.isNaN(u)||u<0)&&(h=!0,u=0),{nextArgIndex:x+2};return{nextArgIndex:x+1}}else{if(D==="a")return w+1<_.length?(c=_.substring(w+1),{nextArgIndex:x+1}):x+1<t.length?(c=t[x+1],{nextArgIndex:x+2}):{nextArgIndex:x+1};if(D==="p")return w+1<_.length?(o=_.substring(w+1),{nextArgIndex:x+1}):x+1<t.length?(o=t[x+1],{nextArgIndex:x+2}):{nextArgIndex:x+1};if(D==="u"){if(w+1<_.length){let M=_.substring(w+1);return f=Number.parseInt(M,10),Number.isNaN(f)||f<0?{nextArgIndex:-2}:{nextArgIndex:x+1}}else if(x+1<t.length)return f=Number.parseInt(t[x+1],10),Number.isNaN(f)||f<0?{nextArgIndex:-2}:{nextArgIndex:x+2};return{nextArgIndex:x+1}}else if(D==="t"){if(w+1<_.length){let M=_.substring(w+1);return d=Number.parseFloat(M),Number.isNaN(d)&&(d=0),{nextArgIndex:x+1}}else if(x+1<t.length)return d=Number.parseFloat(t[x+1]),Number.isNaN(d)&&(d=0),{nextArgIndex:x+2};return{nextArgIndex:x+1}}else if(D==="e"||D==="i"||D==="P"){if(D==="i"&&x+1<t.length)return{nextArgIndex:x+2};w++}else w++}}}return{nextArgIndex:x+1}};for(;m<t.length;){let _=t[m];if(_.startsWith("-")&&_.length>1&&_!=="--"){let x=b(_,m);if(x.nextArgIndex===-1)return{stdout:E(),stderr:E(),exitCode:2};if(x.nextArgIndex===-2)return{stdout:E(),stderr:E(),exitCode:1};m=x.nextArgIndex}else if(_==="--")for(m++;m<t.length;)p.push(t[m]),m++;else p.push(_),m++}if(h)return W(L,L,1);if(p.length===0&&c===null&&p.push("REPLY"),d===0){if(c)Le(e,c);else{for(let _ of p)y(e.state.env,_,"");p.length===0&&y(e.state.env,"REPLY","")}return W(L,L,0)}if(d<0&&d!==-1)return W(L,L,1);let S=r;f>=0?e.state.fileDescriptors?S=e.state.fileDescriptors.get(f)||"":S="":!S&&e.state.groupStdin!==void 0&&(S=H(await ie(e.state.groupStdin)));let $=a===""?"\0":a,g="",v=0,C=!0,N=_=>{if(f>=0&&e.state.fileDescriptors)e.state.fileDescriptors.set(f,S.substring(_));else if(n>=0&&e.state.fileDescriptors){let x=e.state.fileDescriptors.get(n);if(x?.startsWith("__rw__:")){let w=oa(x);if(w){let D=w.position+_;e.state.fileDescriptors.set(n,aa(w.path,D,w.content))}}}else e.state.groupStdin!==void 0&&!r&&(e.state.groupStdin=de(F(S.substring(_))))};if(u>=0){let _=Math.min(u,S.length);g=S.substring(0,_),v=_,C=_>=u,N(v);let x=p[0]||"REPLY";y(e.state.env,x,g);for(let w=1;w<p.length;w++)y(e.state.env,p[w],"");return W(L,L,C?0:1)}else if(l>=0){let _=0,x=0,w=!1;for(;x<S.length&&_<l;){let D=S[x];if(D===$){v=x+1,w=!0;break}if(!i&&D==="\\"&&x+1<S.length){let M=S[x+1];if(M===$&&$===`
526
- `){x+=2,v=x;continue}if(M===$){x+=2,_++,g+=M,v=x;continue}g+=M,x+=2,_++,v=x}else g+=D,x++,_++,v=x}C=_>=l||w,N(v)}else{v=0;let _=0;for(;_<S.length;){let x=S[_];if(x===$){v=_+$.length,C=!0;break}if(!i&&x==="\\"&&_+1<S.length){let w=S[_+1];if(w===`
527
- `){_+=2;continue}if(w===$){g+=w,_+=2;continue}g+=x,g+=w,_+=2;continue}g+=x,_++}if(_>=S.length&&(C=!1,v=_,g.length===0&&S.length===0)){for(let x of p)y(e.state.env,x,"");return c&&Le(e,c),W(L,L,1)}N(v)}$===`
528
- `&&g.endsWith(`
529
- `)&&(g=g.slice(0,-1));let I=_=>i?_:_.replace(/\\(.)/g,"$1");if(p.length===1&&p[0]==="REPLY")return y(e.state.env,"REPLY",I(g)),W(L,L,C?0:1);let P=ar(e.state.env);if(c){let{words:_}=Vs(g,P,void 0,i),x=e.limits?.maxArrayElements??1e5;if(_.length>x)return W(L,F(`read: array element limit exceeded (${x})
530
- `),1);Le(e,c);for(let w=0;w<_.length;w++)y(e.state.env,`${c}_${w}`,I(_[w]));return W(L,L,C?0:1)}let k=p.length,{words:O,wordStarts:R}=Vs(g,P,k,i);for(let _=0;_<p.length;_++){let x=p[_];if(_<p.length-1)y(e.state.env,x,I(O[_]??""));else if(_<R.length){let w=g.substring(R[_]);w=lr(w,P,i),w=I(w),y(e.state.env,x,w)}else y(e.state.env,x,"")}return W(L,L,C?0:1)}function Vn(e,t){if(e.state.callDepth===0&&e.state.sourceDepth===0)return A("bash: return: can only `return' from a function or sourced script\n");let s=e.state.lastExitCode;if(t.length>0){let n=t[0],r=Number.parseInt(n,10);if(n===""||Number.isNaN(r)||!/^-?\d+$/.test(n))return A(`bash: return: ${n}: numeric argument required
513
+ `}return{stdout:V(t),stderr:A(),exitCode:0}}function Rn(e,t){let s=As("TERM"),n=0;if(t[0]==="-l")return ca(t.slice(1));if(t[0]==="-s"||t[0]==="-n"){let l=t[1];if(!l)return{stdout:A(),stderr:V(hi),exitCode:2};let c=As(l);if(!c)return Dn(l);s=c,n=2}else if(t[0]?.startsWith("-")&&t[0]!=="--"){let l=t[0].slice(1),c=As(l);if(!c)return Dn(l);s=c,n=1}else t[0]==="--"&&(n=1);let r=t.slice(n);if(r.length===0)return{stdout:A(),stderr:V(hi),exitCode:1};let i="",a=0,o=0;for(let l of r){let c;if(l.startsWith("%")){if(c=e.processes.resolveJobSpec(l),c===void 0){i+=`bash: kill: ${l}: no such job
514
+ `,o++;continue}}else if(/^\d+$/.test(l)){let f=Number(l);Number.isSafeInteger(f)&&f>0&&(c=f)}if(c===void 0){i+=`bash: kill: ${l}: arguments must be process or job IDs
515
+ `,o++;continue}(s.number===0||s.delivery===void 0?e.processes.get(c)!==void 0:e.processes.kill(c,s.delivery,s.number))?a++:(i+=`bash: kill: (${c}) - No such process
516
+ `,o++)}return{stdout:A(),stderr:V(i),exitCode:a>0||o===0?0:1}}function ua(e){let t=[],s="",n=0;for(let r of e){for(let i of r)i==="("?n++:i===")"&&n--;s?s+=` ${r}`:s=r,n===0&&(t.push(s),s="")}return s&&t.push(s),t}async function Ln(e,t){if(t.length===0)return C(`bash: let: expression expected
517
+ `);let s=ua(t),n=0;for(let r of s)try{let a=De(`(( ${r} ))`).statements[0];if(a&&a.pipelines.length>0&&a.pipelines[0].commands.length>0){let o=a.pipelines[0].commands[0];o.type==="ArithmeticCommand"&&(n=await Q(e,o.expression.expression))}}catch(i){return C(`bash: let: ${r}: ${i.message}
518
+ `)}return W(R,R,n===0?1:0)}async function Mn(e,t){if(e.state.localScopes.length===0)return C(`bash: local: can only be used in a function
519
+ `);let s=e.state.localScopes[e.state.localScopes.length-1],n="",r=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);if(d!==void 0){let p=U(d);c+=`${f}=${p}
520
+ `}}return W(F(c),R,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 S=d[2];if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(u)){n+=`bash: local: \`${c}': not a valid identifier
521
+ `,r=1;continue}if(await ue(e,u,"bash"),!s.has(u)){s.set(u,e.state.env.get(u));let g=`${u}_`;for(let P of e.state.env.keys())P.startsWith(g)&&!P.includes("__")&&(s.has(P)||s.set(P,e.state.env.get(P)))}let E=`${u}_`;for(let g of e.state.env.keys())g.startsWith(E)&&!g.includes("__")&&e.state.env.delete(g);let b=Fe(S);for(let g=0;g<b.length;g++)y(e.state.env,`${u}_${g}`,b[g]);y(e.state.env,`${u}__length`,String(b.length)),Xe(e,u),i&&Be(e,u);continue}let p=c.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=\((.*)\)$/s);if(p){u=p[1];let S=p[2];if(await ue(e,u,"bash"),!s.has(u)){s.set(u,e.state.env.get(u));let M=`${u}_`;for(let k of e.state.env.keys())k.startsWith(M)&&!k.includes("__")&&(s.has(k)||s.set(k,e.state.env.get(k)));let $=`${u}__length`;e.state.env.has($)&&!s.has($)&&s.set($,e.state.env.get($))}let E=Fe(S),b=he(e,u),g=0,P=e.state.env.get(u);b.length===0&&P!==void 0?(e.state.env.set(`${u}_0`,P),e.state.env.delete(u),g=1):b.length>0&&(g=Math.max(...b)+1);for(let M=0;M<E.length;M++)y(e.state.env,`${u}_${g+M}`,se(e,E[M]));let N=g+E.length;y(e.state.env,`${u}__length`,String(N)),Xe(e,u),i&&Be(e,u);continue}let m=c.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=(.*)$/);if(m){u=m[1];let S=se(e,m[2]);await ue(e,u,"bash"),s.has(u)||s.set(u,e.state.env.get(u));let E=x(e.state.env,u);y(e.state.env,u,E+S),Xe(e,u),i&&Be(e,u);continue}let h=c.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([^\]]+)\]=(.*)$/s);if(h){u=h[1];let S=h[2],E=se(e,h[3]);if(await ue(e,u,"bash"),!s.has(u)){s.set(u,e.state.env.get(u));let P=`${u}_`;for(let M of e.state.env.keys())M.startsWith(P)&&!M.includes("__")&&(s.has(M)||s.set(M,e.state.env.get(M)));let N=`${u}__length`;e.state.env.has(N)&&!s.has(N)&&s.set(N,e.state.env.get(N))}let b;try{let P=new Z,N=le(P,S);b=await Q(e,N.expression)}catch{let P=parseInt(S,10);b=Number.isNaN(P)?0:P}y(e.state.env,`${u}_${b}`,E);let g=parseInt(x(e.state.env,`${u}__length`,"0"),10);b>=g&&y(e.state.env,`${u}__length`,String(b+1)),Xe(e,u),i&&Be(e,u);continue}if(c.includes("=")){let S=c.indexOf("=");u=c.slice(0,S),f=se(e,c.slice(S+1))}else u=c;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(u)){n+=`bash: local: \`${c}': not a valid identifier
522
+ `,r=1;continue}let v=s.has(u);if(f!==void 0){let S=e.state.env.get(u);if(e.state.tempEnvBindings){let E=e.state.accessedTempEnvVars?.has(u),b=e.state.mutatedTempEnvVars?.has(u);if(!E&&!b)for(let g=e.state.tempEnvBindings.length-1;g>=0;g--){let P=e.state.tempEnvBindings[g];if(P.has(u)){S=P.get(u);break}}}qr(e,u,S)}if(!v){let S=e.state.env.get(u);if(e.state.tempEnvBindings)for(let E=e.state.tempEnvBindings.length-1;E>=0;E--){let b=e.state.tempEnvBindings[E];if(b.has(u)){S=b.get(u);break}}if(s.set(u,S),a){let E=`${u}_`;for(let g of e.state.env.keys())g.startsWith(E)&&!g.includes("__")&&(s.has(g)||s.set(g,e.state.env.get(g)));let b=`${u}__length`;e.state.env.has(b)&&!s.has(b)&&s.set(b,e.state.env.get(b))}}if(a&&f===void 0){let S=`${u}_`;for(let E of e.state.env.keys())E.startsWith(S)&&!E.includes("__")&&e.state.env.delete(E);y(e.state.env,`${u}__length`,"0")}else if(f!==void 0){if(await ue(e,u,"bash"),i&&f!==""&&!/^[a-zA-Z_][a-zA-Z0-9_]*(\[.+\])?$/.test(f)){n+=`bash: local: \`${f}': invalid variable name for name reference
523
+ `,r=1;continue}y(e.state.env,u,f),e.state.options.allexport&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(u))}else{let S=e.state.tempEnvBindings?.some(E=>E.has(u));!v&&!S&&e.state.env.delete(u)}Xe(e,u),i&&Be(e,u)}return W(R,F(n),r)}async function Wn(e,t,s){let n=U(s),r=`
524
+ `,i=0,a=0,o=0,l=!1,c="MAPFILE",u=0;for(;u<t.length;){let b=t[u];b==="-d"&&u+1<t.length?(r=t[u+1]===""?"\0":t[u+1]||`
525
+ `,u+=2):b==="-n"&&u+1<t.length?(i=Number.parseInt(t[u+1],10)||0,u+=2):b==="-O"&&u+1<t.length?(a=Number.parseInt(t[u+1],10)||0,u+=2):b==="-s"&&u+1<t.length?(o=Number.parseInt(t[u+1],10)||0,u+=2):b==="-t"?(l=!0,u++):b==="-u"||b==="-C"||b==="-c"?u+=2:(b.startsWith("-")||(c=b),u++)}let f=n;!f&&e.state.groupStdin!==void 0&&(f=U(await ie(e.state.groupStdin)));let d=[],p=f,m=0,h=0,v=e.limits?.maxArrayElements??1e5;for(;p.length>0;){let b=p.indexOf(r);if(b===-1){if(p.length>0){if(h<o)h++;else if(i===0||m<i){if(a+m>=v)return W(R,F(`mapfile: array element limit exceeded (${v})
526
+ `),1);let N=p,M=N.indexOf("\0");M!==-1&&(N=N.substring(0,M)),d.push(N),m++}}break}let g=p.substring(0,b),P=g.indexOf("\0");if(P!==-1&&(g=g.substring(0,P)),!l&&r!=="\0"&&(g+=r),p=p.substring(b+r.length),h<o){h++;continue}if(i>0&&m>=i)break;if(a+m>=v)return W(R,F(`mapfile: array element limit exceeded (${v})
527
+ `),1);d.push(g),m++}a===0&&Le(e,c);for(let b=0;b<d.length;b++)y(e.state.env,`${c}_${a+b}`,d[b]);let S=parseInt(x(e.state.env,`${c}__length`,"0"),10),E=a+d.length;return y(e.state.env,`${c}__length`,String(Math.max(S,E))),e.state.groupStdin!==void 0&&!n&&(e.state.groupStdin=A()),W(R,R,0)}function fa(e){if(!e.startsWith("__rw__:"))return null;let t=e.slice(7),s=t.indexOf(":");if(s===-1)return null;let n=Number.parseInt(t.slice(0,s),10);if(Number.isNaN(n)||n<0)return null;let r=s+1,i=t.slice(r,r+n),a=r+n+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 da(e,t,s){return`__rw__:${e.length}:${e}:${t}:${s}`}async function Fn(e,t,s,n=-1){let r=U(s),i=!1,a=`
528
+ `,o="",l=-1,c=-1,u=null,f=-1,d=-1,p=[],m=0,h=!1,v=(_,T)=>{let w=1;for(;w<_.length;){let I=_[w];if(I==="r")i=!0,w++;else if(I==="s")w++;else{if(I==="d")return w+1<_.length?(a=_.substring(w+1),{nextArgIndex:T+1}):T+1<t.length?(a=t[T+1],{nextArgIndex:T+2}):{nextArgIndex:T+1};if(I==="n"){if(w+1<_.length){let L=_.substring(w+1);return l=Number.parseInt(L,10),(Number.isNaN(l)||l<0)&&(h=!0,l=0),{nextArgIndex:T+1}}else if(T+1<t.length)return l=Number.parseInt(t[T+1],10),(Number.isNaN(l)||l<0)&&(h=!0,l=0),{nextArgIndex:T+2};return{nextArgIndex:T+1}}else if(I==="N"){if(w+1<_.length){let L=_.substring(w+1);return c=Number.parseInt(L,10),(Number.isNaN(c)||c<0)&&(h=!0,c=0),{nextArgIndex:T+1}}else if(T+1<t.length)return c=Number.parseInt(t[T+1],10),(Number.isNaN(c)||c<0)&&(h=!0,c=0),{nextArgIndex:T+2};return{nextArgIndex:T+1}}else{if(I==="a")return w+1<_.length?(u=_.substring(w+1),{nextArgIndex:T+1}):T+1<t.length?(u=t[T+1],{nextArgIndex:T+2}):{nextArgIndex:T+1};if(I==="p")return w+1<_.length?(o=_.substring(w+1),{nextArgIndex:T+1}):T+1<t.length?(o=t[T+1],{nextArgIndex:T+2}):{nextArgIndex:T+1};if(I==="u"){if(w+1<_.length){let L=_.substring(w+1);return f=Number.parseInt(L,10),Number.isNaN(f)||f<0?{nextArgIndex:-2}:{nextArgIndex:T+1}}else if(T+1<t.length)return f=Number.parseInt(t[T+1],10),Number.isNaN(f)||f<0?{nextArgIndex:-2}:{nextArgIndex:T+2};return{nextArgIndex:T+1}}else if(I==="t"){if(w+1<_.length){let L=_.substring(w+1);return d=Number.parseFloat(L),Number.isNaN(d)&&(d=0),{nextArgIndex:T+1}}else if(T+1<t.length)return d=Number.parseFloat(t[T+1]),Number.isNaN(d)&&(d=0),{nextArgIndex:T+2};return{nextArgIndex:T+1}}else if(I==="e"||I==="i"||I==="P"){if(I==="i"&&T+1<t.length)return{nextArgIndex:T+2};w++}else w++}}}return{nextArgIndex:T+1}};for(;m<t.length;){let _=t[m];if(_.startsWith("-")&&_.length>1&&_!=="--"){let T=v(_,m);if(T.nextArgIndex===-1)return{stdout:A(),stderr:A(),exitCode:2};if(T.nextArgIndex===-2)return{stdout:A(),stderr:A(),exitCode:1};m=T.nextArgIndex}else if(_==="--")for(m++;m<t.length;)p.push(t[m]),m++;else p.push(_),m++}if(h)return W(R,R,1);if(p.length===0&&u===null&&p.push("REPLY"),d===0){if(u)Le(e,u);else{for(let _ of p)y(e.state.env,_,"");p.length===0&&y(e.state.env,"REPLY","")}return W(R,R,0)}if(d<0&&d!==-1)return W(R,R,1);let S=r;f>=0?e.state.fileDescriptors?S=e.state.fileDescriptors.get(f)||"":S="":!S&&e.state.groupStdin!==void 0&&(S=U(await ie(e.state.groupStdin)));let E=a===""?"\0":a,b="",g=0,P=!0,N=_=>{if(f>=0&&e.state.fileDescriptors)e.state.fileDescriptors.set(f,S.substring(_));else if(n>=0&&e.state.fileDescriptors){let T=e.state.fileDescriptors.get(n);if(T?.startsWith("__rw__:")){let w=fa(T);if(w){let I=w.position+_;e.state.fileDescriptors.set(n,da(w.path,I,w.content))}}}else e.state.groupStdin!==void 0&&!r&&(e.state.groupStdin=de(F(S.substring(_))))};if(c>=0){let _=Math.min(c,S.length);b=S.substring(0,_),g=_,P=_>=c,N(g);let T=p[0]||"REPLY";y(e.state.env,T,b);for(let w=1;w<p.length;w++)y(e.state.env,p[w],"");return W(R,R,P?0:1)}else if(l>=0){let _=0,T=0,w=!1;for(;T<S.length&&_<l;){let I=S[T];if(I===E){g=T+1,w=!0;break}if(!i&&I==="\\"&&T+1<S.length){let L=S[T+1];if(L===E&&E===`
529
+ `){T+=2,g=T;continue}if(L===E){T+=2,_++,b+=L,g=T;continue}b+=L,T+=2,_++,g=T}else b+=I,T++,_++,g=T}P=_>=l||w,N(g)}else{g=0;let _=0;for(;_<S.length;){let T=S[_];if(T===E){g=_+E.length,P=!0;break}if(!i&&T==="\\"&&_+1<S.length){let w=S[_+1];if(w===`
530
+ `){_+=2;continue}if(w===E){b+=w,_+=2;continue}b+=T,b+=w,_+=2;continue}b+=T,_++}if(_>=S.length&&(P=!1,g=_,b.length===0&&S.length===0)){for(let T of p)y(e.state.env,T,"");return u&&Le(e,u),W(R,R,1)}N(g)}E===`
531
+ `&&b.endsWith(`
532
+ `)&&(b=b.slice(0,-1));let M=_=>i?_:_.replace(/\\(.)/g,"$1");if(p.length===1&&p[0]==="REPLY")return y(e.state.env,"REPLY",M(b)),W(R,R,P?0:1);let $=ar(e.state.env);if(u){let{words:_}=Vs(b,$,void 0,i),T=e.limits?.maxArrayElements??1e5;if(_.length>T)return W(R,F(`read: array element limit exceeded (${T})
533
+ `),1);Le(e,u);for(let w=0;w<_.length;w++)y(e.state.env,`${u}_${w}`,M(_[w]));return W(R,R,P?0:1)}let k=p.length,{words:O,wordStarts:D}=Vs(b,$,k,i);for(let _=0;_<p.length;_++){let T=p[_];if(_<p.length-1)y(e.state.env,T,M(O[_]??""));else if(_<D.length){let w=b.substring(D[_]);w=lr(w,$,i),w=M(w),y(e.state.env,T,w)}else y(e.state.env,T,"")}return W(R,R,P?0:1)}function Vn(e,t){if(e.state.callDepth===0&&e.state.sourceDepth===0)return C("bash: return: can only `return' from a function or sourced script\n");let s=e.state.lastExitCode;if(t.length>0){let n=t[0],r=Number.parseInt(n,10);if(n===""||Number.isNaN(r)||!/^-?\d+$/.test(n))return C(`bash: return: ${n}: numeric argument required
531
534
  `,2);s=(r%256+256)%256}throw new ye(s)}var Cs=`set: usage: set [-eux] [+eux] [-o option] [+o option]
532
535
  Options:
533
536
  -e Exit immediately if a command exits with non-zero status
@@ -544,162 +547,159 @@ Options:
544
547
  +o pipefail Disable pipefail
545
548
  -o xtrace Same as -x
546
549
  +o xtrace Disable xtrace
547
- `,pi=new Map([["e","errexit"],["u","nounset"],["x","xtrace"],["v","verbose"],["f","noglob"],["C","noclobber"],["a","allexport"],["n","noexec"],["h",null],["b",null],["m",null],["B",null],["H",null],["P",null],["T",null],["E",null],["p",null]]),mi=new Map([["errexit","errexit"],["pipefail","pipefail"],["nounset","nounset"],["xtrace","xtrace"],["verbose","verbose"],["noclobber","noclobber"],["noglob","noglob"],["allexport","allexport"],["noexec","noexec"],["posix","posix"],["vi","vi"],["emacs","emacs"],["notify",null],["monitor",null],["braceexpand",null],["histexpand",null],["physical",null],["functrace",null],["errtrace",null],["privileged",null],["hashall",null],["ignoreeof",null],["interactive-comments",null],["keyword",null],["onecmd",null]]),gi=["errexit","nounset","pipefail","verbose","xtrace","posix","allexport","noclobber","noglob","noexec","vi","emacs"],yi=["braceexpand","errtrace","functrace","hashall","histexpand","history","ignoreeof","interactive-comments","keyword","monitor","nolog","notify","onecmd","physical","privileged"];function wi(e,t,s){t!==null&&(s&&(t==="vi"?e.state.options.emacs=!1:t==="emacs"&&(e.state.options.vi=!1)),e.state.options[t]=s,ct(e))}function la(e,t){return t+1<e.length&&!e[t+1].startsWith("-")&&!e[t+1].startsWith("+")}function ca(e,t){let s=he(e,t);if(s.length===0)return`${t}=()`;let n=s.map(r=>{let i=T(e.state.env,`${t}_${r}`,"");return`[${r}]=${st(i)}`});return`${t}=(${n.join(" ")})`}function ua(e){return/^[a-zA-Z0-9_]+$/.test(e)?e:`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function fa(e,t){let s=Ze(e,t);if(s.length===0)return`${t}=()`;let n=s.map(r=>{let i=T(e.state.env,`${t}_${r}`,"");return`[${ua(r)}]=${st(i)}`});return`${t}=(${n.join(" ")} )`}function da(e){let t=new Set,s=e.state.associativeArrays??new Set;for(let n of e.state.env.keys()){let r=n.match(/^([a-zA-Z_][a-zA-Z0-9_]*)_(\d+)$/);if(r){let i=r[1];s.has(i)||t.add(i)}}return t}function ha(e){return e.state.associativeArrays??new Set}async function jn(e,t){if(t.includes("--help"))return G(Cs);if(t.length===0){let n=da(e),r=ha(e),i=l=>{for(let u of r){let c=`${u}_`,f=`${u}__length`;if(l!==f&&l.startsWith(c)){if(l.slice(c.length).startsWith("_length"))continue;return!0}}return!1},a=[];for(let[l,u]of e.state.env){if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(l)||n.has(l)||r.has(l))continue;let c=l.match(/^([a-zA-Z_][a-zA-Z0-9_]*)_(\d+)$/);if(c&&n.has(c[1]))continue;let f=l.match(/^([a-zA-Z_][a-zA-Z0-9_]*)__length$/);f&&n.has(f[1])||i(l)||f&&r.has(f[1])||a.push([l,H(u)])}let o=[];for(let[l,u]of a.sort(([c],[f])=>c<f?-1:c>f?1:0))o.push(`${l}=${bs(u)}`);for(let l of[...n].sort((u,c)=>u<c?-1:u>c?1:0))o.push(ca(e,l));for(let l of[...r].sort((u,c)=>u<c?-1:u>c?1:0))o.push(fa(e,l));return o.sort((l,u)=>{let c=l.split("=")[0],f=u.split("=")[0];return c<f?-1:c>f?1:0}),G(o.length>0?`${o.join(`
550
+ `,pi=new Map([["e","errexit"],["u","nounset"],["x","xtrace"],["v","verbose"],["f","noglob"],["C","noclobber"],["a","allexport"],["n","noexec"],["h",null],["b",null],["m",null],["B",null],["H",null],["P",null],["T",null],["E",null],["p",null]]),mi=new Map([["errexit","errexit"],["pipefail","pipefail"],["nounset","nounset"],["xtrace","xtrace"],["verbose","verbose"],["noclobber","noclobber"],["noglob","noglob"],["allexport","allexport"],["noexec","noexec"],["posix","posix"],["vi","vi"],["emacs","emacs"],["notify",null],["monitor",null],["braceexpand",null],["histexpand",null],["physical",null],["functrace",null],["errtrace",null],["privileged",null],["hashall",null],["ignoreeof",null],["interactive-comments",null],["keyword",null],["onecmd",null]]),gi=["errexit","nounset","pipefail","verbose","xtrace","posix","allexport","noclobber","noglob","noexec","vi","emacs"],yi=["braceexpand","errtrace","functrace","hashall","histexpand","history","ignoreeof","interactive-comments","keyword","monitor","nolog","notify","onecmd","physical","privileged"];function wi(e,t,s){t!==null&&(s&&(t==="vi"?e.state.options.emacs=!1:t==="emacs"&&(e.state.options.vi=!1)),e.state.options[t]=s,ct(e))}function ha(e,t){return t+1<e.length&&!e[t+1].startsWith("-")&&!e[t+1].startsWith("+")}function pa(e,t){let s=he(e,t);if(s.length===0)return`${t}=()`;let n=s.map(r=>{let i=x(e.state.env,`${t}_${r}`,"");return`[${r}]=${st(i)}`});return`${t}=(${n.join(" ")})`}function ma(e){return/^[a-zA-Z0-9_]+$/.test(e)?e:`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function ga(e,t){let s=Ze(e,t);if(s.length===0)return`${t}=()`;let n=s.map(r=>{let i=x(e.state.env,`${t}_${r}`,"");return`[${ma(r)}]=${st(i)}`});return`${t}=(${n.join(" ")} )`}function ya(e){let t=new Set,s=e.state.associativeArrays??new Set;for(let n of e.state.env.keys()){let r=n.match(/^([a-zA-Z_][a-zA-Z0-9_]*)_(\d+)$/);if(r){let i=r[1];s.has(i)||t.add(i)}}return t}function wa(e){return e.state.associativeArrays??new Set}async function jn(e,t){if(t.includes("--help"))return G(Cs);if(t.length===0){let n=ya(e),r=wa(e),i=l=>{for(let c of r){let u=`${c}_`,f=`${c}__length`;if(l!==f&&l.startsWith(u)){if(l.slice(u.length).startsWith("_length"))continue;return!0}}return!1},a=[];for(let[l,c]of e.state.env){if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(l)||n.has(l)||r.has(l))continue;let u=l.match(/^([a-zA-Z_][a-zA-Z0-9_]*)_(\d+)$/);if(u&&n.has(u[1]))continue;let f=l.match(/^([a-zA-Z_][a-zA-Z0-9_]*)__length$/);f&&n.has(f[1])||i(l)||f&&r.has(f[1])||a.push([l,U(c)])}let o=[];for(let[l,c]of a.sort(([u],[f])=>u<f?-1:u>f?1:0))o.push(`${l}=${Ss(c)}`);for(let l of[...n].sort((c,u)=>c<u?-1:c>u?1:0))o.push(pa(e,l));for(let l of[...r].sort((c,u)=>c<u?-1:c>u?1:0))o.push(ga(e,l));return o.sort((l,c)=>{let u=l.split("=")[0],f=c.split("=")[0];return u<f?-1:u>f?1:0}),G(o.length>0?`${o.join(`
548
551
  `)}
549
- `:"")}let s=0;for(;s<t.length;){let n=t[s];if((n==="-o"||n==="+o")&&la(t,s)){let r=t[s+1];if(!mi.has(r)){let i=`bash: set: ${r}: invalid option name
550
- ${Cs}`;if(e.state.options.posix)throw await U(e,2,i,!0),new we(1);return A(i)}wi(e,mi.get(r)??null,n==="-o"),s+=2;continue}if(n==="-o"){let r=gi.map(o=>`${o.padEnd(16)}${e.state.options[o]?"on":"off"}`),i=yi.map(o=>`${o.padEnd(16)}off`),a=[...r,...i].sort();return G(`${a.join(`
552
+ `:"")}let s=0;for(;s<t.length;){let n=t[s];if((n==="-o"||n==="+o")&&ha(t,s)){let r=t[s+1];if(!mi.has(r)){let i=`bash: set: ${r}: invalid option name
553
+ ${Cs}`;if(e.state.options.posix)throw await H(e,2,i,!0),new we(1);return C(i)}wi(e,mi.get(r)??null,n==="-o"),s+=2;continue}if(n==="-o"){let r=gi.map(o=>`${o.padEnd(16)}${e.state.options[o]?"on":"off"}`),i=yi.map(o=>`${o.padEnd(16)}off`),a=[...r,...i].sort();return G(`${a.join(`
551
554
  `)}
552
555
  `)}if(n==="+o"){let r=gi.map(o=>`set ${e.state.options[o]?"-o":"+o"} ${o}`),i=yi.map(o=>`set +o ${o}`),a=[...r,...i].sort();return G(`${a.join(`
553
556
  `)}
554
557
  `)}if(n.length>1&&(n[0]==="-"||n[0]==="+")&&n[1]!=="-"){let r=n[0]==="-";for(let i=1;i<n.length;i++){let a=n[i];if(!pi.has(a)){let o=`bash: set: ${n[0]}${a}: invalid option
555
- ${Cs}`;if(e.state.options.posix)throw await U(e,2,o,!0),new we(1);return A(o)}wi(e,pi.get(a)??null,r)}s++;continue}if(n==="--")return zn(e,t.slice(s+1)),B();if(n==="-"){if(e.state.options.xtrace=!1,e.state.options.verbose=!1,ct(e),s+1<t.length)return zn(e,t.slice(s+1)),B();s++;continue}if(n==="+"){s++;continue}if(n.startsWith("-")||n.startsWith("+")){let r=`bash: set: ${n}: invalid option
556
- ${Cs}`;if(e.state.options.posix)throw await U(e,2,r,!0),new we(1);return A(r)}return zn(e,t.slice(s)),B()}return B()}function zn(e,t){let s=1;for(;e.state.env.has(String(s));)e.state.env.delete(String(s)),s++;for(let n=0;n<t.length;n++)y(e.state.env,String(n+1),t[n]);y(e.state.env,"#",String(t.length)),y(e.state.env,"@",t.join(" ")),y(e.state.env,"*",t.join(" "))}async function Bn(e,t){let s=1;if(t.length>0){let a=Number.parseInt(t[0],10);if(Number.isNaN(a)||a<0){let o=`bash: shift: ${t[0]}: numeric argument required
557
- `;if(e.state.options.posix)throw await U(e,2,o,!0),new we(1);return A(o)}s=a}let n=Number.parseInt(T(e.state.env,"#","0"),10);if(s>n){let a=`bash: shift: shift count out of range
558
- `;if(e.state.options.posix)throw await U(e,2,a,!0),new we(1);return A(a)}if(s===0)return B();let r=[];for(let a=1;a<=n;a++)r.push(T(e.state.env,String(a))||"");let i=r.slice(s);for(let a=1;a<=n;a++)e.state.env.delete(String(a));for(let a=0;a<i.length;a++)y(e.state.env,String(a+1),i[a]);return y(e.state.env,"#",String(i.length)),y(e.state.env,"@",i.join(" ")),B()}async function Hn(e,t){let s=t;if(s.length>0&&s[0]==="--"&&(s=s.slice(1)),s.length===0)return W(L,F(`bash: source: filename argument required
559
- `),2);let n=s[0],r=null,i=null;if(n.includes("/")){let u=e.fs.resolvePath(e.state.cwd,n);try{i=await e.fs.readFileText(u),r=u}catch{}}else{let c=T(e.state.env,"PATH","").split(":").filter(f=>f);for(let f of c){let d=e.fs.resolvePath(e.state.cwd,`${f}/${n}`);try{if((await e.fs.stat(d)).isDirectory)continue;i=await e.fs.readFileText(d),r=d;break}catch{}}if(i===null){let f=e.fs.resolvePath(e.state.cwd,n);try{i=await e.fs.readFileText(f),r=f}catch{}}}if(i===null)return A(`bash: ${n}: No such file or directory
560
- `);let a=new Map;if(s.length>1){for(let c=1;c<=9;c++)a.set(String(c),T(e.state.env,String(c)));a.set("#",T(e.state.env,"#")),a.set("@",T(e.state.env,"@"));let u=s.slice(1);y(e.state.env,"#",String(u.length)),y(e.state.env,"@",u.join(" "));for(let c=0;c<u.length&&c<9;c++)y(e.state.env,String(c+1),u[c]);for(let c=u.length+1;c<=9;c++)e.state.env.delete(String(c))}let o=e.state.currentSource,l=()=>{if(e.state.sourceDepth--,e.state.currentSource=o,s.length>1)for(let[u,c]of a)c===void 0?e.state.env.delete(u):y(e.state.env,u,c)};e.state.sourceDepth++,e.state.currentSource=n;try{let u=Ie(i),c=await e.executeScript(u),f=await X(e,c);return l(),f}catch(u){if(l(),await ee(e,u),u instanceof q)throw u;if(u instanceof ye)return W(L,L,u.exitCode);if(u.name==="ParseException")return A(`bash: ${n}: ${u.message}
561
- `);throw u}}function vi(e){return/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e)}function pa(e){return e.startsWith("'")&&e.endsWith("'")||e.startsWith('"')&&e.endsWith('"')}async function bi(e,t){if(pa(t))return null;try{let s=new Z,n=le(s,t);return await Q(e,n.expression)}catch{let s=parseInt(t,10);return Number.isNaN(s)?0:s}}function Si(e,t){if(e.state.localVarStack?.has(t)){let n=ps(e,t);if(n){n.value===void 0?e.state.env.delete(t):e.state.env.set(t,n.value);let r=e.state.localVarStack?.get(t);if(!r||r.length===0)hs(e,t),e.state.localVarStack?.delete(t),e.state.fullyUnsetLocals=e.state.fullyUnsetLocals||new Map,e.state.fullyUnsetLocals.set(t,n.scopeIndex),Un(e,t);else{let i=r[r.length-1];e.state.localVarDepth=e.state.localVarDepth||new Map,e.state.localVarDepth.set(t,i.scopeIndex+1)}return!0}return e.state.env.delete(t),hs(e,t),e.state.localVarStack?.delete(t),e.state.fullyUnsetLocals=e.state.fullyUnsetLocals||new Map,e.state.fullyUnsetLocals.set(t,0),!0}for(let n=e.state.localScopes.length-1;n>=0;n--){let r=e.state.localScopes[n];if(r.has(t)){let i=r.get(t);i===void 0?e.state.env.delete(t):e.state.env.set(t,i),r.delete(t);let a=!1;for(let o=n-1;o>=0;o--)if(e.state.localScopes[o].has(t)){e.state.localVarDepth&&e.state.localVarDepth.set(t,o+1),a=!0;break}return a||hs(e,t),!0}}return!1}function Un(e,t){if(!e.state.tempEnvBindings||e.state.tempEnvBindings.length===0)return!1;for(let s=e.state.tempEnvBindings.length-1;s>=0;s--){let n=e.state.tempEnvBindings[s];if(n.has(t)){let r=n.get(t);return r===void 0?e.state.env.delete(t):e.state.env.set(t,r),n.delete(t),!0}}return!1}async function Ei(e,t){if(t.startsWith("'")&&t.endsWith("'"))return t.slice(1,-1);if(t.startsWith('"')&&t.endsWith('"')){let s=t.slice(1,-1),r=new Z().parseWordFromString(s,!0,!1);return z(e,r)}if(t.includes("$")){let n=new Z().parseWordFromString(t,!1,!1);return z(e,n)}return t}async function Gn(e,t){let s="both",n="",r=0;for(let i of t){if(i==="-v"){s="variable";continue}if(i==="-f"){s="function";continue}if(s==="function"){e.state.functions.delete(i);continue}if(s==="variable"){let u=i.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(u){let d=u[1],p=u[2];if(p==="@"||p==="*"){let g=Ne(e,d);for(let[v]of g)e.state.env.delete(`${d}_${v}`);e.state.env.delete(d);continue}let m=e.state.associativeArrays?.has(d);if(m){let g=await Ei(e,p);e.state.env.delete(`${d}_${g}`);continue}let h=Bs(e,d),b=e.state.declaredVars?.has(d);if((e.state.env.has(d)||b)&&!h&&!m){n+=`bash: unset: ${d}: not an array variable
562
- `,r=1;continue}let $=await bi(e,p);if($===null&&h){n+=`bash: unset: ${p}: not a valid identifier
563
- `,r=1;continue}if($===null)continue;if($<0){let g=Ne(e,d),v=g.length,C=e.state.currentLine;if(v===0){n+=`bash: line ${C}: unset: [${$}]: bad array subscript
564
- `,r=1;continue}let N=v+$;if(N<0){n+=`bash: line ${C}: unset: [${$}]: bad array subscript
565
- `,r=1;continue}let I=g[N][0];e.state.env.delete(`${d}_${I}`);continue}e.state.env.delete(`${d}_${$}`);continue}if(!vi(i)){n+=`bash: unset: \`${i}': not a valid identifier
566
- `,r=1;continue}let c=i;if(ve(e,i)){let d=Me(e,i);d&&d!==i&&(c=d)}if(et(e,c)){n+=`bash: unset: ${c}: cannot unset: readonly variable
567
- `,r=1;continue}let f=dt(e,c);if(f!==void 0&&f!==e.state.callDepth)Si(e,c);else if(e.state.fullyUnsetLocals?.has(c))e.state.env.delete(c);else if(f!==void 0){let d=e.state.accessedTempEnvVars?.has(c),p=e.state.mutatedTempEnvVars?.has(c);if((d||p)&&e.state.localVarStack?.has(c)){let m=ps(e,c);m?m.value===void 0?e.state.env.delete(c):e.state.env.set(c,m.value):e.state.env.delete(c)}else e.state.env.delete(c)}else Un(e,c)||e.state.env.delete(c);e.state.exportedVars?.delete(c);continue}let a=i.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(a){let u=a[1],c=a[2];if(c==="@"||c==="*"){let h=Ne(e,u);for(let[b]of h)e.state.env.delete(`${u}_${b}`);e.state.env.delete(u);continue}let f=e.state.associativeArrays?.has(u);if(f){let h=await Ei(e,c);e.state.env.delete(`${u}_${h}`);continue}let d=Bs(e,u);if(e.state.env.has(u)&&!d&&!f){n+=`bash: unset: ${u}: not an array variable
568
- `,r=1;continue}let m=await bi(e,c);if(m===null&&d){n+=`bash: unset: ${c}: not a valid identifier
569
- `,r=1;continue}if(m===null)continue;if(m<0){let h=Ne(e,u),b=h.length,S=e.state.currentLine;if(b===0){n+=`bash: line ${S}: unset: [${m}]: bad array subscript
570
- `,r=1;continue}let $=b+m;if($<0){n+=`bash: line ${S}: unset: [${m}]: bad array subscript
571
- `,r=1;continue}let g=h[$][0];e.state.env.delete(`${u}_${g}`);continue}e.state.env.delete(`${u}_${m}`);continue}if(!vi(i)){n+=`bash: unset: \`${i}': not a valid identifier
572
- `,r=1;continue}let o=i;if(ve(e,i)){let u=Me(e,i);u&&u!==i&&(o=u)}if(et(e,o)){n+=`bash: unset: ${o}: cannot unset: readonly variable
573
- `,r=1;continue}let l=dt(e,o);if(l!==void 0&&l!==e.state.callDepth)Si(e,o);else if(e.state.fullyUnsetLocals?.has(o))e.state.env.delete(o);else if(l!==void 0){let u=e.state.accessedTempEnvVars?.has(o),c=e.state.mutatedTempEnvVars?.has(o);if((u||c)&&e.state.localVarStack?.has(o)){let f=ps(e,o);f?f.value===void 0?e.state.env.delete(o):e.state.env.set(o,f.value):e.state.env.delete(o)}else e.state.env.delete(o)}else Un(e,o)||e.state.env.delete(o);e.state.exportedVars?.delete(o),e.state.functions.delete(i)}return W(L,F(n),r)}var ma=`wait: usage: wait [id ...]
574
- `;async function qn(e,t){let s=t.find(i=>i.startsWith("-"));if(s)return{stdout:E(),stderr:V(`bash: wait: ${s}: invalid option
575
- ${ma}`),exitCode:2};if(Ye(e.signal),t.length===0){let i,a=new Promise((o,l)=>{i=()=>l(new pe(e.signal?.reason)),e.signal?.addEventListener("abort",i,{once:!0})});try{let o=await(e.signal?Promise.race([e.processes.waitForLineage(e.lineageId),a]):e.processes.waitForLineage(e.lineageId));return{stdout:E(),stderr:E(),exitCode:o}}finally{i&&e.signal?.removeEventListener("abort",i)}}let n=0,r="";for(let i of t){Ye(e.signal);let a=i.startsWith("%")?e.processes.resolveJobSpec(i):/^\d+$/.test(i)?Number(i):void 0;if(a===void 0||!Number.isSafeInteger(a)||!e.processes.canWait(a)){r+=i.startsWith("%")?`bash: wait: ${i}: no such job
576
- `:`bash: wait: pid ${i} is not a child of this shell
577
- `,n=127;continue}let o,l=new Promise((u,c)=>{o=()=>c(new pe(e.signal?.reason)),e.signal?.addEventListener("abort",o,{once:!0})});try{n=await(e.signal?Promise.race([e.processes.wait(a),l]):e.processes.wait(a))}finally{o&&e.signal?.removeEventListener("abort",o)}}return{stdout:E(),stderr:V(r),exitCode:n}}var Zn=["extglob","dotglob","nullglob","failglob","globstar","globskipdots","nocaseglob","nocasematch","expand_aliases","lastpipe","xpg_echo"],ga=["autocd","cdable_vars","cdspell","checkhash","checkjobs","checkwinsize","cmdhist","compat31","compat32","compat40","compat41","compat42","compat43","compat44","complete_fullquote","direxpand","dirspell","execfail","extdebug","extquote","force_fignore","globasciiranges","gnu_errfmt","histappend","histreedit","histverify","hostcomplete","huponexit","inherit_errexit","interactive_comments","lithist","localvar_inherit","localvar_unset","login_shell","mailwarn","no_empty_cmd_completion","progcomp","progcomp_alias","promptvars","restricted_shell","shift_verbose","sourcepath"];function ks(e){return Zn.includes(e)}function ya(e){return ga.includes(e)}function $i(e,t){let s=!1,n=!1,r=!1,i=!1,a=!1,o=[],l=0;for(;l<t.length;){let d=t[l];if(d==="--"){l++;break}if(d.startsWith("-")&&d.length>1){for(let p=1;p<d.length;p++){let m=d[p];switch(m){case"s":s=!0;break;case"u":n=!0;break;case"p":r=!0;break;case"q":i=!0;break;case"o":a=!0;break;default:return{exitCode:2,stdout:E(),stderr:V(`shopt: -${m}: invalid option
578
- `)}}}l++}else break}for(;l<t.length;)o.push(t[l]),l++;if(a)return wa(e,o,s,n,r,i);if(s&&n)return{exitCode:1,stdout:E(),stderr:V(`shopt: cannot set and unset shell options simultaneously
558
+ ${Cs}`;if(e.state.options.posix)throw await H(e,2,o,!0),new we(1);return C(o)}wi(e,pi.get(a)??null,r)}s++;continue}if(n==="--")return zn(e,t.slice(s+1)),B();if(n==="-"){if(e.state.options.xtrace=!1,e.state.options.verbose=!1,ct(e),s+1<t.length)return zn(e,t.slice(s+1)),B();s++;continue}if(n==="+"){s++;continue}if(n.startsWith("-")||n.startsWith("+")){let r=`bash: set: ${n}: invalid option
559
+ ${Cs}`;if(e.state.options.posix)throw await H(e,2,r,!0),new we(1);return C(r)}return zn(e,t.slice(s)),B()}return B()}function zn(e,t){let s=1;for(;e.state.env.has(String(s));)e.state.env.delete(String(s)),s++;for(let n=0;n<t.length;n++)y(e.state.env,String(n+1),t[n]);y(e.state.env,"#",String(t.length)),y(e.state.env,"@",t.join(" ")),y(e.state.env,"*",t.join(" "))}async function Bn(e,t){let s=1;if(t.length>0){let a=Number.parseInt(t[0],10);if(Number.isNaN(a)||a<0){let o=`bash: shift: ${t[0]}: numeric argument required
560
+ `;if(e.state.options.posix)throw await H(e,2,o,!0),new we(1);return C(o)}s=a}let n=Number.parseInt(x(e.state.env,"#","0"),10);if(s>n){let a=`bash: shift: shift count out of range
561
+ `;if(e.state.options.posix)throw await H(e,2,a,!0),new we(1);return C(a)}if(s===0)return B();let r=[];for(let a=1;a<=n;a++)r.push(x(e.state.env,String(a))||"");let i=r.slice(s);for(let a=1;a<=n;a++)e.state.env.delete(String(a));for(let a=0;a<i.length;a++)y(e.state.env,String(a+1),i[a]);return y(e.state.env,"#",String(i.length)),y(e.state.env,"@",i.join(" ")),B()}async function Un(e,t){let s=t;if(s.length>0&&s[0]==="--"&&(s=s.slice(1)),s.length===0)return W(R,F(`bash: source: filename argument required
562
+ `),2);let n=s[0],r=null,i=null;if(n.includes("/")){let c=e.fs.resolvePath(e.state.cwd,n);try{i=await e.fs.readFileText(c),r=c}catch{}}else{let u=x(e.state.env,"PATH","").split(":").filter(f=>f);for(let f of u){let d=e.fs.resolvePath(e.state.cwd,`${f}/${n}`);try{if((await e.fs.stat(d)).isDirectory)continue;i=await e.fs.readFileText(d),r=d;break}catch{}}if(i===null){let f=e.fs.resolvePath(e.state.cwd,n);try{i=await e.fs.readFileText(f),r=f}catch{}}}if(i===null)return C(`bash: ${n}: No such file or directory
563
+ `);let a=new Map;if(s.length>1){for(let u=1;u<=9;u++)a.set(String(u),x(e.state.env,String(u)));a.set("#",x(e.state.env,"#")),a.set("@",x(e.state.env,"@"));let c=s.slice(1);y(e.state.env,"#",String(c.length)),y(e.state.env,"@",c.join(" "));for(let u=0;u<c.length&&u<9;u++)y(e.state.env,String(u+1),c[u]);for(let u=c.length+1;u<=9;u++)e.state.env.delete(String(u))}let o=e.state.currentSource,l=()=>{if(e.state.sourceDepth--,e.state.currentSource=o,s.length>1)for(let[c,u]of a)u===void 0?e.state.env.delete(c):y(e.state.env,c,u)};e.state.sourceDepth++,e.state.currentSource=n;try{let c=De(i),u=await e.executeScript(c),f=await Y(e,u);return l(),f}catch(c){if(l(),await ee(e,c),c instanceof q)throw c;if(c instanceof ye)return W(R,R,c.exitCode);if(c.name==="ParseException")return C(`bash: ${n}: ${c.message}
564
+ `);throw c}}function vi(e){return/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e)}function va(e){return e.startsWith("'")&&e.endsWith("'")||e.startsWith('"')&&e.endsWith('"')}async function bi(e,t){if(va(t))return null;try{let s=new Z,n=le(s,t);return await Q(e,n.expression)}catch{let s=parseInt(t,10);return Number.isNaN(s)?0:s}}function Si(e,t){if(e.state.localVarStack?.has(t)){let n=ms(e,t);if(n){n.value===void 0?e.state.env.delete(t):e.state.env.set(t,n.value);let r=e.state.localVarStack?.get(t);if(!r||r.length===0)ps(e,t),e.state.localVarStack?.delete(t),e.state.fullyUnsetLocals=e.state.fullyUnsetLocals||new Map,e.state.fullyUnsetLocals.set(t,n.scopeIndex),Hn(e,t);else{let i=r[r.length-1];e.state.localVarDepth=e.state.localVarDepth||new Map,e.state.localVarDepth.set(t,i.scopeIndex+1)}return!0}return e.state.env.delete(t),ps(e,t),e.state.localVarStack?.delete(t),e.state.fullyUnsetLocals=e.state.fullyUnsetLocals||new Map,e.state.fullyUnsetLocals.set(t,0),!0}for(let n=e.state.localScopes.length-1;n>=0;n--){let r=e.state.localScopes[n];if(r.has(t)){let i=r.get(t);i===void 0?e.state.env.delete(t):e.state.env.set(t,i),r.delete(t);let a=!1;for(let o=n-1;o>=0;o--)if(e.state.localScopes[o].has(t)){e.state.localVarDepth&&e.state.localVarDepth.set(t,o+1),a=!0;break}return a||ps(e,t),!0}}return!1}function Hn(e,t){if(!e.state.tempEnvBindings||e.state.tempEnvBindings.length===0)return!1;for(let s=e.state.tempEnvBindings.length-1;s>=0;s--){let n=e.state.tempEnvBindings[s];if(n.has(t)){let r=n.get(t);return r===void 0?e.state.env.delete(t):e.state.env.set(t,r),n.delete(t),!0}}return!1}async function Ei(e,t){if(t.startsWith("'")&&t.endsWith("'"))return t.slice(1,-1);if(t.startsWith('"')&&t.endsWith('"')){let s=t.slice(1,-1),r=new Z().parseWordFromString(s,!0,!1);return z(e,r)}if(t.includes("$")){let n=new Z().parseWordFromString(t,!1,!1);return z(e,n)}return t}async function Gn(e,t){let s="both",n="",r=0;for(let i of t){if(i==="-v"){s="variable";continue}if(i==="-f"){s="function";continue}if(s==="function"){e.state.functions.delete(i);continue}if(s==="variable"){let c=i.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(c){let d=c[1],p=c[2];if(p==="@"||p==="*"){let b=xe(e,d);for(let[g]of b)e.state.env.delete(`${d}_${g}`);e.state.env.delete(d);continue}let m=e.state.associativeArrays?.has(d);if(m){let b=await Ei(e,p);e.state.env.delete(`${d}_${b}`);continue}let h=Bs(e,d),v=e.state.declaredVars?.has(d);if((e.state.env.has(d)||v)&&!h&&!m){n+=`bash: unset: ${d}: not an array variable
565
+ `,r=1;continue}let E=await bi(e,p);if(E===null&&h){n+=`bash: unset: ${p}: not a valid identifier
566
+ `,r=1;continue}if(E===null)continue;if(E<0){let b=xe(e,d),g=b.length,P=e.state.currentLine;if(g===0){n+=`bash: line ${P}: unset: [${E}]: bad array subscript
567
+ `,r=1;continue}let N=g+E;if(N<0){n+=`bash: line ${P}: unset: [${E}]: bad array subscript
568
+ `,r=1;continue}let M=b[N][0];e.state.env.delete(`${d}_${M}`);continue}e.state.env.delete(`${d}_${E}`);continue}if(!vi(i)){n+=`bash: unset: \`${i}': not a valid identifier
569
+ `,r=1;continue}let u=i;if(ve(e,i)){let d=Me(e,i);d&&d!==i&&(u=d)}if(et(e,u)){n+=`bash: unset: ${u}: cannot unset: readonly variable
570
+ `,r=1;continue}let f=dt(e,u);if(f!==void 0&&f!==e.state.callDepth)Si(e,u);else if(e.state.fullyUnsetLocals?.has(u))e.state.env.delete(u);else if(f!==void 0){let d=e.state.accessedTempEnvVars?.has(u),p=e.state.mutatedTempEnvVars?.has(u);if((d||p)&&e.state.localVarStack?.has(u)){let m=ms(e,u);m?m.value===void 0?e.state.env.delete(u):e.state.env.set(u,m.value):e.state.env.delete(u)}else e.state.env.delete(u)}else Hn(e,u)||e.state.env.delete(u);e.state.exportedVars?.delete(u);continue}let a=i.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(a){let c=a[1],u=a[2];if(u==="@"||u==="*"){let h=xe(e,c);for(let[v]of h)e.state.env.delete(`${c}_${v}`);e.state.env.delete(c);continue}let f=e.state.associativeArrays?.has(c);if(f){let h=await Ei(e,u);e.state.env.delete(`${c}_${h}`);continue}let d=Bs(e,c);if(e.state.env.has(c)&&!d&&!f){n+=`bash: unset: ${c}: not an array variable
571
+ `,r=1;continue}let m=await bi(e,u);if(m===null&&d){n+=`bash: unset: ${u}: not a valid identifier
572
+ `,r=1;continue}if(m===null)continue;if(m<0){let h=xe(e,c),v=h.length,S=e.state.currentLine;if(v===0){n+=`bash: line ${S}: unset: [${m}]: bad array subscript
573
+ `,r=1;continue}let E=v+m;if(E<0){n+=`bash: line ${S}: unset: [${m}]: bad array subscript
574
+ `,r=1;continue}let b=h[E][0];e.state.env.delete(`${c}_${b}`);continue}e.state.env.delete(`${c}_${m}`);continue}if(!vi(i)){n+=`bash: unset: \`${i}': not a valid identifier
575
+ `,r=1;continue}let o=i;if(ve(e,i)){let c=Me(e,i);c&&c!==i&&(o=c)}if(et(e,o)){n+=`bash: unset: ${o}: cannot unset: readonly variable
576
+ `,r=1;continue}let l=dt(e,o);if(l!==void 0&&l!==e.state.callDepth)Si(e,o);else if(e.state.fullyUnsetLocals?.has(o))e.state.env.delete(o);else if(l!==void 0){let c=e.state.accessedTempEnvVars?.has(o),u=e.state.mutatedTempEnvVars?.has(o);if((c||u)&&e.state.localVarStack?.has(o)){let f=ms(e,o);f?f.value===void 0?e.state.env.delete(o):e.state.env.set(o,f.value):e.state.env.delete(o)}else e.state.env.delete(o)}else Hn(e,o)||e.state.env.delete(o);e.state.exportedVars?.delete(o),e.state.functions.delete(i)}return W(R,F(n),r)}var ba=`wait: usage: wait [id ...]
577
+ `;async function qn(e,t){let s=t.indexOf("--"),n=s===-1?t:t.slice(s+1),i=(s===-1?t:t.slice(0,s)).find(l=>l.startsWith("-"));if(i)return{stdout:A(),stderr:V(`bash: wait: ${i}: invalid option
578
+ ${ba}`),exitCode:2};if(t=n,Ye(e.signal),t.length===0){let l,c=new Promise((u,f)=>{l=()=>f(new pe(e.signal?.reason)),e.signal?.addEventListener("abort",l,{once:!0})});try{let u=await(e.signal?Promise.race([e.processes.waitForLineage(e.lineageId),c]):e.processes.waitForLineage(e.lineageId));return{stdout:A(),stderr:A(),exitCode:u}}finally{l&&e.signal?.removeEventListener("abort",l)}}let a=0,o="";for(let l of t){Ye(e.signal);let c=l.startsWith("%")?e.processes.resolveJobSpec(l):/^\d+$/.test(l)?Number(l):void 0;if(c===void 0||!Number.isSafeInteger(c)||!e.processes.canWait(c)){o+=l.startsWith("%")?`bash: wait: ${l}: no such job
579
+ `:`bash: wait: pid ${l} is not a child of this shell
580
+ `,a=127;continue}let u,f=new Promise((d,p)=>{u=()=>p(new pe(e.signal?.reason)),e.signal?.addEventListener("abort",u,{once:!0})});try{a=await(e.signal?Promise.race([e.processes.wait(c),f]):e.processes.wait(c))}finally{u&&e.signal?.removeEventListener("abort",u)}}return{stdout:A(),stderr:V(o),exitCode:a}}var Zn=["extglob","dotglob","nullglob","failglob","globstar","globskipdots","nocaseglob","nocasematch","expand_aliases","lastpipe","xpg_echo"],Sa=["autocd","cdable_vars","cdspell","checkhash","checkjobs","checkwinsize","cmdhist","compat31","compat32","compat40","compat41","compat42","compat43","compat44","complete_fullquote","direxpand","dirspell","execfail","extdebug","extquote","force_fignore","globasciiranges","gnu_errfmt","histappend","histreedit","histverify","hostcomplete","huponexit","inherit_errexit","interactive_comments","lithist","localvar_inherit","localvar_unset","login_shell","mailwarn","no_empty_cmd_completion","progcomp","progcomp_alias","promptvars","restricted_shell","shift_verbose","sourcepath"];function ks(e){return Zn.includes(e)}function Ea(e){return Sa.includes(e)}function $i(e,t){let s=!1,n=!1,r=!1,i=!1,a=!1,o=[],l=0;for(;l<t.length;){let d=t[l];if(d==="--"){l++;break}if(d.startsWith("-")&&d.length>1){for(let p=1;p<d.length;p++){let m=d[p];switch(m){case"s":s=!0;break;case"u":n=!0;break;case"p":r=!0;break;case"q":i=!0;break;case"o":a=!0;break;default:return{exitCode:2,stdout:A(),stderr:V(`shopt: -${m}: invalid option
581
+ `)}}}l++}else break}for(;l<t.length;)o.push(t[l]),l++;if(a)return $a(e,o,s,n,r,i);if(s&&n)return{exitCode:1,stdout:A(),stderr:V(`shopt: cannot set and unset shell options simultaneously
579
582
  `)};if(o.length===0){if(s||n){let p=[];for(let m of Zn){let h=e.state.shoptOptions[m];s&&h?p.push(r?`shopt -s ${m}`:`${m} on`):n&&!h&&p.push(r?`shopt -u ${m}`:`${m} off`)}return{exitCode:0,stdout:p.length>0?V(`${p.join(`
580
583
  `)}
581
- `):E(),stderr:E()}}let d=[];for(let p of Zn){let m=e.state.shoptOptions[p];d.push(r?`shopt ${m?"-s":"-u"} ${p}`:`${p} ${m?"on":"off"}`)}return{exitCode:0,stdout:V(`${d.join(`
584
+ `):A(),stderr:A()}}let d=[];for(let p of Zn){let m=e.state.shoptOptions[p];d.push(r?`shopt ${m?"-s":"-u"} ${p}`:`${p} ${m?"on":"off"}`)}return{exitCode:0,stdout:V(`${d.join(`
582
585
  `)}
583
- `),stderr:E()}}let u=!1,c="",f=[];for(let d of o){if(!ks(d)&&!ya(d)){c+=`shopt: ${d}: invalid shell option name
584
- `,u=!0;continue}if(s)ks(d)&&(e.state.shoptOptions[d]=!0,Zs(e));else if(n)ks(d)&&(e.state.shoptOptions[d]=!1,Zs(e));else if(ks(d)){let p=e.state.shoptOptions[d];i?p||(u=!0):r?(f.push(`shopt ${p?"-s":"-u"} ${d}`),p||(u=!0)):(f.push(`${d} ${p?"on":"off"}`),p||(u=!0))}else i?u=!0:r?(f.push(`shopt -u ${d}`),u=!0):(f.push(`${d} off`),u=!0)}return{exitCode:u?1:0,stdout:f.length>0?V(`${f.join(`
586
+ `),stderr:A()}}let c=!1,u="",f=[];for(let d of o){if(!ks(d)&&!Ea(d)){u+=`shopt: ${d}: invalid shell option name
587
+ `,c=!0;continue}if(s)ks(d)&&(e.state.shoptOptions[d]=!0,Zs(e));else if(n)ks(d)&&(e.state.shoptOptions[d]=!1,Zs(e));else if(ks(d)){let p=e.state.shoptOptions[d];i?p||(c=!0):r?(f.push(`shopt ${p?"-s":"-u"} ${d}`),p||(c=!0)):(f.push(`${d} ${p?"on":"off"}`),p||(c=!0))}else i?c=!0:r?(f.push(`shopt -u ${d}`),c=!0):(f.push(`${d} off`),c=!0)}return{exitCode:c?1:0,stdout:f.length>0?V(`${f.join(`
585
588
  `)}
586
- `):E(),stderr:V(c)}}function wa(e,t,s,n,r,i){let a=new Map([["errexit","errexit"],["pipefail","pipefail"],["nounset","nounset"],["xtrace","xtrace"],["verbose","verbose"],["posix","posix"],["allexport","allexport"],["noclobber","noclobber"],["noglob","noglob"],["noexec","noexec"],["vi","vi"],["emacs","emacs"]]),o=["braceexpand","errtrace","functrace","hashall","histexpand","history","ignoreeof","interactive-comments","keyword","monitor","nolog","notify","onecmd","physical","privileged"],l=[...a.keys(),...o].sort();if(t.length===0){let d=[];for(let p of l){let m=o.includes(p),h=a.get(p),b=m||!h?!1:e.state.options[h];s&&!b||n&&b||d.push(r?`set ${b?"-o":"+o"} ${p}`:`${p} ${b?"on":"off"}`)}return{exitCode:0,stdout:d.length>0?V(`${d.join(`
589
+ `):A(),stderr:V(u)}}function $a(e,t,s,n,r,i){let a=new Map([["errexit","errexit"],["pipefail","pipefail"],["nounset","nounset"],["xtrace","xtrace"],["verbose","verbose"],["posix","posix"],["allexport","allexport"],["noclobber","noclobber"],["noglob","noglob"],["noexec","noexec"],["vi","vi"],["emacs","emacs"]]),o=["braceexpand","errtrace","functrace","hashall","histexpand","history","ignoreeof","interactive-comments","keyword","monitor","nolog","notify","onecmd","physical","privileged"],l=[...a.keys(),...o].sort();if(t.length===0){let d=[];for(let p of l){let m=o.includes(p),h=a.get(p),v=m||!h?!1:e.state.options[h];s&&!v||n&&v||d.push(r?`set ${v?"-o":"+o"} ${p}`:`${p} ${v?"on":"off"}`)}return{exitCode:0,stdout:d.length>0?V(`${d.join(`
587
590
  `)}
588
- `):E(),stderr:E()}}let u=!1,c="",f=[];for(let d of t){let p=a.has(d),m=o.includes(d);if(!p&&!m){c+=`shopt: ${d}: invalid option name
589
- `,u=!0;continue}if(m){s||n||(i?u=!0:r?(f.push(`set +o ${d}`),u=!0):(f.push(`${d} off`),u=!0));continue}let h=a.get(d);if(h)if(s)h==="vi"?e.state.options.emacs=!1:h==="emacs"&&(e.state.options.vi=!1),e.state.options[h]=!0,ct(e);else if(n)e.state.options[h]=!1,ct(e);else{let b=e.state.options[h];i?b||(u=!0):r?(f.push(`set ${b?"-o":"+o"} ${d}`),b||(u=!0)):(f.push(`${d} ${b?"on":"off"}`),b||(u=!0))}}return{exitCode:u?1:0,stdout:f.length>0?V(`${f.join(`
591
+ `):A(),stderr:A()}}let c=!1,u="",f=[];for(let d of t){let p=a.has(d),m=o.includes(d);if(!p&&!m){u+=`shopt: ${d}: invalid option name
592
+ `,c=!0;continue}if(m){s||n||(i?c=!0:r?(f.push(`set +o ${d}`),c=!0):(f.push(`${d} off`),c=!0));continue}let h=a.get(d);if(h)if(s)h==="vi"?e.state.options.emacs=!1:h==="emacs"&&(e.state.options.vi=!1),e.state.options[h]=!0,ct(e);else if(n)e.state.options[h]=!1,ct(e);else{let v=e.state.options[h];i?v||(c=!0):r?(f.push(`set ${v?"-o":"+o"} ${d}`),v||(c=!0)):(f.push(`${d} ${v?"on":"off"}`),v||(c=!0))}}return{exitCode:c?1:0,stdout:f.length>0?V(`${f.join(`
590
593
  `)}
591
- `):E(),stderr:V(c)}}async function Ai(e,t,s){if(t.includes("/")){let a=e.fs.resolvePath(e.state.cwd,t);if(!await e.fs.exists(a))return{error:"not_found",path:a};let o=a.split("/").pop()||t,l=e.commands.get(o);try{let u=await e.fs.stat(a);return u.isDirectory?{error:"permission_denied",path:a}:l?{cmd:l,path:a}:(u.mode&73)!==0?{script:!0,path:a}:{error:"permission_denied",path:a}}catch{return{error:"not_found",path:a}}}if(!s&&e.state.hashTable){let a=e.state.hashTable.get(t);if(a)if(await e.fs.exists(a)){let o=e.commands.get(t);if(o)return{cmd:o,path:a};try{let l=await e.fs.stat(a);if(!l.isDirectory&&(l.mode&73)!==0)return{script:!0,path:a}}catch{}}else e.state.hashTable.delete(t)}let r=(s??T(e.state.env,"PATH","/usr/bin:/bin")).split(":");for(let a of r){if(!a)continue;let l=`${a.startsWith("/")?a:e.fs.resolvePath(e.state.cwd,a)}/${t}`;if(await e.fs.exists(l))try{let u=await e.fs.stat(l);if(u.isDirectory)continue;let c=(u.mode&73)!==0,f=e.commands.get(t),d=a==="/bin"||a==="/usr/bin";if(f&&d)return{cmd:f,path:l};if(c){if(f&&!d)return{script:!0,path:l};if(!f)return{script:!0,path:l}}}catch{}}if(!await e.fs.exists("/usr/bin")){let a=e.commands.get(t);if(a)return{cmd:a,path:`/usr/bin/${t}`}}return null}async function Ps(e,t){let s=[];if(t.includes("/")){let i=e.fs.resolvePath(e.state.cwd,t);if(await e.fs.exists(i))try{let a=await e.fs.stat(i);a.isDirectory||(a.mode&73)!==0&&s.push(t)}catch{}return s}let r=T(e.state.env,"PATH","/usr/bin:/bin").split(":");for(let i of r){if(!i)continue;let o=`${i.startsWith("/")?i:e.fs.resolvePath(e.state.cwd,i)}/${t}`;if(await e.fs.exists(o)){try{if((await e.fs.stat(o)).isDirectory)continue}catch{continue}s.push(i.startsWith("/")?o:`${i}/${t}`)}}return s}async function _i(e,t,s,n){let r=!1,i=!1,a=!1,o=!1,l=!1,u=[];for(let h of t)if(h.startsWith("-")&&h.length>1)for(let b of h.slice(1))b==="t"?r=!0:b==="p"?i=!0:b==="P"?a=!0:b==="a"?o=!0:b==="f"&&(l=!0);else u.push(h);let c="",f="",d=0,p=!1,m=!1;for(let h of u){let b=!1;if(a){if(o){let N=await n(h);if(N.length>0){for(let I of N)c+=`${I}
592
- `;p=!0,b=!0}}else{let N=await s(h);N&&(c+=`${N}
593
- `,p=!0,b=!0)}b||(m=!0);continue}let S=!l&&e.state.functions.has(h);if(o&&S){if(!i)if(r)c+=`function
594
- `;else{let N=e.state.functions.get(h),I=N?Ci(h,N):`${h} is a function
595
- `;c+=I}b=!0}let $=e.state.env.get(`BASH_ALIAS_${h}`);if($!==void 0&&(o||!b)&&(i||(r?c+=`alias
596
- `:c+=`${h} is aliased to \`${H($)}'
597
- `),b=!0,!o)||sn.has(h)&&(o||!b)&&(i||(r?c+=`keyword
598
- `:c+=`${h} is a shell keyword
599
- `),b=!0,!o))continue;if(!o&&S&&!b){if(!i)if(r)c+=`function
600
- `;else{let N=e.state.functions.get(h),I=N?Ci(h,N):`${h} is a function
601
- `;c+=I}b=!0;continue}if(!(Ue.has(h)&&(o||!b)&&(i||(r?c+=`builtin
602
- `:c+=`${h} is a shell builtin
603
- `),b=!0,!o))){if(o){let N=await n(h);for(let I of N)i?c+=`${I}
604
- `:r?c+=`file
605
- `:c+=`${h} is ${I}
606
- `,p=!0,b=!0}else if(!b){let N=await s(h);N&&(i?c+=`${N}
607
- `:r?c+=`file
608
- `:c+=`${h} is ${N}
609
- `,p=!0,b=!0)}if(!b&&(m=!0,!r&&!i)){let N=!0;if(h.includes("/")){let I=e.fs.resolvePath(e.state.cwd,h);await e.fs.exists(I)&&(N=!1)}N&&(f+=`bash: type: ${h}: not found
610
- `)}}}return i?d=m&&!p?1:0:d=m?1:0,W(F(c),F(f),d)}function Ci(e,t){let s;return t.body.type==="Group"?s=t.body.body.map(r=>Lt(r)).join("; "):s=Lt(t.body),`${e} is a function
594
+ `):A(),stderr:V(u)}}async function Ai(e,t,s){if(t.includes("/")){let a=e.fs.resolvePath(e.state.cwd,t);if(!await e.fs.exists(a))return{error:"not_found",path:a};let o=a.split("/").pop()||t,l=e.commands.get(o);try{let c=await e.fs.stat(a);return c.isDirectory?{error:"permission_denied",path:a}:l?{cmd:l,path:a}:(c.mode&73)!==0?{script:!0,path:a}:{error:"permission_denied",path:a}}catch{return{error:"not_found",path:a}}}if(!s&&e.state.hashTable){let a=e.state.hashTable.get(t);if(a)if(await e.fs.exists(a)){let o=e.commands.get(t);if(o)return{cmd:o,path:a};try{let l=await e.fs.stat(a);if(!l.isDirectory&&(l.mode&73)!==0)return{script:!0,path:a}}catch{}}else e.state.hashTable.delete(t)}let r=(s??x(e.state.env,"PATH","/usr/bin:/bin")).split(":");for(let a of r){if(!a)continue;let l=`${a.startsWith("/")?a:e.fs.resolvePath(e.state.cwd,a)}/${t}`;if(await e.fs.exists(l))try{let c=await e.fs.stat(l);if(c.isDirectory)continue;let u=(c.mode&73)!==0,f=e.commands.get(t),d=a==="/bin"||a==="/usr/bin";if(f&&d)return{cmd:f,path:l};if(u){if(f&&!d)return{script:!0,path:l};if(!f)return{script:!0,path:l}}}catch{}}if(!await e.fs.exists("/usr/bin")){let a=e.commands.get(t);if(a)return{cmd:a,path:`/usr/bin/${t}`}}return null}async function Ps(e,t){let s=[];if(t.includes("/")){let i=e.fs.resolvePath(e.state.cwd,t);if(await e.fs.exists(i))try{let a=await e.fs.stat(i);a.isDirectory||(a.mode&73)!==0&&s.push(t)}catch{}return s}let r=x(e.state.env,"PATH","/usr/bin:/bin").split(":");for(let i of r){if(!i)continue;let o=`${i.startsWith("/")?i:e.fs.resolvePath(e.state.cwd,i)}/${t}`;if(await e.fs.exists(o)){try{if((await e.fs.stat(o)).isDirectory)continue}catch{continue}s.push(i.startsWith("/")?o:`${i}/${t}`)}}return s}async function _i(e,t,s,n){let r=!1,i=!1,a=!1,o=!1,l=!1,c=[];for(let h of t)if(h.startsWith("-")&&h.length>1)for(let v of h.slice(1))v==="t"?r=!0:v==="p"?i=!0:v==="P"?a=!0:v==="a"?o=!0:v==="f"&&(l=!0);else c.push(h);let u="",f="",d=0,p=!1,m=!1;for(let h of c){let v=!1;if(a){if(o){let N=await n(h);if(N.length>0){for(let M of N)u+=`${M}
595
+ `;p=!0,v=!0}}else{let N=await s(h);N&&(u+=`${N}
596
+ `,p=!0,v=!0)}v||(m=!0);continue}let S=!l&&e.state.functions.has(h);if(o&&S){if(!i)if(r)u+=`function
597
+ `;else{let N=e.state.functions.get(h),M=N?Ci(h,N):`${h} is a function
598
+ `;u+=M}v=!0}let E=e.state.env.get(`BASH_ALIAS_${h}`);if(E!==void 0&&(o||!v)&&(i||(r?u+=`alias
599
+ `:u+=`${h} is aliased to \`${U(E)}'
600
+ `),v=!0,!o)||sn.has(h)&&(o||!v)&&(i||(r?u+=`keyword
601
+ `:u+=`${h} is a shell keyword
602
+ `),v=!0,!o))continue;if(!o&&S&&!v){if(!i)if(r)u+=`function
603
+ `;else{let N=e.state.functions.get(h),M=N?Ci(h,N):`${h} is a function
604
+ `;u+=M}v=!0;continue}if(!(He.has(h)&&(o||!v)&&(i||(r?u+=`builtin
605
+ `:u+=`${h} is a shell builtin
606
+ `),v=!0,!o))){if(o){let N=await n(h);for(let M of N)i?u+=`${M}
607
+ `:r?u+=`file
608
+ `:u+=`${h} is ${M}
609
+ `,p=!0,v=!0}else if(!v){let N=await s(h);N&&(i?u+=`${N}
610
+ `:r?u+=`file
611
+ `:u+=`${h} is ${N}
612
+ `,p=!0,v=!0)}if(!v&&(m=!0,!r&&!i)){let N=!0;if(h.includes("/")){let M=e.fs.resolvePath(e.state.cwd,h);await e.fs.exists(M)&&(N=!1)}N&&(f+=`bash: type: ${h}: not found
613
+ `)}}}return i?d=m&&!p?1:0:d=m?1:0,W(F(u),F(f),d)}function Ci(e,t){let s;return t.body.type==="Group"?s=t.body.body.map(r=>Mt(r)).join("; "):s=Mt(t.body),`${e} is a function
611
614
  ${e} ()
612
615
  {
613
616
  ${s}
614
617
  }
615
- `}function Lt(e){if(Array.isArray(e))return e.map(t=>Lt(t)).join("; ");if(e.type==="Statement"){let t=[];for(let s=0;s<e.pipelines.length;s++){let n=e.pipelines[s];t.push(va(n)),e.operators[s]&&t.push(e.operators[s])}return t.join(" ")}if(e.type==="SimpleCommand"){let t=e,s=[];t.name&&s.push(ki(t.name));for(let n of t.args)s.push(ki(n));return s.join(" ")}return e.type==="Group"?`{ ${e.body.map(n=>Lt(n)).join("; ")}; }`:"..."}function va(e){let t=e.commands.map(s=>Lt(s));return(e.negated?"! ":"")+t.join(" | ")}function ki(e){let t="";for(let s of e.parts)s.type==="Literal"?t+=s.value:s.type==="DoubleQuoted"?t+=`"${s.parts.map(n=>Pi(n)).join("")}"`:s.type==="SingleQuoted"?t+=`'${s.value}'`:t+=Pi(s);return t}function Pi(e){let t=e;return t.type==="Literal"?t.value??"":t.type==="Variable"?`$${t.name}`:""}async function xi(e,t,s,n){let r="",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)n?r+=`${o} is an alias for "${H(l)}"
616
- `:r+=`alias ${o}='${H(l)}'
618
+ `}function Mt(e){if(Array.isArray(e))return e.map(t=>Mt(t)).join("; ");if(e.type==="Statement"){let t=[];for(let s=0;s<e.pipelines.length;s++){let n=e.pipelines[s];t.push(Aa(n)),e.operators[s]&&t.push(e.operators[s])}return t.join(" ")}if(e.type==="SimpleCommand"){let t=e,s=[];t.name&&s.push(ki(t.name));for(let n of t.args)s.push(ki(n));return s.join(" ")}return e.type==="Group"?`{ ${e.body.map(n=>Mt(n)).join("; ")}; }`:"..."}function Aa(e){let t=e.commands.map(s=>Mt(s));return(e.negated?"! ":"")+t.join(" | ")}function ki(e){let t="";for(let s of e.parts)s.type==="Literal"?t+=s.value:s.type==="DoubleQuoted"?t+=`"${s.parts.map(n=>Pi(n)).join("")}"`:s.type==="SingleQuoted"?t+=`'${s.value}'`:t+=Pi(s);return t}function Pi(e){let t=e;return t.type==="Literal"?t.value??"":t.type==="Variable"?`$${t.name}`:""}async function Ti(e,t,s,n){let r="",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)n?r+=`${o} is an alias for "${U(l)}"
619
+ `:r+=`alias ${o}='${U(l)}'
617
620
  `;else if(sn.has(o))n?r+=`${o} is a shell keyword
618
621
  `:r+=`${o}
619
- `;else if(Ue.has(o))n?r+=`${o} is a shell builtin
622
+ `;else if(He.has(o))n?r+=`${o} is a shell builtin
620
623
  `:r+=`${o}
621
624
  `;else if(e.state.functions.has(o))n?r+=`${o} is a function
622
625
  `:r+=`${o}
623
- `;else if(o.includes("/")){let u=e.fs.resolvePath(e.state.cwd,o),c=!1;if(await e.fs.exists(u))try{let f=await e.fs.stat(u);f.isDirectory||(f.mode&73)!==0&&(n?r+=`${o} is ${o}
626
+ `;else if(o.includes("/")){let c=e.fs.resolvePath(e.state.cwd,o),u=!1;if(await e.fs.exists(c))try{let f=await e.fs.stat(c);f.isDirectory||(f.mode&73)!==0&&(n?r+=`${o} is ${o}
624
627
  `:r+=`${o}
625
- `,c=!0)}catch{}c||(n&&(i+=`${o}: not found
626
- `),a=1)}else if(e.commands.has(o)){let c=T(e.state.env,"PATH","/usr/bin:/bin").split(":"),f=null;for(let d of c){if(!d)continue;let p=`${d}/${o}`;try{let m=await e.fs.stat(p);if(!m.isDirectory&&(m.mode&73)!==0){f=p;break}}catch{}}f||(f=`/usr/bin/${o}`),n?r+=`${o} is ${f}
628
+ `,u=!0)}catch{}u||(n&&(i+=`${o}: not found
629
+ `),a=1)}else if(e.commands.has(o)){let u=x(e.state.env,"PATH","/usr/bin:/bin").split(":"),f=null;for(let d of u){if(!d)continue;let p=`${d}/${o}`;try{let m=await e.fs.stat(p);if(!m.isDirectory&&(m.mode&73)!==0){f=p;break}}catch{}}f||(f=`/usr/bin/${o}`),n?r+=`${o} is ${f}
627
630
  `:r+=`${f}
628
631
  `}else n&&(i+=`${o}: not found
629
- `),a=1}return W(F(r),F(i),a)}async function Ti(e,t){if(t.includes("/")){let r=e.fs.resolvePath(e.state.cwd,t);if(await e.fs.exists(r)){try{let i=await e.fs.stat(r);if(i.isDirectory||!((i.mode&73)!==0))return null}catch{return null}return t}return null}let n=T(e.state.env,"PATH","/usr/bin:/bin").split(":");for(let r of n){if(!r)continue;let a=`${r.startsWith("/")?r:e.fs.resolvePath(e.state.cwd,r)}/${t}`;if(await e.fs.exists(a)){try{if((await e.fs.stat(a)).isDirectory)continue}catch{continue}return`${r}/${t}`}}if(e.commands.has(t)){for(let r of n)if(r==="/usr/bin"||r==="/bin")return`${r}/${t}`;return`/usr/bin/${t}`}return null}async function Ni(e,t,s,n,r,i,a,o){let{ctx:l,runCommand:u}=e,c=bt(s);if(l.coverage&&Ue.has(t)&&l.coverage.hit(`bash:builtin:${t}`),t==="export")return xn(l,c);if(t==="unset")return Gn(l,c);if(t==="exit")return _n(l,c);if(t==="local")return Mn(l,c);if(t==="set")return jn(l,c);if(t==="break")return Ks(l,c);if(t==="continue")return pn(l,c);if(t==="return")return Vn(l,c);if(t==="eval"&&l.state.options.posix)return Ss(l,c,r);if(t==="shift")return Bn(l,c);if(t==="getopts")return Es(l,c);if(t==="compgen")return un(l,c);if(t==="complete")return dn(l,c);if(t==="compopt")return hn(l,c);if(t==="pushd")return await Cn(l,c);if(t==="popd")return kn(l,c);if(t==="dirs")return Pn(l,c);if(t==="source"||t===".")return Hn(l,c);if(t==="read")return await Fn(l,c,await ie(r),o);if(t==="mapfile"||t==="readarray")return await Wn(l,c,await ie(r));if(t==="declare"||t==="typeset")return En(l,c);if(t==="readonly")return $n(l,c);if(!i){let f=l.state.functions.get(t);if(f)return vs(l,f,c,r)}if(t==="eval")return Ss(l,c,r);if(t==="cd")return await Xs(l,c);if(t===":"||t==="true")return B();if(t==="false")return ae(!1);if(t==="let")return Ln(l,c);if(t==="command")return ba(e,c,r);if(t==="builtin")return Sa(e,c,r);if(t==="shopt")return $i(l,c);if(t==="exec"){if(s.length===0)return B();let[f,...d]=s;return u(H(f),d,[],r,!1,!1,-1)}if(t==="wait")return await qn(l,c);if(t==="jobs")return await On(l,c,(f,d)=>u(f,d.map(F),d.map(()=>!1),E()));if(t==="kill")return Rn(l,c);if(t==="type")return await _i(l,c,f=>Ti(l,f),f=>Ps(l,f));if(t==="hash")return Tn(l,c);if(t==="help")return Nn(l,c);if(t==="["||t==="test"){let f=c;if(t==="["){if(c[c.length-1]!=="]")return A("[: missing `]'\n",2);f=c.slice(0,-1)}return Ot(l,f)}return null}async function ba(e,t,s){let{ctx:n,runCommand:r}=e;if(t.length===0)return B();let i=!1,a=!1,o=!1,l=t;for(;l.length>0&&l[0].startsWith("-");){let f=l[0];if(f==="--"){l=l.slice(1);break}for(let d of f.slice(1))d==="p"?i=!0:d==="V"?a=!0:d==="v"&&(o=!0);l=l.slice(1)}if(l.length===0)return B();if(o||a)return await xi(n,l,o,a);let[u,...c]=l;return r(u,c.map(f=>F(f)),[],s,!0,i,-1)}async function Sa(e,t,s){let{runCommand:n}=e;if(t.length===0)return B();let r=t;if(r[0]==="--"&&(r=r.slice(1),r.length===0))return B();let i=r[0];if(!Ue.has(i))return A(`bash: builtin: ${i}: not a shell builtin
630
- `);let[,...a]=r;return n(i,a.map(o=>F(o)),[],s,!0,!1,-1)}async function Oi(e,t,s,n,r){let{buildExportedEnv:i,ctx:a,executeUserScript:o}=e,u=await Ai(a,t,r?"/usr/bin:/bin":void 0);if(!u)return Lr(t)?A(`bash: ${t}: command not available in browser environments. Exclude '${t}' from your commands or use the Node.js bundle.
631
- `,127):A(`bash: ${t}: command not found
632
- `,127);if("error"in u)return u.error==="permission_denied"?A(`bash: ${t}: Permission denied
633
- `,126):A(`bash: ${t}: No such file or directory
634
- `,127);if("script"in u)return t.includes("/")||(a.state.hashTable||(a.state.hashTable=new Map),a.state.hashTable.set(t,u.path)),await o(u.path,s,n);let{cmd:c,path:f}=u;t.includes("/")||(a.state.hashTable||(a.state.hashTable=new Map),a.state.hashTable.set(t,f));let d,p=n.getReader(),m=await p.read();p.releaseLock(),m.done||!m.value||m.value.length===0?a.state.groupStdin?d=a.state.groupStdin:d=E():d=rt(de(m.value),n);let h=i(),b={fs:a.fs,cwd:a.state.cwd,env:a.state.env,exportedEnv:h,stdin:d,limits:a.limits,exec:a.execFn,fetch:a.fetch,getRegisteredCommands:()=>Array.from(a.commands.keys()),sleep:a.sleep,trace:a.trace,fileDescriptors:a.state.fileDescriptors,xpgEcho:a.state.shoptOptions.xpg_echo,coverage:a.coverage,signal:a.signal};try{return await c.execute(s,b)}catch(S){if(S instanceof oe)throw S;return A(`${t}: ${je(S)}
635
- `)}}async function _s(e,t){let s=e.state.inCondition;e.state.inCondition=!0;let n=0;try{for(let r of t){let i=await e.executeStatement(r);await X(e,i),n=i.exitCode}}catch(r){throw await ee(e,r),r}finally{e.state.inCondition=s}return{stdout:E(),stderr:E(),exitCode:n}}function Mt(e,t){return e instanceof $e?e.levels>1&&t>1?(e.levels--,{action:"rethrow",error:e}):{action:"break"}:e instanceof Ae?e.levels>1&&t>1?(e.levels--,{action:"rethrow",error:e}):{action:"continue"}:e instanceof ye||e instanceof Ce||e instanceof q||e instanceof oe?{action:"rethrow",error:e}:{action:"error",exitCode:1,error:e}}async function xs(e,t){let s=0;try{for(let n of t){let r=await e.executeStatement(n);await X(e,r),s=r.exitCode}}catch(n){let r=await ee(e,n);if(qt(n)||n instanceof Ce||n instanceof q||n instanceof oe||n instanceof ze)throw n;if(!r){let i=je(n);await X(e,A(i.endsWith(`
632
+ `),a=1}return W(F(r),F(i),a)}async function Ni(e,t){if(t.includes("/")){let r=e.fs.resolvePath(e.state.cwd,t);if(await e.fs.exists(r)){try{let i=await e.fs.stat(r);if(i.isDirectory||!((i.mode&73)!==0))return null}catch{return null}return t}return null}let n=x(e.state.env,"PATH","/usr/bin:/bin").split(":");for(let r of n){if(!r)continue;let a=`${r.startsWith("/")?r:e.fs.resolvePath(e.state.cwd,r)}/${t}`;if(await e.fs.exists(a)){try{if((await e.fs.stat(a)).isDirectory)continue}catch{continue}return`${r}/${t}`}}if(e.commands.has(t)){for(let r of n)if(r==="/usr/bin"||r==="/bin")return`${r}/${t}`;return`/usr/bin/${t}`}return null}async function xi(e,t,s,n,r,i,a,o){let{ctx:l,runCommand:c}=e,u=bt(s);if(l.coverage&&He.has(t)&&l.coverage.hit(`bash:builtin:${t}`),t==="export")return Tn(l,u);if(t==="unset")return Gn(l,u);if(t==="exit")return _n(l,u);if(t==="local")return Mn(l,u);if(t==="set")return jn(l,u);if(t==="break")return Xs(l,u);if(t==="continue")return pn(l,u);if(t==="return")return Vn(l,u);if(t==="eval"&&l.state.options.posix)return Es(l,u,r);if(t==="shift")return Bn(l,u);if(t==="getopts")return $s(l,u);if(t==="compgen")return un(l,u);if(t==="complete")return dn(l,u);if(t==="compopt")return hn(l,u);if(t==="pushd")return await Cn(l,u);if(t==="popd")return kn(l,u);if(t==="dirs")return Pn(l,u);if(t==="source"||t===".")return Un(l,u);if(t==="read")return await Fn(l,u,await ie(r),o);if(t==="mapfile"||t==="readarray")return await Wn(l,u,await ie(r));if(t==="declare"||t==="typeset")return En(l,u);if(t==="readonly")return $n(l,u);if(!i){let f=l.state.functions.get(t);if(f)return bs(l,f,u,r)}if(t==="eval")return Es(l,u,r);if(t==="cd")return await Ks(l,u);if(t===":"||t==="true")return B();if(t==="false")return ae(!1);if(t==="let")return Ln(l,u);if(t==="command")return Ca(e,u,r);if(t==="builtin")return ka(e,u,r);if(t==="shopt")return $i(l,u);if(t==="exec"){if(s.length===0)return B();let[f,...d]=s;return c(U(f),d,[],r,!1,!1,-1)}if(t==="wait")return await qn(l,u);if(t==="jobs")return await On(l,u,(f,d)=>c(f,d.map(F),d.map(()=>!1),A()));if(t==="kill")return Rn(l,u);if(t==="type")return await _i(l,u,f=>Ni(l,f),f=>Ps(l,f));if(t==="hash")return Nn(l,u);if(t==="help")return xn(l,u);if(t==="["||t==="test"){let f=u;if(t==="["){if(u[u.length-1]!=="]")return C("[: missing `]'\n",2);f=u.slice(0,-1)}return Ot(l,f)}return null}async function Ca(e,t,s){let{ctx:n,runCommand:r}=e;if(t.length===0)return B();let i=!1,a=!1,o=!1,l=t;for(;l.length>0&&l[0].startsWith("-");){let f=l[0];if(f==="--"){l=l.slice(1);break}for(let d of f.slice(1))d==="p"?i=!0:d==="V"?a=!0:d==="v"&&(o=!0);l=l.slice(1)}if(l.length===0)return B();if(o||a)return await Ti(n,l,o,a);let[c,...u]=l;return r(c,u.map(f=>F(f)),[],s,!0,i,-1)}async function ka(e,t,s){let{runCommand:n}=e;if(t.length===0)return B();let r=t;if(r[0]==="--"&&(r=r.slice(1),r.length===0))return B();let i=r[0];if(!He.has(i))return C(`bash: builtin: ${i}: not a shell builtin
633
+ `);let[,...a]=r;return n(i,a.map(o=>F(o)),[],s,!0,!1,-1)}async function Oi(e,t,s,n,r){let{buildExportedEnv:i,ctx:a,executeUserScript:o}=e,c=await Ai(a,t,r?"/usr/bin:/bin":void 0);if(!c)return Lr(t)?C(`bash: ${t}: command not available in browser environments. Exclude '${t}' from your commands or use the Node.js bundle.
634
+ `,127):C(`bash: ${t}: command not found
635
+ `,127);if("error"in c)return c.error==="permission_denied"?C(`bash: ${t}: Permission denied
636
+ `,126):C(`bash: ${t}: No such file or directory
637
+ `,127);if("script"in c)return t.includes("/")||(a.state.hashTable||(a.state.hashTable=new Map),a.state.hashTable.set(t,c.path)),await o(c.path,s,n);let{cmd:u,path:f}=c;t.includes("/")||(a.state.hashTable||(a.state.hashTable=new Map),a.state.hashTable.set(t,f));let d,p=n.getReader(),m=await p.read();p.releaseLock(),m.done||!m.value||m.value.length===0?a.state.groupStdin?d=a.state.groupStdin:d=A():d=rt(de(m.value),n);let h=i(),v={fs:a.fs,cwd:a.state.cwd,env:a.state.env,exportedEnv:h,stdin:d,limits:a.limits,exec:a.execFn,fetch:a.fetch,getRegisteredCommands:()=>Array.from(a.commands.keys()),sleep:a.sleep,trace:a.trace,fileDescriptors:a.state.fileDescriptors,xpgEcho:a.state.shoptOptions.xpg_echo,coverage:a.coverage,signal:a.signal};try{return await u.execute(s,v)}catch(S){if(S instanceof oe)throw S;return C(`${t}: ${je(S)}
638
+ `)}}async function _s(e,t){let s=e.state.inCondition;e.state.inCondition=!0;let n=0;try{for(let r of t){let i=await e.executeStatement(r);await Y(e,i),n=i.exitCode}}catch(r){throw await ee(e,r),r}finally{e.state.inCondition=s}return{stdout:A(),stderr:A(),exitCode:n}}function Wt(e,t){return e instanceof $e?e.levels>1&&t>1?(e.levels--,{action:"rethrow",error:e}):{action:"break"}:e instanceof Ae?e.levels>1&&t>1?(e.levels--,{action:"rethrow",error:e}):{action:"continue"}:e instanceof ye||e instanceof Ce||e instanceof q||e instanceof oe?{action:"rethrow",error:e}:{action:"error",exitCode:1,error:e}}async function Ts(e,t){let s=0;try{for(let n of t){let r=await e.executeStatement(n);await Y(e,r),s=r.exitCode}}catch(n){let r=await ee(e,n);if(Zt(n)||n instanceof Ce||n instanceof q||n instanceof oe||n instanceof ze)throw n;if(!r){let i=je(n);await Y(e,C(i.endsWith(`
636
639
  `)?i:`${i}
637
- `))}return{stdout:E(),stderr:E(),exitCode:1}}return{stdout:E(),stderr:E(),exitCode:s}}var Ea="+ ";async function Di(e){let t=e.state.env.get("PS4"),s=e.substitutionDepth??0;if(t===void 0)return`${"+".repeat(s+1)} `;let n=H(t);if(n==="")return"";try{let i=new Z().parseWordFromString(n,!1,!1),a=await z(e,i);return s>0&&a.length>0?`${a[0].repeat(s)}${a}`:a}catch{await U(e,2,`bash: ${n}: bad substitution
638
- `);let r=n||Ea;return s>0&&r.length>0?`${r[0].repeat(s)}${r}`:r}}function $a(e){return e.map(t=>Aa(t)).join(" ")}function Aa(e){if(e==="")return"''";if(!/[\s'"\\$`!*?[\]{}|&;<>()~#\n\t]/.test(e))return e;let s=/[\x00-\x1f\x7f]/.test(e),n=e.includes(`
639
- `),r=e.includes(" "),i=e.includes("\\"),a=e.includes("'");if(s||n||r||i){let l="";for(let u of e){let c=u.charCodeAt(0);u===`
640
- `?l+="\\n":u===" "?l+="\\t":u==="\\"?l+="\\\\":u==="'"?l+="'":u==='"'?l+='"':c<32||c===127?c<256?l+=`\\x${c.toString(16).padStart(2,"0")}`:l+=`\\u${c.toString(16).padStart(4,"0")}`:l+=u}return`$'${l}'`}return a?`"${e.replace(/([\\$`"])/g,"\\$1")}"`:`'${e}'`}async function Ts(e,t,s){if(!e.state.options.xtrace)return"";let n=await Di(e),r=[t,...s],i=$a(r);return`${n}${i}
641
- `}async function Ii(e,t,s){return e.state.options.xtrace?`${await Di(e)}${t}=${s}
642
- `:""}function Wt(e){let t=je(e);return t.endsWith(`
640
+ `))}return{stdout:A(),stderr:A(),exitCode:1}}return{stdout:A(),stderr:A(),exitCode:s}}var Pa="+ ";async function Ii(e){let t=e.state.env.get("PS4"),s=e.substitutionDepth??0;if(t===void 0)return`${"+".repeat(s+1)} `;let n=U(t);if(n==="")return"";try{let i=new Z().parseWordFromString(n,!1,!1),a=await z(e,i);return s>0&&a.length>0?`${a[0].repeat(s)}${a}`:a}catch{await H(e,2,`bash: ${n}: bad substitution
641
+ `);let r=n||Pa;return s>0&&r.length>0?`${r[0].repeat(s)}${r}`:r}}function _a(e){return e.map(t=>Ta(t)).join(" ")}function Ta(e){if(e==="")return"''";if(!/[\s'"\\$`!*?[\]{}|&;<>()~#\n\t]/.test(e))return e;let s=/[\x00-\x1f\x7f]/.test(e),n=e.includes(`
642
+ `),r=e.includes(" "),i=e.includes("\\"),a=e.includes("'");if(s||n||r||i){let l="";for(let c of e){let u=c.charCodeAt(0);c===`
643
+ `?l+="\\n":c===" "?l+="\\t":c==="\\"?l+="\\\\":c==="'"?l+="'":c==='"'?l+='"':u<32||u===127?u<256?l+=`\\x${u.toString(16).padStart(2,"0")}`:l+=`\\u${u.toString(16).padStart(4,"0")}`:l+=c}return`$'${l}'`}return a?`"${e.replace(/([\\$`"])/g,"\\$1")}"`:`'${e}'`}async function Ns(e,t,s){if(!e.state.options.xtrace)return"";let n=await Ii(e),r=[t,...s],i=_a(r);return`${n}${i}
644
+ `}async function Di(e,t,s){return e.state.options.xtrace?`${await Ii(e)}${t}=${s}
645
+ `:""}function Ft(e){let t=je(e);return t.endsWith(`
643
646
  `)?t:`${t}
644
- `}async function gt(e,t,s){let n=await Te(e,e.outputChannels,t);return n.error?K(e,n.channels,()=>X(e,n.error)):K(e,n.channels,async()=>{try{let r=await s(n.legacyRedirections);return{stdout:E(),stderr:E(),exitCode:r}}catch(r){let i=await ee(e,r);if(r instanceof Error&&"code"in r&&r.code==="ENOSPC")return i?{stdout:E(),stderr:E(),exitCode:1}:await X(e,A(Wt(r)));throw r}})}async function Ri(e,t){return gt(e,t.redirections,async()=>{for(let s of t.clauses)if((await _s(e,s.condition)).exitCode===0)return(await xs(e,s.body)).exitCode;return t.elseBody?(await xs(e,t.elseBody)).exitCode:0})}async function Li(e,t){return gt(e,t.redirections,async()=>{let s=0,n=0;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t.variable))return await X(e,A(`bash: \`${t.variable}': not a valid identifier
645
- `)),1;let r=[];if(t.words===null)r=T(e.state.env,"@","").split(" ").filter(Boolean);else if(t.words.length>0)try{for(let i of t.words){let a=await We(e,i);r.push(...a.values)}}catch(i){if(i instanceof Gt)return await ee(e,i),1;throw i}e.state.loopDepth++;try{for(let i of r){if(n++,e.signal?.aborted)throw new pe(e.signal.reason);n>e.limits.maxLoopIterations&&De(`for loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations"),y(e.state.env,t.variable,i),e.state.options.xtrace&&await U(e,2,await Ts(e,"for",[t.variable,"in",...r]));try{for(let a of t.body){let o=await e.executeStatement(a);await X(e,o),s=o.exitCode}}catch(a){let o=await ee(e,a),l=Mt(a,e.state.loopDepth);if(l.action==="break")break;if(l.action==="continue")continue;if(l.action==="error")return o||await X(e,A(Wt(l.error))),l.exitCode??1;throw l.error}}}finally{e.state.loopDepth--}return s})}async function Mi(e,t){return gt(e,t.redirections,async()=>{let s=t.line;s!==void 0&&(e.state.currentLine=s);let n=0,r=0;t.init&&await Q(e,t.init.expression),e.state.loopDepth++;try{for(;;){if(r++,e.signal?.aborted)throw new pe(e.signal.reason);if(r>e.limits.maxLoopIterations&&De(`for loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations"),t.condition&&(s!==void 0&&(e.state.currentLine=s),await Q(e,t.condition.expression)===0))break;try{for(let i of t.body){let a=await e.executeStatement(i);await X(e,a),n=a.exitCode}}catch(i){let a=await ee(e,i),o=Mt(i,e.state.loopDepth);if(o.action==="break")break;if(o.action==="continue"){t.update&&await Q(e,t.update.expression);continue}if(o.action==="error")return a||await X(e,A(Wt(o.error))),o.exitCode??1;throw o.error}t.update&&await Q(e,t.update.expression)}}finally{e.state.loopDepth--}return n})}async function Wi(e,t,s=E()){return gt(e,t.redirections,async n=>{let r=0,i=0,a=s,o=!1;for(let u of n)if((u.operator==="<<"||u.operator==="<<-")&&u.target.type==="HereDoc"){let c=u.target,f=await z(e,c.content);c.stripTabs&&(f=f.split(`
647
+ `}async function gt(e,t,s){let n=await Ne(e,e.outputChannels,t);return n.error?K(e,n.channels,()=>Y(e,n.error)):K(e,n.channels,async()=>{try{let r=await s(n.legacyRedirections);return{stdout:A(),stderr:A(),exitCode:r}}catch(r){let i=await ee(e,r);if(r instanceof Error&&"code"in r&&r.code==="ENOSPC")return i?{stdout:A(),stderr:A(),exitCode:1}:await Y(e,C(Ft(r)));throw r}})}async function Ri(e,t){return gt(e,t.redirections,async()=>{for(let s of t.clauses)if((await _s(e,s.condition)).exitCode===0)return(await Ts(e,s.body)).exitCode;return t.elseBody?(await Ts(e,t.elseBody)).exitCode:0})}async function Li(e,t){return gt(e,t.redirections,async()=>{let s=0,n=0;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t.variable))return await Y(e,C(`bash: \`${t.variable}': not a valid identifier
648
+ `)),1;let r=[];if(t.words===null)r=x(e.state.env,"@","").split(" ").filter(Boolean);else if(t.words.length>0)try{for(let i of t.words){let a=await We(e,i);r.push(...a.values)}}catch(i){if(i instanceof qt)return await ee(e,i),1;throw i}e.state.loopDepth++;try{for(let i of r){if(n++,e.signal?.aborted)throw new pe(e.signal.reason);n>e.limits.maxLoopIterations&&Ie(`for loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations"),y(e.state.env,t.variable,i),e.state.options.xtrace&&await H(e,2,await Ns(e,"for",[t.variable,"in",...r]));try{for(let a of t.body){let o=await e.executeStatement(a);await Y(e,o),s=o.exitCode}}catch(a){let o=await ee(e,a),l=Wt(a,e.state.loopDepth);if(l.action==="break")break;if(l.action==="continue")continue;if(l.action==="error")return o||await Y(e,C(Ft(l.error))),l.exitCode??1;throw l.error}}}finally{e.state.loopDepth--}return s})}async function Mi(e,t){return gt(e,t.redirections,async()=>{let s=t.line;s!==void 0&&(e.state.currentLine=s);let n=0,r=0;t.init&&await Q(e,t.init.expression),e.state.loopDepth++;try{for(;;){if(r++,e.signal?.aborted)throw new pe(e.signal.reason);if(r>e.limits.maxLoopIterations&&Ie(`for loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations"),t.condition&&(s!==void 0&&(e.state.currentLine=s),await Q(e,t.condition.expression)===0))break;try{for(let i of t.body){let a=await e.executeStatement(i);await Y(e,a),n=a.exitCode}}catch(i){let a=await ee(e,i),o=Wt(i,e.state.loopDepth);if(o.action==="break")break;if(o.action==="continue"){t.update&&await Q(e,t.update.expression);continue}if(o.action==="error")return a||await Y(e,C(Ft(o.error))),o.exitCode??1;throw o.error}t.update&&await Q(e,t.update.expression)}}finally{e.state.loopDepth--}return n})}async function Wi(e,t,s=A()){return gt(e,t.redirections,async n=>{let r=0,i=0,a=s,o=!1;for(let c of n)if((c.operator==="<<"||c.operator==="<<-")&&c.target.type==="HereDoc"){let u=c.target,f=await z(e,u.content);u.stripTabs&&(f=f.split(`
646
649
  `).map(d=>d.replace(/^\t+/,"")).join(`
647
- `)),a=V(f),o=!0}else if(u.operator==="<<<"&&u.target.type==="Word")a=V(`${await z(e,u.target)}
648
- `),o=!0;else if(u.operator==="<"&&u.target.type==="Word"){let c=await z(e,u.target);try{let f=e.fs.resolvePath(e.state.cwd,c);a=await e.fs.readFile(f),o=!0}catch{return await X(e,A(`bash: ${c}: No such file or directory
649
- `)),1}}let l=e.state.groupStdin;if(o)e.state.groupStdin=a;else{let u=await ie(s);u.length>0&&(e.state.groupStdin=de(u))}e.state.loopDepth++;try{for(;;){if(i++,e.signal?.aborted)throw new pe(e.signal.reason);i>e.limits.maxLoopIterations&&De(`while loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations");let u=0,c=!1,f=!1;try{u=(await _s(e,t.condition)).exitCode}catch(d){if(await ee(e,d),d instanceof $e){if(d.levels>1&&e.state.loopDepth>1)throw d.levels--,d;c=!0}else if(d instanceof Ae){if(d.levels>1&&e.state.loopDepth>1)throw d.levels--,d;f=!0}else throw d}if(c)break;if(!f){if(u!==0)break;try{for(let d of t.body){let p=await e.executeStatement(d);await X(e,p),r=p.exitCode}}catch(d){let p=await ee(e,d),m=Mt(d,e.state.loopDepth);if(m.action==="break")break;if(m.action==="continue")continue;if(m.action==="error")return p||await X(e,A(Wt(m.error))),m.exitCode??1;throw m.error}}}}finally{e.state.loopDepth--,e.state.groupStdin=l}return r})}async function Fi(e,t){return gt(e,t.redirections,async()=>{let s=0,n=0;e.state.loopDepth++;try{for(;;){if(n++,e.signal?.aborted)throw new pe(e.signal.reason);if(n>e.limits.maxLoopIterations&&De(`until loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations"),(await _s(e,t.condition)).exitCode===0)break;try{for(let i of t.body){let a=await e.executeStatement(i);await X(e,a),s=a.exitCode}}catch(i){let a=await ee(e,i),o=Mt(i,e.state.loopDepth);if(o.action==="break")break;if(o.action==="continue")continue;if(o.action==="error")return a||await X(e,A(Wt(o.error))),o.exitCode??1;throw o.error}}}finally{e.state.loopDepth--}return s})}async function Vi(e,t){return gt(e,t.redirections,async()=>{let s=0,n=await z(e,t.word),r=!1;for(let i=0;i<t.items.length;i++){let a=t.items[i],o=r;if(!r)for(let l of a.patterns){let u=await z(e,l);mr(l)&&(u=hr(u));let c=e.state.shoptOptions.nocasematch,f=e.state.shoptOptions.extglob;if(ft(n,u,c,f)){o=!0;break}}if(o){if(s=(await xs(e,a.body)).exitCode,a.terminator===";;")break;a.terminator===";&"?r=!0:r=!1}else r=!1}return s})}async function Ca(e,t,s){let n=Pe(),r=s?Pe():void 0,i=Qe(e.outputChannels);Ms(i,1,n),r&&Ms(i,2,r);try{let a=await K(e,i,t);return{...a,stdout:rt(a.stdout,n.stream()),stderr:r?rt(a.stderr,r.stream()):a.stderr}}catch(a){await K(e,i,()=>ee(e,a));let o=n.stream(),l=r?.stream()??E();if(a instanceof At)return{stdout:o,stderr:l,exitCode:1};if(a instanceof q)return{stdout:o,stderr:l,exitCode:a.exitCode};if(a instanceof Ce)return{stdout:o,stderr:l,exitCode:a.exitCode};throw await X(e,{stdout:o,stderr:l,exitCode:1},!1),a}}async function zi(e,t,s){let n=t.timed?performance.now():0,r=E(),i=B(),a=0,o=[],l=t.commands.length>1,u=e.state.lastArg;for(let d=0;d<t.commands.length;d++){let p=t.commands[d],m=d===t.commands.length-1,h=d===0,b=t.pipeStderr?.[d]??!1;l&&(e.state.lastArg=F(""),h||(e.state.groupStdin=void 0));let S=l&&(!m||!e.state.shoptOptions.lastpipe),$=S?new Map(e.state.env):null,g;try{if(m){let v=()=>s(p,r);g=S?await K(e,Qe(e.outputChannels),v):await v()}else g=await Ca(e,()=>s(p,r),b)}catch(v){if(await ee(e,v),v instanceof At)g={stdout:E(),stderr:E(),exitCode:1};else if(v instanceof q&&t.commands.length>1)g={stdout:E(),stderr:E(),exitCode:v.exitCode};else if(v instanceof Ce&&t.commands.length>1)g={stdout:E(),stderr:E(),exitCode:v.exitCode};else throw $&&(e.state.env=$),v}if($&&(e.state.env=$),e.signal?.aborted===!0&&g.exitCode===new pe(e.signal.reason).exitCode)throw await X(e,g,!1),new pe(e.signal.reason);if(o.push(g.exitCode),g.exitCode!==0&&(a=g.exitCode),m)i=g;else if(b)r=rt(g.stderr,g.stdout),i={stdout:E(),stderr:E(),exitCode:g.exitCode};else{let v=g.stdout;await X(e,g,!0,[2]),r=v,i={stdout:E(),stderr:E(),exitCode:g.exitCode}}}e.state.options.pipefail&&a!==0&&(i={...i,exitCode:a}),t.negated&&(i={...i,exitCode:i.exitCode===0?1:0});let c=i.exitCode;if(i=await X(e,i),i.exitCode!==c&&o.length>0&&(o[o.length-1]=i.exitCode),t.commands.length>1||t.commands.length===1&&t.commands[0].type==="SimpleCommand"){for(let d of e.state.env.keys())d.startsWith("PIPESTATUS_")&&e.state.env.delete(d);for(let d=0;d<o.length;d++)y(e.state.env,`PIPESTATUS_${d}`,String(o[d]));y(e.state.env,"PIPESTATUS__length",String(o.length))}if(t.timed){let p=(performance.now()-n)/1e3,m=Math.floor(p/60),h=p%60,b;t.timePosix?b=`real ${p.toFixed(2)}
650
+ `)),a=V(f),o=!0}else if(c.operator==="<<<"&&c.target.type==="Word")a=V(`${await z(e,c.target)}
651
+ `),o=!0;else if(c.operator==="<"&&c.target.type==="Word"){let u=await z(e,c.target);try{let f=e.fs.resolvePath(e.state.cwd,u);a=await e.fs.readFile(f),o=!0}catch{return await Y(e,C(await Dt(e,u))),1}}let l=e.state.groupStdin;if(o)e.state.groupStdin=a;else{let c=await ie(s);c.length>0&&(e.state.groupStdin=de(c))}e.state.loopDepth++;try{for(;;){if(i++,e.signal?.aborted)throw new pe(e.signal.reason);i>e.limits.maxLoopIterations&&Ie(`while loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations");let c=0,u=!1,f=!1;try{c=(await _s(e,t.condition)).exitCode}catch(d){if(await ee(e,d),d instanceof $e){if(d.levels>1&&e.state.loopDepth>1)throw d.levels--,d;u=!0}else if(d instanceof Ae){if(d.levels>1&&e.state.loopDepth>1)throw d.levels--,d;f=!0}else throw d}if(u)break;if(!f){if(c!==0)break;try{for(let d of t.body){let p=await e.executeStatement(d);await Y(e,p),r=p.exitCode}}catch(d){let p=await ee(e,d),m=Wt(d,e.state.loopDepth);if(m.action==="break")break;if(m.action==="continue")continue;if(m.action==="error")return p||await Y(e,C(Ft(m.error))),m.exitCode??1;throw m.error}}}}finally{e.state.loopDepth--,e.state.groupStdin=l}return r})}async function Fi(e,t){return gt(e,t.redirections,async()=>{let s=0,n=0;e.state.loopDepth++;try{for(;;){if(n++,e.signal?.aborted)throw new pe(e.signal.reason);if(n>e.limits.maxLoopIterations&&Ie(`until loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations"),(await _s(e,t.condition)).exitCode===0)break;try{for(let i of t.body){let a=await e.executeStatement(i);await Y(e,a),s=a.exitCode}}catch(i){let a=await ee(e,i),o=Wt(i,e.state.loopDepth);if(o.action==="break")break;if(o.action==="continue")continue;if(o.action==="error")return a||await Y(e,C(Ft(o.error))),o.exitCode??1;throw o.error}}}finally{e.state.loopDepth--}return s})}async function Vi(e,t){return gt(e,t.redirections,async()=>{let s=0,n=await z(e,t.word),r=!1;for(let i=0;i<t.items.length;i++){let a=t.items[i],o=r;if(!r)for(let l of a.patterns){let c=await z(e,l);mr(l)&&(c=hr(c));let u=e.state.shoptOptions.nocasematch,f=e.state.shoptOptions.extglob;if(ft(n,c,u,f)){o=!0;break}}if(o){if(s=(await Ts(e,a.body)).exitCode,a.terminator===";;")break;a.terminator===";&"?r=!0:r=!1}else r=!1}return s})}async function Na(e,t,s){let n=Pe(),r=s?Pe():void 0,i=Qe(e.outputChannels);Ms(i,1,n),r&&Ms(i,2,r);try{let a=await K(e,i,t);return{...a,stdout:rt(a.stdout,n.stream()),stderr:r?rt(a.stderr,r.stream()):a.stderr}}catch(a){await K(e,i,()=>ee(e,a));let o=n.stream(),l=r?.stream()??A();if(a instanceof At)return{stdout:o,stderr:l,exitCode:1};if(a instanceof q)return{stdout:o,stderr:l,exitCode:a.exitCode};if(a instanceof Ce)return{stdout:o,stderr:l,exitCode:a.exitCode};throw await Y(e,{stdout:o,stderr:l,exitCode:1},!1),a}}async function zi(e,t,s){let n=t.timed?performance.now():0,r=A(),i=B(),a=0,o=[],l=t.commands.length>1,c=e.state.lastArg;for(let d=0;d<t.commands.length;d++){let p=t.commands[d],m=d===t.commands.length-1,h=d===0,v=t.pipeStderr?.[d]??!1;l&&(e.state.lastArg=F(""),h||(e.state.groupStdin=void 0));let S=l&&(!m||!e.state.shoptOptions.lastpipe),E=S?new Map(e.state.env):null,b;try{if(m){let g=()=>s(p,r);b=S?await K(e,Qe(e.outputChannels),g):await g()}else b=await Na(e,()=>s(p,r),v)}catch(g){if(await ee(e,g),g instanceof At)b={stdout:A(),stderr:A(),exitCode:1};else if(g instanceof q&&t.commands.length>1)b={stdout:A(),stderr:A(),exitCode:g.exitCode};else if(g instanceof Ce&&t.commands.length>1)b={stdout:A(),stderr:A(),exitCode:g.exitCode};else throw E&&(e.state.env=E),g}if(E&&(e.state.env=E),e.signal?.aborted===!0&&b.exitCode===new pe(e.signal.reason).exitCode)throw await Y(e,b,!1),new pe(e.signal.reason);if(o.push(b.exitCode),b.exitCode!==0&&(a=b.exitCode),m)i=b;else if(v)r=rt(b.stderr,b.stdout),i={stdout:A(),stderr:A(),exitCode:b.exitCode};else{let g=b.stdout;await Y(e,b,!0,[2]),r=g,i={stdout:A(),stderr:A(),exitCode:b.exitCode}}}e.state.options.pipefail&&a!==0&&(i={...i,exitCode:a}),t.negated&&(i={...i,exitCode:i.exitCode===0?1:0});let u=i.exitCode;if(i=await Y(e,i),i.exitCode!==u&&o.length>0&&(o[o.length-1]=i.exitCode),t.commands.length>1||t.commands.length===1&&t.commands[0].type==="SimpleCommand"){for(let d of e.state.env.keys())d.startsWith("PIPESTATUS_")&&e.state.env.delete(d);for(let d=0;d<o.length;d++)y(e.state.env,`PIPESTATUS_${d}`,String(o[d]));y(e.state.env,"PIPESTATUS__length",String(o.length))}if(t.timed){let p=(performance.now()-n)/1e3,m=Math.floor(p/60),h=p%60,v;t.timePosix?v=`real ${p.toFixed(2)}
650
652
  user 0.00
651
653
  sys 0.00
652
- `:b=`
654
+ `:v=`
653
655
  real ${`${m}m${h.toFixed(3)}s`}
654
656
  user 0m0.000s
655
657
  sys 0m0.000s
656
- `,await U(e,2,b)}return l&&!e.state.shoptOptions.lastpipe&&(e.state.lastArg=u),i}async function ji(e,t){let s=new Map,n="";for(let r of t.assignments){let i=r.name;if(r.array){let f=await ka(e,t,i,r.array,r.append,s);if(f.error)return{continueToNext:!1,xtraceOutput:n,tempAssignments:s,error:f.error};if(n+=f.xtraceOutput,f.continueToNext)continue}let a=r.value?await it(e,r.value):L,o=r.value?H(a):"";if(o.length>e.limits.maxStringLength&&De(`word expansion: string length limit exceeded (${e.limits.maxStringLength} bytes)`,"iterations"),i.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[\]$/))return{continueToNext:!1,xtraceOutput:n,tempAssignments:s,error:A(`bash: ${i}: bad array subscript
657
- `)};let u=i.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(u){let f=await Na(e,t,u[1],u[2],o,r.append,s);if(f.error)return{continueToNext:!1,xtraceOutput:n,tempAssignments:s,error:f.error};if(f.continueToNext)continue}let c=await Da(e,t,i,o,r.append,s,a);if(c.error)return{continueToNext:!1,xtraceOutput:n,tempAssignments:s,error:c.error};n+=c.xtraceOutput,c.continueToNext}return{continueToNext:!1,xtraceOutput:n,tempAssignments:s}}async function ka(e,t,s,n,r,i){let a="";if(/\[.+\]$/.test(s))return{continueToNext:!1,xtraceOutput:"",error:A(`bash: ${s}: cannot assign list to array member
658
- `)};if(ve(e,s)){let c=fr(e,s);if(c===void 0||c==="")throw new q(1);let f=Me(e,s);if(f&&/^[a-zA-Z_][a-zA-Z0-9_]*\[@\]$/.test(f))return{continueToNext:!1,xtraceOutput:"",error:A(`bash: ${s}: cannot assign list to array member
658
+ `,await H(e,2,v)}return l&&!e.state.shoptOptions.lastpipe&&(e.state.lastArg=c),i}async function ji(e,t){let s=new Map,n="";for(let r of t.assignments){let i=r.name;if(r.array){let f=await xa(e,t,i,r.array,r.append,s);if(f.error)return{continueToNext:!1,xtraceOutput:n,tempAssignments:s,error:f.error};if(n+=f.xtraceOutput,f.continueToNext)continue}let a=r.value?await it(e,r.value):R,o=r.value?U(a):"";if(o.length>e.limits.maxStringLength&&Ie(`word expansion: string length limit exceeded (${e.limits.maxStringLength} bytes)`,"iterations"),i.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[\]$/))return{continueToNext:!1,xtraceOutput:n,tempAssignments:s,error:C(`bash: ${i}: bad array subscript
659
+ `)};let c=i.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(c){let f=await La(e,t,c[1],c[2],o,r.append,s);if(f.error)return{continueToNext:!1,xtraceOutput:n,tempAssignments:s,error:f.error};if(f.continueToNext)continue}let u=await Wa(e,t,i,o,r.append,s,a);if(u.error)return{continueToNext:!1,xtraceOutput:n,tempAssignments:s,error:u.error};n+=u.xtraceOutput,u.continueToNext}return{continueToNext:!1,xtraceOutput:n,tempAssignments:s}}async function xa(e,t,s,n,r,i){let a="";if(/\[.+\]$/.test(s))return{continueToNext:!1,xtraceOutput:"",error:C(`bash: ${s}: cannot assign list to array member
660
+ `)};if(ve(e,s)){let u=fr(e,s);if(u===void 0||u==="")throw new q(1);let f=Me(e,s);if(f&&/^[a-zA-Z_][a-zA-Z0-9_]*\[@\]$/.test(f))return{continueToNext:!1,xtraceOutput:"",error:C(`bash: ${s}: cannot assign list to array member
659
661
  `)}}if(et(e,s)){if(t.name)return a+=`bash: ${s}: readonly variable
660
- `,{continueToNext:!0,xtraceOutput:a};let c=await ue(e,s);if(c)return{continueToNext:!1,xtraceOutput:"",error:c}}let o=e.state.associativeArrays?.has(s),l=Pa(n),u=()=>{let c=`${s}_`;for(let f of e.state.env.keys())f.startsWith(c)&&!f.includes("__")&&e.state.env.delete(f);e.state.env.delete(s)};if(o&&l?await _a(e,t,s,n,r,u,c=>{a+=c}):l?await xa(e,s,n,r,u):await Ta(e,s,n,r,u),t.name){i.set(s,e.state.env.get(s));let f=`(${n.map(d=>Kt(d)).join(" ")})`;y(e.state.env,s,f)}return{continueToNext:!0,xtraceOutput:a}}function Pa(e){return e.some(t=>{if(t.parts.length>=2){let s=t.parts[0],n=t.parts[1];if(s.type!=="Glob"||!s.pattern.startsWith("["))return!1;if(s.pattern==="["&&(n.type==="DoubleQuoted"||n.type==="SingleQuoted")){if(t.parts.length<3)return!1;let r=t.parts[2];return r.type!=="Literal"?!1:r.value.startsWith("]=")||r.value.startsWith("]+=")}return n.type!=="Literal"?!1:n.value.startsWith("]")?n.value.startsWith("]=")||n.value.startsWith("]+="):s.pattern.endsWith("]")?n.value.startsWith("=")||n.value.startsWith("+="):!1}return!1})}async function _a(e,t,s,n,r,i,a){let o=[];for(let l of n){let u=Fs(l);if(u){let{key:c,valueParts:f,append:d}=u,p;f.length>0?p=await z(e,{type:"Word",parts:f}):p="",p=se(e,p),o.push({type:"keyed",key:c,value:p,append:d})}else{let c=await z(e,l);o.push({type:"invalid",expandedValue:c})}}r||i();for(let l of o)if(l.type==="keyed")if(l.append){let u=T(e.state.env,`${s}_${l.key}`,"");y(e.state.env,`${s}_${l.key}`,u+l.value)}else y(e.state.env,`${s}_${l.key}`,l.value);else{let u=t.line??e.state.currentLine??1;a(`bash: line ${u}: ${s}: ${l.expandedValue}: must use subscript when assigning associative array
661
- `)}}async function xa(e,t,s,n,r){let i=[];for(let o of s){let l=Fs(o);if(l){let{key:u,valueParts:c,append:f}=l,d;c.length>0?d=await z(e,{type:"Word",parts:c}):d="",d=se(e,d),i.push({type:"keyed",indexExpr:u,value:d,append:f})}else{let u=await We(e,o);i.push({type:"non-keyed",values:u.values})}}n||r();let a=0;for(let o of i)if(o.type==="keyed"){let l;try{let u=new Z,c=le(u,o.indexExpr);l=await Q(e,c.expression,!1)}catch{if(/^-?\d+$/.test(o.indexExpr))l=Number.parseInt(o.indexExpr,10);else{let u=T(e.state.env,o.indexExpr);l=u?Number.parseInt(u,10):0,Number.isNaN(l)&&(l=0)}}if(o.append){let u=T(e.state.env,`${t}_${l}`,"");y(e.state.env,`${t}_${l}`,u+o.value)}else y(e.state.env,`${t}_${l}`,o.value);a=l+1}else for(let l of o.values)y(e.state.env,`${t}_${a++}`,l)}async function Ta(e,t,s,n,r){let i=[];for(let o of s){let l=await We(e,o);i.push(...l.values)}let a=0;if(n){let o=Ne(e,t);if(o.length>0)a=Math.max(...o.map(([u])=>typeof u=="number"?u:0))+1;else{let l=e.state.env.get(t);l!==void 0&&(e.state.env.set(`${t}_0`,l),e.state.env.delete(t),a=1)}}else r();for(let o=0;o<i.length;o++)y(e.state.env,`${t}_${a+o}`,i[o]);n||y(e.state.env,`${t}__length`,String(i.length))}async function Na(e,t,s,n,r,i,a){let o=s;if(ve(e,s)){let f=Me(e,s);if(f&&f!==s){if(f.includes("["))return{continueToNext:!1,xtraceOutput:"",error:A(`bash: \`${f}': not a valid identifier
662
- `)};o=f}}if(et(e,o)){if(t.name)return{continueToNext:!0,xtraceOutput:""};let f=await ue(e,o);if(f)return{continueToNext:!1,xtraceOutput:"",error:f}}let l=e.state.associativeArrays?.has(o),u;if(l)u=await Bi(e,o,n);else{let f=await Oa(e,o,n);if(f.error)return{continueToNext:!1,xtraceOutput:"",error:f.error};u=`${o}_${f.index}`}let c=i?T(e.state.env,u)+r:r;if(t.name)a.set(u,e.state.env.get(u)),y(e.state.env,u,c);else{let f=dt(e,o);if(f!==void 0&&f===e.state.callDepth&&e.state.localScopes.length>0){let d=e.state.localScopes[e.state.localScopes.length-1];d.has(u)||d.set(u,e.state.env.get(u))}y(e.state.env,u,c)}return{continueToNext:!0,xtraceOutput:""}}async function Bi(e,t,s){let n;if(s.startsWith("'")&&s.endsWith("'"))n=s.slice(1,-1);else if(s.startsWith('"')&&s.endsWith('"')){let r=s.slice(1,-1),a=new Z().parseWordFromString(r,!0,!1);n=await z(e,a)}else if(s.includes("$")){let i=new Z().parseWordFromString(s,!1,!1);n=await z(e,i)}else n=s;return`${t}_${n}`}async function Oa(e,t,s){let n=s;s.startsWith('"')&&s.endsWith('"')&&s.length>=2&&(n=s.slice(1,-1));let r;if(/^-?\d+$/.test(n))r=Number.parseInt(n,10);else{try{let i=new Z,a=le(i,n);r=await Q(e,a.expression,!1)}catch(i){if(i instanceof Xe){let l=`bash: line ${e.state.currentLine}: ${s}: ${i.message}
663
- `;if(i.fatal)throw await U(e,2,l,!0),new q(1);return{index:0,error:A(l)}}let a=T(e.state.env,s);r=a?Number.parseInt(a,10):0}Number.isNaN(r)&&(r=0)}if(r<0){let i=Ne(e,t);if(i.length===0){let o=e.state.currentLine;return{index:0,error:A(`bash: line ${o}: ${t}[${s}]: bad array subscript
664
- `)}}if(r=Math.max(...i.map(([o])=>typeof o=="number"?o:0))+1+r,r<0){let o=e.state.currentLine;return{index:0,error:A(`bash: line ${o}: ${t}[${s}]: bad array subscript
665
- `)}}}return{index:r}}async function Da(e,t,s,n,r,i,a){let o="",l=s,u=null;if(ve(e,s)){let h=dr(e,s,n);if(h===void 0)return{continueToNext:!1,xtraceOutput:"",error:A(`bash: ${s}: circular name reference
666
- `)};if(h===null)return{continueToNext:!0,xtraceOutput:""};l=h;let b=l.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);b&&(u={arrayName:b[1],subscriptExpr:b[2]},l=b[1])}if(et(e,l)){if(t.name)return o+=`bash: ${l}: readonly variable
667
- `,{continueToNext:!0,xtraceOutput:o};let h=await ue(e,l);if(h)return{continueToNext:!1,xtraceOutput:"",error:h}}let c,f=!!a&&!r&&!u;if(It(e,l)){f=!1;try{let h=new Z;if(r){let S=`(${T(e.state.env,l,"0")}) + (${n})`,$=le(h,S);c=String(await Q(e,$.expression))}else{let b=le(h,n);c=String(await Q(e,b.expression))}}catch{c="0"}}else{let{isArray:h}=await import("./chunks/expansion-IB7ZIBIF.js"),b=h(e,l);b&&(f=!1);let S=b?`${l}_0`:l;c=r?T(e.state.env,S)+n:n}let d=mt(e,l,c);d!==c&&(f=!1),c=d,o+=await Ii(e,l,c);let p=l;if(u)p=await Ia(e,u);else{let{isArray:h}=await import("./chunks/expansion-IB7ZIBIF.js");h(e,l)&&(p=`${l}_0`,f=!1)}let m=f?()=>e.state.env.set(p,a):()=>y(e.state.env,p,c);return t.name?(i.set(p,e.state.env.get(p)),m()):(m(),e.state.options.allexport&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(l)),e.state.tempEnvBindings?.some(h=>h.has(l))&&(e.state.mutatedTempEnvVars=e.state.mutatedTempEnvVars||new Set,e.state.mutatedTempEnvVars.add(l))),{continueToNext:!1,xtraceOutput:o}}async function Ia(e,t){let{arrayName:s,subscriptExpr:n}=t;if(e.state.associativeArrays?.has(s))return Bi(e,s,n);let i;if(/^-?\d+$/.test(n))i=Number.parseInt(n,10);else{try{let a=new Z,o=le(a,n);i=await Q(e,o.expression,!1)}catch{let a=T(e.state.env,n);i=a?Number.parseInt(a,10):0}Number.isNaN(i)&&(i=0)}if(i<0){let a=Ne(e,s);a.length>0&&(i=Math.max(...a.map(l=>l[0]))+1+i)}return`${s}_${i}`}async function Hi(e,t,s,n){let r=Qe(e.outputChannels),i=new Map(e.state.env),a=e.state.cwd,o=e.state.fileDescriptors,l=e.state.nextFd;e.state.fileDescriptors=o?new Map(o):void 0;let u={...e.state.options},c=new Map(e.state.functions),f=e.state.localScopes,d=e.state.localVarStack,p=e.state.localVarDepth,m=e.state.fullyUnsetLocals;if(e.state.localScopes=f.map(C=>new Map(C)),d){e.state.localVarStack=new Map;for(let[C,N]of d.entries())e.state.localVarStack.set(C,N.map(I=>({...I})))}p&&(e.state.localVarDepth=new Map(p)),m&&(e.state.fullyUnsetLocals=new Map(m));let h=e.state.loopDepth,b=e.state.parentHasLoopContext;e.state.parentHasLoopContext=h>0,e.state.loopDepth=0;let S=e.state.lastArg,$=e.state.bashPid;e.state.bashPid=e.state.nextVirtualPid++;let g=e.state.groupStdin,v=()=>{e.state.env=i,e.state.cwd=a,e.state.fileDescriptors=o,e.state.nextFd=l,e.state.options=u,e.state.functions=c,e.state.localScopes=f,e.state.localVarStack=d,e.state.localVarDepth=p,e.state.fullyUnsetLocals=m,e.state.loopDepth=h,e.state.parentHasLoopContext=b,e.state.groupStdin=g,e.state.bashPid=$,e.state.lastArg=S};try{let C=t.redirections.length===0?{channels:r,legacyRedirections:[]}:await Te(e,r,t.redirections);return C.error?await K(e,C.channels,()=>te(e,()=>Promise.resolve(C.error))):await K(e,C.channels,async()=>{let N=I=>W(E(),E(),I);try{let I=await ie(s);I.length>0&&(e.state.groupStdin=de(I));let P=0;for(let k of t.body){let O=await n(k);P=(await te(e,()=>Promise.resolve(O))).exitCode}return await N(P)}catch(I){let{diagnosticWritten:P,writeFailure:k}=await qe(e,I);if(k)return k;if(I instanceof oe)throw I;return I instanceof ze||I instanceof $e||I instanceof Ae?await N(0):I instanceof q||I instanceof ye||I instanceof Ce||I instanceof we?await N(I.exitCode):(P||await te(e,()=>Promise.resolve(A(`${je(I)}
668
- `))),await N(1))}})}catch(C){throw await K(e,r,()=>ee(e,C)),C}finally{v()}}async function Ui(e,t,s,n){let r=t.redirections.length===0?{channels:e.outputChannels,legacyRedirections:[]}:await Te(e,e.outputChannels,t.redirections);return r.error?K(e,r.channels,()=>te(e,()=>Promise.resolve(r.error))):K(e,r.channels,async()=>{let i=e.state.groupStdin;try{let a=await ht(e,r.legacyRedirections);if(a)return await te(e,()=>Promise.resolve(a));let o=await ie(s),l=de(o),u=!1;for(let f of r.legacyRedirections)if(!f.fdVariable){if((f.operator==="<<"||f.operator==="<<-")&&f.target.type==="HereDoc"){let d=f.target,p=await z(e,d.content);d.stripTabs&&(p=p.split(`
662
+ `,{continueToNext:!0,xtraceOutput:a};let u=await ue(e,s);if(u)return{continueToNext:!1,xtraceOutput:"",error:u}}let o=e.state.associativeArrays?.has(s),l=Oa(n),c=()=>{let u=`${s}_`;for(let f of e.state.env.keys())f.startsWith(u)&&!f.includes("__")&&e.state.env.delete(f);e.state.env.delete(s)};if(o&&l?await Ia(e,t,s,n,r,c,u=>{a+=u}):l?await Da(e,s,n,r,c):await Ra(e,s,n,r,c),t.name){i.set(s,e.state.env.get(s));let f=`(${n.map(d=>Kt(d)).join(" ")})`;y(e.state.env,s,f)}return{continueToNext:!0,xtraceOutput:a}}function Oa(e){return e.some(t=>{if(t.parts.length>=2){let s=t.parts[0],n=t.parts[1];if(s.type!=="Glob"||!s.pattern.startsWith("["))return!1;if(s.pattern==="["&&(n.type==="DoubleQuoted"||n.type==="SingleQuoted")){if(t.parts.length<3)return!1;let r=t.parts[2];return r.type!=="Literal"?!1:r.value.startsWith("]=")||r.value.startsWith("]+=")}return n.type!=="Literal"?!1:n.value.startsWith("]")?n.value.startsWith("]=")||n.value.startsWith("]+="):s.pattern.endsWith("]")?n.value.startsWith("=")||n.value.startsWith("+="):!1}return!1})}async function Ia(e,t,s,n,r,i,a){let o=[];for(let l of n){let c=Fs(l);if(c){let{key:u,valueParts:f,append:d}=c,p;f.length>0?p=await z(e,{type:"Word",parts:f}):p="",p=se(e,p),o.push({type:"keyed",key:u,value:p,append:d})}else{let u=await z(e,l);o.push({type:"invalid",expandedValue:u})}}r||i();for(let l of o)if(l.type==="keyed")if(l.append){let c=x(e.state.env,`${s}_${l.key}`,"");y(e.state.env,`${s}_${l.key}`,c+l.value)}else y(e.state.env,`${s}_${l.key}`,l.value);else{let c=t.line??e.state.currentLine??1;a(`bash: line ${c}: ${s}: ${l.expandedValue}: must use subscript when assigning associative array
663
+ `)}}async function Da(e,t,s,n,r){let i=[];for(let o of s){let l=Fs(o);if(l){let{key:c,valueParts:u,append:f}=l,d;u.length>0?d=await z(e,{type:"Word",parts:u}):d="",d=se(e,d),i.push({type:"keyed",indexExpr:c,value:d,append:f})}else{let c=await We(e,o);i.push({type:"non-keyed",values:c.values})}}n||r();let a=0;for(let o of i)if(o.type==="keyed"){let l;try{let c=new Z,u=le(c,o.indexExpr);l=await Q(e,u.expression,!1)}catch{if(/^-?\d+$/.test(o.indexExpr))l=Number.parseInt(o.indexExpr,10);else{let c=x(e.state.env,o.indexExpr);l=c?Number.parseInt(c,10):0,Number.isNaN(l)&&(l=0)}}if(o.append){let c=x(e.state.env,`${t}_${l}`,"");y(e.state.env,`${t}_${l}`,c+o.value)}else y(e.state.env,`${t}_${l}`,o.value);a=l+1}else for(let l of o.values)y(e.state.env,`${t}_${a++}`,l)}async function Ra(e,t,s,n,r){let i=[];for(let o of s){let l=await We(e,o);i.push(...l.values)}let a=0;if(n){let o=xe(e,t);if(o.length>0)a=Math.max(...o.map(([c])=>typeof c=="number"?c:0))+1;else{let l=e.state.env.get(t);l!==void 0&&(e.state.env.set(`${t}_0`,l),e.state.env.delete(t),a=1)}}else r();for(let o=0;o<i.length;o++)y(e.state.env,`${t}_${a+o}`,i[o]);n||y(e.state.env,`${t}__length`,String(i.length))}async function La(e,t,s,n,r,i,a){let o=s;if(ve(e,s)){let f=Me(e,s);if(f&&f!==s){if(f.includes("["))return{continueToNext:!1,xtraceOutput:"",error:C(`bash: \`${f}': not a valid identifier
664
+ `)};o=f}}if(et(e,o)){if(t.name)return{continueToNext:!0,xtraceOutput:""};let f=await ue(e,o);if(f)return{continueToNext:!1,xtraceOutput:"",error:f}}let l=e.state.associativeArrays?.has(o),c;if(l)c=await Bi(e,o,n);else{let f=await Ma(e,o,n);if(f.error)return{continueToNext:!1,xtraceOutput:"",error:f.error};c=`${o}_${f.index}`}let u=i?x(e.state.env,c)+r:r;if(t.name)a.set(c,e.state.env.get(c)),y(e.state.env,c,u);else{let f=dt(e,o);if(f!==void 0&&f===e.state.callDepth&&e.state.localScopes.length>0){let d=e.state.localScopes[e.state.localScopes.length-1];d.has(c)||d.set(c,e.state.env.get(c))}y(e.state.env,c,u)}return{continueToNext:!0,xtraceOutput:""}}async function Bi(e,t,s){let n;if(s.startsWith("'")&&s.endsWith("'"))n=s.slice(1,-1);else if(s.startsWith('"')&&s.endsWith('"')){let r=s.slice(1,-1),a=new Z().parseWordFromString(r,!0,!1);n=await z(e,a)}else if(s.includes("$")){let i=new Z().parseWordFromString(s,!1,!1);n=await z(e,i)}else n=s;return`${t}_${n}`}async function Ma(e,t,s){let n=s;s.startsWith('"')&&s.endsWith('"')&&s.length>=2&&(n=s.slice(1,-1));let r;if(/^-?\d+$/.test(n))r=Number.parseInt(n,10);else{try{let i=new Z,a=le(i,n);r=await Q(e,a.expression,!1)}catch(i){if(i instanceof Ke){let l=`bash: line ${e.state.currentLine}: ${s}: ${i.message}
665
+ `;if(i.fatal)throw await H(e,2,l,!0),new q(1);return{index:0,error:C(l)}}let a=x(e.state.env,s);r=a?Number.parseInt(a,10):0}Number.isNaN(r)&&(r=0)}if(r<0){let i=xe(e,t);if(i.length===0){let o=e.state.currentLine;return{index:0,error:C(`bash: line ${o}: ${t}[${s}]: bad array subscript
666
+ `)}}if(r=Math.max(...i.map(([o])=>typeof o=="number"?o:0))+1+r,r<0){let o=e.state.currentLine;return{index:0,error:C(`bash: line ${o}: ${t}[${s}]: bad array subscript
667
+ `)}}}return{index:r}}async function Wa(e,t,s,n,r,i,a){let o="",l=s,c=null;if(ve(e,s)){let h=dr(e,s,n);if(h===void 0)return{continueToNext:!1,xtraceOutput:"",error:C(`bash: ${s}: circular name reference
668
+ `)};if(h===null)return{continueToNext:!0,xtraceOutput:""};l=h;let v=l.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);v&&(c={arrayName:v[1],subscriptExpr:v[2]},l=v[1])}if(et(e,l)){if(t.name)return o+=`bash: ${l}: readonly variable
669
+ `,{continueToNext:!0,xtraceOutput:o};let h=await ue(e,l);if(h)return{continueToNext:!1,xtraceOutput:"",error:h}}let u,f=!!a&&!r&&!c;if(Rt(e,l)){f=!1;try{let h=new Z;if(r){let S=`(${x(e.state.env,l,"0")}) + (${n})`,E=le(h,S);u=String(await Q(e,E.expression))}else{let v=le(h,n);u=String(await Q(e,v.expression))}}catch{u="0"}}else{let{isArray:h}=await import("./chunks/expansion-IB7ZIBIF.js"),v=h(e,l);v&&(f=!1);let S=v?`${l}_0`:l;u=r?x(e.state.env,S)+n:n}let d=mt(e,l,u);d!==u&&(f=!1),u=d,o+=await Di(e,l,u);let p=l;if(c)p=await Fa(e,c);else{let{isArray:h}=await import("./chunks/expansion-IB7ZIBIF.js");h(e,l)&&(p=`${l}_0`,f=!1)}let m=f?()=>e.state.env.set(p,a):()=>y(e.state.env,p,u);return t.name?(i.set(p,e.state.env.get(p)),m()):(m(),e.state.options.allexport&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(l)),e.state.tempEnvBindings?.some(h=>h.has(l))&&(e.state.mutatedTempEnvVars=e.state.mutatedTempEnvVars||new Set,e.state.mutatedTempEnvVars.add(l))),{continueToNext:!1,xtraceOutput:o}}async function Fa(e,t){let{arrayName:s,subscriptExpr:n}=t;if(e.state.associativeArrays?.has(s))return Bi(e,s,n);let i;if(/^-?\d+$/.test(n))i=Number.parseInt(n,10);else{try{let a=new Z,o=le(a,n);i=await Q(e,o.expression,!1)}catch{let a=x(e.state.env,n);i=a?Number.parseInt(a,10):0}Number.isNaN(i)&&(i=0)}if(i<0){let a=xe(e,s);a.length>0&&(i=Math.max(...a.map(l=>l[0]))+1+i)}return`${s}_${i}`}async function Ui(e,t,s,n){let r=Qe(e.outputChannels),i=new Map(e.state.env),a=e.state.cwd,o=e.state.fileDescriptors,l=e.state.nextFd;e.state.fileDescriptors=o?new Map(o):void 0;let c={...e.state.options},u=new Map(e.state.functions),f=e.state.localScopes,d=e.state.localVarStack,p=e.state.localVarDepth,m=e.state.fullyUnsetLocals;if(e.state.localScopes=f.map(N=>new Map(N)),d){e.state.localVarStack=new Map;for(let[N,M]of d.entries())e.state.localVarStack.set(N,M.map($=>({...$})))}p&&(e.state.localVarDepth=new Map(p)),m&&(e.state.fullyUnsetLocals=new Map(m));let h=e.state.loopDepth,v=e.state.parentHasLoopContext;e.state.parentHasLoopContext=h>0,e.state.loopDepth=0;let S=e.state.lastArg,E=e.state.bashPid;e.state.bashPid=e.state.nextVirtualPid++;let b=e.state.groupStdin,g=e.lineageId;e.lineageId=e.processes.createLineageId();let P=()=>{e.lineageId=g,e.state.env=i,e.state.cwd=a,e.state.fileDescriptors=o,e.state.nextFd=l,e.state.options=c,e.state.functions=u,e.state.localScopes=f,e.state.localVarStack=d,e.state.localVarDepth=p,e.state.fullyUnsetLocals=m,e.state.loopDepth=h,e.state.parentHasLoopContext=v,e.state.groupStdin=b,e.state.bashPid=E,e.state.lastArg=S};try{let N=t.redirections.length===0?{channels:r,legacyRedirections:[]}:await Ne(e,r,t.redirections);return N.error?await K(e,N.channels,()=>te(e,()=>Promise.resolve(N.error))):await K(e,N.channels,async()=>{let M=$=>W(A(),A(),$);try{let $=await ie(s);$.length>0&&(e.state.groupStdin=de($));let k=0;for(let O of t.body){let D=await n(O);k=(await te(e,()=>Promise.resolve(D))).exitCode}return await M(k)}catch($){let{diagnosticWritten:k,writeFailure:O}=await qe(e,$);if(O)return O;if($ instanceof oe)throw $;return $ instanceof ze||$ instanceof $e||$ instanceof Ae?await M(0):$ instanceof q||$ instanceof ye||$ instanceof Ce||$ instanceof we?await M($.exitCode):(k||await te(e,()=>Promise.resolve(C(`${je($)}
670
+ `))),await M(1))}})}catch(N){throw await K(e,r,()=>ee(e,N)),N}finally{P()}}async function Hi(e,t,s,n){let r=t.redirections.length===0?{channels:e.outputChannels,legacyRedirections:[]}:await Ne(e,e.outputChannels,t.redirections);return r.error?K(e,r.channels,()=>te(e,()=>Promise.resolve(r.error))):K(e,r.channels,async()=>{let i=e.state.groupStdin;try{let a=await ht(e,r.legacyRedirections);if(a)return await te(e,()=>Promise.resolve(a));let o=await ie(s),l=de(o),c=!1;for(let f of r.legacyRedirections)if(!f.fdVariable){if((f.operator==="<<"||f.operator==="<<-")&&f.target.type==="HereDoc"){let d=f.target,p=await z(e,d.content);d.stripTabs&&(p=p.split(`
669
671
  `).map(h=>h.replace(/^\t+/,"")).join(`
670
- `));let m=f.fd??0;m!==0?(e.state.fileDescriptors||(e.state.fileDescriptors=new Map),e.state.fileDescriptors.set(m,p)):(l=V(p),u=!0)}else if(f.operator==="<<<"&&f.target.type==="Word")l=V(`${await z(e,f.target)}
671
- `),u=!0;else if(f.operator==="<"&&f.target.type==="Word"){let d=await z(e,f.target);try{let p=e.fs.resolvePath(e.state.cwd,d);l=await e.fs.readFile(p),u=!0}catch{return await te(e,()=>Promise.resolve(A(`bash: ${d}: No such file or directory
672
- `)))}}}(u||o.length>0)&&(e.state.groupStdin=l);let c=0;for(let f of t.body){let d=await n(f);c=(await te(e,()=>Promise.resolve(d))).exitCode}return W(E(),E(),c)}catch(a){let{diagnosticWritten:o,writeFailure:l}=await qe(e,a);if(l)return l;if(qt(a)||a instanceof Ce||a instanceof q||a instanceof we||a instanceof ze||a instanceof oe)throw a;return o||await te(e,()=>Promise.resolve(A(`${je(a)}
673
- `))),W(E(),E(),1)}finally{e.state.groupStdin=i}})}async function Gi(e,t,s,n,r){let i;try{i=await e.fs.readFileText(t)}catch{return A(`bash: ${t}: No such file or directory
674
- `,127)}if(i.startsWith("#!")){let b=i.indexOf(`
675
- `);b!==-1&&(i=i.slice(b+1))}let a=new Map(e.state.env),o=e.state.cwd,l={...e.state.options},u=e.state.loopDepth,c=e.state.parentHasLoopContext,f=e.state.lastArg,d=e.state.bashPid,p=e.state.groupStdin,m=e.state.currentSource,h=()=>{e.state.env=a,e.state.cwd=o,e.state.options=l,e.state.loopDepth=u,e.state.parentHasLoopContext=c,e.state.lastArg=f,e.state.bashPid=d,e.state.groupStdin=p,e.state.currentSource=m};try{e.state.parentHasLoopContext=u>0,e.state.loopDepth=0,e.state.bashPid=e.state.nextVirtualPid++;let b=await ie(n);b.length>0&&(e.state.groupStdin=de(b)),e.state.currentSource=t,y(e.state.env,"0",t),y(e.state.env,"#",String(s.length)),y(e.state.env,"@",s.join(" ")),y(e.state.env,"*",s.join(" "));for(let v=0;v<s.length&&v<9;v++)y(e.state.env,String(v+1),s[v]);for(let v=s.length+1;v<=9;v++)e.state.env.delete(String(v));let $=new Z().parse(i),g=await r($);return await te(e,()=>Promise.resolve(g))}catch(b){let{writeFailure:S}=await qe(e,b);if(S)return S;if(b instanceof q||b instanceof oe)throw b;if(b.name==="ParseException")return A(`bash: ${t}: ${b.message}
676
- `);throw b}finally{h()}}function Ra(e,t){for(let s of t.parts)switch(s.type){case"Bytes":case"Literal":case"SingleQuoted":case"Escaped":continue;case"DoubleQuoted":for(let n of s.parts)switch(n.type){case"Bytes":case"Literal":case"SingleQuoted":case"Escaped":continue;case"ParameterExpansion":if(n.operation||n.parameter==="@"||n.parameter==="*"||n.parameter.endsWith("[@]")||n.parameter.endsWith("[*]"))return!1;if(ve(e,n.parameter)){let r=Me(e,n.parameter);if(r&&(r.endsWith("[@]")||r.endsWith("[*]")))return!1}continue;case"CommandSubstitution":continue;default:return!1}continue;case"ParameterExpansion":return!1;default:return!1}return t.parts.length>0}var Ft=class e{ctx;constructor(t,s){this.ctx={state:s,fs:t.fs,commands:t.commands,processes:t.processes,lineageId:t.lineageId,outputChannels:t.outputChannels,reportedDiagnostics:new WeakSet,limits:t.limits,jobTracker:t.jobTracker,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,signal:t.signal}}buildExportedEnv(){let t=this.ctx.state.exportedVars,s=this.ctx.state.tempExportedVars,n=new Set;if(t)for(let i of t)n.add(i);if(s)for(let i of s)n.add(i);if(n.size===0)return Object.create(null);let r=Object.create(null);for(let i of n)this.ctx.state.env.has(i)&&(r[i]=T(this.ctx.state.env,i));return r}async executeRootScript(t){let s=await this.executeScript(t);return Ye(this.ctx.signal),X(this.ctx,s)}async executeScript(t){let s=0;for(let n of t.statements)try{let r=await this.executeStatement(n),i=this.ctx.signal?.aborted===!0&&r.exitCode===new pe(this.ctx.signal.reason).exitCode;await X(this.ctx,r,!i),s=r.exitCode,this.ctx.state.lastExitCode=s,y(this.ctx.state.env,"?",String(s))}catch(r){if(await ee(this.ctx,r),r instanceof q)throw r;if(r instanceof we)return s=r.exitCode,this.ctx.state.lastExitCode=s,y(this.ctx.state.env,"?",String(s)),{stdout:E(),stderr:E(),exitCode:s,env:Ge(this.ctx.state.env)};if(r instanceof oe)throw r;if(r instanceof Ce)return s=r.exitCode,this.ctx.state.lastExitCode=s,y(this.ctx.state.env,"?",String(s)),{stdout:E(),stderr:E(),exitCode:s,env:Ge(this.ctx.state.env)};if(r instanceof er)return s=1,this.ctx.state.lastExitCode=s,y(this.ctx.state.env,"?",String(s)),{stdout:E(),stderr:E(),exitCode:s,env:Ge(this.ctx.state.env)};if(r instanceof At)return s=1,this.ctx.state.lastExitCode=s,y(this.ctx.state.env,"?",String(s)),{stdout:E(),stderr:E(),exitCode:s,env:Ge(this.ctx.state.env)};if(r instanceof Xe){s=1,this.ctx.state.lastExitCode=s,y(this.ctx.state.env,"?",String(s));continue}if(r instanceof tr){s=1,this.ctx.state.lastExitCode=s,y(this.ctx.state.env,"?",String(s));continue}if(r instanceof $e||r instanceof Ae){if(this.ctx.state.loopDepth>0)throw r;continue}throw r instanceof ye,r}return{stdout:E(),stderr:E(),exitCode:s,env:Ge(this.ctx.state.env)}}async executeUserScript(t,s,n=E()){return Gi(this.ctx,t,bt(s),n,r=>this.executeScript(r))}async executeStatement(t){if(Ye(this.ctx.signal),this.ctx.state.commandCount++,this.ctx.state.commandCount>this.ctx.limits.maxCommandCount&&De(`too many commands executed (>${this.ctx.limits.maxCommandCount}), increase executionLimits.maxCommandCount`,"commands"),this.ctx.signal&&this.ctx.state.commandCount%1024===0&&(await new Promise(o=>setTimeout(o,0)),Ye(this.ctx.signal)),t.deferredError)throw new Zt(t.deferredError.message,t.line??1,1);if(this.ctx.state.options.noexec)return B();if(this.ctx.state.errexitSafe=!1,this.ctx.state.options.verbose&&!this.ctx.state.suppressVerbose&&t.sourceText&&await U(this.ctx,2,`${t.sourceText}
677
- `),t.background){if(this.ctx.processes.runningCount>=this.ctx.limits.maxConcurrentJobs)return this.ctx.jobTracker.limitExceeded=!0,await U(this.ctx,2,`bash: maximum concurrent jobs (${this.ctx.limits.maxConcurrentJobs}) exceeded
678
- `),A("",oe.EXIT_CODE);let o=this.ctx.state,l={...o,env:new Map([...o.env].map(([m,h])=>[m,h.slice()])),functions:new Map(o.functions),localScopes:o.localScopes.map(m=>new Map([...m].map(([h,b])=>[h,b?.slice()]))),options:{...o.options},shoptOptions:{...o.shoptOptions},lastArg:o.lastArg.slice(),groupStdin:void 0,...o.fileDescriptors?{fileDescriptors:new Map(o.fileDescriptors)}:{},...o.readonlyVars?{readonlyVars:new Set(o.readonlyVars)}:{},...o.associativeArrays?{associativeArrays:new Set(o.associativeArrays)}:{},...o.namerefs?{namerefs:new Set(o.namerefs)}:{},...o.boundNamerefs?{boundNamerefs:new Set(o.boundNamerefs)}:{},...o.invalidNamerefs?{invalidNamerefs:new Set(o.invalidNamerefs)}:{},...o.integerVars?{integerVars:new Set(o.integerVars)}:{},...o.lowercaseVars?{lowercaseVars:new Set(o.lowercaseVars)}:{},...o.uppercaseVars?{uppercaseVars:new Set(o.uppercaseVars)}:{},...o.exportedVars?{exportedVars:new Set(o.exportedVars)}:{},...o.tempExportedVars?{tempExportedVars:new Set(o.tempExportedVars)}:{},...o.localExportedVars?{localExportedVars:o.localExportedVars.map(m=>new Set(m))}:{},...o.declaredVars?{declaredVars:new Set(o.declaredVars)}:{},...o.localVarDepth?{localVarDepth:new Map(o.localVarDepth)}:{},...o.localVarStack?{localVarStack:new Map([...o.localVarStack].map(([m,h])=>[m,h.map(b=>({...b,value:b.value?.slice()}))]))}:{},...o.fullyUnsetLocals?{fullyUnsetLocals:new Map(o.fullyUnsetLocals)}:{},...o.tempEnvBindings?{tempEnvBindings:o.tempEnvBindings.map(m=>new Map([...m].map(([h,b])=>[h,b?.slice()])))}:{},...o.mutatedTempEnvVars?{mutatedTempEnvVars:new Set(o.mutatedTempEnvVars)}:{},...o.accessedTempEnvVars?{accessedTempEnvVars:new Set(o.accessedTempEnvVars)}:{},...o.callLineStack?{callLineStack:[...o.callLineStack]}:{},...o.funcNameStack?{funcNameStack:[...o.funcNameStack]}:{},...o.sourceStack?{sourceStack:[...o.sourceStack]}:{},...o.completionSpecs?{completionSpecs:new Map(o.completionSpecs)}:{},...o.directoryStack?{directoryStack:[...o.directoryStack]}:{},...o.hashTable?{hashTable:new Map(o.hashTable)}:{}},u=this.ctx.processes,c=this.ctx.outputChannels,f=m=>Qe(c,(h,b)=>u.observesOutput?Pe({write(S){return u.observeOutput(m,h,S),b.write(S)}},!1):b),d=t.sourceText?.trim()||"<background job>",p;try{p=u.start(d,async(m,h)=>{let b=f(m);l.bashPid=m,l.nextVirtualPid=Math.max(l.nextVirtualPid,m+1);let S=kt(this.ctx.signal,h),$=new e({fs:this.ctx.fs,commands:this.ctx.commands,processes:u,lineageId:this.ctx.lineageId,outputChannels:b,limits:this.ctx.limits,jobTracker:this.ctx.jobTracker,exec:(g,v)=>this.ctx.execFn(g,{...v,signal:kt(S,v?.signal)}),fetch:this.ctx.fetch,sleep:this.ctx.sleep,trace:this.ctx.trace,coverage:this.ctx.coverage,signal:S},l);try{return(await $.executeRootScript({type:"Script",statements:[{...t,background:!1,sourceText:void 0}]})).exitCode}catch(g){if(g instanceof pe||g instanceof q)return g.exitCode;if(g instanceof oe)return this.ctx.jobTracker.limitExceeded=!0,oe.EXIT_CODE;throw g}},this.ctx.lineageId),this.ctx.jobTracker.started=!0}catch(m){return await U(this.ctx,2,`bash: ${m instanceof Error?m.message:String(m)}
679
- `),A("",1)}return this.ctx.state.lastBackgroundPid=p,B()}let s=0,n=-1,r=!1;for(let o=0;o<t.pipelines.length;o++){let l=t.pipelines[o],u=o>0?t.operators[o-1]:null;if(u==="&&"&&s!==0||u==="||"&&s===0)continue;s=(await this.executePipeline(l)).exitCode,n=o,r=l.negated,this.ctx.state.lastExitCode=s,y(this.ctx.state.env,"?",String(s))}let i=n<t.pipelines.length-1,a=this.ctx.state.errexitSafe;if(this.ctx.state.errexitSafe=i||r||a,this.ctx.state.options.errexit&&s!==0&&n===t.pipelines.length-1&&!r&&!this.ctx.state.inCondition&&!a)throw new Ce(s);return{stdout:E(),stderr:E(),exitCode:s}}async executePipeline(t){return zi(this.ctx,t,(s,n)=>this.executeCommand(s,n))}async executeCommand(t,s){switch(this.ctx.coverage?.hit(`bash:cmd:${t.type}`),t.type){case"SimpleCommand":return this.executeSimpleCommand(t,s);case"If":return Ri(this.ctx,t);case"For":return Li(this.ctx,t);case"CStyleFor":return Mi(this.ctx,t);case"While":return Wi(this.ctx,t,s);case"Until":return Fi(this.ctx,t);case"Case":return Vi(this.ctx,t);case"Subshell":return this.executeSubshell(t,s);case"Group":return this.executeGroup(t,s);case"FunctionDef":return ei(this.ctx,t);case"ArithmeticCommand":return this.executeArithmeticCommand(t);case"ConditionalCommand":return this.executeConditionalCommand(t);default:return B()}}async executeSimpleCommand(t,s){this.ctx.reportedDiagnostics=new WeakSet;try{return await this.executeSimpleCommandInner(t,s)}catch(n){if(n instanceof Gt)return await ee(this.ctx,n),{stdout:E(),stderr:E(),exitCode:1};throw n}}async executeSimpleCommandInner(t,s){if(t.line!==void 0&&(this.ctx.state.currentLine=t.line),this.ctx.state.shoptOptions.expand_aliases&&t.name){let P=t,k=100;for(;k>0;){let O=this.expandAlias(P);if(O===P)break;P=O,k--}this.aliasExpansionStack.clear(),P!==t&&(t=P)}let n=await ji(this.ctx,t);if(n.error)return n.error;let r=n.tempAssignments,i=n.xtraceOutput;if(!t.name){if(await U(this.ctx,2,i),t.redirections.length>0){let P=this.ctx.outputChannels,k=await Te(this.ctx,P,t.redirections);if(k.error)return await K(this.ctx,k.channels,()=>te(this.ctx,()=>Promise.resolve(k.error)));let O={stdout:E(),stderr:E(),exitCode:0},R=[1,2].filter(_=>{let x=P.bindings.get(_),w=k.channels.bindings.get(_);return x?.sink!==w?.sink||Re(P,_)!==Re(k.channels,_)});return await K(this.ctx,k.channels,()=>te(this.ctx,()=>Promise.resolve(O),R))}return this.ctx.state.lastArg=F(""),{stdout:E(),stderr:E(),exitCode:this.ctx.state.lastExitCode}}let a=t.name&&Dt(t.name,["local","declare","typeset","export","readonly"]),o=Array.from(r.keys());if(o.length>0&&!a){this.ctx.state.tempExportedVars=this.ctx.state.tempExportedVars||new Set;for(let P of o)this.ctx.state.tempExportedVars.add(P)}let l=-1,u=Dt(t.name,["exec"])&&(t.args.length===0||t.args.length===1&&Dt(t.args[0],["--"])),c=await z(this.ctx,t.name),f=[],d=[];if(Dt(t.name,["local","declare","typeset","export","readonly"])&&(c==="local"||c==="declare"||c==="typeset"||c==="export"||c==="readonly"))for(let P of t.args){let k=await Ir(this.ctx,P);if(k)f.push(F(k)),d.push(!0);else{let O=await Rr(this.ctx,P);if(O!==null)f.push(F(O)),d.push(!0);else{let R=await We(this.ctx,P);for(let _ of R.values)f.push(F(_)),d.push(R.quoted)}}}else for(let P of t.args)if(Ra(this.ctx,P))f.push(await it(this.ctx,P)),d.push(!0);else{let k=await We(this.ctx,P);for(let O of k.values)f.push(F(O)),d.push(k.quoted)}let m=this.ctx.outputChannels,h=!u&&t.redirections.length>0?await Te(this.ctx,m,t.redirections,{persistMovedSource:Ue.has(c)}):void 0;if(h?.error){await U(this.ctx,2,i);for(let[P,k]of r)k===void 0?this.ctx.state.env.delete(P):this.ctx.state.env.set(P,k);return await K(this.ctx,h.channels,()=>te(this.ctx,()=>Promise.resolve(h.error)))}let b=t.redirections.some(P=>{if(u&&(P.operator==="<"||P.operator==="<&")||P.fdVariable)return!1;if(P.operator==="<<"||P.operator==="<<-"||P.operator==="<<<")return!0;let k=P.fd??0;return(P.operator==="<"||P.operator==="<&")&&k===0}),S=null,$=L;b?$=await ie(s):S=s;let g=h?.legacyRedirections??t.redirections;for(let P of g)if(!(P.fdVariable||u&&(P.operator==="<"||P.operator==="<&"))){if((P.operator==="<<"||P.operator==="<<-")&&P.target.type==="HereDoc"){let k=P.target,O=P.fd??0;if(O===0&&!k.stripTabs)$=await it(this.ctx,k.content);else{let R=await z(this.ctx,k.content);k.stripTabs&&(R=R.split(`
672
+ `));let m=f.fd??0;m!==0?(e.state.fileDescriptors||(e.state.fileDescriptors=new Map),e.state.fileDescriptors.set(m,p)):(l=V(p),c=!0)}else if(f.operator==="<<<"&&f.target.type==="Word")l=V(`${await z(e,f.target)}
673
+ `),c=!0;else if(f.operator==="<"&&f.target.type==="Word"){let d=await z(e,f.target);try{let p=e.fs.resolvePath(e.state.cwd,d);l=await e.fs.readFile(p),c=!0}catch{return await te(e,()=>Promise.resolve(C(`bash: ${d}: No such file or directory
674
+ `)))}}}(c||o.length>0)&&(e.state.groupStdin=l);let u=0;for(let f of t.body){let d=await n(f);u=(await te(e,()=>Promise.resolve(d))).exitCode}return W(A(),A(),u)}catch(a){let{diagnosticWritten:o,writeFailure:l}=await qe(e,a);if(l)return l;if(Zt(a)||a instanceof Ce||a instanceof q||a instanceof we||a instanceof ze||a instanceof oe)throw a;return o||await te(e,()=>Promise.resolve(C(`${je(a)}
675
+ `))),W(A(),A(),1)}finally{e.state.groupStdin=i}})}async function Gi(e,t,s,n,r){let i;try{i=await e.fs.readFileText(t)}catch{return C(`bash: ${t}: No such file or directory
676
+ `,127)}if(i.startsWith("#!")){let v=i.indexOf(`
677
+ `);v!==-1&&(i=i.slice(v+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,p=e.state.groupStdin,m=e.state.currentSource,h=()=>{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=p,e.state.currentSource=m};try{e.state.parentHasLoopContext=c>0,e.state.loopDepth=0,e.state.bashPid=e.state.nextVirtualPid++;let v=await ie(n);v.length>0&&(e.state.groupStdin=de(v)),e.state.currentSource=t,y(e.state.env,"0",t),y(e.state.env,"#",String(s.length)),y(e.state.env,"@",s.join(" ")),y(e.state.env,"*",s.join(" "));for(let g=0;g<s.length&&g<9;g++)y(e.state.env,String(g+1),s[g]);for(let g=s.length+1;g<=9;g++)e.state.env.delete(String(g));let E=new Z().parse(i),b=await r(E);return await te(e,()=>Promise.resolve(b))}catch(v){let{writeFailure:S}=await qe(e,v);if(S)return S;if(v instanceof q||v instanceof oe)throw v;if(v.name==="ParseException")return C(`bash: ${t}: ${v.message}
678
+ `);throw v}finally{h()}}function Va(e,t){for(let s of t.parts)switch(s.type){case"Bytes":case"Literal":case"SingleQuoted":case"Escaped":continue;case"DoubleQuoted":for(let n of s.parts)switch(n.type){case"Bytes":case"Literal":case"SingleQuoted":case"Escaped":continue;case"ParameterExpansion":if(n.operation||n.parameter==="@"||n.parameter==="*"||n.parameter.endsWith("[@]")||n.parameter.endsWith("[*]"))return!1;if(ve(e,n.parameter)){let r=Me(e,n.parameter);if(r&&(r.endsWith("[@]")||r.endsWith("[*]")))return!1}continue;case"CommandSubstitution":continue;default:return!1}continue;case"ParameterExpansion":return!1;default:return!1}return t.parts.length>0}var Vt=class e{ctx;constructor(t,s){this.ctx={state:s,fs:t.fs,commands:t.commands,processes:t.processes,lineageId:t.lineageId,outputChannels:t.outputChannels,reportedDiagnostics:new WeakSet,limits:t.limits,jobTracker:t.jobTracker,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,signal:t.signal}}buildExportedEnv(){let t=this.ctx.state.exportedVars,s=this.ctx.state.tempExportedVars,n=new Set;if(t)for(let i of t)n.add(i);if(s)for(let i of s)n.add(i);if(n.size===0)return Object.create(null);let r=Object.create(null);for(let i of n)this.ctx.state.env.has(i)&&(r[i]=x(this.ctx.state.env,i));return r}async executeRootScript(t){let s=await this.executeScript(t);return Ye(this.ctx.signal),Y(this.ctx,s)}async executeScript(t){let s=0;for(let n of t.statements)try{let r=await this.executeStatement(n),i=this.ctx.signal?.aborted===!0&&r.exitCode===new pe(this.ctx.signal.reason).exitCode;await Y(this.ctx,r,!i),s=r.exitCode,this.ctx.state.lastExitCode=s,y(this.ctx.state.env,"?",String(s))}catch(r){if(await ee(this.ctx,r),r instanceof q)throw r;if(r instanceof we)return s=r.exitCode,this.ctx.state.lastExitCode=s,y(this.ctx.state.env,"?",String(s)),{stdout:A(),stderr:A(),exitCode:s,env:Ge(this.ctx.state.env)};if(r instanceof oe)throw r;if(r instanceof Ce)return s=r.exitCode,this.ctx.state.lastExitCode=s,y(this.ctx.state.env,"?",String(s)),{stdout:A(),stderr:A(),exitCode:s,env:Ge(this.ctx.state.env)};if(r instanceof er)return s=1,this.ctx.state.lastExitCode=s,y(this.ctx.state.env,"?",String(s)),{stdout:A(),stderr:A(),exitCode:s,env:Ge(this.ctx.state.env)};if(r instanceof At)return s=1,this.ctx.state.lastExitCode=s,y(this.ctx.state.env,"?",String(s)),{stdout:A(),stderr:A(),exitCode:s,env:Ge(this.ctx.state.env)};if(r instanceof Ke){s=1,this.ctx.state.lastExitCode=s,y(this.ctx.state.env,"?",String(s));continue}if(r instanceof tr){s=1,this.ctx.state.lastExitCode=s,y(this.ctx.state.env,"?",String(s));continue}if(r instanceof $e||r instanceof Ae){if(this.ctx.state.loopDepth>0)throw r;continue}throw r instanceof ye,r}return{stdout:A(),stderr:A(),exitCode:s,env:Ge(this.ctx.state.env)}}async executeUserScript(t,s,n=A()){return Gi(this.ctx,t,bt(s),n,r=>this.executeScript(r))}async executeStatement(t){if(Ye(this.ctx.signal),this.ctx.state.commandCount++,this.ctx.state.commandCount>this.ctx.limits.maxCommandCount&&Ie(`too many commands executed (>${this.ctx.limits.maxCommandCount}), increase executionLimits.maxCommandCount`,"commands"),this.ctx.signal&&this.ctx.state.commandCount%1024===0&&(await new Promise(o=>setTimeout(o,0)),Ye(this.ctx.signal)),t.deferredError)throw new Jt(t.deferredError.message,t.line??1,1);if(this.ctx.state.options.noexec)return B();if(this.ctx.state.errexitSafe=!1,this.ctx.state.options.verbose&&!this.ctx.state.suppressVerbose&&t.sourceText&&await H(this.ctx,2,`${t.sourceText}
679
+ `),t.background){if(this.ctx.processes.runningCount>=this.ctx.limits.maxConcurrentJobs)return this.ctx.jobTracker.limitExceeded=!0,await H(this.ctx,2,`bash: maximum concurrent jobs (${this.ctx.limits.maxConcurrentJobs}) exceeded
680
+ `),C("",oe.EXIT_CODE);let o=this.ctx.state,l={...o,env:new Map([...o.env].map(([h,v])=>[h,v.slice()])),functions:new Map(o.functions),localScopes:o.localScopes.map(h=>new Map([...h].map(([v,S])=>[v,S?.slice()]))),options:{...o.options},shoptOptions:{...o.shoptOptions},lastArg:o.lastArg.slice(),groupStdin:void 0,...o.fileDescriptors?{fileDescriptors:new Map(o.fileDescriptors)}:{},...o.readonlyVars?{readonlyVars:new Set(o.readonlyVars)}:{},...o.associativeArrays?{associativeArrays:new Set(o.associativeArrays)}:{},...o.namerefs?{namerefs:new Set(o.namerefs)}:{},...o.boundNamerefs?{boundNamerefs:new Set(o.boundNamerefs)}:{},...o.invalidNamerefs?{invalidNamerefs:new Set(o.invalidNamerefs)}:{},...o.integerVars?{integerVars:new Set(o.integerVars)}:{},...o.lowercaseVars?{lowercaseVars:new Set(o.lowercaseVars)}:{},...o.uppercaseVars?{uppercaseVars:new Set(o.uppercaseVars)}:{},...o.exportedVars?{exportedVars:new Set(o.exportedVars)}:{},...o.tempExportedVars?{tempExportedVars:new Set(o.tempExportedVars)}:{},...o.localExportedVars?{localExportedVars:o.localExportedVars.map(h=>new Set(h))}:{},...o.declaredVars?{declaredVars:new Set(o.declaredVars)}:{},...o.localVarDepth?{localVarDepth:new Map(o.localVarDepth)}:{},...o.localVarStack?{localVarStack:new Map([...o.localVarStack].map(([h,v])=>[h,v.map(S=>({...S,value:S.value?.slice()}))]))}:{},...o.fullyUnsetLocals?{fullyUnsetLocals:new Map(o.fullyUnsetLocals)}:{},...o.tempEnvBindings?{tempEnvBindings:o.tempEnvBindings.map(h=>new Map([...h].map(([v,S])=>[v,S?.slice()])))}:{},...o.mutatedTempEnvVars?{mutatedTempEnvVars:new Set(o.mutatedTempEnvVars)}:{},...o.accessedTempEnvVars?{accessedTempEnvVars:new Set(o.accessedTempEnvVars)}:{},...o.callLineStack?{callLineStack:[...o.callLineStack]}:{},...o.funcNameStack?{funcNameStack:[...o.funcNameStack]}:{},...o.sourceStack?{sourceStack:[...o.sourceStack]}:{},...o.completionSpecs?{completionSpecs:new Map(o.completionSpecs)}:{},...o.directoryStack?{directoryStack:[...o.directoryStack]}:{},...o.hashTable?{hashTable:new Map(o.hashTable)}:{}},c=this.ctx.processes,u=this.ctx.outputChannels,f=h=>Qe(u,(v,S)=>c.observesOutput?Pe({write(E){return c.observeOutput(h,v,E),S.write(E)}},!1):S),d=t.sourceText?.trim()||"<background job>",p=c.createLineageId(),m;try{m=c.start(d,async(h,v)=>{let S=f(h);l.bashPid=h,l.nextVirtualPid=Math.max(l.nextVirtualPid,h+1);let E=kt(this.ctx.signal,v),b=new e({fs:this.ctx.fs,commands:this.ctx.commands,processes:c,lineageId:p,outputChannels:S,limits:this.ctx.limits,jobTracker:this.ctx.jobTracker,exec:(g,P)=>this.ctx.execFn(g,{...P,signal:kt(E,P?.signal)}),fetch:this.ctx.fetch,sleep:this.ctx.sleep,trace:this.ctx.trace,coverage:this.ctx.coverage,signal:E},l);try{return(await b.executeRootScript({type:"Script",statements:[{...t,background:!1,sourceText:void 0}]})).exitCode}catch(g){if(g instanceof pe||g instanceof q)return g.exitCode;if(g instanceof oe)return this.ctx.jobTracker.limitExceeded=!0,oe.EXIT_CODE;throw g}},this.ctx.lineageId),this.ctx.jobTracker.started=!0}catch(h){return await H(this.ctx,2,`bash: ${h instanceof Error?h.message:String(h)}
681
+ `),C("",1)}return this.ctx.state.lastBackgroundPid=m,B()}let s=0,n=-1,r=!1;for(let o=0;o<t.pipelines.length;o++){let l=t.pipelines[o],c=o>0?t.operators[o-1]:null;if(c==="&&"&&s!==0||c==="||"&&s===0)continue;s=(await this.executePipeline(l)).exitCode,n=o,r=l.negated,this.ctx.state.lastExitCode=s,y(this.ctx.state.env,"?",String(s))}let i=n<t.pipelines.length-1,a=this.ctx.state.errexitSafe;if(this.ctx.state.errexitSafe=i||r||a,this.ctx.state.options.errexit&&s!==0&&n===t.pipelines.length-1&&!r&&!this.ctx.state.inCondition&&!a)throw new Ce(s);return{stdout:A(),stderr:A(),exitCode:s}}async executePipeline(t){return zi(this.ctx,t,(s,n)=>this.executeCommand(s,n))}async executeCommand(t,s){switch(this.ctx.coverage?.hit(`bash:cmd:${t.type}`),t.type){case"SimpleCommand":return this.executeSimpleCommand(t,s);case"If":return Ri(this.ctx,t);case"For":return Li(this.ctx,t);case"CStyleFor":return Mi(this.ctx,t);case"While":return Wi(this.ctx,t,s);case"Until":return Fi(this.ctx,t);case"Case":return Vi(this.ctx,t);case"Subshell":return this.executeSubshell(t,s);case"Group":return this.executeGroup(t,s);case"FunctionDef":return ei(this.ctx,t);case"ArithmeticCommand":return this.executeArithmeticCommand(t);case"ConditionalCommand":return this.executeConditionalCommand(t);default:return B()}}async executeSimpleCommand(t,s){this.ctx.reportedDiagnostics=new WeakSet;try{return await this.executeSimpleCommandInner(t,s)}catch(n){if(n instanceof qt)return await ee(this.ctx,n),{stdout:A(),stderr:A(),exitCode:1};throw n}}async executeSimpleCommandInner(t,s){if(t.line!==void 0&&(this.ctx.state.currentLine=t.line),this.ctx.state.shoptOptions.expand_aliases&&t.name){let $=t,k=100;for(;k>0;){let O=this.expandAlias($);if(O===$)break;$=O,k--}this.aliasExpansionStack.clear(),$!==t&&(t=$)}let n=await ji(this.ctx,t);if(n.error)return n.error;let r=n.tempAssignments,i=n.xtraceOutput;if(!t.name){if(await H(this.ctx,2,i),t.redirections.length>0){let $=this.ctx.outputChannels,k=await Ne(this.ctx,$,t.redirections);if(k.error)return await K(this.ctx,k.channels,()=>te(this.ctx,()=>Promise.resolve(k.error)));let O={stdout:A(),stderr:A(),exitCode:0},D=[1,2].filter(_=>{let T=$.bindings.get(_),w=k.channels.bindings.get(_);return T?.sink!==w?.sink||Re($,_)!==Re(k.channels,_)});return await K(this.ctx,k.channels,()=>te(this.ctx,()=>Promise.resolve(O),D))}return this.ctx.state.lastArg=F(""),{stdout:A(),stderr:A(),exitCode:this.ctx.state.lastExitCode}}let a=t.name&&It(t.name,["local","declare","typeset","export","readonly"]),o=Array.from(r.keys());if(o.length>0&&!a){this.ctx.state.tempExportedVars=this.ctx.state.tempExportedVars||new Set;for(let $ of o)this.ctx.state.tempExportedVars.add($)}let l=-1,c=It(t.name,["exec"])&&(t.args.length===0||t.args.length===1&&It(t.args[0],["--"])),u=await z(this.ctx,t.name),f=[],d=[];if(It(t.name,["local","declare","typeset","export","readonly"])&&(u==="local"||u==="declare"||u==="typeset"||u==="export"||u==="readonly"))for(let $ of t.args){let k=await Dr(this.ctx,$);if(k)f.push(F(k)),d.push(!0);else{let O=await Rr(this.ctx,$);if(O!==null)f.push(F(O)),d.push(!0);else{let D=await We(this.ctx,$);for(let _ of D.values)f.push(F(_)),d.push(D.quoted)}}}else for(let $ of t.args)if(Va(this.ctx,$))f.push(await it(this.ctx,$)),d.push(!0);else{let k=await We(this.ctx,$);for(let O of k.values)f.push(F(O)),d.push(k.quoted)}let m=this.ctx.outputChannels,h=!c&&t.redirections.length>0?await Ne(this.ctx,m,t.redirections,{persistMovedSource:He.has(u)}):void 0;if(h?.error){await H(this.ctx,2,i);for(let[$,k]of r)k===void 0?this.ctx.state.env.delete($):this.ctx.state.env.set($,k);return await K(this.ctx,h.channels,()=>te(this.ctx,()=>Promise.resolve(h.error)))}let v=t.redirections.some($=>{if(c&&($.operator==="<"||$.operator==="<&")||$.fdVariable)return!1;if($.operator==="<<"||$.operator==="<<-"||$.operator==="<<<")return!0;let k=$.fd??0;return($.operator==="<"||$.operator==="<&")&&k===0}),S=null,E=R;v?E=await ie(s):S=s;let b=h?.legacyRedirections??t.redirections;for(let $ of b)if(!($.fdVariable||c&&($.operator==="<"||$.operator==="<&"))){if(($.operator==="<<"||$.operator==="<<-")&&$.target.type==="HereDoc"){let k=$.target,O=$.fd??0;if(O===0&&!k.stripTabs)E=await it(this.ctx,k.content);else{let D=await z(this.ctx,k.content);k.stripTabs&&(D=D.split(`
680
682
  `).map(_=>_.replace(/^\t+/,"")).join(`
681
- `)),O!==0?(this.ctx.state.fileDescriptors||(this.ctx.state.fileDescriptors=new Map),this.ctx.state.fileDescriptors.set(O,R)):$=F(R)}continue}if(P.operator==="<<<"&&P.target.type==="Word"){let k=await it(this.ctx,P.target);$=Qn(k,F(`
682
- `));continue}if(P.operator==="<"&&P.target.type==="Word")try{let k=await z(this.ctx,P.target),O=this.ctx.fs.resolvePath(this.ctx.state.cwd,k);$=await ie(await this.ctx.fs.readFile(O))}catch{let k=await z(this.ctx,P.target);for(let[O,R]of r)R===void 0?this.ctx.state.env.delete(O):this.ctx.state.env.set(O,R);return A(`bash: ${k}: No such file or directory
683
- `)}if(P.operator==="<&"&&(P.fd??0)===0&&P.target.type==="Word"){let k=await z(this.ctx,P.target),O=k.startsWith("&")?k.slice(1):k;if(O!=="-"&&!/^\d+-?$/.test(O)){for(let[_,x]of r)x===void 0?this.ctx.state.env.delete(_):this.ctx.state.env.set(_,x);return A(`bash: ${k}: ambiguous redirect
684
- `)}let R=Number.parseInt(O,10);if(!Number.isNaN(R)&&Re(this.ctx.outputChannels,R)){for(let[_,x]of r)x===void 0?this.ctx.state.env.delete(_):this.ctx.state.env.set(_,x);return A(Ve(R))}if(!Number.isNaN(R)&&this.ctx.state.fileDescriptors){let _=this.ctx.state.fileDescriptors.get(R);if(_!==void 0)if(_.startsWith("__rw__:")){let x=ms(_);x&&($=F(x.content.slice(x.position)),l=R)}else _.startsWith("__file__:")||_.startsWith("__file_append__:")||($=F(_));else if(R>=3&&!this.ctx.outputChannels.bindings.get(R)?.sink){for(let[x,w]of r)w===void 0?this.ctx.state.env.delete(x):this.ctx.state.env.set(x,w);return A(Ve(R))}}else if(!Number.isNaN(R)&&R>=3&&!this.ctx.outputChannels.bindings.get(R)?.sink){for(let[_,x]of r)x===void 0?this.ctx.state.env.delete(_):this.ctx.state.env.set(_,x);return A(Ve(R))}}}if(!c){if(t.name.parts.every(k=>k.type==="CommandSubstitution"||k.type==="ParameterExpansion"||k.type==="ArithmeticExpansion")){if(f.length>0){let k=H(f.shift());return d.shift(),await this.runCommand(k,f,d,S??de($),!1,!1,l)}return{stdout:E(),stderr:E(),exitCode:this.ctx.state.lastExitCode}}return A(`bash: : command not found
685
- `,127)}await U(this.ctx,2,i);let v=await Ts(this.ctx,c,f.map(P=>H(P)));if(await U(this.ctx,2,v),c==="exec"&&(f.length===0||H(f[0])==="--")){let P=[],k=this.ctx.outputChannels;for(;k;)P.push([k,new Map(k.bindings)]),k=k.parent;let O=this.ctx.state.fileDescriptors?new Map(this.ctx.state.fileDescriptors):void 0,R=this.ctx.state.nextFd,_=new Map;for(let w of t.redirections)w.fdVariable&&!_.has(w.fdVariable)&&_.set(w.fdVariable,this.ctx.state.env.get(w.fdVariable));let x=await Qr(this.ctx,t.redirections);if(x.error){let w;try{w=await K(this.ctx,x.channels,()=>te(this.ctx,()=>Promise.resolve(x.error)))}finally{for(let[D,M]of P)D.bindings=new Map(M);this.ctx.state.fileDescriptors=O,this.ctx.state.nextFd=R;for(let[D,M]of _)M===void 0?this.ctx.state.env.delete(D):this.ctx.state.env.set(D,M)}return w}for(let w of x.legacyRedirections){if(w.target.type==="HereDoc"||w.fdVariable)continue;let D=await z(this.ctx,w.target),M=w.fd??(w.operator==="<"||w.operator==="<>"?0:1);if(this.ctx.state.fileDescriptors||(this.ctx.state.fileDescriptors=new Map),w.operator==="<"){let J=this.ctx.fs.resolvePath(this.ctx.state.cwd,D);try{let j=await this.ctx.fs.readFileText(J);this.ctx.state.fileDescriptors.set(M,j)}catch{let j;try{j=await te(this.ctx,()=>Promise.resolve(A(`bash: ${D}: No such file or directory
686
- `)))}finally{for(let[Y,re]of P)Y.bindings=new Map(re);this.ctx.state.fileDescriptors=O,this.ctx.state.nextFd=R;for(let[Y,re]of _)re===void 0?this.ctx.state.env.delete(Y):this.ctx.state.env.set(Y,re)}return j}}else if(w.operator==="<>"){let J=this.ctx.fs.resolvePath(this.ctx.state.cwd,D);try{let j=await this.ctx.fs.readFileText(J);this.ctx.state.fileDescriptors.set(M,`__rw__:${J.length}:${J}:0:${j}`)}catch{await this.ctx.fs.writeFile(J,"","utf8"),this.ctx.state.fileDescriptors.set(M,`__rw__:${J.length}:${J}:0:`)}}else if(w.operator==="<&")if(D==="-")this.ctx.state.fileDescriptors.delete(M);else{let J=D.endsWith("-"),j=Number.parseInt(J?D.slice(0,-1):D,10);if(!Number.isNaN(j)){let Y=this.ctx.state.fileDescriptors.get(j)??`__dupin__:${j}`;this.ctx.state.fileDescriptors.set(M,Y),J&&this.ctx.state.fileDescriptors.delete(j)}}}for(let[w,D]of r)D===void 0?this.ctx.state.env.delete(w):this.ctx.state.env.set(w,D);if(this.ctx.state.tempExportedVars)for(let w of r.keys())this.ctx.state.tempExportedVars.delete(w);return B()}r.size>0&&(this.ctx.state.tempEnvBindings=this.ctx.state.tempEnvBindings||[],this.ctx.state.tempEnvBindings.push(new Map(r)));let C,N=null,I=h?[1,2].filter(P=>{let k=m.bindings.get(P),O=h.channels.bindings.get(P);return k?.sink!==O?.sink||Re(m,P)!==Re(h.channels,P)}):[];try{try{let P=()=>this.runCommand(c,f,d,S??de($),!1,!1,l);C=h?await K(this.ctx,h.channels,P):await P()}catch(P){let k=null;if(h&&(k=(await K(this.ctx,h.channels,()=>qe(this.ctx,P,I))).writeFailure,k&&(C=k)),!k)if(P instanceof $e||P instanceof Ae)N=P,C=B();else throw P}if(C.exitCode===127&&Ue.has(c)&&h?.channels.bindings.get(1)?.descriptor==="__file__:/dev/full"&&(C=G(`
687
- `)),h&&I.length>0&&(C=await K(this.ctx,h.channels,()=>te(this.ctx,()=>Promise.resolve(C),I))),N)throw N;if(f.length>0){let P=H(f[f.length-1]);if((c==="declare"||c==="local"||c==="typeset")&&/^[a-zA-Z_][a-zA-Z0-9_]*=\(/.test(P)){let k=P.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\(/);k&&(P=k[1])}this.ctx.state.lastArg=F(P)}else this.ctx.state.lastArg=F(c)}finally{let P=Jr(c)&&c!=="unset"&&c!=="eval";if(!this.ctx.state.options.posix||!P)for(let[O,R]of r)this.ctx.state.fullyUnsetLocals?.has(O)||(R===void 0?this.ctx.state.env.delete(O):this.ctx.state.env.set(O,R));if(this.ctx.state.tempExportedVars)for(let O of r.keys())this.ctx.state.tempExportedVars.delete(O);r.size>0&&this.ctx.state.tempEnvBindings&&this.ctx.state.tempEnvBindings.pop()}return C}async runCommand(t,s,n,r,i=!1,a=!1,o=-1){let l={ctx:this.ctx,runCommand:(c,f,d,p,m,h,b)=>this.runCommand(c,f,d,p,m,h,b),buildExportedEnv:()=>this.buildExportedEnv(),executeUserScript:(c,f,d)=>this.executeUserScript(c,f,d??E())},u=await Ni(l,t,s,n,r,i,a,o);return u!==null?u:Oi(l,t,s,r,a)}aliasExpansionStack=new Set;expandAlias(t){return Js(this.ctx.state,t,this.aliasExpansionStack)}async findCommandInPath(t){return Ps(this.ctx,t)}async executeSubshell(t,s=E()){return Hi(this.ctx,t,s,n=>this.executeStatement(n))}async executeGroup(t,s=E()){return Ui(this.ctx,t,s,n=>this.executeStatement(n))}async executeArithmeticCommand(t){t.line!==void 0&&(this.ctx.state.currentLine=t.line);let s=this.ctx.outputChannels,n=await Te(this.ctx,s,t.redirections);if(n.error)return K(this.ctx,n.channels,()=>te(this.ctx,()=>Promise.resolve(n.error)));let r=[1,2].filter(i=>{let a=s.bindings.get(i),o=n.channels.bindings.get(i);return a?.sink!==o?.sink||Re(s,i)!==Re(n.channels,i)});return K(this.ctx,n.channels,async()=>{let i;try{let a=await Q(this.ctx,t.expression.expression);i=ae(a!==0)}catch(a){i=A(`bash: arithmetic expression: ${a.message}
688
- `)}return r.length>0?te(this.ctx,()=>Promise.resolve(i),r):i})}async executeConditionalCommand(t){t.line!==void 0&&(this.ctx.state.currentLine=t.line);let s=this.ctx.outputChannels,n=await Te(this.ctx,s,t.redirections);if(n.error)return K(this.ctx,n.channels,()=>te(this.ctx,()=>Promise.resolve(n.error)));let r=[1,2].filter(i=>{let a=s.bindings.get(i),o=n.channels.bindings.get(i);return a?.sink!==o?.sink||Re(s,i)!==Re(n.channels,i)});return K(this.ctx,n.channels,async()=>{let i;try{let a=await Je(this.ctx,t.expression);i=ae(a)}catch(a){let o=a instanceof Xe?1:2;i=A(`bash: conditional expression: ${a.message}
689
- `,o)}return r.length>0?te(this.ctx,()=>Promise.resolve(i),r):i})}};var ge={maxCallDepth:100,maxCommandCount:1e4,maxLoopIterations:1e4,maxAwkIterations:1e4,maxSedIterations:1e4,maxJqIterations:1e4,maxSqliteTimeoutMs:5e3,maxPythonTimeoutMs:3e4,maxGlobOperations:1e5,maxStringLength:10485760,maxArrayElements:1e5,maxHeredocSize:10485760,maxSubstitutionDepth:50,maxConcurrentJobs:128};function qi(e){return e?{maxCallDepth:e.maxCallDepth??ge.maxCallDepth,maxCommandCount:e.maxCommandCount??ge.maxCommandCount,maxLoopIterations:e.maxLoopIterations??ge.maxLoopIterations,maxAwkIterations:e.maxAwkIterations??ge.maxAwkIterations,maxSedIterations:e.maxSedIterations??ge.maxSedIterations,maxJqIterations:e.maxJqIterations??ge.maxJqIterations,maxSqliteTimeoutMs:e.maxSqliteTimeoutMs??ge.maxSqliteTimeoutMs,maxPythonTimeoutMs:e.maxPythonTimeoutMs??ge.maxPythonTimeoutMs,maxGlobOperations:e.maxGlobOperations??ge.maxGlobOperations,maxStringLength:e.maxStringLength??ge.maxStringLength,maxArrayElements:e.maxArrayElements??ge.maxArrayElements,maxHeredocSize:e.maxHeredocSize??ge.maxHeredocSize,maxSubstitutionDepth:e.maxSubstitutionDepth??ge.maxSubstitutionDepth,maxConcurrentJobs:e.maxConcurrentJobs??ge.maxConcurrentJobs}:{...ge}}function Zi(e){try{let t=new URL(e);return{origin:t.origin,pathname:t.pathname,href:t.href}}catch{return null}}function La(e){let t=Zi(e);return t?{origin:t.origin,pathPrefix:t.pathname}:null}function Ma(e,t){let s=Zi(e);if(!s)return!1;let n=La(t);return!n||s.origin!==n.origin?!1:n.pathPrefix==="/"||n.pathPrefix===""?!0:s.pathname.startsWith(n.pathPrefix)}function Jn(e,t){return!t||t.length===0?!1:t.some(s=>Ma(e,s))}var Vt=class extends Error{constructor(t){super(`Network access denied: URL not in allow-list: ${t}`),this.name="NetworkAccessDeniedError"}},zt=class extends Error{constructor(t){super(`Too many redirects (max: ${t})`),this.name="TooManyRedirectsError"}},jt=class extends Error{constructor(t){super(`Redirect target not in allow-list: ${t}`),this.name="RedirectNotAllowedError"}},Ns=class extends Error{constructor(t,s){super(`HTTP method '${t}' not allowed. Allowed methods: ${s.join(", ")}`),this.name="MethodNotAllowedError"}},Bt=class extends Error{constructor(t){super(`Response body too large (max: ${t} bytes)`),this.name="ResponseTooLargeError"}};var Wa=20,Fa=3e4,Va=10485760,za=["GET","HEAD"],ja=new Set(["GET","HEAD","OPTIONS"]),Ba=new Set([301,302,303,307,308]);function Kn(e){let t=e.maxRedirects??Wa,s=e.timeoutMs??Fa,n=e.maxResponseSize??Va,r=e.dangerouslyAllowFullInternetAccess?["GET","HEAD","POST","PUT","DELETE","PATCH","OPTIONS"]:e.allowedMethods??za;function i(l){if(!e.dangerouslyAllowFullInternetAccess&&!Jn(l,e.allowedUrlPrefixes??[]))throw new Vt(l)}function a(l){if(e.dangerouslyAllowFullInternetAccess)return;let u=l.toUpperCase();if(!r.includes(u))throw new Ns(u,r)}async function o(l,u={}){let c=u.method?.toUpperCase()??"GET";i(l),a(c);let f=l,d=0,p=u.followRedirects??!0,m=u.timeoutMs!==void 0?Math.min(u.timeoutMs,s):s;for(;;){let h=new AbortController,b=setTimeout(()=>h.abort(),m);try{let S={method:c,headers:u.headers,signal:h.signal,redirect:"manual"};u.body&&!ja.has(c)&&(S.body=u.body);let $=await fetch(f,S);if(Ba.has($.status)&&p){let g=$.headers.get("location");if(!g)return await Ji($,f,n);let v=new URL(g,f).href;if(!e.dangerouslyAllowFullInternetAccess&&!Jn(v,e.allowedUrlPrefixes??[]))throw new jt(v);if(d++,d>t)throw new zt(t);f=v;continue}return await Ji($,f,n)}finally{clearTimeout(b)}}}return o}async function Ji(e,t,s){let n=Object.create(null);if(e.headers.forEach((i,a)=>{n[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 Bt(s)}}let r;if(s>0&&e.body){let i=e.body.getReader(),a=new TextDecoder,o=[],l=0;for(;;){let{done:u,value:c}=await i.read();if(u)break;if(l+=c.byteLength,l>s)throw i.cancel(),new Bt(s);o.push(a.decode(c,{stream:!0}))}o.push(a.decode()),r=o.join("")}else r=await e.text();return{status:e.status,statusText:e.statusText,headers:n,body:r,url:t}}var Ha=1e3,Ua=64,Ga=globalThis.setTimeout.bind(globalThis),qa=globalThis.clearTimeout.bind(globalThis),Os=class{jobs=new Map;reapedWaitStatuses=new Map;reapedWaitLineages=new Map;options;nextPid=Ha;nextLineageId=1;highestJobNumber=0;runningJobs=0;disposed=!1;disposePromise;constructor(t={}){this.options=t}start(t,s,n){if(this.disposed)throw new Error("Cannot start a job on a disposed ProcessTable");let r=this.nextPid++,i=new AbortController,a=this.highestJobNumber+1,o={info:{pid:r,command:t,startedAt:Date.now(),state:"running"},jobNumber:a,lineageId:n,controller:i,promise:Promise.resolve(0)};return this.jobs.set(r,o),this.highestJobNumber=a,this.runningJobs++,o.promise=Promise.resolve().then(()=>s(r,i.signal)).catch(()=>i.signal.aborted?sr(i.signal.reason):1).then(l=>{this.jobs.get(r)===o&&this.runningJobs--,o.info={...o.info,state:"done",exitCode:l},o.controller=void 0,o.promise=void 0;try{Promise.resolve(this.options.onJobExit?.(r,l)).catch(()=>{})}catch{}return l}),r}list(){return[...this.jobs.values()].sort((t,s)=>t.jobNumber-s.jobNumber).map(t=>({...t.info}))}listJobs(t,s={}){let n=[...this.jobs.values()].sort((l,u)=>l.jobNumber-u.jobNumber),r=n.at(-1)?.info.pid,i=n.at(-2)?.info.pid,a=[],o=[];for(let l of n)t&&!t.has(l.info.pid)||s.runningOnly&&l.info.state!=="running"||s.stoppedOnly||s.changedOnly&&l.changedStateReported===l.info.state||(o.push({...l.info,jobNumber:l.jobNumber,marker:l.info.pid===r?"+":l.info.pid===i?"-":" "}),s.changedOnly&&(l.changedStateReported=l.info.state),l.info.state==="done"&&(a.push(l.info.pid),this.rememberWaitStatus(l.info.pid,l.info.exitCode??1,l.lineageId)));return this.deleteJobs(a),o}get(t){let s=this.jobs.get(t)?.info;return s?{...s}:void 0}kill(t,s,n){let r=this.jobs.get(t);return!r||r.info.state==="done"?!1:(s!=="SIGSTOP"&&s!=="SIGCONT"&&r.controller?.abort(n??s),!0)}async wait(t){if(t!==void 0){let r=this.jobs.get(t);if(!r)return this.reapedWaitStatuses.get(t)??127;let i=r.info.state==="done"?r.info.exitCode??1:await(r.promise??Promise.resolve(1));return this.jobs.get(t)===r&&(this.rememberWaitStatus(t,i,r.lineageId),this.deleteJobs([t])),i}let s=[...this.jobs.values()],n=new Set([...this.reapedWaitStatuses.keys(),...s.map(r=>r.info.pid)]);s.length>0&&(await Promise.all(s.map(r=>r.promise??Promise.resolve(r.info.exitCode??1))),this.deleteJobs(s.map(r=>r.info.pid)));for(let r of n)this.reapedWaitStatuses.delete(r),this.reapedWaitLineages.delete(r);return 0}async waitForLineage(t){let s=[...this.jobs.values()].filter(r=>r.lineageId===t),n=[...this.reapedWaitLineages.entries()].flatMap(([r,i])=>i===t?[r]:[]);s.length>0&&(await Promise.all(s.map(r=>r.promise??Promise.resolve(r.info.exitCode??1))),this.deleteJobs(s.map(r=>r.info.pid)));for(let r of[...n,...s.map(i=>i.info.pid)])this.reapedWaitStatuses.delete(r),this.reapedWaitLineages.delete(r);return 0}createLineageId(){return this.nextLineageId++}abortAll(t="SIGTERM"){for(let s of this.jobs.values())s.info.state==="running"&&s.controller?.abort(t)}dispose(){if(this.disposePromise)return this.disposePromise;this.disposed=!0;let t=[...this.jobs.values()],s=()=>{};this.disposePromise=new Promise(r=>{s=r}),this.abortAll("SIGKILL"),this.jobs.clear(),this.reapedWaitStatuses.clear(),this.reapedWaitLineages.clear(),this.highestJobNumber=0,this.runningJobs=0;let n=Ga(s,this.options.disposeTimeoutMs??1e3);return Promise.allSettled(t.flatMap(r=>r.promise?[r.promise]:[])).then(()=>{qa(n),s()}),this.disposePromise}get runningCount(){return this.runningJobs}getJobNumber(t){return this.jobs.get(t)?.jobNumber}canWait(t){return this.jobs.has(t)||this.reapedWaitStatuses.has(t)}resolveJobSpec(t){let s=[...this.jobs.values()].sort((i,a)=>i.jobNumber-a.jobNumber);if(t==="%+"||t==="%%")return s.at(-1)?.info.pid;if(t==="%-")return s.at(-2)?.info.pid;let n=/^%(\d+)$/.exec(t);if(!n)return;let r=Number.parseInt(n[1],10);return s.find(i=>i.jobNumber===r)?.info.pid}get observesOutput(){return this.options.onJobOutput!==void 0}observeOutput(t,s,n){try{Promise.resolve(this.options.onJobOutput?.(t,s,n)).catch(()=>{})}catch{}}rememberWaitStatus(t,s,n){if(this.reapedWaitStatuses.delete(t),this.reapedWaitLineages.delete(t),this.reapedWaitStatuses.set(t,s),this.reapedWaitLineages.set(t,n),this.reapedWaitStatuses.size>Ua){let r=this.reapedWaitStatuses.keys().next().value;r!==void 0&&(this.reapedWaitStatuses.delete(r),this.reapedWaitLineages.delete(r))}}deleteJobs(t){let s=!1;for(let n of t){let r=this.jobs.get(n);r&&(this.jobs.delete(n),s||=r.jobNumber===this.highestJobNumber)}if(s){this.highestJobNumber=0;for(let n of this.jobs.values())this.highestJobNumber=Math.max(this.highestJobNumber,n.jobNumber)}}};function Ki(){let e=[{prop:"Function",target:globalThis,violationType:"function_constructor",strategy:"throw",reason:"Function constructor allows arbitrary code execution"},{prop:"eval",target:globalThis,violationType:"eval",strategy:"throw",reason:"eval() allows arbitrary code execution"},{prop:"setTimeout",target:globalThis,violationType:"setTimeout",strategy:"throw",reason:"setTimeout with string argument allows code execution"},{prop:"setInterval",target:globalThis,violationType:"setInterval",strategy:"throw",reason:"setInterval with string argument allows code execution"},{prop:"setImmediate",target:globalThis,violationType:"setImmediate",strategy:"throw",reason:"setImmediate could be used to escape sandbox context"},{prop:"env",target:process,violationType:"process_env",strategy:"throw",reason:"process.env could leak sensitive environment variables"},{prop:"binding",target:process,violationType:"process_binding",strategy:"throw",reason:"process.binding provides access to native Node.js modules"},{prop:"_linkedBinding",target:process,violationType:"process_binding",strategy:"throw",reason:"process._linkedBinding provides access to native Node.js modules"},{prop:"dlopen",target:process,violationType:"process_dlopen",strategy:"throw",reason:"process.dlopen allows loading native addons"},{prop:"WeakRef",target:globalThis,violationType:"weak_ref",strategy:"throw",reason:"WeakRef could be used to leak references outside sandbox"},{prop:"FinalizationRegistry",target:globalThis,violationType:"finalization_registry",strategy:"throw",reason:"FinalizationRegistry could be used to leak references outside sandbox"},{prop:"Reflect",target:globalThis,violationType:"reflect",strategy:"freeze",reason:"Reflect provides introspection capabilities"},{prop:"Proxy",target:globalThis,violationType:"proxy",strategy:"throw",reason:"Proxy allows intercepting and modifying object behavior"},{prop:"WebAssembly",target:globalThis,violationType:"webassembly",strategy:"throw",reason:"WebAssembly allows executing arbitrary compiled code"},{prop:"SharedArrayBuffer",target:globalThis,violationType:"shared_array_buffer",strategy:"throw",reason:"SharedArrayBuffer could enable side-channel communication or timing attacks"},{prop:"Atomics",target:globalThis,violationType:"atomics",strategy:"throw",reason:"Atomics could enable side-channel communication or timing attacks"}];try{let t=Object.getPrototypeOf(async()=>{}).constructor;t&&t!==Function&&e.push({prop:"constructor",target:Object.getPrototypeOf(async()=>{}),violationType:"async_function_constructor",strategy:"throw",reason:"AsyncFunction constructor allows arbitrary async code execution"})}catch{}try{let t=Object.getPrototypeOf(function*(){}).constructor;t&&t!==Function&&e.push({prop:"constructor",target:Object.getPrototypeOf(function*(){}),violationType:"generator_function_constructor",strategy:"throw",reason:"GeneratorFunction constructor allows arbitrary generator code execution"})}catch{}try{let t=Object.getPrototypeOf(async function*(){}).constructor;t&&t!==Function&&t!==Object.getPrototypeOf(async()=>{}).constructor&&e.push({prop:"constructor",target:Object.getPrototypeOf(async function*(){}),violationType:"async_generator_function_constructor",strategy:"throw",reason:"AsyncGeneratorFunction constructor allows arbitrary async generator code execution"})}catch{}return e.filter(t=>{try{return t.target[t.prop]!==void 0}catch{return!1}})}var Ht=typeof __BROWSER__<"u"&&__BROWSER__;function Xi(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}var Yn=null;if(!Ht)try{let e="node:module",{createRequire:t}=await import(e);Yn=t(import.meta.url)("node:async_hooks").AsyncLocalStorage}catch(e){console.debug("[DefenseInDepthBox] AsyncLocalStorage not available, defense-in-depth disabled:",e instanceof Error?e.message:e)}var Za=`
690
-
691
- This is a defense-in-depth measure and indicates a bug in just-bash. Please report this at security@vercel.com`,me=class extends Error{violation;constructor(t,s){super(t+Za),this.violation=s,this.name="SecurityViolationError"}},Se=!Ht&&Yn?new Yn:null,Ja=1e3,Xn={enabled:!0,auditMode:!1};function Ka(e){return e===void 0?{...Xn,enabled:!1}:typeof e=="boolean"?{...Xn,enabled:e}:{...Xn,...e}}var Ds=class e{static instance=null;config;refCount=0;originalDescriptors=[];violations=[];activationTime=0;totalActiveTimeMs=0;constructor(t){this.config=t}static getInstance(t){return e.instance||(e.instance=new e(Ka(t))),e.instance}static resetInstance(){e.instance&&(e.instance.forceDeactivate(),e.instance=null)}static isInSandboxedContext(){return Se?Se?.getStore()?.sandboxActive===!0:!1}static getCurrentExecutionId(){if(Se)return Se?.getStore()?.executionId}updateConfig(t){this.config={...this.config,...t}}activate(){if(Ht||!this.config.enabled){let s=Xi();return{run:n=>n(),deactivate:()=>{},executionId:s}}this.refCount++,this.refCount===1&&(this.applyPatches(),this.activationTime=Date.now());let t=Xi();return{run:s=>Se.run({sandboxActive:!0,executionId:t},s),deactivate:()=>{this.refCount--,this.refCount===0&&(this.restorePatches(),this.totalActiveTimeMs+=Date.now()-this.activationTime),this.refCount<0&&(this.refCount=0)},executionId:t}}forceDeactivate(){this.refCount>0&&(this.restorePatches(),this.totalActiveTimeMs+=Date.now()-this.activationTime),this.refCount=0}isActive(){return this.refCount>0}getStats(){return{violationsBlocked:this.violations.length,violations:[...this.violations],activeTimeMs:this.totalActiveTimeMs+(this.refCount>0?Date.now()-this.activationTime:0),refCount:this.refCount}}clearViolations(){this.violations=[]}getPathForTarget(t,s){return t===globalThis?`globalThis.${s}`:t===process?`process.${s}`:t===Error?`Error.${s}`:t===Function.prototype?`Function.prototype.${s}`:t===Object.prototype?`Object.prototype.${s}`:`<object>.${s}`}shouldBlock(){return Ht||this.config.auditMode||!Se?!1:Se?.getStore()?.sandboxActive===!0}recordViolation(t,s,n){let r={timestamp:Date.now(),type:t,message:n,path:s,stack:new Error().stack,executionId:Se?.getStore()?.executionId};if(this.violations.length<Ja&&this.violations.push(r),this.config.onViolation)try{this.config.onViolation(r)}catch(i){console.debug("[DefenseInDepthBox] onViolation callback threw:",i instanceof Error?i.message:i)}return r}createBlockingProxy(t,s,n){let r=this;return new Proxy(t,{apply(i,a,o){if(r.shouldBlock()){let l=`${s} is blocked during script execution`,u=r.recordViolation(n,s,l);throw new me(l,u)}return r.config.auditMode&&Se?.getStore()?.sandboxActive===!0&&r.recordViolation(n,s,`${s} called (audit mode)`),Reflect.apply(i,a,o)},construct(i,a,o){if(r.shouldBlock()){let l=`${s} constructor is blocked during script execution`,u=r.recordViolation(n,s,l);throw new me(l,u)}return r.config.auditMode&&Se?.getStore()?.sandboxActive===!0&&r.recordViolation(n,s,`${s} constructor called (audit mode)`),Reflect.construct(i,a,o)}})}createBlockingObjectProxy(t,s,n){let r=this;return new Proxy(t,{get(i,a,o){if(r.shouldBlock()){let l=`${s}.${String(a)}`,u=`${l} is blocked during script execution`,c=r.recordViolation(n,l,u);throw new me(u,c)}if(r.config.auditMode&&Se?.getStore()?.sandboxActive===!0){let l=`${s}.${String(a)}`;r.recordViolation(n,l,`${l} accessed (audit mode)`)}return Reflect.get(i,a,o)},set(i,a,o,l){if(r.shouldBlock()){let u=`${s}.${String(a)}`,c=`${u} modification is blocked during script execution`,f=r.recordViolation(n,u,c);throw new me(c,f)}return Reflect.set(i,a,o,l)},ownKeys(i){if(r.shouldBlock()){let a=`${s} enumeration is blocked during script execution`,o=r.recordViolation(n,s,a);throw new me(a,o)}return Reflect.ownKeys(i)},getOwnPropertyDescriptor(i,a){if(r.shouldBlock()){let o=`${s}.${String(a)}`,l=`${o} descriptor access is blocked during script execution`,u=r.recordViolation(n,o,l);throw new me(l,u)}return Reflect.getOwnPropertyDescriptor(i,a)},has(i,a){if(r.shouldBlock()){let o=`${s}.${String(a)}`,l=`${o} existence check is blocked during script execution`,u=r.recordViolation(n,o,l);throw new me(l,u)}return Reflect.has(i,a)}})}applyPatches(){let t=Ki();for(let s of t)this.applyPatch(s);this.protectConstructorChain(),this.protectErrorPrepareStackTrace(),this.protectModuleLoad(),this.protectProcessMainModule()}protectConstructorChain(){this.patchPrototypeConstructor(Function.prototype,"Function.prototype.constructor","function_constructor");try{let t=Object.getPrototypeOf(async()=>{}).constructor;t&&t!==Function&&this.patchPrototypeConstructor(t.prototype,"AsyncFunction.prototype.constructor","async_function_constructor")}catch(t){console.debug("[DefenseInDepthBox] Could not patch AsyncFunction.prototype.constructor:",t instanceof Error?t.message:t)}try{let t=Object.getPrototypeOf(function*(){}).constructor;t&&t!==Function&&this.patchPrototypeConstructor(t.prototype,"GeneratorFunction.prototype.constructor","generator_function_constructor")}catch(t){console.debug("[DefenseInDepthBox] Could not patch GeneratorFunction.prototype.constructor:",t instanceof Error?t.message:t)}try{let t=Object.getPrototypeOf(async function*(){}).constructor,s=Object.getPrototypeOf(async()=>{}).constructor;t&&t!==Function&&t!==s&&this.patchPrototypeConstructor(t.prototype,"AsyncGeneratorFunction.prototype.constructor","async_generator_function_constructor")}catch(t){console.debug("[DefenseInDepthBox] Could not patch AsyncGeneratorFunction.prototype.constructor:",t instanceof Error?t.message:t)}}protectErrorPrepareStackTrace(){let t=this;try{let s=Object.getOwnPropertyDescriptor(Error,"prepareStackTrace");this.originalDescriptors.push({target:Error,prop:"prepareStackTrace",descriptor:s});let n=s?.value;Object.defineProperty(Error,"prepareStackTrace",{get(){return n},set(r){if(t.shouldBlock()){let i="Error.prepareStackTrace modification is blocked during script execution",a=t.recordViolation("error_prepare_stack_trace","Error.prepareStackTrace",i);throw new me(i,a)}t.config.auditMode&&Se?.getStore()?.sandboxActive===!0&&t.recordViolation("error_prepare_stack_trace","Error.prepareStackTrace","Error.prepareStackTrace set (audit mode)"),n=r},configurable:!0})}catch(s){console.debug("[DefenseInDepthBox] Could not protect Error.prepareStackTrace:",s instanceof Error?s.message:s)}}patchPrototypeConstructor(t,s,n){let r=this;try{let i=Object.getOwnPropertyDescriptor(t,"constructor");this.originalDescriptors.push({target:t,prop:"constructor",descriptor:i});let a=i?.value;Object.defineProperty(t,"constructor",{get(){if(r.shouldBlock()){let o=`${s} access is blocked during script execution`,l=r.recordViolation(n,s,o);throw new me(o,l)}return r.config.auditMode&&Se?.getStore()?.sandboxActive===!0&&r.recordViolation(n,s,`${s} accessed (audit mode)`),a},set(o){if(r.shouldBlock()){let l=`${s} modification is blocked during script execution`,u=r.recordViolation(n,s,l);throw new me(l,u)}Object.defineProperty(this,"constructor",{value:o,writable:!0,configurable:!0})},configurable:!0})}catch(i){console.debug(`[DefenseInDepthBox] Could not patch ${s}:`,i instanceof Error?i.message:i)}}protectProcessMainModule(){if(typeof process>"u")return;let t=this;try{let s=Object.getOwnPropertyDescriptor(process,"mainModule");this.originalDescriptors.push({target:process,prop:"mainModule",descriptor:s});let n=s?.value;n!==void 0&&Object.defineProperty(process,"mainModule",{get(){if(t.shouldBlock()){let r="process.mainModule access is blocked during script execution",i=t.recordViolation("process_main_module","process.mainModule",r);throw new me(r,i)}return t.config.auditMode&&Se?.getStore()?.sandboxActive===!0&&t.recordViolation("process_main_module","process.mainModule","process.mainModule accessed (audit mode)"),n},set(r){if(t.shouldBlock()){let i="process.mainModule modification is blocked during script execution",a=t.recordViolation("process_main_module","process.mainModule",i);throw new me(i,a)}Object.defineProperty(process,"mainModule",{value:r,writable:!0,configurable:!0})},configurable:!0})}catch(s){console.debug("[DefenseInDepthBox] Could not protect process.mainModule:",s instanceof Error?s.message:s)}}protectModuleLoad(){if(!Ht)try{let t=null;if(typeof process<"u"){let a=process.mainModule;a&&typeof a=="object"&&(t=a.constructor)}if(!t&&typeof Ut<"u"&&typeof Ut.main<"u"&&(t=Ut.main.constructor),!t||typeof t._load!="function")return;let s=t._load,n=Object.getOwnPropertyDescriptor(t,"_load");this.originalDescriptors.push({target:t,prop:"_load",descriptor:n});let i=this.createBlockingProxy(s,"Module._load","module_load");Object.defineProperty(t,"_load",{value:i,writable:!0,configurable:!0})}catch(t){console.debug("[DefenseInDepthBox] Could not protect Module._load:",t instanceof Error?t.message:t)}}applyPatch(t){let{target:s,prop:n,violationType:r,strategy:i}=t;try{let a=s[n];if(a===void 0)return;let o=Object.getOwnPropertyDescriptor(s,n);if(this.originalDescriptors.push({target:s,prop:n,descriptor:o}),i==="freeze")typeof a=="object"&&a!==null&&Object.freeze(a);else{let l=this.getPathForTarget(s,n),u=typeof a=="function"?this.createBlockingProxy(a,l,r):this.createBlockingObjectProxy(a,l,r);Object.defineProperty(s,n,{value:u,writable:!0,configurable:!0})}}catch(a){let o=this.getPathForTarget(s,n);console.debug(`[DefenseInDepthBox] Could not patch ${o}:`,a instanceof Error?a.message:a)}}restorePatches(){for(let t=this.originalDescriptors.length-1;t>=0;t--){let{target:s,prop:n,descriptor:r}=this.originalDescriptors[t];try{r?Object.defineProperty(s,n,r):delete s[n]}catch(i){let a=this.getPathForTarget(s,n);console.debug(`[DefenseInDepthBox] Could not restore ${a}:`,i instanceof Error?i.message:i)}}this.originalDescriptors=[]}};var Xa=globalThis.setTimeout.bind(globalThis),Is=class{fs;processes;commands=new Map;useDefaultLayout=!1;limits;secureFetch;sleepFn;traceFn;logger;defenseInDepthConfig;coverageWriter;state;constructor(t={}){let s=t.fs??new Tt(t.files);this.fs=s,this.processes=t.processes??new Os,this.useDefaultLayout=!t.cwd&&!t.files;let n=t.cwd||(this.useDefaultLayout?"/home/user":"/"),r=new Map,i=[["HOME",this.useDefaultLayout?"/home/user":"/"],["PATH","/usr/bin:/bin"],["IFS",`
692
- `],["OSTYPE","linux-gnu"],["MACHTYPE","x86_64-pc-linux-gnu"],["HOSTTYPE","x86_64"],["HOSTNAME","localhost"],["PWD",n],["OLDPWD",n],["OPTIND","1"]];for(let[a,o]of i)y(r,a,o);for(let[a,o]of Object.entries(t.env??{}))y(r,a,o);if(this.limits=qi({...t.executionLimits,...t.maxCallDepth!==void 0&&{maxCallDepth:t.maxCallDepth},...t.maxCommandCount!==void 0&&{maxCommandCount:t.maxCommandCount},...t.maxLoopIterations!==void 0&&{maxLoopIterations:t.maxLoopIterations}}),t.network&&(this.secureFetch=Kn(t.network)),this.sleepFn=t.sleep,this.traceFn=t.trace,this.logger=t.logger,this.defenseInDepthConfig=t.defenseInDepth,this.coverageWriter=t.coverage,this.state={env:r,cwd:n,previousDir:"/home/user",functions:new Map,localScopes:[],callDepth:0,sourceDepth:0,commandCount:0,lastExitCode:0,lastArg:L,startTime:Date.now(),lastBackgroundPid:0,bashPid:Ls().pid,nextVirtualPid:Ls().pid+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},y(this.state.env,"SHELLOPTS",Gs(this.state.options)),y(this.state.env,"BASHOPTS",qs(this.state.shoptOptions)),_r(s,this.useDefaultLayout),n!=="/"&&s instanceof Tt)try{s.mkdirSync(n,{recursive:!0})}catch{}for(let a of Sr(t.commands))this.registerCommand(a);if(t.network)for(let a of Er())this.registerCommand(a);if(t.python)for(let a of $r())this.registerCommand(a);if(t.customCommands)for(let a of t.customCommands)Ar(a)?this.registerCommand(Cr(a)):this.registerCommand(a)}registerCommand(t){this.commands.set(t.name,t);let s=this.fs;if(typeof s.writeFileSync=="function"){let n=`#!/bin/bash
683
+ `)),O!==0?(this.ctx.state.fileDescriptors||(this.ctx.state.fileDescriptors=new Map),this.ctx.state.fileDescriptors.set(O,D)):E=F(D)}continue}if($.operator==="<<<"&&$.target.type==="Word"){let k=await it(this.ctx,$.target);E=Qn(k,F(`
684
+ `));continue}if($.operator==="<"&&$.target.type==="Word")try{let k=await z(this.ctx,$.target),O=this.ctx.fs.resolvePath(this.ctx.state.cwd,k);E=await ie(await this.ctx.fs.readFile(O))}catch{let k=await z(this.ctx,$.target);for(let[O,D]of r)D===void 0?this.ctx.state.env.delete(O):this.ctx.state.env.set(O,D);return C(await Dt(this.ctx,k))}if($.operator==="<&"&&($.fd??0)===0&&$.target.type==="Word"){let k=await z(this.ctx,$.target),O=k.startsWith("&")?k.slice(1):k;if(O!=="-"&&!/^\d+-?$/.test(O)){for(let[_,T]of r)T===void 0?this.ctx.state.env.delete(_):this.ctx.state.env.set(_,T);return C(`bash: ${k}: ambiguous redirect
685
+ `)}let D=Number.parseInt(O,10);if(!Number.isNaN(D)&&Re(this.ctx.outputChannels,D)){for(let[_,T]of r)T===void 0?this.ctx.state.env.delete(_):this.ctx.state.env.set(_,T);return C(Ve(D))}if(!Number.isNaN(D)&&this.ctx.state.fileDescriptors){let _=this.ctx.state.fileDescriptors.get(D);if(_!==void 0)if(_.startsWith("__rw__:")){let T=gs(_);T&&(E=F(T.content.slice(T.position)),l=D)}else _.startsWith("__file__:")||_.startsWith("__file_append__:")||(E=F(_));else if(D>=3&&!this.ctx.outputChannels.bindings.get(D)?.sink){for(let[T,w]of r)w===void 0?this.ctx.state.env.delete(T):this.ctx.state.env.set(T,w);return C(Ve(D))}}else if(!Number.isNaN(D)&&D>=3&&!this.ctx.outputChannels.bindings.get(D)?.sink){for(let[_,T]of r)T===void 0?this.ctx.state.env.delete(_):this.ctx.state.env.set(_,T);return C(Ve(D))}}}if(!u){if(t.name.parts.every(k=>k.type==="CommandSubstitution"||k.type==="ParameterExpansion"||k.type==="ArithmeticExpansion")){if(f.length>0){let k=U(f.shift());return d.shift(),await this.runCommand(k,f,d,S??de(E),!1,!1,l)}return{stdout:A(),stderr:A(),exitCode:this.ctx.state.lastExitCode}}return C(`bash: : command not found
686
+ `,127)}await H(this.ctx,2,i);let g=await Ns(this.ctx,u,f.map($=>U($)));if(await H(this.ctx,2,g),u==="exec"&&(f.length===0||U(f[0])==="--")){let $=[],k=this.ctx.outputChannels;for(;k;)$.push([k,new Map(k.bindings)]),k=k.parent;let O=this.ctx.state.fileDescriptors?new Map(this.ctx.state.fileDescriptors):void 0,D=this.ctx.state.nextFd,_=new Map;for(let w of t.redirections)w.fdVariable&&!_.has(w.fdVariable)&&_.set(w.fdVariable,this.ctx.state.env.get(w.fdVariable));let T=await Qr(this.ctx,t.redirections);if(T.error){let w;try{w=await K(this.ctx,T.channels,()=>te(this.ctx,()=>Promise.resolve(T.error)))}finally{for(let[I,L]of $)I.bindings=new Map(L);this.ctx.state.fileDescriptors=O,this.ctx.state.nextFd=D;for(let[I,L]of _)L===void 0?this.ctx.state.env.delete(I):this.ctx.state.env.set(I,L)}return w}for(let w of T.legacyRedirections){if(w.target.type==="HereDoc"||w.fdVariable)continue;let I=await z(this.ctx,w.target),L=w.fd??(w.operator==="<"||w.operator==="<>"?0:1);if(this.ctx.state.fileDescriptors||(this.ctx.state.fileDescriptors=new Map),w.operator==="<"){let J=this.ctx.fs.resolvePath(this.ctx.state.cwd,I);try{let j=await this.ctx.fs.readFileText(J);this.ctx.state.fileDescriptors.set(L,j)}catch{let j;try{let X=await Dt(this.ctx,I);j=await te(this.ctx,()=>Promise.resolve(C(X)))}finally{for(let[X,re]of $)X.bindings=new Map(re);this.ctx.state.fileDescriptors=O,this.ctx.state.nextFd=D;for(let[X,re]of _)re===void 0?this.ctx.state.env.delete(X):this.ctx.state.env.set(X,re)}return j}}else if(w.operator==="<>"){let J=this.ctx.fs.resolvePath(this.ctx.state.cwd,I);try{let j=await this.ctx.fs.readFileText(J);this.ctx.state.fileDescriptors.set(L,`__rw__:${J.length}:${J}:0:${j}`)}catch{await this.ctx.fs.writeFile(J,"","utf8"),this.ctx.state.fileDescriptors.set(L,`__rw__:${J.length}:${J}:0:`)}}else if(w.operator==="<&")if(I==="-")this.ctx.state.fileDescriptors.delete(L);else{let J=I.endsWith("-"),j=Number.parseInt(J?I.slice(0,-1):I,10);if(!Number.isNaN(j)){let X=this.ctx.state.fileDescriptors.get(j)??`__dupin__:${j}`;this.ctx.state.fileDescriptors.set(L,X),J&&this.ctx.state.fileDescriptors.delete(j)}}}for(let[w,I]of r)I===void 0?this.ctx.state.env.delete(w):this.ctx.state.env.set(w,I);if(this.ctx.state.tempExportedVars)for(let w of r.keys())this.ctx.state.tempExportedVars.delete(w);return B()}r.size>0&&(this.ctx.state.tempEnvBindings=this.ctx.state.tempEnvBindings||[],this.ctx.state.tempEnvBindings.push(new Map(r)));let P,N=null,M=h?[1,2].filter($=>{let k=m.bindings.get($),O=h.channels.bindings.get($);return k?.sink!==O?.sink||Re(m,$)!==Re(h.channels,$)}):[];try{try{let $=()=>this.runCommand(u,f,d,S??de(E),!1,!1,l);P=h?await K(this.ctx,h.channels,$):await $()}catch($){let k=null;if(h&&(k=(await K(this.ctx,h.channels,()=>qe(this.ctx,$,M))).writeFailure,k&&(P=k)),!k)if($ instanceof $e||$ instanceof Ae)N=$,P=B();else throw $}if(P.exitCode===127&&He.has(u)&&h?.channels.bindings.get(1)?.descriptor==="__file__:/dev/full"&&(P=G(`
687
+ `)),h&&M.length>0&&(P=await K(this.ctx,h.channels,()=>te(this.ctx,()=>Promise.resolve(P),M))),N)throw N;if(f.length>0){let $=U(f[f.length-1]);if((u==="declare"||u==="local"||u==="typeset")&&/^[a-zA-Z_][a-zA-Z0-9_]*=\(/.test($)){let k=$.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\(/);k&&($=k[1])}this.ctx.state.lastArg=F($)}else this.ctx.state.lastArg=F(u)}finally{let $=Jr(u)&&u!=="unset"&&u!=="eval";if(!this.ctx.state.options.posix||!$)for(let[O,D]of r)this.ctx.state.fullyUnsetLocals?.has(O)||(D===void 0?this.ctx.state.env.delete(O):this.ctx.state.env.set(O,D));if(this.ctx.state.tempExportedVars)for(let O of r.keys())this.ctx.state.tempExportedVars.delete(O);r.size>0&&this.ctx.state.tempEnvBindings&&this.ctx.state.tempEnvBindings.pop()}return P}async runCommand(t,s,n,r,i=!1,a=!1,o=-1){let l={ctx:this.ctx,runCommand:(u,f,d,p,m,h,v)=>this.runCommand(u,f,d,p,m,h,v),buildExportedEnv:()=>this.buildExportedEnv(),executeUserScript:(u,f,d)=>this.executeUserScript(u,f,d??A())},c=await xi(l,t,s,n,r,i,a,o);return c!==null?c:Oi(l,t,s,r,a)}aliasExpansionStack=new Set;expandAlias(t){return Js(this.ctx.state,t,this.aliasExpansionStack)}async findCommandInPath(t){return Ps(this.ctx,t)}async executeSubshell(t,s=A()){return Ui(this.ctx,t,s,n=>this.executeStatement(n))}async executeGroup(t,s=A()){return Hi(this.ctx,t,s,n=>this.executeStatement(n))}async executeArithmeticCommand(t){t.line!==void 0&&(this.ctx.state.currentLine=t.line);let s=this.ctx.outputChannels,n=await Ne(this.ctx,s,t.redirections);if(n.error)return K(this.ctx,n.channels,()=>te(this.ctx,()=>Promise.resolve(n.error)));let r=[1,2].filter(i=>{let a=s.bindings.get(i),o=n.channels.bindings.get(i);return a?.sink!==o?.sink||Re(s,i)!==Re(n.channels,i)});return K(this.ctx,n.channels,async()=>{let i;try{let a=await Q(this.ctx,t.expression.expression);i=ae(a!==0)}catch(a){i=C(`bash: arithmetic expression: ${a.message}
688
+ `)}return r.length>0?te(this.ctx,()=>Promise.resolve(i),r):i})}async executeConditionalCommand(t){t.line!==void 0&&(this.ctx.state.currentLine=t.line);let s=this.ctx.outputChannels,n=await Ne(this.ctx,s,t.redirections);if(n.error)return K(this.ctx,n.channels,()=>te(this.ctx,()=>Promise.resolve(n.error)));let r=[1,2].filter(i=>{let a=s.bindings.get(i),o=n.channels.bindings.get(i);return a?.sink!==o?.sink||Re(s,i)!==Re(n.channels,i)});return K(this.ctx,n.channels,async()=>{let i;try{let a=await Je(this.ctx,t.expression);i=ae(a)}catch(a){let o=a instanceof Ke?1:2;i=C(`bash: conditional expression: ${a.message}
689
+ `,o)}return r.length>0?te(this.ctx,()=>Promise.resolve(i),r):i})}};var ge={maxCallDepth:100,maxCommandCount:1e4,maxLoopIterations:1e4,maxAwkIterations:1e4,maxSedIterations:1e4,maxJqIterations:1e4,maxSqliteTimeoutMs:5e3,maxPythonTimeoutMs:3e4,maxGlobOperations:1e5,maxStringLength:10485760,maxArrayElements:1e5,maxHeredocSize:10485760,maxSubstitutionDepth:50,maxConcurrentJobs:128};function qi(e){return e?{maxCallDepth:e.maxCallDepth??ge.maxCallDepth,maxCommandCount:e.maxCommandCount??ge.maxCommandCount,maxLoopIterations:e.maxLoopIterations??ge.maxLoopIterations,maxAwkIterations:e.maxAwkIterations??ge.maxAwkIterations,maxSedIterations:e.maxSedIterations??ge.maxSedIterations,maxJqIterations:e.maxJqIterations??ge.maxJqIterations,maxSqliteTimeoutMs:e.maxSqliteTimeoutMs??ge.maxSqliteTimeoutMs,maxPythonTimeoutMs:e.maxPythonTimeoutMs??ge.maxPythonTimeoutMs,maxGlobOperations:e.maxGlobOperations??ge.maxGlobOperations,maxStringLength:e.maxStringLength??ge.maxStringLength,maxArrayElements:e.maxArrayElements??ge.maxArrayElements,maxHeredocSize:e.maxHeredocSize??ge.maxHeredocSize,maxSubstitutionDepth:e.maxSubstitutionDepth??ge.maxSubstitutionDepth,maxConcurrentJobs:e.maxConcurrentJobs??ge.maxConcurrentJobs}:{...ge}}function Zi(e){try{let t=new URL(e);return{origin:t.origin,pathname:t.pathname,href:t.href}}catch{return null}}function za(e){let t=Zi(e);return t?{origin:t.origin,pathPrefix:t.pathname}:null}function ja(e,t){let s=Zi(e);if(!s)return!1;let n=za(t);return!n||s.origin!==n.origin?!1:n.pathPrefix==="/"||n.pathPrefix===""?!0:s.pathname.startsWith(n.pathPrefix)}function Jn(e,t){return!t||t.length===0?!1:t.some(s=>ja(e,s))}var zt=class extends Error{constructor(t){super(`Network access denied: URL not in allow-list: ${t}`),this.name="NetworkAccessDeniedError"}},jt=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"}},xs=class extends Error{constructor(t,s){super(`HTTP method '${t}' not allowed. Allowed methods: ${s.join(", ")}`),this.name="MethodNotAllowedError"}},Ut=class extends Error{constructor(t){super(`Response body too large (max: ${t} bytes)`),this.name="ResponseTooLargeError"}};var Ba=20,Ua=3e4,Ha=10485760,Ga=["GET","HEAD"],qa=new Set(["GET","HEAD","OPTIONS"]),Za=new Set([301,302,303,307,308]);function Xn(e){let t=e.maxRedirects??Ba,s=e.timeoutMs??Ua,n=e.maxResponseSize??Ha,r=e.dangerouslyAllowFullInternetAccess?["GET","HEAD","POST","PUT","DELETE","PATCH","OPTIONS"]:e.allowedMethods??Ga;function i(l){if(!e.dangerouslyAllowFullInternetAccess&&!Jn(l,e.allowedUrlPrefixes??[]))throw new zt(l)}function a(l){if(e.dangerouslyAllowFullInternetAccess)return;let c=l.toUpperCase();if(!r.includes(c))throw new xs(c,r)}async function o(l,c={}){let u=c.method?.toUpperCase()??"GET";i(l),a(u);let f=l,d=0,p=c.followRedirects??!0,m=c.timeoutMs!==void 0?Math.min(c.timeoutMs,s):s;for(;;){let h=new AbortController,v=setTimeout(()=>h.abort(),m);try{let S={method:u,headers:c.headers,signal:h.signal,redirect:"manual"};c.body&&!qa.has(u)&&(S.body=c.body);let E=await fetch(f,S);if(Za.has(E.status)&&p){let b=E.headers.get("location");if(!b)return await Ji(E,f,n);let g=new URL(b,f).href;if(!e.dangerouslyAllowFullInternetAccess&&!Jn(g,e.allowedUrlPrefixes??[]))throw new Bt(g);if(d++,d>t)throw new jt(t);f=g;continue}return await Ji(E,f,n)}finally{clearTimeout(v)}}}return o}async function Ji(e,t,s){let n=Object.create(null);if(e.headers.forEach((i,a)=>{n[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 Ut(s)}}let r;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 Ut(s);o.push(a.decode(u,{stream:!0}))}o.push(a.decode()),r=o.join("")}else r=await e.text();return{status:e.status,statusText:e.statusText,headers:n,body:r,url:t}}var Ja=1e3,Xa=4096,Ka=globalThis.setTimeout.bind(globalThis),Ya=globalThis.clearTimeout.bind(globalThis),Os=class{jobs=new Map;reapedWaitStatuses=new Map;reapedWaitLineages=new Map;reapedJobNumbers=new Map;options;nextPid=Ja;nextLineageId=1;highestJobNumber=0;runningJobs=0;disposed=!1;disposePromise;constructor(t={}){this.options=t}start(t,s,n){if(this.disposed)throw new Error("Cannot start a job on a disposed ProcessTable");let r=this.nextPid++,i=new AbortController,a=this.highestJobNumber+1,o={info:{pid:r,command:t,startedAt:Date.now(),state:"running"},jobNumber:a,lineageId:n,controller:i,promise:Promise.resolve(0)};return this.jobs.set(r,o),this.highestJobNumber=a,this.runningJobs++,o.promise=Promise.resolve().then(()=>s(r,i.signal)).catch(()=>i.signal.aborted?sr(i.signal.reason):1).then(l=>{let c=this.jobs.get(r)===o;c&&this.runningJobs--,o.info={...o.info,state:"done",exitCode:l},o.controller=void 0,o.promise=void 0,c&&(this.rememberWaitStatus(r,l,o.lineageId,o.jobNumber),this.deleteJobs([r]));try{Promise.resolve(this.options.onJobExit?.(r,l)).catch(()=>{})}catch{}return l}),r}list(){return[...this.jobs.values()].sort((t,s)=>t.jobNumber-s.jobNumber).map(t=>({...t.info}))}listJobs(t,s={}){let n=[...this.jobs.values()].sort((o,l)=>o.jobNumber-l.jobNumber),r=n.at(-1)?.info.pid,i=n.at(-2)?.info.pid,a=[];for(let o of n)t&&!t.has(o.info.pid)||s.runningOnly&&o.info.state!=="running"||s.stoppedOnly||s.changedOnly&&o.changedStateReported===o.info.state||(a.push({...o.info,jobNumber:o.jobNumber,marker:o.info.pid===r?"+":o.info.pid===i?"-":" "}),s.changedOnly&&(o.changedStateReported=o.info.state));return a}get(t){let s=this.jobs.get(t)?.info;return s?{...s}:void 0}kill(t,s,n){let r=this.jobs.get(t);return!r||r.info.state==="done"?!1:(s!=="SIGSTOP"&&s!=="SIGCONT"&&r.controller?.abort(n??s),!0)}async wait(t){if(t!==void 0){let r=this.jobs.get(t);if(!r)return this.reapedWaitStatuses.get(t)??127;let i=r.info.state==="done"?r.info.exitCode??1:await(r.promise??Promise.resolve(1));return this.jobs.get(t)===r&&(this.rememberWaitStatus(t,i,r.lineageId),this.deleteJobs([t])),i}let s=[...this.jobs.values()],n=new Set([...this.reapedWaitStatuses.keys(),...s.map(r=>r.info.pid)]);s.length>0&&(await Promise.all(s.map(r=>r.promise??Promise.resolve(r.info.exitCode??1))),this.deleteJobs(s.map(r=>r.info.pid)));for(let r of n)this.forgetWaitStatus(r);return 0}async waitForLineage(t){let s=new Set;for(;;){let n=[...this.jobs.values()].filter(r=>r.lineageId===t);if(n.length===0)break;await Promise.all(n.map(r=>r.promise??Promise.resolve(r.info.exitCode??1)));for(let r of n)s.add(r.info.pid);this.deleteJobs(n.map(r=>r.info.pid))}for(let[n,r]of this.reapedWaitLineages)r===t&&s.add(n);for(let n of s)this.forgetWaitStatus(n);return 0}createLineageId(){return this.nextLineageId++}abortAll(t="SIGTERM"){for(let s of this.jobs.values())s.info.state==="running"&&s.controller?.abort(t)}dispose(){if(this.disposePromise)return this.disposePromise;this.disposed=!0;let t=[...this.jobs.values()],s=()=>{};this.disposePromise=new Promise(r=>{s=r}),this.abortAll("SIGKILL"),this.jobs.clear(),this.reapedWaitStatuses.clear(),this.reapedWaitLineages.clear(),this.reapedJobNumbers.clear(),this.highestJobNumber=0,this.runningJobs=0;let n=Ka(s,this.options.disposeTimeoutMs??1e3);return n.unref?.(),Promise.allSettled(t.flatMap(r=>r.promise?[r.promise]:[])).then(()=>{Ya(n),s()}),this.disposePromise}get runningCount(){return this.runningJobs}getJobNumber(t){return this.jobs.get(t)?.jobNumber}canWait(t){return this.jobs.has(t)||this.reapedWaitStatuses.has(t)}resolveJobSpec(t){let s=[...this.jobs.values()].sort((i,a)=>i.jobNumber-a.jobNumber);if(t==="%+"||t==="%%")return s.at(-1)?.info.pid;if(t==="%-")return(s.at(-2)??s.at(-1))?.info.pid;let n=/^%(\d+)$/.exec(t);if(!n)return;let r=Number.parseInt(n[1],10);return s.find(i=>i.jobNumber===r)?.info.pid??this.reapedJobNumbers.get(r)}get observesOutput(){return this.options.onJobOutput!==void 0}observeOutput(t,s,n){try{Promise.resolve(this.options.onJobOutput?.(t,s,n)).catch(()=>{})}catch{}}rememberWaitStatus(t,s,n,r){if(this.forgetWaitStatus(t),this.reapedWaitStatuses.set(t,s),this.reapedWaitLineages.set(t,n),r!==void 0&&this.reapedJobNumbers.set(r,t),this.reapedWaitStatuses.size>Xa){let i=this.reapedWaitStatuses.keys().next().value;i!==void 0&&this.forgetWaitStatus(i)}}forgetWaitStatus(t){this.reapedWaitStatuses.delete(t),this.reapedWaitLineages.delete(t);for(let[s,n]of this.reapedJobNumbers)n===t&&this.reapedJobNumbers.delete(s)}deleteJobs(t){let s=!1;for(let n of t){let r=this.jobs.get(n);r&&(this.jobs.delete(n),s||=r.jobNumber===this.highestJobNumber)}if(s){this.highestJobNumber=0;for(let n of this.jobs.values())this.highestJobNumber=Math.max(this.highestJobNumber,n.jobNumber)}}};function Xi(){let e=[{prop:"Function",target:globalThis,violationType:"function_constructor",strategy:"throw",reason:"Function constructor allows arbitrary code execution"},{prop:"eval",target:globalThis,violationType:"eval",strategy:"throw",reason:"eval() allows arbitrary code execution"},{prop:"setTimeout",target:globalThis,violationType:"setTimeout",strategy:"throw",reason:"setTimeout with string argument allows code execution"},{prop:"setInterval",target:globalThis,violationType:"setInterval",strategy:"throw",reason:"setInterval with string argument allows code execution"},{prop:"setImmediate",target:globalThis,violationType:"setImmediate",strategy:"throw",reason:"setImmediate could be used to escape sandbox context"},{prop:"env",target:process,violationType:"process_env",strategy:"throw",reason:"process.env could leak sensitive environment variables"},{prop:"binding",target:process,violationType:"process_binding",strategy:"throw",reason:"process.binding provides access to native Node.js modules"},{prop:"_linkedBinding",target:process,violationType:"process_binding",strategy:"throw",reason:"process._linkedBinding provides access to native Node.js modules"},{prop:"dlopen",target:process,violationType:"process_dlopen",strategy:"throw",reason:"process.dlopen allows loading native addons"},{prop:"WeakRef",target:globalThis,violationType:"weak_ref",strategy:"throw",reason:"WeakRef could be used to leak references outside sandbox"},{prop:"FinalizationRegistry",target:globalThis,violationType:"finalization_registry",strategy:"throw",reason:"FinalizationRegistry could be used to leak references outside sandbox"},{prop:"Reflect",target:globalThis,violationType:"reflect",strategy:"freeze",reason:"Reflect provides introspection capabilities"},{prop:"Proxy",target:globalThis,violationType:"proxy",strategy:"throw",reason:"Proxy allows intercepting and modifying object behavior"},{prop:"WebAssembly",target:globalThis,violationType:"webassembly",strategy:"throw",reason:"WebAssembly allows executing arbitrary compiled code"},{prop:"SharedArrayBuffer",target:globalThis,violationType:"shared_array_buffer",strategy:"throw",reason:"SharedArrayBuffer could enable side-channel communication or timing attacks"},{prop:"Atomics",target:globalThis,violationType:"atomics",strategy:"throw",reason:"Atomics could enable side-channel communication or timing attacks"}];try{let t=Object.getPrototypeOf(async()=>{}).constructor;t&&t!==Function&&e.push({prop:"constructor",target:Object.getPrototypeOf(async()=>{}),violationType:"async_function_constructor",strategy:"throw",reason:"AsyncFunction constructor allows arbitrary async code execution"})}catch{}try{let t=Object.getPrototypeOf(function*(){}).constructor;t&&t!==Function&&e.push({prop:"constructor",target:Object.getPrototypeOf(function*(){}),violationType:"generator_function_constructor",strategy:"throw",reason:"GeneratorFunction constructor allows arbitrary generator code execution"})}catch{}try{let t=Object.getPrototypeOf(async function*(){}).constructor;t&&t!==Function&&t!==Object.getPrototypeOf(async()=>{}).constructor&&e.push({prop:"constructor",target:Object.getPrototypeOf(async function*(){}),violationType:"async_generator_function_constructor",strategy:"throw",reason:"AsyncGeneratorFunction constructor allows arbitrary async generator code execution"})}catch{}return e.filter(t=>{try{return t.target[t.prop]!==void 0}catch{return!1}})}var Ht=typeof __BROWSER__<"u"&&__BROWSER__;function Ki(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}var Yn=null;if(!Ht)try{let e="node:module",{createRequire:t}=await import(e);Yn=t(import.meta.url)("node:async_hooks").AsyncLocalStorage}catch(e){console.debug("[DefenseInDepthBox] AsyncLocalStorage not available, defense-in-depth disabled:",e instanceof Error?e.message:e)}var Qa=`
690
+
691
+ This is a defense-in-depth measure and indicates a bug in just-bash. Please report this at security@vercel.com`,me=class extends Error{violation;constructor(t,s){super(t+Qa),this.violation=s,this.name="SecurityViolationError"}},Se=!Ht&&Yn?new Yn:null,el=1e3,Kn={enabled:!0,auditMode:!1};function tl(e){return e===void 0?{...Kn,enabled:!1}:typeof e=="boolean"?{...Kn,enabled:e}:{...Kn,...e}}var Is=class e{static instance=null;config;refCount=0;originalDescriptors=[];violations=[];activationTime=0;totalActiveTimeMs=0;constructor(t){this.config=t}static getInstance(t){return e.instance||(e.instance=new e(tl(t))),e.instance}static resetInstance(){e.instance&&(e.instance.forceDeactivate(),e.instance=null)}static isInSandboxedContext(){return Se?Se?.getStore()?.sandboxActive===!0:!1}static getCurrentExecutionId(){if(Se)return Se?.getStore()?.executionId}updateConfig(t){this.config={...this.config,...t}}activate(){if(Ht||!this.config.enabled){let s=Ki();return{run:n=>n(),deactivate:()=>{},executionId:s}}this.refCount++,this.refCount===1&&(this.applyPatches(),this.activationTime=Date.now());let t=Ki();return{run:s=>Se.run({sandboxActive:!0,executionId:t},s),deactivate:()=>{this.refCount--,this.refCount===0&&(this.restorePatches(),this.totalActiveTimeMs+=Date.now()-this.activationTime),this.refCount<0&&(this.refCount=0)},executionId:t}}forceDeactivate(){this.refCount>0&&(this.restorePatches(),this.totalActiveTimeMs+=Date.now()-this.activationTime),this.refCount=0}isActive(){return this.refCount>0}getStats(){return{violationsBlocked:this.violations.length,violations:[...this.violations],activeTimeMs:this.totalActiveTimeMs+(this.refCount>0?Date.now()-this.activationTime:0),refCount:this.refCount}}clearViolations(){this.violations=[]}getPathForTarget(t,s){return t===globalThis?`globalThis.${s}`:t===process?`process.${s}`:t===Error?`Error.${s}`:t===Function.prototype?`Function.prototype.${s}`:t===Object.prototype?`Object.prototype.${s}`:`<object>.${s}`}shouldBlock(){return Ht||this.config.auditMode||!Se?!1:Se?.getStore()?.sandboxActive===!0}recordViolation(t,s,n){let r={timestamp:Date.now(),type:t,message:n,path:s,stack:new Error().stack,executionId:Se?.getStore()?.executionId};if(this.violations.length<el&&this.violations.push(r),this.config.onViolation)try{this.config.onViolation(r)}catch(i){console.debug("[DefenseInDepthBox] onViolation callback threw:",i instanceof Error?i.message:i)}return r}createBlockingProxy(t,s,n){let r=this;return new Proxy(t,{apply(i,a,o){if(r.shouldBlock()){let l=`${s} is blocked during script execution`,c=r.recordViolation(n,s,l);throw new me(l,c)}return r.config.auditMode&&Se?.getStore()?.sandboxActive===!0&&r.recordViolation(n,s,`${s} called (audit mode)`),Reflect.apply(i,a,o)},construct(i,a,o){if(r.shouldBlock()){let l=`${s} constructor is blocked during script execution`,c=r.recordViolation(n,s,l);throw new me(l,c)}return r.config.auditMode&&Se?.getStore()?.sandboxActive===!0&&r.recordViolation(n,s,`${s} constructor called (audit mode)`),Reflect.construct(i,a,o)}})}createBlockingObjectProxy(t,s,n){let r=this;return new Proxy(t,{get(i,a,o){if(r.shouldBlock()){let l=`${s}.${String(a)}`,c=`${l} is blocked during script execution`,u=r.recordViolation(n,l,c);throw new me(c,u)}if(r.config.auditMode&&Se?.getStore()?.sandboxActive===!0){let l=`${s}.${String(a)}`;r.recordViolation(n,l,`${l} accessed (audit mode)`)}return Reflect.get(i,a,o)},set(i,a,o,l){if(r.shouldBlock()){let c=`${s}.${String(a)}`,u=`${c} modification is blocked during script execution`,f=r.recordViolation(n,c,u);throw new me(u,f)}return Reflect.set(i,a,o,l)},ownKeys(i){if(r.shouldBlock()){let a=`${s} enumeration is blocked during script execution`,o=r.recordViolation(n,s,a);throw new me(a,o)}return Reflect.ownKeys(i)},getOwnPropertyDescriptor(i,a){if(r.shouldBlock()){let o=`${s}.${String(a)}`,l=`${o} descriptor access is blocked during script execution`,c=r.recordViolation(n,o,l);throw new me(l,c)}return Reflect.getOwnPropertyDescriptor(i,a)},has(i,a){if(r.shouldBlock()){let o=`${s}.${String(a)}`,l=`${o} existence check is blocked during script execution`,c=r.recordViolation(n,o,l);throw new me(l,c)}return Reflect.has(i,a)}})}applyPatches(){let t=Xi();for(let s of t)this.applyPatch(s);this.protectConstructorChain(),this.protectErrorPrepareStackTrace(),this.protectModuleLoad(),this.protectProcessMainModule()}protectConstructorChain(){this.patchPrototypeConstructor(Function.prototype,"Function.prototype.constructor","function_constructor");try{let t=Object.getPrototypeOf(async()=>{}).constructor;t&&t!==Function&&this.patchPrototypeConstructor(t.prototype,"AsyncFunction.prototype.constructor","async_function_constructor")}catch(t){console.debug("[DefenseInDepthBox] Could not patch AsyncFunction.prototype.constructor:",t instanceof Error?t.message:t)}try{let t=Object.getPrototypeOf(function*(){}).constructor;t&&t!==Function&&this.patchPrototypeConstructor(t.prototype,"GeneratorFunction.prototype.constructor","generator_function_constructor")}catch(t){console.debug("[DefenseInDepthBox] Could not patch GeneratorFunction.prototype.constructor:",t instanceof Error?t.message:t)}try{let t=Object.getPrototypeOf(async function*(){}).constructor,s=Object.getPrototypeOf(async()=>{}).constructor;t&&t!==Function&&t!==s&&this.patchPrototypeConstructor(t.prototype,"AsyncGeneratorFunction.prototype.constructor","async_generator_function_constructor")}catch(t){console.debug("[DefenseInDepthBox] Could not patch AsyncGeneratorFunction.prototype.constructor:",t instanceof Error?t.message:t)}}protectErrorPrepareStackTrace(){let t=this;try{let s=Object.getOwnPropertyDescriptor(Error,"prepareStackTrace");this.originalDescriptors.push({target:Error,prop:"prepareStackTrace",descriptor:s});let n=s?.value;Object.defineProperty(Error,"prepareStackTrace",{get(){return n},set(r){if(t.shouldBlock()){let i="Error.prepareStackTrace modification is blocked during script execution",a=t.recordViolation("error_prepare_stack_trace","Error.prepareStackTrace",i);throw new me(i,a)}t.config.auditMode&&Se?.getStore()?.sandboxActive===!0&&t.recordViolation("error_prepare_stack_trace","Error.prepareStackTrace","Error.prepareStackTrace set (audit mode)"),n=r},configurable:!0})}catch(s){console.debug("[DefenseInDepthBox] Could not protect Error.prepareStackTrace:",s instanceof Error?s.message:s)}}patchPrototypeConstructor(t,s,n){let r=this;try{let i=Object.getOwnPropertyDescriptor(t,"constructor");this.originalDescriptors.push({target:t,prop:"constructor",descriptor:i});let a=i?.value;Object.defineProperty(t,"constructor",{get(){if(r.shouldBlock()){let o=`${s} access is blocked during script execution`,l=r.recordViolation(n,s,o);throw new me(o,l)}return r.config.auditMode&&Se?.getStore()?.sandboxActive===!0&&r.recordViolation(n,s,`${s} accessed (audit mode)`),a},set(o){if(r.shouldBlock()){let l=`${s} modification is blocked during script execution`,c=r.recordViolation(n,s,l);throw new me(l,c)}Object.defineProperty(this,"constructor",{value:o,writable:!0,configurable:!0})},configurable:!0})}catch(i){console.debug(`[DefenseInDepthBox] Could not patch ${s}:`,i instanceof Error?i.message:i)}}protectProcessMainModule(){if(typeof process>"u")return;let t=this;try{let s=Object.getOwnPropertyDescriptor(process,"mainModule");this.originalDescriptors.push({target:process,prop:"mainModule",descriptor:s});let n=s?.value;n!==void 0&&Object.defineProperty(process,"mainModule",{get(){if(t.shouldBlock()){let r="process.mainModule access is blocked during script execution",i=t.recordViolation("process_main_module","process.mainModule",r);throw new me(r,i)}return t.config.auditMode&&Se?.getStore()?.sandboxActive===!0&&t.recordViolation("process_main_module","process.mainModule","process.mainModule accessed (audit mode)"),n},set(r){if(t.shouldBlock()){let i="process.mainModule modification is blocked during script execution",a=t.recordViolation("process_main_module","process.mainModule",i);throw new me(i,a)}Object.defineProperty(process,"mainModule",{value:r,writable:!0,configurable:!0})},configurable:!0})}catch(s){console.debug("[DefenseInDepthBox] Could not protect process.mainModule:",s instanceof Error?s.message:s)}}protectModuleLoad(){if(!Ht)try{let t=null;if(typeof process<"u"){let a=process.mainModule;a&&typeof a=="object"&&(t=a.constructor)}if(!t&&typeof Gt<"u"&&typeof Gt.main<"u"&&(t=Gt.main.constructor),!t||typeof t._load!="function")return;let s=t._load,n=Object.getOwnPropertyDescriptor(t,"_load");this.originalDescriptors.push({target:t,prop:"_load",descriptor:n});let i=this.createBlockingProxy(s,"Module._load","module_load");Object.defineProperty(t,"_load",{value:i,writable:!0,configurable:!0})}catch(t){console.debug("[DefenseInDepthBox] Could not protect Module._load:",t instanceof Error?t.message:t)}}applyPatch(t){let{target:s,prop:n,violationType:r,strategy:i}=t;try{let a=s[n];if(a===void 0)return;let o=Object.getOwnPropertyDescriptor(s,n);if(this.originalDescriptors.push({target:s,prop:n,descriptor:o}),i==="freeze")typeof a=="object"&&a!==null&&Object.freeze(a);else{let l=this.getPathForTarget(s,n),c=typeof a=="function"?this.createBlockingProxy(a,l,r):this.createBlockingObjectProxy(a,l,r);Object.defineProperty(s,n,{value:c,writable:!0,configurable:!0})}}catch(a){let o=this.getPathForTarget(s,n);console.debug(`[DefenseInDepthBox] Could not patch ${o}:`,a instanceof Error?a.message:a)}}restorePatches(){for(let t=this.originalDescriptors.length-1;t>=0;t--){let{target:s,prop:n,descriptor:r}=this.originalDescriptors[t];try{r?Object.defineProperty(s,n,r):delete s[n]}catch(i){let a=this.getPathForTarget(s,n);console.debug(`[DefenseInDepthBox] Could not restore ${a}:`,i instanceof Error?i.message:i)}}this.originalDescriptors=[]}};var sl=globalThis.setTimeout.bind(globalThis),Ds=class{fs;processes;commands=new Map;useDefaultLayout=!1;limits;secureFetch;sleepFn;traceFn;logger;defenseInDepthConfig;coverageWriter;state;constructor(t={}){let s=t.fs??new Nt(t.files);this.fs=s,this.processes=t.processes??new Os,this.useDefaultLayout=!t.cwd&&!t.files;let n=t.cwd||(this.useDefaultLayout?"/home/user":"/"),r=new Map,i=[["HOME",this.useDefaultLayout?"/home/user":"/"],["PATH","/usr/bin:/bin"],["IFS",`
692
+ `],["OSTYPE","linux-gnu"],["MACHTYPE","x86_64-pc-linux-gnu"],["HOSTTYPE","x86_64"],["HOSTNAME","localhost"],["PWD",n],["OLDPWD",n],["OPTIND","1"]];for(let[a,o]of i)y(r,a,o);for(let[a,o]of Object.entries(t.env??{}))y(r,a,o);if(this.limits=qi({...t.executionLimits,...t.maxCallDepth!==void 0&&{maxCallDepth:t.maxCallDepth},...t.maxCommandCount!==void 0&&{maxCommandCount:t.maxCommandCount},...t.maxLoopIterations!==void 0&&{maxLoopIterations:t.maxLoopIterations}}),t.network&&(this.secureFetch=Xn(t.network)),this.sleepFn=t.sleep,this.traceFn=t.trace,this.logger=t.logger,this.defenseInDepthConfig=t.defenseInDepth,this.coverageWriter=t.coverage,this.state={env:r,cwd:n,previousDir:"/home/user",functions:new Map,localScopes:[],callDepth:0,sourceDepth:0,commandCount:0,lastExitCode:0,lastArg:R,startTime:Date.now(),lastBackgroundPid:0,bashPid:Ls().pid,nextVirtualPid:Ls().pid+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},y(this.state.env,"SHELLOPTS",Gs(this.state.options)),y(this.state.env,"BASHOPTS",qs(this.state.shoptOptions)),_r(s,this.useDefaultLayout),n!=="/"&&s instanceof Nt)try{s.mkdirSync(n,{recursive:!0})}catch{}for(let a of Sr(t.commands))this.registerCommand(a);if(t.network)for(let a of Er())this.registerCommand(a);if(t.python)for(let a of $r())this.registerCommand(a);if(t.customCommands)for(let a of t.customCommands)Ar(a)?this.registerCommand(Cr(a)):this.registerCommand(a)}registerCommand(t){this.commands.set(t.name,t);let s=this.fs;if(typeof s.writeFileSync=="function"){let n=`#!/bin/bash
693
693
  # Built-in command: ${t.name}
694
- `;try{s.writeFileSync(`/bin/${t.name}`,n)}catch{}try{s.writeFileSync(`/usr/bin/${t.name}`,n)}catch{}}}logResult(t,s,n){try{let r=this.logger;if(r){let i=s.text(),a=n.text();i.length>0&&r.debug("stdout",{output:i}),a.length>0&&r.info("stderr",{output:a}),r.info("exit",{exitCode:t.exitCode})}return{...t,stdout:s.stream(),stderr:n.stream()}}finally{s.seal(),n.seal()}}async exec(t,s){if(this.state.callDepth===0&&(this.state.commandCount=0),this.state.commandCount++,this.state.commandCount>this.limits.maxCommandCount)return{stdout:E(),stderr:V(`bash: maximum command count (${this.limits.maxCommandCount}) exceeded (possible infinite loop). Increase with executionLimits.maxCommandCount option.
695
- `),exitCode:1,env:ke(this.state.env,s?.env)};if(!t.trim())return{stdout:E(),stderr:E(),exitCode:0,env:ke(this.state.env,s?.env)};if(s?.signal?.aborted)return{stdout:E(),stderr:E(),exitCode:new pe(s.signal.reason).exitCode,env:ke(this.state.env,s?.env)};let n=new Set,r=g=>{if(g)return{async write(v){try{await g.write(v)}catch(C){throw n.add(C),C}}}},i=Pe(r(s?.stdoutSink)),a=Pe(r(s?.stderrSink)),o=s?.processes??this.processes,l=s?.lineageId??o.createLineageId(),u=s?.jobTracker??{started:!1,limitExceeded:!1};this.logger?.info("exec",{command:t});let c=s?.cwd??this.state.cwd,f,d=c;if(s?.cwd)if(s.env&&"PWD"in s.env)f=s.env.PWD;else if(s?.env&&!("PWD"in s.env))try{f=await this.fs.realpath(c),d=f}catch{f=c}else f=c;let p=new Map(this.state.env);if(s?.env)for(let[g,v]of Object.entries(s.env))y(p,g,v);f!==void 0&&y(p,"PWD",f);let m={...this.state,env:p,cwd:d,functions:new Map(this.state.functions),localScopes:[...this.state.localScopes],options:{...this.state.options},fileDescriptors:this.state.fileDescriptors?new Map(this.state.fileDescriptors):void 0,hashTable:this.state.hashTable,groupStdin:s?.stdin||void 0},h=t;s?.rawScript||(h=Ya(t));let S=(this.defenseInDepthConfig?Ds.getInstance(this.defenseInDepthConfig):null)?.activate(),$=!1;try{let g=async()=>{let v=Ie(h);$=!0;let C={fs:this.fs,commands:this.commands,outputChannels:{bindings:new Map([[1,{sink:i}],[2,{sink:a}]])},limits:this.limits,jobTracker:u,processes:o,lineageId:l,exec:(P,k)=>this.exec(P,{...k,jobTracker:u,processes:o,lineageId:l,signal:kt(s?.signal,k?.signal)}),fetch:this.secureFetch,sleep:this.sleepFn,trace:this.traceFn,coverage:this.coverageWriter,signal:s?.signal},I=await new Ft(C,m).executeRootScript(v);return u.started&&(await new Promise(P=>Xa(P,0)),u.limitExceeded&&(I={...I,exitCode:oe.EXIT_CODE})),this.logResult(I,i,a)};return S?await S.run(g):await g()}catch(g){if(n.has(g))throw g;if(g instanceof q)return this.logResult({exitCode:g.exitCode,env:ke(this.state.env,s?.env)},i,a);if(g instanceof we)return this.logResult({exitCode:g.exitCode,env:ke(this.state.env,s?.env)},i,a);if(g instanceof Xe)return $||await a.write(F(`bash: ${g.message}
696
- `)),this.logResult({exitCode:1,env:ke(this.state.env,s?.env)},i,a);if(g instanceof pe)return this.logResult({exitCode:g.exitCode,env:ke(this.state.env,s?.env)},i,a);if(g instanceof oe)return this.logResult({exitCode:oe.EXIT_CODE,env:ke(this.state.env,s?.env)},i,a);if(g instanceof me)return await a.write(F(`bash: security violation: ${g.message}
697
- `)),this.logResult({exitCode:1,env:ke(this.state.env,s?.env)},i,a);if(g.name==="ParseException")return await a.write(F(`bash: syntax error: ${g.message}
698
- `)),this.logResult({exitCode:2,env:ke(this.state.env,s?.env)},i,a);if(g instanceof or)return await a.write(F(`bash: ${g.message}
699
- `)),this.logResult({exitCode:2,env:ke(this.state.env,s?.env)},i,a);if(g instanceof RangeError)return await a.write(F(`bash: ${g.message}
700
- `)),this.logResult({exitCode:1,env:ke(this.state.env,s?.env)},i,a);throw g}finally{S?.deactivate()}}async readFile(t){return this.fs.readFileText(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 Ge(this.state.env)}};function Ya(e){let t=e.split(`
701
- `),s=[],n=[];for(let r=0;r<t.length;r++){let i=t[r];if(n.length>0){let l=n[n.length-1];if((l.stripTabs?i.replace(/^\t+/,""):i)===l.delimiter){s.push(i.trimStart()),n.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 u=l[1]==="-",c=l[3];n.push({delimiter:c,stripTabs:u})}}return s.join(`
702
- `)}import*as ne from"node:fs";import*as yt from"node:path";var Qa="/home/user/project";function fe(e,t){if(e.includes("\0"))throw new Error(`ENOENT: path contains null byte, ${t} '${e}'`)}var wt=class{root;mountPoint;readOnly;maxFileReadSize;memory=new Map;deleted=new Set;constructor(t){this.root=yt.resolve(t.root);let s=t.mountPoint??Qa;if(this.mountPoint=s==="/"?"/":s.replace(/\/+$/,""),!this.mountPoint.startsWith("/"))throw new Error(`Mount point must be an absolute path: ${s}`);if(this.readOnly=t.readOnly??!1,this.maxFileReadSize=t.maxFileReadSize??10485760,!ne.existsSync(this.root))throw new Error(`OverlayFs root does not exist: ${this.root}`);if(!ne.statSync(this.root).isDirectory())throw new Error(`OverlayFs root is not a directory: ${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 n of t)s+=`/${n}`,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 r=this.normalizePath(t).split("/").filter(Boolean),i="";for(let a of r)i+=`/${a}`,this.memory.has(i)||this.memory.set(i,{type:"directory",mode:493,mtime:new Date})}writeFileSync(t,s){let n=this.normalizePath(t),r=this.getDirname(n);r!=="/"&&this.mkdirSync(r);let{chunks:i,size:a}=at(s);this.memory.set(n,{type:"file",chunks:i,size:a,mode:420,mtime:new Date})}getDirname(t){let s=t.lastIndexOf("/");return s===0?"/":t.slice(0,s)}normalizePath(t){if(!t||t==="/")return"/";let s=t.endsWith("/")&&t!=="/"?t.slice(0,-1):t;s.startsWith("/")||(s=`/${s}`);let n=s.split("/").filter(i=>i&&i!=="."),r=[];for(let i of n)i===".."?r.pop():r.push(i);return`/${r.join("/")}`||"/"}getRelativeToMount(t){return this.mountPoint==="/"?t:t===this.mountPoint?"/":t.startsWith(`${this.mountPoint}/`)?t.slice(this.mountPoint.length):null}toRealPath(t){let s=this.normalizePath(t),n=this.getRelativeToMount(s);if(n===null)return null;let r=yt.join(this.root,n),i=yt.resolve(r);return!i.startsWith(this.root)&&i!==this.root.replace(/\/$/,"")?null:i}dirname(t){let s=this.normalizePath(t);if(s==="/")return"/";let n=s.lastIndexOf("/");return n===0?"/":s.slice(0,n)}ensureParentDirs(t){let s=this.dirname(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=this.normalizePath(t);if(this.deleted.has(s))return!1;if(this.memory.has(s))return!0;let n=this.toRealPath(s);if(!n)return!1;try{return await ne.promises.access(n),!0}catch{return!1}}async readFile(t){let s=await this.readFileChunks(t);return Et(s)}async readRange(t,s,n){Qt(s,n);let r=await this.resolveForRead(t);if(r.kind==="memory")return es(r.chunks,r.size,s,n);if(n===0||s>=r.size)return new Uint8Array(0);let i=Math.min(n,r.size-s),a=new Uint8Array(i),o=await ne.promises.open(r.realPath,"r");try{let{bytesRead:l}=await o.read(a,0,i,s);return l===i?a:a.subarray(0,l)}finally{await o.close()}}async resolveForRead(t,s=new Set){fe(t,"open");let n=this.normalizePath(t);if(s.has(n))throw new Error(`ELOOP: too many levels of symbolic links, open '${t}'`);if(s.add(n),this.deleted.has(n))throw new Error(`ENOENT: no such file or directory, open '${t}'`);let r=this.memory.get(n);if(r){if(r.type==="symlink"){let a=this.resolveSymlink(n,r.target);return this.resolveForRead(a,s)}if(r.type!=="file")throw new Error(`EISDIR: illegal operation on a directory, read '${t}'`);return{kind:"memory",chunks:r.chunks,size:r.size}}let i=this.toRealPath(n);if(!i)throw new Error(`ENOENT: no such file or directory, open '${t}'`);try{let a=await ne.promises.lstat(i);if(a.isSymbolicLink()){let o=await ne.promises.readlink(i),l=this.resolveSymlink(n,o);return this.resolveForRead(l,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})`);return{kind:"real",realPath:i,size:a.size}}catch(a){throw a.code==="ENOENT"?new Error(`ENOENT: no such file or directory, open '${t}'`):a}}async readFileText(t,s){let n=await this.readFileChunks(t),r=He(s);return Yt(n,r)}async readFileChunks(t,s=new Set){fe(t,"open");let n=this.normalizePath(t);if(s.has(n))throw new Error(`ELOOP: too many levels of symbolic links, open '${t}'`);if(s.add(n),this.deleted.has(n))throw new Error(`ENOENT: no such file or directory, open '${t}'`);let r=this.memory.get(n);if(r){if(r.type==="symlink"){let a=this.resolveSymlink(n,r.target);return this.readFileChunks(a,s)}if(r.type!=="file")throw new Error(`EISDIR: illegal operation on a directory, read '${t}'`);return r.chunks}let i=this.toRealPath(n);if(!i)throw new Error(`ENOENT: no such file or directory, open '${t}'`);try{let a=await ne.promises.lstat(i);if(a.isSymbolicLink()){let c=await ne.promises.readlink(i),f=this.resolveSymlink(n,c);return this.readFileChunks(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=await ne.promises.readFile(i),l=new Uint8Array(o.buffer,o.byteOffset,o.byteLength),{chunks:u}=at(l);return u}catch(a){throw a.code==="ENOENT"?new Error(`ENOENT: no such file or directory, open '${t}'`):a}}async writeFile(t,s,n){fe(t,"write"),this.assertWritable(`write '${t}'`);let r=this.normalizePath(t);this.ensureParentDirs(r);let i=He(n),{chunks:a,size:o}=await lt(s,i);this.memory.set(r,{type:"file",chunks:a,size:o,mode:420,mtime:new Date}),this.deleted.delete(r)}async appendFile(t,s,n){fe(t,"append"),this.assertWritable(`append '${t}'`);let r=this.normalizePath(t),i=He(n),{chunks:a,size:o}=await lt(s,i),l=[],u=0;try{l=await this.readFileChunks(r);for(let c of l)u+=c.length}catch{}this.ensureParentDirs(r),this.memory.set(r,{type:"file",chunks:[...l,...a],size:u+o,mode:420,mtime:new Date}),this.deleted.delete(r)}async exists(t){return t.includes("\0")?!1:this.existsInOverlay(t)}async stat(t,s=new Set){fe(t,"stat");let n=this.normalizePath(t);if(s.has(n))throw new Error(`ELOOP: too many levels of symbolic links, stat '${t}'`);if(s.add(n),this.deleted.has(n))throw new Error(`ENOENT: no such file or directory, stat '${t}'`);let r=this.memory.get(n);if(r){if(r.type==="symlink"){let o=this.resolveSymlink(n,r.target);return this.stat(o,s)}let a=0;return r.type==="file"&&(a=r.size),{isFile:r.type==="file",isDirectory:r.type==="directory",isSymbolicLink:!1,mode:r.mode,size:a,mtime:r.mtime}}let i=this.toRealPath(n);if(!i)throw new Error(`ENOENT: no such file or directory, stat '${t}'`);try{let a=await ne.promises.stat(i);return{isFile:a.isFile(),isDirectory:a.isDirectory(),isSymbolicLink:!1,mode:a.mode,size:a.size,mtime:a.mtime}}catch(a){throw a.code==="ENOENT"?new Error(`ENOENT: no such file or directory, stat '${t}'`):a}}async lstat(t){fe(t,"lstat");let s=this.normalizePath(t);if(this.deleted.has(s))throw new Error(`ENOENT: no such file or directory, lstat '${t}'`);let n=this.memory.get(s);if(n){if(n.type==="symlink")return{isFile:!1,isDirectory:!1,isSymbolicLink:!0,mode:n.mode,size:n.target.length,mtime:n.mtime};let i=0;return n.type==="file"&&(i=n.size),{isFile:n.type==="file",isDirectory:n.type==="directory",isSymbolicLink:!1,mode:n.mode,size:i,mtime:n.mtime}}let r=this.toRealPath(s);if(!r)throw new Error(`ENOENT: no such file or directory, lstat '${t}'`);try{let i=await ne.promises.lstat(r);return{isFile:i.isFile(),isDirectory:i.isDirectory(),isSymbolicLink:i.isSymbolicLink(),mode:i.mode,size:i.size,mtime:i.mtime}}catch(i){throw i.code==="ENOENT"?new Error(`ENOENT: no such file or directory, lstat '${t}'`):i}}resolveSymlink(t,s){if(s.startsWith("/"))return this.normalizePath(s);let n=this.dirname(t);return this.normalizePath(n==="/"?`/${s}`:`${n}/${s}`)}async mkdir(t,s){fe(t,"mkdir"),this.assertWritable(`mkdir '${t}'`);let n=this.normalizePath(t);if(await this.existsInOverlay(n)){if(!s?.recursive)throw new Error(`EEXIST: file already exists, mkdir '${t}'`);return}let i=this.dirname(n);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(n,{type:"directory",mode:493,mtime:new Date}),this.deleted.delete(n)}async readdirCore(t,s){if(this.deleted.has(s))throw new Error(`ENOENT: no such file or directory, scandir '${t}'`);let n=new Map,r=new Set,i=s==="/"?"/":`${s}/`;for(let o of this.deleted)if(o.startsWith(i)){let l=o.slice(i.length),u=l.split("/")[0];u&&!l.includes("/",u.length)&&r.add(u)}for(let[o,l]of this.memory)if(o!==s&&o.startsWith(i)){let u=o.slice(i.length),c=u.split("/")[0];c&&!r.has(c)&&!u.includes("/",1)&&n.set(c,{name:c,isFile:l.type==="file",isDirectory:l.type==="directory",isSymbolicLink:l.type==="symlink"})}let a=this.toRealPath(s);if(a)try{let o=await ne.promises.readdir(a,{withFileTypes:!0});for(let l of o)!r.has(l.name)&&!n.has(l.name)&&n.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 if(o.code!=="ENOTDIR")throw o}return n}async resolveForReaddir(t,s=!1){let n=this.normalizePath(t),r=new Set,i=s,a=this.memory.get(n);for(;a&&a.type==="symlink";){if(r.has(n))throw new Error(`ELOOP: too many levels of symbolic links, scandir '${t}'`);r.add(n),i=!0,n=this.resolveSymlink(n,a.target),a=this.memory.get(n)}if(a)return{normalized:n,outsideOverlay:!1};if(this.getRelativeToMount(n)===null)return{normalized:n,outsideOverlay:!0};let l=this.toRealPath(n);if(!l)return{normalized:n,outsideOverlay:!0};try{if((await ne.promises.lstat(l)).isSymbolicLink()){let c=await ne.promises.readlink(l),f=this.resolveSymlink(n,c);return this.resolveForReaddir(f,!0)}return{normalized:n,outsideOverlay:!1}}catch{return i?{normalized:n,outsideOverlay:!0}:{normalized:n,outsideOverlay:!1}}}async readdir(t){fe(t,"scandir");let{normalized:s,outsideOverlay:n}=await this.resolveForReaddir(t);if(n)return[];let r=await this.readdirCore(t,s);return Array.from(r.keys()).sort((i,a)=>i<a?-1:i>a?1:0)}async readdirWithFileTypes(t){fe(t,"scandir");let{normalized:s,outsideOverlay:n}=await this.resolveForReaddir(t);if(n)return[];let r=await this.readdirCore(t,s);return Array.from(r.values()).sort((i,a)=>i.name<a.name?-1:i.name>a.name?1:0)}async rm(t,s){fe(t,"rm"),this.assertWritable(`rm '${t}'`);let n=this.normalizePath(t);if(!await this.existsInOverlay(n)){if(s?.force)return;throw new Error(`ENOENT: no such file or directory, rm '${t}'`)}try{if((await this.stat(n)).isDirectory){let a=await this.readdir(n);if(a.length>0){if(!s?.recursive)throw new Error(`ENOTEMPTY: directory not empty, rm '${t}'`);for(let o of a){let l=n==="/"?`/${o}`:`${n}/${o}`;await this.rm(l,s)}}}}catch{}this.deleted.add(n),this.memory.delete(n)}async cp(t,s,n){fe(t,"cp"),fe(s,"cp"),this.assertWritable(`cp '${s}'`);let r=this.normalizePath(t),i=this.normalizePath(s);if(!await this.existsInOverlay(r))throw new Error(`ENOENT: no such file or directory, cp '${t}'`);let o=await this.stat(r);if(o.isFile){let l=await this.readFileChunks(r);await this.writeFile(i,Et(l))}else if(o.isDirectory){if(!n?.recursive)throw new Error(`EISDIR: is a directory, cp '${t}'`);await this.mkdir(i,{recursive:!0});let l=await this.readdir(r);for(let u of l){let c=r==="/"?`/${u}`:`${r}/${u}`,f=i==="/"?`/${u}`:`${i}/${u}`;await this.cp(c,f,n)}}}async mv(t,s){this.assertWritable(`mv '${s}'`),await this.cp(t,s,{recursive:!0}),await this.rm(t,{recursive:!0})}resolvePath(t,s){if(s.startsWith("/"))return this.normalizePath(s);let n=t==="/"?`/${s}`:`${t}/${s}`;return this.normalizePath(n)}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 n=this.toRealPath(t);if(n)try{let r=ne.readdirSync(n);for(let i of r){let a=t==="/"?`/${i}`:`${t}/${i}`;if(this.deleted.has(a))continue;s.add(a);let o=yt.join(n,i);ne.statSync(o).isDirectory()&&this.scanRealFs(a,s)}}catch{}}async chmod(t,s){fe(t,"chmod"),this.assertWritable(`chmod '${t}'`);let n=this.normalizePath(t);if(!await this.existsInOverlay(n))throw new Error(`ENOENT: no such file or directory, chmod '${t}'`);let i=this.memory.get(n);if(i){i.mode=s;return}let a=await this.stat(n);if(a.isFile){let o=await this.readFileChunks(n),l=0;for(let u of o)l+=u.length;this.memory.set(n,{type:"file",chunks:o,size:l,mode:s,mtime:new Date})}else a.isDirectory&&this.memory.set(n,{type:"directory",mode:s,mtime:new Date})}async symlink(t,s){fe(s,"symlink"),this.assertWritable(`symlink '${s}'`);let n=this.normalizePath(s);if(await this.existsInOverlay(n))throw new Error(`EEXIST: file already exists, symlink '${s}'`);this.ensureParentDirs(n),this.memory.set(n,{type:"symlink",target:t,mode:511,mtime:new Date}),this.deleted.delete(n)}async link(t,s){fe(t,"link"),fe(s,"link"),this.assertWritable(`link '${s}'`);let n=this.normalizePath(t),r=this.normalizePath(s);if(!await this.existsInOverlay(n))throw new Error(`ENOENT: no such file or directory, link '${t}'`);let a=await this.stat(n);if(!a.isFile)throw new Error(`EPERM: operation not permitted, link '${t}'`);if(await this.existsInOverlay(r))throw new Error(`EEXIST: file already exists, link '${s}'`);let l=await this.readFileChunks(n),u=0;for(let c of l)u+=c.length;this.ensureParentDirs(r),this.memory.set(r,{type:"file",chunks:l,size:u,mode:a.mode,mtime:new Date}),this.deleted.delete(r)}async readlink(t){fe(t,"readlink");let s=this.normalizePath(t);if(this.deleted.has(s))throw new Error(`ENOENT: no such file or directory, readlink '${t}'`);let n=this.memory.get(s);if(n){if(n.type!=="symlink")throw new Error(`EINVAL: invalid argument, readlink '${t}'`);return n.target}let r=this.toRealPath(s);if(!r)throw new Error(`ENOENT: no such file or directory, readlink '${t}'`);try{return await ne.promises.readlink(r)}catch(i){throw i.code==="ENOENT"?new Error(`ENOENT: no such file or directory, readlink '${t}'`):i.code==="EINVAL"?new Error(`EINVAL: invalid argument, readlink '${t}'`):i}}async realpath(t){fe(t,"realpath");let s=this.normalizePath(t),n=new Set,r=async o=>{let l=o==="/"?[]:o.slice(1).split("/"),u="";for(let c of l){if(u=`${u}/${c}`,n.has(u))throw new Error(`ELOOP: too many levels of symbolic links, realpath '${t}'`);if(this.deleted.has(u))throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);let f=this.memory.get(u),d=0,p=40;for(;f&&f.type==="symlink"&&d<p;){if(n.add(u),u=this.resolveSymlink(u,f.target),d++,n.has(u))throw new Error(`ELOOP: too many levels of symbolic links, realpath '${t}'`);if(this.deleted.has(u))throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);f=this.memory.get(u)}if(d>=p)throw new Error(`ELOOP: too many levels of symbolic links, realpath '${t}'`);if(!f){let m=this.toRealPath(u);if(m)try{if((await ne.promises.lstat(m)).isSymbolicLink()){let b=await ne.promises.readlink(m);return n.add(u),u=this.resolveSymlink(u,b),r(u)}}catch(h){throw h.code==="ENOENT"?new Error(`ENOENT: no such file or directory, realpath '${t}'`):h}}}return u||"/"},i=await r(s);if(!await this.existsInOverlay(i))throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);return i}async utimes(t,s,n){fe(t,"utimes"),this.assertWritable(`utimes '${t}'`);let r=this.normalizePath(t);if(!await this.existsInOverlay(r))throw new Error(`ENOENT: no such file or directory, utimes '${t}'`);let a=this.memory.get(r);if(a){a.mtime=n;return}let o=await this.stat(r);if(o.isFile){let l=await this.readFileChunks(r),u=0;for(let c of l)u+=c.length;this.memory.set(r,{type:"file",chunks:l,size:u,mode:o.mode,mtime:n})}else o.isDirectory&&this.memory.set(r,{type:"directory",mode:o.mode,mtime:n})}};function Qi(){console.log(`just-bash - A secure bash environment for AI agents
694
+ `;try{s.writeFileSync(`/bin/${t.name}`,n)}catch{}try{s.writeFileSync(`/usr/bin/${t.name}`,n)}catch{}}}logResult(t,s,n){try{let r=this.logger;if(r){let i=s.text(),a=n.text();i.length>0&&r.debug("stdout",{output:i}),a.length>0&&r.info("stderr",{output:a}),r.info("exit",{exitCode:t.exitCode})}return{...t,stdout:s.stream(),stderr:n.stream()}}finally{s.seal(),n.seal()}}async exec(t,s){if(this.state.callDepth===0&&(this.state.commandCount=0),this.state.commandCount++,this.state.commandCount>this.limits.maxCommandCount)return{stdout:A(),stderr:V(`bash: maximum command count (${this.limits.maxCommandCount}) exceeded (possible infinite loop). Increase with executionLimits.maxCommandCount option.
695
+ `),exitCode:1,env:ke(this.state.env,s?.env)};if(!t.trim())return{stdout:A(),stderr:A(),exitCode:0,env:ke(this.state.env,s?.env)};if(s?.signal?.aborted)return{stdout:A(),stderr:A(),exitCode:new pe(s.signal.reason).exitCode,env:ke(this.state.env,s?.env)};let n=new Set,r=b=>{if(b)return{async write(g){try{await b.write(g)}catch(P){throw n.add(P),P}}}},i=Pe(r(s?.stdoutSink)),a=Pe(r(s?.stderrSink)),o=s?.processes??this.processes,l=s?.lineageId??o.createLineageId(),c=s?.jobTracker??{started:!1,limitExceeded:!1};this.logger?.info("exec",{command:t});let u=s?.cwd??this.state.cwd,f,d=u;if(s?.cwd)if(s.env&&"PWD"in s.env)f=s.env.PWD;else if(s?.env&&!("PWD"in s.env))try{f=await this.fs.realpath(u),d=f}catch{f=u}else f=u;let p=new Map(this.state.env);if(s?.env)for(let[b,g]of Object.entries(s.env))y(p,b,g);f!==void 0&&y(p,"PWD",f);let m={...this.state,env:p,cwd:d,functions:new Map(this.state.functions),localScopes:[...this.state.localScopes],options:{...this.state.options},fileDescriptors:this.state.fileDescriptors?new Map(this.state.fileDescriptors):void 0,hashTable:this.state.hashTable,groupStdin:s?.stdin||void 0},h=t;s?.rawScript||(h=nl(t));let S=(this.defenseInDepthConfig?Is.getInstance(this.defenseInDepthConfig):null)?.activate(),E=!1;try{let b=async()=>{let g=De(h);E=!0;let P={fs:this.fs,commands:this.commands,outputChannels:{bindings:new Map([[1,{sink:i}],[2,{sink:a}]])},limits:this.limits,jobTracker:c,processes:o,lineageId:l,exec:($,k)=>this.exec($,{...k,jobTracker:c,processes:o,signal:kt(s?.signal,k?.signal)}),fetch:this.secureFetch,sleep:this.sleepFn,trace:this.traceFn,coverage:this.coverageWriter,signal:s?.signal},M=await new Vt(P,m).executeRootScript(g);return c.started&&(await new Promise($=>sl($,0)),c.limitExceeded&&(M={...M,exitCode:oe.EXIT_CODE})),this.logResult(M,i,a)};return S?await S.run(b):await b()}catch(b){if(n.has(b))throw b;if(b instanceof q)return this.logResult({exitCode:b.exitCode,env:ke(this.state.env,s?.env)},i,a);if(b instanceof we)return this.logResult({exitCode:b.exitCode,env:ke(this.state.env,s?.env)},i,a);if(b instanceof Ke)return E||await a.write(F(`bash: ${b.message}
696
+ `)),this.logResult({exitCode:1,env:ke(this.state.env,s?.env)},i,a);if(b instanceof pe)return this.logResult({exitCode:b.exitCode,env:ke(this.state.env,s?.env)},i,a);if(b instanceof oe)return this.logResult({exitCode:oe.EXIT_CODE,env:ke(this.state.env,s?.env)},i,a);if(b instanceof me)return await a.write(F(`bash: security violation: ${b.message}
697
+ `)),this.logResult({exitCode:1,env:ke(this.state.env,s?.env)},i,a);if(b.name==="ParseException")return await a.write(F(`bash: syntax error: ${b.message}
698
+ `)),this.logResult({exitCode:2,env:ke(this.state.env,s?.env)},i,a);if(b instanceof or)return await a.write(F(`bash: ${b.message}
699
+ `)),this.logResult({exitCode:2,env:ke(this.state.env,s?.env)},i,a);if(b instanceof RangeError)return await a.write(F(`bash: ${b.message}
700
+ `)),this.logResult({exitCode:1,env:ke(this.state.env,s?.env)},i,a);throw b}finally{S?.deactivate()}}async readFile(t){return this.fs.readFileText(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 Ge(this.state.env)}};function nl(e){let t=e.split(`
701
+ `),s=[],n=[];for(let r=0;r<t.length;r++){let i=t[r];if(n.length>0){let l=n[n.length-1];if((l.stripTabs?i.replace(/^\t+/,""):i)===l.delimiter){s.push(i.trimStart()),n.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];n.push({delimiter:u,stripTabs:c})}}return s.join(`
702
+ `)}import*as ne from"node:fs";import*as yt from"node:path";var rl="/home/user/project";function fe(e,t){if(e.includes("\0"))throw new Error(`ENOENT: path contains null byte, ${t} '${e}'`)}var wt=class{root;mountPoint;readOnly;maxFileReadSize;memory=new Map;deleted=new Set;constructor(t){this.root=yt.resolve(t.root);let s=t.mountPoint??rl;if(this.mountPoint=s==="/"?"/":s.replace(/\/+$/,""),!this.mountPoint.startsWith("/"))throw new Error(`Mount point must be an absolute path: ${s}`);if(this.readOnly=t.readOnly??!1,this.maxFileReadSize=t.maxFileReadSize??10485760,!ne.existsSync(this.root))throw new Error(`OverlayFs root does not exist: ${this.root}`);if(!ne.statSync(this.root).isDirectory())throw new Error(`OverlayFs root is not a directory: ${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 n of t)s+=`/${n}`,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 r=this.normalizePath(t).split("/").filter(Boolean),i="";for(let a of r)i+=`/${a}`,this.memory.has(i)||this.memory.set(i,{type:"directory",mode:493,mtime:new Date})}writeFileSync(t,s){let n=this.normalizePath(t),r=this.getDirname(n);r!=="/"&&this.mkdirSync(r);let{chunks:i,size:a}=at(s);this.memory.set(n,{type:"file",chunks:i,size:a,mode:420,mtime:new Date})}getDirname(t){let s=t.lastIndexOf("/");return s===0?"/":t.slice(0,s)}normalizePath(t){if(!t||t==="/")return"/";let s=t.endsWith("/")&&t!=="/"?t.slice(0,-1):t;s.startsWith("/")||(s=`/${s}`);let n=s.split("/").filter(i=>i&&i!=="."),r=[];for(let i of n)i===".."?r.pop():r.push(i);return`/${r.join("/")}`||"/"}getRelativeToMount(t){return this.mountPoint==="/"?t:t===this.mountPoint?"/":t.startsWith(`${this.mountPoint}/`)?t.slice(this.mountPoint.length):null}toRealPath(t){let s=this.normalizePath(t),n=this.getRelativeToMount(s);if(n===null)return null;let r=yt.join(this.root,n),i=yt.resolve(r);return!i.startsWith(this.root)&&i!==this.root.replace(/\/$/,"")?null:i}dirname(t){let s=this.normalizePath(t);if(s==="/")return"/";let n=s.lastIndexOf("/");return n===0?"/":s.slice(0,n)}ensureParentDirs(t){let s=this.dirname(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=this.normalizePath(t);if(this.deleted.has(s))return!1;if(this.memory.has(s))return!0;let n=this.toRealPath(s);if(!n)return!1;try{return await ne.promises.access(n),!0}catch{return!1}}async readFile(t){let s=await this.readFileChunks(t);return Et(s)}async readRange(t,s,n){es(s,n);let r=await this.resolveForRead(t);if(r.kind==="memory")return ts(r.chunks,r.size,s,n);if(n===0||s>=r.size)return new Uint8Array(0);let i=Math.min(n,r.size-s),a=new Uint8Array(i),o=await ne.promises.open(r.realPath,"r");try{let{bytesRead:l}=await o.read(a,0,i,s);return l===i?a:a.subarray(0,l)}finally{await o.close()}}async resolveForRead(t,s=new Set){fe(t,"open");let n=this.normalizePath(t);if(s.has(n))throw new Error(`ELOOP: too many levels of symbolic links, open '${t}'`);if(s.add(n),this.deleted.has(n))throw new Error(`ENOENT: no such file or directory, open '${t}'`);let r=this.memory.get(n);if(r){if(r.type==="symlink"){let a=this.resolveSymlink(n,r.target);return this.resolveForRead(a,s)}if(r.type!=="file")throw new Error(`EISDIR: illegal operation on a directory, read '${t}'`);return{kind:"memory",chunks:r.chunks,size:r.size}}let i=this.toRealPath(n);if(!i)throw new Error(`ENOENT: no such file or directory, open '${t}'`);try{let a=await ne.promises.lstat(i);if(a.isSymbolicLink()){let o=await ne.promises.readlink(i),l=this.resolveSymlink(n,o);return this.resolveForRead(l,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})`);return{kind:"real",realPath:i,size:a.size}}catch(a){throw a.code==="ENOENT"?new Error(`ENOENT: no such file or directory, open '${t}'`):a}}async readFileText(t,s){let n=await this.readFileChunks(t),r=Ue(s);return Qt(n,r)}async readFileChunks(t,s=new Set){fe(t,"open");let n=this.normalizePath(t);if(s.has(n))throw new Error(`ELOOP: too many levels of symbolic links, open '${t}'`);if(s.add(n),this.deleted.has(n))throw new Error(`ENOENT: no such file or directory, open '${t}'`);let r=this.memory.get(n);if(r){if(r.type==="symlink"){let a=this.resolveSymlink(n,r.target);return this.readFileChunks(a,s)}if(r.type!=="file")throw new Error(`EISDIR: illegal operation on a directory, read '${t}'`);return r.chunks}let i=this.toRealPath(n);if(!i)throw new Error(`ENOENT: no such file or directory, open '${t}'`);try{let a=await ne.promises.lstat(i);if(a.isSymbolicLink()){let u=await ne.promises.readlink(i),f=this.resolveSymlink(n,u);return this.readFileChunks(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=await ne.promises.readFile(i),l=new Uint8Array(o.buffer,o.byteOffset,o.byteLength),{chunks:c}=at(l);return c}catch(a){throw a.code==="ENOENT"?new Error(`ENOENT: no such file or directory, open '${t}'`):a}}async writeFile(t,s,n){fe(t,"write"),this.assertWritable(`write '${t}'`);let r=this.normalizePath(t);this.ensureParentDirs(r);let i=Ue(n),{chunks:a,size:o}=await lt(s,i);this.memory.set(r,{type:"file",chunks:a,size:o,mode:420,mtime:new Date}),this.deleted.delete(r)}async appendFile(t,s,n){fe(t,"append"),this.assertWritable(`append '${t}'`);let r=this.normalizePath(t),i=Ue(n),{chunks:a,size:o}=await lt(s,i),l=[],c=0;try{l=await this.readFileChunks(r);for(let u of l)c+=u.length}catch{}this.ensureParentDirs(r),this.memory.set(r,{type:"file",chunks:[...l,...a],size:c+o,mode:420,mtime:new Date}),this.deleted.delete(r)}async exists(t){return t.includes("\0")?!1:this.existsInOverlay(t)}async stat(t,s=new Set){fe(t,"stat");let n=this.normalizePath(t);if(s.has(n))throw new Error(`ELOOP: too many levels of symbolic links, stat '${t}'`);if(s.add(n),this.deleted.has(n))throw new Error(`ENOENT: no such file or directory, stat '${t}'`);let r=this.memory.get(n);if(r){if(r.type==="symlink"){let o=this.resolveSymlink(n,r.target);return this.stat(o,s)}let a=0;return r.type==="file"&&(a=r.size),{isFile:r.type==="file",isDirectory:r.type==="directory",isSymbolicLink:!1,mode:r.mode,size:a,mtime:r.mtime}}let i=this.toRealPath(n);if(!i)throw new Error(`ENOENT: no such file or directory, stat '${t}'`);try{let a=await ne.promises.stat(i);return{isFile:a.isFile(),isDirectory:a.isDirectory(),isSymbolicLink:!1,mode:a.mode,size:a.size,mtime:a.mtime}}catch(a){throw a.code==="ENOENT"?new Error(`ENOENT: no such file or directory, stat '${t}'`):a}}async lstat(t){fe(t,"lstat");let s=this.normalizePath(t);if(this.deleted.has(s))throw new Error(`ENOENT: no such file or directory, lstat '${t}'`);let n=this.memory.get(s);if(n){if(n.type==="symlink")return{isFile:!1,isDirectory:!1,isSymbolicLink:!0,mode:n.mode,size:n.target.length,mtime:n.mtime};let i=0;return n.type==="file"&&(i=n.size),{isFile:n.type==="file",isDirectory:n.type==="directory",isSymbolicLink:!1,mode:n.mode,size:i,mtime:n.mtime}}let r=this.toRealPath(s);if(!r)throw new Error(`ENOENT: no such file or directory, lstat '${t}'`);try{let i=await ne.promises.lstat(r);return{isFile:i.isFile(),isDirectory:i.isDirectory(),isSymbolicLink:i.isSymbolicLink(),mode:i.mode,size:i.size,mtime:i.mtime}}catch(i){throw i.code==="ENOENT"?new Error(`ENOENT: no such file or directory, lstat '${t}'`):i}}resolveSymlink(t,s){if(s.startsWith("/"))return this.normalizePath(s);let n=this.dirname(t);return this.normalizePath(n==="/"?`/${s}`:`${n}/${s}`)}async mkdir(t,s){fe(t,"mkdir"),this.assertWritable(`mkdir '${t}'`);let n=this.normalizePath(t);if(await this.existsInOverlay(n)){if(!s?.recursive)throw new Error(`EEXIST: file already exists, mkdir '${t}'`);return}let i=this.dirname(n);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(n,{type:"directory",mode:493,mtime:new Date}),this.deleted.delete(n)}async readdirCore(t,s){if(this.deleted.has(s))throw new Error(`ENOENT: no such file or directory, scandir '${t}'`);let n=new Map,r=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)&&r.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&&!r.has(u)&&!c.includes("/",1)&&n.set(u,{name:u,isFile:l.type==="file",isDirectory:l.type==="directory",isSymbolicLink:l.type==="symlink"})}let a=this.toRealPath(s);if(a)try{let o=await ne.promises.readdir(a,{withFileTypes:!0});for(let l of o)!r.has(l.name)&&!n.has(l.name)&&n.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 if(o.code!=="ENOTDIR")throw o}return n}async resolveForReaddir(t,s=!1){let n=this.normalizePath(t),r=new Set,i=s,a=this.memory.get(n);for(;a&&a.type==="symlink";){if(r.has(n))throw new Error(`ELOOP: too many levels of symbolic links, scandir '${t}'`);r.add(n),i=!0,n=this.resolveSymlink(n,a.target),a=this.memory.get(n)}if(a)return{normalized:n,outsideOverlay:!1};if(this.getRelativeToMount(n)===null)return{normalized:n,outsideOverlay:!0};let l=this.toRealPath(n);if(!l)return{normalized:n,outsideOverlay:!0};try{if((await ne.promises.lstat(l)).isSymbolicLink()){let u=await ne.promises.readlink(l),f=this.resolveSymlink(n,u);return this.resolveForReaddir(f,!0)}return{normalized:n,outsideOverlay:!1}}catch{return i?{normalized:n,outsideOverlay:!0}:{normalized:n,outsideOverlay:!1}}}async readdir(t){fe(t,"scandir");let{normalized:s,outsideOverlay:n}=await this.resolveForReaddir(t);if(n)return[];let r=await this.readdirCore(t,s);return Array.from(r.keys()).sort((i,a)=>i<a?-1:i>a?1:0)}async readdirWithFileTypes(t){fe(t,"scandir");let{normalized:s,outsideOverlay:n}=await this.resolveForReaddir(t);if(n)return[];let r=await this.readdirCore(t,s);return Array.from(r.values()).sort((i,a)=>i.name<a.name?-1:i.name>a.name?1:0)}async rm(t,s){fe(t,"rm"),this.assertWritable(`rm '${t}'`);let n=this.normalizePath(t);if(!await this.existsInOverlay(n)){if(s?.force)return;throw new Error(`ENOENT: no such file or directory, rm '${t}'`)}try{if((await this.stat(n)).isDirectory){let a=await this.readdir(n);if(a.length>0){if(!s?.recursive)throw new Error(`ENOTEMPTY: directory not empty, rm '${t}'`);for(let o of a){let l=n==="/"?`/${o}`:`${n}/${o}`;await this.rm(l,s)}}}}catch{}this.deleted.add(n),this.memory.delete(n)}async cp(t,s,n){fe(t,"cp"),fe(s,"cp"),this.assertWritable(`cp '${s}'`);let r=this.normalizePath(t),i=this.normalizePath(s);if(!await this.existsInOverlay(r))throw new Error(`ENOENT: no such file or directory, cp '${t}'`);let o=await this.stat(r);if(o.isFile){let l=await this.readFileChunks(r);await this.writeFile(i,Et(l))}else if(o.isDirectory){if(!n?.recursive)throw new Error(`EISDIR: is a directory, cp '${t}'`);await this.mkdir(i,{recursive:!0});let l=await this.readdir(r);for(let c of l){let u=r==="/"?`/${c}`:`${r}/${c}`,f=i==="/"?`/${c}`:`${i}/${c}`;await this.cp(u,f,n)}}}async mv(t,s){this.assertWritable(`mv '${s}'`),await this.cp(t,s,{recursive:!0}),await this.rm(t,{recursive:!0})}resolvePath(t,s){if(s.startsWith("/"))return this.normalizePath(s);let n=t==="/"?`/${s}`:`${t}/${s}`;return this.normalizePath(n)}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 n=this.toRealPath(t);if(n)try{let r=ne.readdirSync(n);for(let i of r){let a=t==="/"?`/${i}`:`${t}/${i}`;if(this.deleted.has(a))continue;s.add(a);let o=yt.join(n,i);ne.statSync(o).isDirectory()&&this.scanRealFs(a,s)}}catch{}}async chmod(t,s){fe(t,"chmod"),this.assertWritable(`chmod '${t}'`);let n=this.normalizePath(t);if(!await this.existsInOverlay(n))throw new Error(`ENOENT: no such file or directory, chmod '${t}'`);let i=this.memory.get(n);if(i){i.mode=s;return}let a=await this.stat(n);if(a.isFile){let o=await this.readFileChunks(n),l=0;for(let c of o)l+=c.length;this.memory.set(n,{type:"file",chunks:o,size:l,mode:s,mtime:new Date})}else a.isDirectory&&this.memory.set(n,{type:"directory",mode:s,mtime:new Date})}async symlink(t,s){fe(s,"symlink"),this.assertWritable(`symlink '${s}'`);let n=this.normalizePath(s);if(await this.existsInOverlay(n))throw new Error(`EEXIST: file already exists, symlink '${s}'`);this.ensureParentDirs(n),this.memory.set(n,{type:"symlink",target:t,mode:511,mtime:new Date}),this.deleted.delete(n)}async link(t,s){fe(t,"link"),fe(s,"link"),this.assertWritable(`link '${s}'`);let n=this.normalizePath(t),r=this.normalizePath(s);if(!await this.existsInOverlay(n))throw new Error(`ENOENT: no such file or directory, link '${t}'`);let a=await this.stat(n);if(!a.isFile)throw new Error(`EPERM: operation not permitted, link '${t}'`);if(await this.existsInOverlay(r))throw new Error(`EEXIST: file already exists, link '${s}'`);let l=await this.readFileChunks(n),c=0;for(let u of l)c+=u.length;this.ensureParentDirs(r),this.memory.set(r,{type:"file",chunks:l,size:c,mode:a.mode,mtime:new Date}),this.deleted.delete(r)}async readlink(t){fe(t,"readlink");let s=this.normalizePath(t);if(this.deleted.has(s))throw new Error(`ENOENT: no such file or directory, readlink '${t}'`);let n=this.memory.get(s);if(n){if(n.type!=="symlink")throw new Error(`EINVAL: invalid argument, readlink '${t}'`);return n.target}let r=this.toRealPath(s);if(!r)throw new Error(`ENOENT: no such file or directory, readlink '${t}'`);try{return await ne.promises.readlink(r)}catch(i){throw i.code==="ENOENT"?new Error(`ENOENT: no such file or directory, readlink '${t}'`):i.code==="EINVAL"?new Error(`EINVAL: invalid argument, readlink '${t}'`):i}}async realpath(t){fe(t,"realpath");let s=this.normalizePath(t),n=new Set,r=async o=>{let l=o==="/"?[]:o.slice(1).split("/"),c="";for(let u of l){if(c=`${c}/${u}`,n.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,p=40;for(;f&&f.type==="symlink"&&d<p;){if(n.add(c),c=this.resolveSymlink(c,f.target),d++,n.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>=p)throw new Error(`ELOOP: too many levels of symbolic links, realpath '${t}'`);if(!f){let m=this.toRealPath(c);if(m)try{if((await ne.promises.lstat(m)).isSymbolicLink()){let v=await ne.promises.readlink(m);return n.add(c),c=this.resolveSymlink(c,v),r(c)}}catch(h){throw h.code==="ENOENT"?new Error(`ENOENT: no such file or directory, realpath '${t}'`):h}}}return c||"/"},i=await r(s);if(!await this.existsInOverlay(i))throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);return i}async utimes(t,s,n){fe(t,"utimes"),this.assertWritable(`utimes '${t}'`);let r=this.normalizePath(t);if(!await this.existsInOverlay(r))throw new Error(`ENOENT: no such file or directory, utimes '${t}'`);let a=this.memory.get(r);if(a){a.mtime=n;return}let o=await this.stat(r);if(o.isFile){let l=await this.readFileChunks(r),c=0;for(let u of l)c+=u.length;this.memory.set(r,{type:"file",chunks:l,size:c,mode:o.mode,mtime:n})}else o.isDirectory&&this.memory.set(r,{type:"directory",mode:o.mode,mtime:n})}};function Qi(){console.log(`just-bash - A secure bash environment for AI agents
703
703
 
704
704
  Usage:
705
705
  just-bash [options] [script-file]
@@ -745,5 +745,5 @@ Examples:
745
745
 
746
746
  # Allow write operations (writes stay in memory)
747
747
  just-bash -c 'echo test > /tmp/file.txt && cat /tmp/file.txt' --allow-write
748
- `)}function el(){console.log("just-bash 1.0.0")}function tl(e){let t={root:process.cwd(),cwd:"/",cwdOverridden:!1,errexit:!1,allowWrite:!1,python:!1,json:!1,help:!1,version:!1},s=0;for(;s<e.length;){let n=e[s];if(n==="-h"||n==="--help")t.help=!0,s++;else if(n==="-v"||n==="--version")t.version=!0,s++;else if(n==="-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(n==="-e"||n==="--errexit")t.errexit=!0,s++;else if(n==="--root")s+1>=e.length&&(console.error("Error: --root requires a path argument"),process.exit(1)),t.root=Yi(e[s+1]),s+=2;else if(n==="--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(n==="--json")t.json=!0,s++;else if(n==="--allow-write")t.allowWrite=!0,s++;else if(n==="--python")t.python=!0,s++;else if(n.startsWith("-"))if(n.length>2&&!n.startsWith("--")){let r=n.slice(1);for(let i of r)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: ${n}`),process.exit(1);else!t.scriptFile&&!t.script?t.scriptFile=n:t.scriptFile&&t.root===process.cwd()&&(t.root=Yi(n)),s++}return t}function sl(e){if(!e||e==="/")return"/";let t=e.endsWith("/")&&e!=="/"?e.slice(0,-1):e;t.startsWith("/")||(t=`/${t}`);let s=t.split("/").filter(r=>r&&r!=="."),n=[];for(let r of s)r===".."?n.pop():n.push(r);return`/${n.join("/")}`||"/"}async function nl(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf-8")}async function rl(){let e=process.argv.slice(2),t=tl(e);t.help&&(Qi(),process.exit(0)),t.version&&(el(),process.exit(0));let s;if(t.script)s=t.script;else if(t.scriptFile){let o=new wt({root:t.root}),l=o.getMountPoint();try{let u=t.scriptFile.startsWith("/")?t.scriptFile:`${l}/${t.scriptFile}`;s=await o.readFileText(u,"utf-8")}catch(u){console.error(`Error: Cannot read script file: ${t.scriptFile}`),console.error(u instanceof Error?u.message:String(u)),process.exit(1)}}else process.stdin.isTTY?(Qi(),process.exit(1)):s=await nl();s.trim()||(t.json&&console.log(JSON.stringify({stdout:"",stderr:"",exitCode:0})),process.exit(0));let n=new wt({root:t.root,readOnly:!t.allowWrite}),r=n.getMountPoint(),i=t.cwdOverridden?sl(t.cwd):r,a=new Is({fs:n,cwd:i,python:t.python});t.errexit&&(s=`set -e
749
- ${s}`);try{let o=await a.exec(s);if(t.json){let[l,u]=await Promise.all([Rs(o.stdout),Rs(o.stderr)]);console.log(JSON.stringify({stdout:l,stderr:u,exitCode:o.exitCode}))}else{for await(let l of $t(o.stdout))process.stdout.write(l);for await(let l of $t(o.stderr))process.stderr.write(l)}process.exit(o.exitCode)}catch(o){t.json?console.log(JSON.stringify({stdout:"",stderr:o instanceof Error?o.message:String(o),exitCode:1})):console.error(o instanceof Error?o.message:String(o)),process.exit(1)}}rl().catch(e=>{console.error("Fatal error:",e),process.exit(1)});
748
+ `)}function il(){console.log("just-bash 1.0.0")}function ol(e){let t={root:process.cwd(),cwd:"/",cwdOverridden:!1,errexit:!1,allowWrite:!1,python:!1,json:!1,help:!1,version:!1},s=0;for(;s<e.length;){let n=e[s];if(n==="-h"||n==="--help")t.help=!0,s++;else if(n==="-v"||n==="--version")t.version=!0,s++;else if(n==="-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(n==="-e"||n==="--errexit")t.errexit=!0,s++;else if(n==="--root")s+1>=e.length&&(console.error("Error: --root requires a path argument"),process.exit(1)),t.root=Yi(e[s+1]),s+=2;else if(n==="--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(n==="--json")t.json=!0,s++;else if(n==="--allow-write")t.allowWrite=!0,s++;else if(n==="--python")t.python=!0,s++;else if(n.startsWith("-"))if(n.length>2&&!n.startsWith("--")){let r=n.slice(1);for(let i of r)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: ${n}`),process.exit(1);else!t.scriptFile&&!t.script?t.scriptFile=n:t.scriptFile&&t.root===process.cwd()&&(t.root=Yi(n)),s++}return t}function al(e){if(!e||e==="/")return"/";let t=e.endsWith("/")&&e!=="/"?e.slice(0,-1):e;t.startsWith("/")||(t=`/${t}`);let s=t.split("/").filter(r=>r&&r!=="."),n=[];for(let r of s)r===".."?n.pop():n.push(r);return`/${n.join("/")}`||"/"}async function ll(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf-8")}async function cl(){let e=process.argv.slice(2),t=ol(e);t.help&&(Qi(),process.exit(0)),t.version&&(il(),process.exit(0));let s;if(t.script)s=t.script;else if(t.scriptFile){let o=new wt({root:t.root}),l=o.getMountPoint();try{let c=t.scriptFile.startsWith("/")?t.scriptFile:`${l}/${t.scriptFile}`;s=await o.readFileText(c,"utf-8")}catch(c){console.error(`Error: Cannot read script file: ${t.scriptFile}`),console.error(c instanceof Error?c.message:String(c)),process.exit(1)}}else process.stdin.isTTY?(Qi(),process.exit(1)):s=await ll();s.trim()||(t.json&&console.log(JSON.stringify({stdout:"",stderr:"",exitCode:0})),process.exit(0));let n=new wt({root:t.root,readOnly:!t.allowWrite}),r=n.getMountPoint(),i=t.cwdOverridden?al(t.cwd):r,a=new Ds({fs:n,cwd:i,python:t.python});t.errexit&&(s=`set -e
749
+ ${s}`);try{let o=await a.exec(s);if(t.json){let[l,c]=await Promise.all([Rs(o.stdout),Rs(o.stderr)]);console.log(JSON.stringify({stdout:l,stderr:c,exitCode:o.exitCode}))}else{for await(let l of $t(o.stdout))process.stdout.write(l);for await(let l of $t(o.stderr))process.stderr.write(l)}process.exit(o.exitCode)}catch(o){t.json?console.log(JSON.stringify({stdout:"",stderr:o instanceof Error?o.message:String(o),exitCode:1})):console.error(o instanceof Error?o.message:String(o)),process.exit(1)}}cl().catch(e=>{console.error("Fatal error:",e),process.exit(1)});