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,148 +1,150 @@
1
- import{$ as An,A as qs,B as rs,C as yn,D as Zs,E as gn,F as Ee,G as qe,H as wn,I as vn,J as Xs,K as Js,L as ze,M as bn,N as En,O as Ie,P as Ks,R as Sn,S as $n,T as Se,U as ot,V as de,W as Re,X as ns,Y as Pn,Z as z,_ as Cn,a as hn,aa as je,b as Us,ba as kn,c as pn,ca as xn,d as mn,da as pt,e as ts,ea as ee,f as ce,g as X,h as Fe,i as ss,j as it,k as Gs,l as Hs,m as We,n as Lt,o as Ft,p as G,q as _e,r as K,s as Wt,t as Y,u as te,v as Qe,w as se,x as me,y as Ve,z as et}from"./chunks/chunk-S6UKQQAB.js";import{a as Mt}from"./chunks/chunk-VAEB4OUK.js";import{a as dn}from"./chunks/chunk-MIFIRXNI.js";import{a as Ye,b as xe}from"./chunks/chunk-UBLR5ACC.js";import{a as Rt}from"./chunks/chunk-XYWNAVNS.js";import{a as Ce,b as Ae,c as ve,d as ke,e as cn,f as q,g as nt,h as It,i as Qt,j as un,k as ae,l as fn,m as pe,n as Ke,o as Ge,p as es,q as be}from"./chunks/chunk-BX5K34KY.js";import"./chunks/chunk-NUFRM6SI.js";import{a as He}from"./chunks/chunk-44UOCSGV.js";import{a as dt,b as S,d as fe,e as ht,f as V,g as re,h as Yt,i as rt,j as fo,k as Bs,l as ho,m as po,n as mo}from"./chunks/chunk-KL7SL7ES.js";import{a as Dt,g as R,h as W,i as B,j as an,k as ft,l as T,m as g,n as ln}from"./chunks/chunk-DEQBZDPB.js";var at=[{name:"echo",load:async()=>(await import("./chunks/echo-PC3TVS6B.js")).echoCommand},{name:"cat",load:async()=>(await import("./chunks/cat-L3YELBYM.js")).catCommand},{name:"printf",load:async()=>(await import("./chunks/printf-6XMXHDAE.js")).printfCommand},{name:"ls",load:async()=>(await import("./chunks/ls-7JNJXADY.js")).lsCommand},{name:"mkdir",load:async()=>(await import("./chunks/mkdir-NM4BUUUC.js")).mkdirCommand},{name:"rmdir",load:async()=>(await import("./chunks/rmdir-Z4ZRV32S.js")).rmdirCommand},{name:"touch",load:async()=>(await import("./chunks/touch-PC42E2OS.js")).touchCommand},{name:"rm",load:async()=>(await import("./chunks/rm-7ERREV4V.js")).rmCommand},{name:"cp",load:async()=>(await import("./chunks/cp-73PGBEPL.js")).cpCommand},{name:"mv",load:async()=>(await import("./chunks/mv-VDGF4VTT.js")).mvCommand},{name:"ln",load:async()=>(await import("./chunks/ln-SHI7B5FY.js")).lnCommand},{name:"chmod",load:async()=>(await import("./chunks/chmod-IJMA7OGQ.js")).chmodCommand},{name:"pwd",load:async()=>(await import("./chunks/pwd-KKLARPNT.js")).pwdCommand},{name:"readlink",load:async()=>(await import("./chunks/readlink-6XCFQQJH.js")).readlinkCommand},{name:"head",load:async()=>(await import("./chunks/head-EFRLGDOE.js")).headCommand},{name:"tail",load:async()=>(await import("./chunks/tail-TULUAGKH.js")).tailCommand},{name:"wc",load:async()=>(await import("./chunks/wc-U424DF7O.js")).wcCommand},{name:"stat",load:async()=>(await import("./chunks/stat-Z22X56GM.js")).statCommand},{name:"grep",load:async()=>(await import("./chunks/grep-7RC5DPOS.js")).grepCommand},{name:"fgrep",load:async()=>(await import("./chunks/grep-7RC5DPOS.js")).fgrepCommand},{name:"egrep",load:async()=>(await import("./chunks/grep-7RC5DPOS.js")).egrepCommand},{name:"rg",load:async()=>(await import("./chunks/rg-NIW2Q5SV.js")).rgCommand},{name:"sed",load:async()=>(await import("./chunks/sed-VLSHT4XR.js")).sedCommand},{name:"awk",load:async()=>(await import("./chunks/awk2-RAKURI6M.js")).awkCommand2},{name:"sort",load:async()=>(await import("./chunks/sort-KCG2A34N.js")).sortCommand},{name:"uniq",load:async()=>(await import("./chunks/uniq-7HD4DCMD.js")).uniqCommand},{name:"comm",load:async()=>(await import("./chunks/comm-X7VETT2U.js")).commCommand},{name:"cut",load:async()=>(await import("./chunks/cut-7I6UA67F.js")).cutCommand},{name:"paste",load:async()=>(await import("./chunks/paste-HD4NKO4X.js")).pasteCommand},{name:"tr",load:async()=>(await import("./chunks/tr-F7JZV44S.js")).trCommand},{name:"rev",load:async()=>(await import("./chunks/rev-NJ2ZPNAT.js")).rev},{name:"nl",load:async()=>(await import("./chunks/nl-PD7BPFUB.js")).nl},{name:"fold",load:async()=>(await import("./chunks/fold-5VRJN4CL.js")).fold},{name:"expand",load:async()=>(await import("./chunks/expand-OYPZZOZC.js")).expand},{name:"unexpand",load:async()=>(await import("./chunks/unexpand-KAIAW5TX.js")).unexpand},{name:"strings",load:async()=>(await import("./chunks/strings-EKWOLUFJ.js")).strings},{name:"split",load:async()=>(await import("./chunks/split-EVSSQ6VR.js")).split},{name:"column",load:async()=>(await import("./chunks/column-N7MHP5SX.js")).column},{name:"join",load:async()=>(await import("./chunks/join-36QXZEGR.js")).join},{name:"tee",load:async()=>(await import("./chunks/tee-DPV6AVMH.js")).teeCommand},{name:"find",load:async()=>(await import("./chunks/find-DESNHKKS.js")).findCommand},{name:"basename",load:async()=>(await import("./chunks/basename-Q7SIX77Q.js")).basenameCommand},{name:"dirname",load:async()=>(await import("./chunks/dirname-2TM4IG7K.js")).dirnameCommand},{name:"tree",load:async()=>(await import("./chunks/tree-SVRMFKLQ.js")).treeCommand},{name:"du",load:async()=>(await import("./chunks/du-KTUJVIGD.js")).duCommand},{name:"env",load:async()=>(await import("./chunks/env-MFQH47JH.js")).envCommand},{name:"printenv",load:async()=>(await import("./chunks/env-MFQH47JH.js")).printenvCommand},{name:"alias",load:async()=>(await import("./chunks/alias-CIPN5HGG.js")).aliasCommand},{name:"unalias",load:async()=>(await import("./chunks/alias-CIPN5HGG.js")).unaliasCommand},{name:"history",load:async()=>(await import("./chunks/history-J3C24VIU.js")).historyCommand},{name:"xargs",load:async()=>(await import("./chunks/xargs-SWPLSROG.js")).xargsCommand},{name:"true",load:async()=>(await import("./chunks/true-T4XKISHJ.js")).trueCommand},{name:"false",load:async()=>(await import("./chunks/true-T4XKISHJ.js")).falseCommand},{name:"clear",load:async()=>(await import("./chunks/clear-J6WBUIX6.js")).clearCommand},{name:"yes",load:async()=>(await import("./chunks/yes-5BWAW2VY.js")).yesCommand},{name:"bash",load:async()=>(await import("./chunks/bash-HKSQMKKV.js")).bashCommand},{name:"sh",load:async()=>(await import("./chunks/bash-HKSQMKKV.js")).shCommand},{name:"jq",load:async()=>(await import("./chunks/jq-5KN27BBY.js")).jqCommand},{name:"base64",load:async()=>(await import("./chunks/base64-4GSA7KNI.js")).base64Command},{name:"diff",load:async()=>(await import("./chunks/diff-O5NFSBS5.js")).diffCommand},{name:"date",load:async()=>(await import("./chunks/date-MOZRIQXR.js")).dateCommand},{name:"sleep",load:async()=>(await import("./chunks/sleep-SAQIXUFW.js")).sleepCommand},{name:"timeout",load:async()=>(await import("./chunks/timeout-YRSN3MWF.js")).timeoutCommand},{name:"time",load:async()=>(await import("./chunks/time-RXWT5RNC.js")).timeCommand},{name:"seq",load:async()=>(await import("./chunks/seq-RCBD3IYO.js")).seqCommand},{name:"expr",load:async()=>(await import("./chunks/expr-4PIUWNB7.js")).exprCommand},{name:"md5sum",load:async()=>(await import("./chunks/md5sum-J7XPNTQZ.js")).md5sumCommand},{name:"sha1sum",load:async()=>(await import("./chunks/sha1sum-RMRQ75AE.js")).sha1sumCommand},{name:"sha256sum",load:async()=>(await import("./chunks/sha256sum-TGW5BMJR.js")).sha256sumCommand},{name:"file",load:async()=>(await import("./chunks/file-DZRW6GNH.js")).fileCommand},{name:"html-to-markdown",load:async()=>(await import("./chunks/html-to-markdown-TFBDHAZZ.js")).htmlToMarkdownCommand},{name:"help",load:async()=>(await import("./chunks/help-3XYFOR43.js")).helpCommand},{name:"which",load:async()=>(await import("./chunks/which-OY73BBGP.js")).whichCommand},{name:"tac",load:async()=>(await import("./chunks/tac-RSIVIUEI.js")).tac},{name:"hostname",load:async()=>(await import("./chunks/hostname-D54LLZ5I.js")).hostname},{name:"whoami",load:async()=>(await import("./chunks/whoami-KUZQQOVR.js")).whoami},{name:"od",load:async()=>(await import("./chunks/od-D6RO3GJE.js")).od},{name:"gzip",load:async()=>(await import("./chunks/gzip-WH2JWAWT.js")).gzipCommand},{name:"gunzip",load:async()=>(await import("./chunks/gzip-WH2JWAWT.js")).gunzipCommand},{name:"zcat",load:async()=>(await import("./chunks/gzip-WH2JWAWT.js")).zcatCommand}];(typeof __BROWSER__>"u"||!__BROWSER__)&&(at.push({name:"tar",load:async()=>(await import("./chunks/tar-KQPQPRTZ.js")).tarCommand}),at.push({name:"yq",load:async()=>(await import("./chunks/yq-URX6MHLP.js")).yqCommand}),at.push({name:"xan",load:async()=>(await import("./chunks/xan-N66EXZFT.js")).xanCommand}),at.push({name:"sqlite3",load:async()=>(await import("./chunks/sqlite3-M6BXLMYI.js")).sqlite3Command}));var is=[];(typeof __BROWSER__>"u"||!__BROWSER__)&&(is.push({name:"python3",load:async()=>(await import("./chunks/python3-KPG6SQQV.js")).python3Command}),is.push({name:"python",load:async()=>(await import("./chunks/python3-KPG6SQQV.js")).pythonCommand}));var Tn=[{name:"curl",load:async()=>(await import("./chunks/curl-MGBYKD7U.js")).curlCommand}],_n=new Map;function Ys(e){return{name:e.name,async execute(t,s){let r=_n.get(e.name);if(r||(r=await e.load(),_n.set(e.name,r)),s.coverage&&(typeof __BROWSER__>"u"||!__BROWSER__)){let{emitFlagCoverage:n}=await import("./chunks/flag-coverage-QMBN7WOW.js"),{decodeArgs:i}=await import("./chunks/bytes-JUNATFIO.js");n(s.coverage,e.name,i(t))}return r.execute(t,s)}}}function yo(){return at.map(e=>e.name)}function go(){return Tn.map(e=>e.name)}function Nn(e){return(e?at.filter(s=>e.includes(s.name)):at).map(Ys)}function On(){return Tn.map(Ys)}function wo(){return is.map(e=>e.name)}function Dn(){return is.map(Ys)}function In(e){return"load"in e&&typeof e.load=="function"}function vo(e,t){return{name:e,async execute(s,r){let n={...r,env:ln(r.env)},i=await t(ft(s),n);return typeof i.stdout=="string"?{stdout:V(i.stdout),stderr:V(i.stderr),exitCode:i.exitCode}:i}}}function Rn(e){let t=null;return{name:e.name,async execute(s,r){return t||(t=await e.load()),t.execute(s,r)}}}var bo=new TextEncoder;function Eo(e){return typeof e=="object"&&e!==null&&typeof e.getReader=="function"}function So(e,t){if(e instanceof Uint8Array)return e;if(t==="base64")return Uint8Array.from(atob(e),s=>s.charCodeAt(0));if(t==="hex"){let s=new Uint8Array(e.length/2);for(let r=0;r<e.length;r+=2)s[r/2]=parseInt(e.slice(r,r+2),16);return s}if(t==="binary"||t==="latin1"){if(e.length<=65536)return Uint8Array.from(e,n=>n.charCodeAt(0));let r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return r}return bo.encode(e)}function Ln(e){if(e.length===0)return[];if(e.length<=dt)return[e];let t=[];for(let s=0;s<e.length;s+=dt)t.push(e.subarray(s,Math.min(s+dt,e.length)));return t}function mt(e,t){let s=So(e,t);return{chunks:Ln(s),size:s.length}}async function Ze(e,t){if(Eo(e)){let s=[],r=0;for await(let n of Bs(e))if(n.length<=dt)s.push(n),r+=n.length;else for(let i of Ln(n))s.push(i),r+=i.length;return{chunks:s,size:r}}return mt(e,t)}function os(e,t){if(t==="base64")return btoa(dn(Mn(e)));if(t==="hex"){let n="";for(let i of e)for(let a=0;a<i.length;a++)n+=i[a].toString(16).padStart(2,"0");return n}if(t==="binary"||t==="latin1"){if(typeof Buffer<"u")return Buffer.from(Mn(e)).toString(t);let n=65536,i="";for(let a of e)if(a.length<=n)i+=String.fromCharCode(...a);else for(let o=0;o<a.length;o+=n){let l=a.subarray(o,o+n);i+=String.fromCharCode(...l)}return i}let s=new TextDecoder,r="";for(let n of e)n.length>0&&(r+=s.decode(n,{stream:!0}));return r+=s.decode(),r}function Mn(e){let t=0;for(let n of e)t+=n.length;if(t===0)return new Uint8Array(0);if(e.length===1)return e[0];let s=new Uint8Array(t),r=0;for(let n of e)s.set(n,r),r+=n.length;return s}function Te(e){if(e!=null)return typeof e=="string"?e:e.encoding??void 0}function yt(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 as(e,t,s,r){if(s>=t||r===0)return new Uint8Array(0);let n=Math.min(s+r,t),i=n-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<n){let f=Math.max(0,s-l),d=Math.min(u.length,n-l),p=u.subarray(f,d);a.set(p,o),o+=p.length}l=c}return a}function $o(e){return typeof e=="object"&&e!==null&&!(e instanceof Uint8Array)&&!(e instanceof ReadableStream)&&"content"in e}function ue(e,t){if(e.includes("\0"))throw new Error(`ENOENT: path contains null byte, ${t} '${e}'`)}var Xe=class{data=new Map;constructor(t){if(this.data.set("/",{type:"directory",mode:493,mtime:new Date}),t)for(let[s,r]of Object.entries(t))if($o(r)){if(r.content instanceof ReadableStream)throw new Error("InMemoryFs: streams not supported in InitialFiles; use writeFile() after construction");this.writeFileSync(s,r.content,void 0,{mode:r.mode,mtime:r.mtime})}else{if(r instanceof ReadableStream)throw new Error("InMemoryFs: streams not supported in InitialFiles; use writeFile() after construction");this.writeFileSync(s,r)}}normalizePath(t){if(!t||t==="/")return"/";let s=t.endsWith("/")&&t!=="/"?t.slice(0,-1):t;s.startsWith("/")||(s=`/${s}`);let r=s.split("/").filter(i=>i&&i!=="."),n=[];for(let i of r)i===".."?n.pop():n.push(i);return`/${n.join("/")}`||"/"}dirname(t){let s=this.normalizePath(t);if(s==="/")return"/";let r=s.lastIndexOf("/");return r===0?"/":s.slice(0,r)}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,r,n){ue(t,"write");let i=this.normalizePath(t);this.ensureParentDirs(i);let a=Te(r),{chunks:o,size:l}=mt(s,a);this.data.set(i,{type:"file",chunks:o,size:l,mode:n?.mode??420,mtime:n?.mtime??new Date})}async readFile(t){ue(t,"open");let s=this.resolvePathWithSymlinks(t),r=this.data.get(s);if(!r)throw new Error(`ENOENT: no such file or directory, open '${t}'`);if(r.type!=="file")throw new Error(`EISDIR: illegal operation on a directory, read '${t}'`);return ht(r.chunks)}async readRange(t,s,r){yt(s,r),ue(t,"open");let n=this.resolvePathWithSymlinks(t),i=this.data.get(n);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 as(i.chunks,i.size,s,r)}async readFileText(t,s){ue(t,"open");let r=this.resolvePathWithSymlinks(t),n=this.data.get(r);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}'`);let i=Te(s);return os(n.chunks,i)}async writeFile(t,s,r){ue(t,"write");let n=this.normalizePath(t);this.ensureParentDirs(n);let i=Te(r),{chunks:a,size:o}=await Ze(s,i);this.data.set(n,{type:"file",chunks:a,size:o,mode:420,mtime:new Date})}async appendFile(t,s,r){ue(t,"append");let n=this.normalizePath(t),i=this.data.get(n);if(i&&i.type==="directory")throw new Error(`EISDIR: illegal operation on a directory, write '${t}'`);let a=Te(r),{chunks:o,size:l}=await Ze(s,a);i?.type==="file"?this.data.set(n,{type:"file",chunks:[...i.chunks,...o],size:i.size+l,mode:i.mode,mtime:new Date}):(this.ensureParentDirs(n),this.data.set(n,{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){ue(t,"stat");let s=this.resolvePathWithSymlinks(t),r=this.data.get(s);if(!r)throw new Error(`ENOENT: no such file or directory, stat '${t}'`);let n=0;return r.type==="file"&&(n=r.size),{isFile:r.type==="file",isDirectory:r.type==="directory",isSymbolicLink:!1,mode:r.mode,size:n,mtime:r.mtime||new Date}}async lstat(t){ue(t,"lstat");let s=this.resolveIntermediateSymlinks(t),r=this.data.get(s);if(!r)throw new Error(`ENOENT: no such file or directory, lstat '${t}'`);if(r.type==="symlink")return{isFile:!1,isDirectory:!1,isSymbolicLink:!0,mode:r.mode,size:r.target.length,mtime:r.mtime||new Date};let n=0;return r.type==="file"&&(n=r.size),{isFile:r.type==="file",isDirectory:r.type==="directory",isSymbolicLink:!1,mode:r.mode,size:n,mtime:r.mtime||new Date}}resolveSymlink(t,s){if(s.startsWith("/"))return this.normalizePath(s);let r=this.dirname(t);return this.normalizePath(r==="/"?`/${s}`:`${r}/${s}`)}resolveIntermediateSymlinks(t){let s=this.normalizePath(t);if(s==="/")return"/";let r=s.slice(1).split("/");if(r.length<=1)return s;let n="",i=new Set;for(let a=0;a<r.length-1;a++){let o=r[a];n=`${n}/${o}`;let l=this.data.get(n),u=0,c=40;for(;l&&l.type==="symlink"&&u<c;){if(i.has(n))throw new Error(`ELOOP: too many levels of symbolic links, lstat '${t}'`);i.add(n),n=this.resolveSymlink(n,l.target),l=this.data.get(n),u++}if(u>=c)throw new Error(`ELOOP: too many levels of symbolic links, lstat '${t}'`)}return`${n}/${r[r.length-1]}`}resolvePathWithSymlinks(t){let s=this.normalizePath(t);if(s==="/")return"/";let r=s.slice(1).split("/"),n="",i=new Set;for(let a of r){n=`${n}/${a}`;let o=this.data.get(n),l=0,u=40;for(;o&&o.type==="symlink"&&l<u;){if(i.has(n))throw new Error(`ELOOP: too many levels of symbolic links, open '${t}'`);i.add(n),n=this.resolveSymlink(n,o.target),o=this.data.get(n),l++}if(l>=u)throw new Error(`ELOOP: too many levels of symbolic links, open '${t}'`)}return n}async mkdir(t,s){this.mkdirSync(t,s)}mkdirSync(t,s){ue(t,"mkdir");let r=this.normalizePath(t);if(this.data.has(r)){if(this.data.get(r)?.type==="file")throw new Error(`EEXIST: file already exists, mkdir '${t}'`);if(!s?.recursive)throw new Error(`EEXIST: directory already exists, mkdir '${t}'`);return}let n=this.dirname(r);if(n!=="/"&&!this.data.has(n))if(s?.recursive)this.mkdirSync(n,{recursive:!0});else throw new Error(`ENOENT: no such file or directory, mkdir '${t}'`);this.data.set(r,{type:"directory",mode:493,mtime:new Date})}async readdir(t){return(await this.readdirWithFileTypes(t)).map(r=>r.name)}async readdirWithFileTypes(t){ue(t,"scandir");let s=this.normalizePath(t),r=this.data.get(s);if(!r)throw new Error(`ENOENT: no such file or directory, scandir '${t}'`);let n=new Set;for(;r&&r.type==="symlink";){if(n.has(s))throw new Error(`ELOOP: too many levels of symbolic links, scandir '${t}'`);n.add(s),s=this.resolveSymlink(s,r.target),r=this.data.get(s)}if(!r)throw new Error(`ENOENT: no such file or directory, scandir '${t}'`);if(r.type!=="directory")throw new Error(`ENOTDIR: not a directory, scandir '${t}'`);let i=s==="/"?"/":`${s}/`,a=new Map;for(let[o,l]of this.data.entries())if(o!==s&&o.startsWith(i)){let 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){ue(t,"rm");let r=this.normalizePath(t),n=this.data.get(r);if(!n){if(s?.force)return;throw new Error(`ENOENT: no such file or directory, rm '${t}'`)}if(n.type==="directory"){let i=await this.readdir(r);if(i.length>0){if(!s?.recursive)throw new Error(`ENOTEMPTY: directory not empty, rm '${t}'`);for(let a of i){let o=r==="/"?`/${a}`:`${r}/${a}`;await this.rm(o,s)}}}this.data.delete(r)}async cp(t,s,r){ue(t,"cp"),ue(s,"cp");let n=this.normalizePath(t),i=this.normalizePath(s),a=this.data.get(n);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(!r?.recursive)throw new Error(`EISDIR: is a directory, cp '${t}'`);await this.mkdir(i,{recursive:!0});let o=await this.readdir(n);for(let l of o){let u=n==="/"?`/${l}`:`${n}/${l}`,c=i==="/"?`/${l}`:`${i}/${l}`;await this.cp(u,c,r)}}}async mv(t,s){await this.cp(t,s,{recursive:!0}),await this.rm(t,{recursive:!0})}getAllPaths(){return Array.from(this.data.keys())}resolvePath(t,s){if(s.startsWith("/"))return this.normalizePath(s);let r=t==="/"?`/${s}`:`${t}/${s}`;return this.normalizePath(r)}async chmod(t,s){ue(t,"chmod");let r=this.normalizePath(t),n=this.data.get(r);if(!n)throw new Error(`ENOENT: no such file or directory, chmod '${t}'`);n.mode=s}async symlink(t,s){ue(s,"symlink");let r=this.normalizePath(s);if(this.data.has(r))throw new Error(`EEXIST: file already exists, symlink '${s}'`);this.ensureParentDirs(r),this.data.set(r,{type:"symlink",target:t,mode:511,mtime:new Date})}async link(t,s){ue(t,"link"),ue(s,"link");let r=this.normalizePath(t),n=this.normalizePath(s),i=this.data.get(r);if(!i)throw new Error(`ENOENT: no such file or directory, link '${t}'`);if(i.type!=="file")throw new Error(`EPERM: operation not permitted, link '${t}'`);if(this.data.has(n))throw new Error(`EEXIST: file already exists, link '${s}'`);this.ensureParentDirs(n),this.data.set(n,{type:"file",chunks:[...i.chunks],size:i.size,mode:i.mode,mtime:i.mtime})}async readlink(t){ue(t,"readlink");let s=this.normalizePath(t),r=this.data.get(s);if(!r)throw new Error(`ENOENT: no such file or directory, readlink '${t}'`);if(r.type!=="symlink")throw new Error(`EINVAL: invalid argument, readlink '${t}'`);return r.target}async realpath(t){ue(t,"realpath");let s=this.resolvePathWithSymlinks(t);if(!this.data.has(s))throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);return s}async utimes(t,s,r){ue(t,"utimes");let n=this.normalizePath(t),i=this.resolvePathWithSymlinks(n),a=this.data.get(i);if(!a)throw new Error(`ENOENT: no such file or directory, utimes '${t}'`);a.mtime=r}};function Po(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 Ao(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 ko(e){e.mkdirSync("/proc/self/fd",{recursive:!0}),e.writeFileSync("/proc/version",`${hn}
1
+ import{$ as Cn,A as Zs,B as is,C as yn,D as Xs,E as gn,F as Ee,G as qe,H as wn,I as vn,J as Js,K as Ks,L as ze,M as bn,N as En,O as Ie,P as Ys,R as Sn,S as $n,T as Se,U as ot,V as de,W as Re,X as os,Y as Pn,Z as z,_ as An,a as hn,aa as je,b as Hs,ba as kn,c as pn,ca as Tn,d as mn,da as pt,e as rs,ea as ee,f as ce,g as X,h as Fe,i as ns,j as it,k as Gs,l as qs,m as We,n as Lt,o as Ft,p as H,q as xe,r as Y,s as Wt,t as Q,u as te,v as Qe,w as se,x as me,y as Ve,z as et}from"./chunks/chunk-S6UKQQAB.js";import{a as Mt}from"./chunks/chunk-VAEB4OUK.js";import{a as dn}from"./chunks/chunk-MIFIRXNI.js";import{a as Ye,b as Te}from"./chunks/chunk-UBLR5ACC.js";import{a as Rt}from"./chunks/chunk-XYWNAVNS.js";import{a as Ae,b as Ce,c as ve,d as ke,e as un,f as q,g as nt,h as It,i as es,j as fn,k as ae,l as ts,m as pe,n as Ke,o as He,p as ss,q as be}from"./chunks/chunk-BX5K34KY.js";import"./chunks/chunk-NUFRM6SI.js";import{a as Ge}from"./chunks/chunk-44UOCSGV.js";import{a as dt,b as P,d as fe,e as ht,f as V,g as re,h as Qt,i as rt,j as fo,k as Us,l as ho,m as po,n as mo}from"./chunks/chunk-KL7SL7ES.js";import{a as Dt,g as R,h as W,i as B,j as ln,k as ft,l as N,m as g,n as cn}from"./chunks/chunk-DEQBZDPB.js";var at=[{name:"echo",load:async()=>(await import("./chunks/echo-PC3TVS6B.js")).echoCommand},{name:"cat",load:async()=>(await import("./chunks/cat-L3YELBYM.js")).catCommand},{name:"printf",load:async()=>(await import("./chunks/printf-6XMXHDAE.js")).printfCommand},{name:"ls",load:async()=>(await import("./chunks/ls-7JNJXADY.js")).lsCommand},{name:"mkdir",load:async()=>(await import("./chunks/mkdir-NM4BUUUC.js")).mkdirCommand},{name:"rmdir",load:async()=>(await import("./chunks/rmdir-Z4ZRV32S.js")).rmdirCommand},{name:"touch",load:async()=>(await import("./chunks/touch-PC42E2OS.js")).touchCommand},{name:"rm",load:async()=>(await import("./chunks/rm-7ERREV4V.js")).rmCommand},{name:"cp",load:async()=>(await import("./chunks/cp-73PGBEPL.js")).cpCommand},{name:"mv",load:async()=>(await import("./chunks/mv-VDGF4VTT.js")).mvCommand},{name:"ln",load:async()=>(await import("./chunks/ln-SHI7B5FY.js")).lnCommand},{name:"chmod",load:async()=>(await import("./chunks/chmod-IJMA7OGQ.js")).chmodCommand},{name:"pwd",load:async()=>(await import("./chunks/pwd-KKLARPNT.js")).pwdCommand},{name:"readlink",load:async()=>(await import("./chunks/readlink-6XCFQQJH.js")).readlinkCommand},{name:"head",load:async()=>(await import("./chunks/head-EFRLGDOE.js")).headCommand},{name:"tail",load:async()=>(await import("./chunks/tail-TULUAGKH.js")).tailCommand},{name:"wc",load:async()=>(await import("./chunks/wc-U424DF7O.js")).wcCommand},{name:"stat",load:async()=>(await import("./chunks/stat-Z22X56GM.js")).statCommand},{name:"grep",load:async()=>(await import("./chunks/grep-7RC5DPOS.js")).grepCommand},{name:"fgrep",load:async()=>(await import("./chunks/grep-7RC5DPOS.js")).fgrepCommand},{name:"egrep",load:async()=>(await import("./chunks/grep-7RC5DPOS.js")).egrepCommand},{name:"rg",load:async()=>(await import("./chunks/rg-NIW2Q5SV.js")).rgCommand},{name:"sed",load:async()=>(await import("./chunks/sed-VLSHT4XR.js")).sedCommand},{name:"awk",load:async()=>(await import("./chunks/awk2-RAKURI6M.js")).awkCommand2},{name:"sort",load:async()=>(await import("./chunks/sort-KCG2A34N.js")).sortCommand},{name:"uniq",load:async()=>(await import("./chunks/uniq-7HD4DCMD.js")).uniqCommand},{name:"comm",load:async()=>(await import("./chunks/comm-X7VETT2U.js")).commCommand},{name:"cut",load:async()=>(await import("./chunks/cut-7I6UA67F.js")).cutCommand},{name:"paste",load:async()=>(await import("./chunks/paste-HD4NKO4X.js")).pasteCommand},{name:"tr",load:async()=>(await import("./chunks/tr-F7JZV44S.js")).trCommand},{name:"rev",load:async()=>(await import("./chunks/rev-NJ2ZPNAT.js")).rev},{name:"nl",load:async()=>(await import("./chunks/nl-PD7BPFUB.js")).nl},{name:"fold",load:async()=>(await import("./chunks/fold-5VRJN4CL.js")).fold},{name:"expand",load:async()=>(await import("./chunks/expand-OYPZZOZC.js")).expand},{name:"unexpand",load:async()=>(await import("./chunks/unexpand-KAIAW5TX.js")).unexpand},{name:"strings",load:async()=>(await import("./chunks/strings-EKWOLUFJ.js")).strings},{name:"split",load:async()=>(await import("./chunks/split-EVSSQ6VR.js")).split},{name:"column",load:async()=>(await import("./chunks/column-N7MHP5SX.js")).column},{name:"join",load:async()=>(await import("./chunks/join-36QXZEGR.js")).join},{name:"tee",load:async()=>(await import("./chunks/tee-DPV6AVMH.js")).teeCommand},{name:"find",load:async()=>(await import("./chunks/find-DESNHKKS.js")).findCommand},{name:"basename",load:async()=>(await import("./chunks/basename-Q7SIX77Q.js")).basenameCommand},{name:"dirname",load:async()=>(await import("./chunks/dirname-2TM4IG7K.js")).dirnameCommand},{name:"tree",load:async()=>(await import("./chunks/tree-SVRMFKLQ.js")).treeCommand},{name:"du",load:async()=>(await import("./chunks/du-KTUJVIGD.js")).duCommand},{name:"env",load:async()=>(await import("./chunks/env-MFQH47JH.js")).envCommand},{name:"printenv",load:async()=>(await import("./chunks/env-MFQH47JH.js")).printenvCommand},{name:"alias",load:async()=>(await import("./chunks/alias-CIPN5HGG.js")).aliasCommand},{name:"unalias",load:async()=>(await import("./chunks/alias-CIPN5HGG.js")).unaliasCommand},{name:"history",load:async()=>(await import("./chunks/history-J3C24VIU.js")).historyCommand},{name:"xargs",load:async()=>(await import("./chunks/xargs-SWPLSROG.js")).xargsCommand},{name:"true",load:async()=>(await import("./chunks/true-T4XKISHJ.js")).trueCommand},{name:"false",load:async()=>(await import("./chunks/true-T4XKISHJ.js")).falseCommand},{name:"clear",load:async()=>(await import("./chunks/clear-J6WBUIX6.js")).clearCommand},{name:"yes",load:async()=>(await import("./chunks/yes-5BWAW2VY.js")).yesCommand},{name:"bash",load:async()=>(await import("./chunks/bash-HKSQMKKV.js")).bashCommand},{name:"sh",load:async()=>(await import("./chunks/bash-HKSQMKKV.js")).shCommand},{name:"jq",load:async()=>(await import("./chunks/jq-5KN27BBY.js")).jqCommand},{name:"base64",load:async()=>(await import("./chunks/base64-4GSA7KNI.js")).base64Command},{name:"diff",load:async()=>(await import("./chunks/diff-O5NFSBS5.js")).diffCommand},{name:"date",load:async()=>(await import("./chunks/date-MOZRIQXR.js")).dateCommand},{name:"sleep",load:async()=>(await import("./chunks/sleep-SAQIXUFW.js")).sleepCommand},{name:"timeout",load:async()=>(await import("./chunks/timeout-YRSN3MWF.js")).timeoutCommand},{name:"time",load:async()=>(await import("./chunks/time-RXWT5RNC.js")).timeCommand},{name:"seq",load:async()=>(await import("./chunks/seq-RCBD3IYO.js")).seqCommand},{name:"expr",load:async()=>(await import("./chunks/expr-4PIUWNB7.js")).exprCommand},{name:"md5sum",load:async()=>(await import("./chunks/md5sum-J7XPNTQZ.js")).md5sumCommand},{name:"sha1sum",load:async()=>(await import("./chunks/sha1sum-RMRQ75AE.js")).sha1sumCommand},{name:"sha256sum",load:async()=>(await import("./chunks/sha256sum-TGW5BMJR.js")).sha256sumCommand},{name:"file",load:async()=>(await import("./chunks/file-DZRW6GNH.js")).fileCommand},{name:"html-to-markdown",load:async()=>(await import("./chunks/html-to-markdown-TFBDHAZZ.js")).htmlToMarkdownCommand},{name:"help",load:async()=>(await import("./chunks/help-3XYFOR43.js")).helpCommand},{name:"which",load:async()=>(await import("./chunks/which-OY73BBGP.js")).whichCommand},{name:"tac",load:async()=>(await import("./chunks/tac-RSIVIUEI.js")).tac},{name:"hostname",load:async()=>(await import("./chunks/hostname-D54LLZ5I.js")).hostname},{name:"whoami",load:async()=>(await import("./chunks/whoami-KUZQQOVR.js")).whoami},{name:"od",load:async()=>(await import("./chunks/od-D6RO3GJE.js")).od},{name:"gzip",load:async()=>(await import("./chunks/gzip-WH2JWAWT.js")).gzipCommand},{name:"gunzip",load:async()=>(await import("./chunks/gzip-WH2JWAWT.js")).gunzipCommand},{name:"zcat",load:async()=>(await import("./chunks/gzip-WH2JWAWT.js")).zcatCommand}];(typeof __BROWSER__>"u"||!__BROWSER__)&&(at.push({name:"tar",load:async()=>(await import("./chunks/tar-KQPQPRTZ.js")).tarCommand}),at.push({name:"yq",load:async()=>(await import("./chunks/yq-URX6MHLP.js")).yqCommand}),at.push({name:"xan",load:async()=>(await import("./chunks/xan-N66EXZFT.js")).xanCommand}),at.push({name:"sqlite3",load:async()=>(await import("./chunks/sqlite3-M6BXLMYI.js")).sqlite3Command}));var as=[];(typeof __BROWSER__>"u"||!__BROWSER__)&&(as.push({name:"python3",load:async()=>(await import("./chunks/python3-KPG6SQQV.js")).python3Command}),as.push({name:"python",load:async()=>(await import("./chunks/python3-KPG6SQQV.js")).pythonCommand}));var _n=[{name:"curl",load:async()=>(await import("./chunks/curl-MGBYKD7U.js")).curlCommand}],xn=new Map;function Qs(e){return{name:e.name,async execute(t,s){let r=xn.get(e.name);if(r||(r=await e.load(),xn.set(e.name,r)),s.coverage&&(typeof __BROWSER__>"u"||!__BROWSER__)){let{emitFlagCoverage:n}=await import("./chunks/flag-coverage-QMBN7WOW.js"),{decodeArgs:i}=await import("./chunks/bytes-JUNATFIO.js");n(s.coverage,e.name,i(t))}return r.execute(t,s)}}}function yo(){return at.map(e=>e.name)}function go(){return _n.map(e=>e.name)}function Nn(e){return(e?at.filter(s=>e.includes(s.name)):at).map(Qs)}function On(){return _n.map(Qs)}function wo(){return as.map(e=>e.name)}function Dn(){return as.map(Qs)}function In(e){return"load"in e&&typeof e.load=="function"}function vo(e,t){return{name:e,async execute(s,r){let n={...r,env:cn(r.env)},i=await t(ft(s),n);return typeof i.stdout=="string"?{stdout:V(i.stdout),stderr:V(i.stderr),exitCode:i.exitCode}:i}}}function Rn(e){let t=null;return{name:e.name,async execute(s,r){return t||(t=await e.load()),t.execute(s,r)}}}var bo=new TextEncoder;function Eo(e){return typeof e=="object"&&e!==null&&typeof e.getReader=="function"}function So(e,t){if(e instanceof Uint8Array)return e;if(t==="base64")return Uint8Array.from(atob(e),s=>s.charCodeAt(0));if(t==="hex"){let s=new Uint8Array(e.length/2);for(let r=0;r<e.length;r+=2)s[r/2]=parseInt(e.slice(r,r+2),16);return s}if(t==="binary"||t==="latin1"){if(e.length<=65536)return Uint8Array.from(e,n=>n.charCodeAt(0));let r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return r}return bo.encode(e)}function Ln(e){if(e.length===0)return[];if(e.length<=dt)return[e];let t=[];for(let s=0;s<e.length;s+=dt)t.push(e.subarray(s,Math.min(s+dt,e.length)));return t}function mt(e,t){let s=So(e,t);return{chunks:Ln(s),size:s.length}}async function Ze(e,t){if(Eo(e)){let s=[],r=0;for await(let n of Us(e))if(n.length<=dt)s.push(n),r+=n.length;else for(let i of Ln(n))s.push(i),r+=i.length;return{chunks:s,size:r}}return mt(e,t)}function ls(e,t){if(t==="base64")return btoa(dn(Mn(e)));if(t==="hex"){let n="";for(let i of e)for(let a=0;a<i.length;a++)n+=i[a].toString(16).padStart(2,"0");return n}if(t==="binary"||t==="latin1"){if(typeof Buffer<"u")return Buffer.from(Mn(e)).toString(t);let n=65536,i="";for(let a of e)if(a.length<=n)i+=String.fromCharCode(...a);else for(let o=0;o<a.length;o+=n){let l=a.subarray(o,o+n);i+=String.fromCharCode(...l)}return i}let s=new TextDecoder,r="";for(let n of e)n.length>0&&(r+=s.decode(n,{stream:!0}));return r+=s.decode(),r}function Mn(e){let t=0;for(let n of e)t+=n.length;if(t===0)return new Uint8Array(0);if(e.length===1)return e[0];let s=new Uint8Array(t),r=0;for(let n of e)s.set(n,r),r+=n.length;return s}function _e(e){if(e!=null)return typeof e=="string"?e:e.encoding??void 0}function yt(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 cs(e,t,s,r){if(s>=t||r===0)return new Uint8Array(0);let n=Math.min(s+r,t),i=n-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<n){let f=Math.max(0,s-l),d=Math.min(c.length,n-l),p=c.subarray(f,d);a.set(p,o),o+=p.length}l=u}return a}function $o(e){return typeof e=="object"&&e!==null&&!(e instanceof Uint8Array)&&!(e instanceof ReadableStream)&&"content"in e}function ue(e,t){if(e.includes("\0"))throw new Error(`ENOENT: path contains null byte, ${t} '${e}'`)}var Xe=class{data=new Map;constructor(t){if(this.data.set("/",{type:"directory",mode:493,mtime:new Date}),t)for(let[s,r]of Object.entries(t))if($o(r)){if(r.content instanceof ReadableStream)throw new Error("InMemoryFs: streams not supported in InitialFiles; use writeFile() after construction");this.writeFileSync(s,r.content,void 0,{mode:r.mode,mtime:r.mtime})}else{if(r instanceof ReadableStream)throw new Error("InMemoryFs: streams not supported in InitialFiles; use writeFile() after construction");this.writeFileSync(s,r)}}normalizePath(t){if(!t||t==="/")return"/";let s=t.endsWith("/")&&t!=="/"?t.slice(0,-1):t;s.startsWith("/")||(s=`/${s}`);let r=s.split("/").filter(i=>i&&i!=="."),n=[];for(let i of r)i===".."?n.pop():n.push(i);return`/${n.join("/")}`||"/"}dirname(t){let s=this.normalizePath(t);if(s==="/")return"/";let r=s.lastIndexOf("/");return r===0?"/":s.slice(0,r)}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,r,n){ue(t,"write");let i=this.normalizePath(t);this.ensureParentDirs(i);let a=_e(r),{chunks:o,size:l}=mt(s,a);this.data.set(i,{type:"file",chunks:o,size:l,mode:n?.mode??420,mtime:n?.mtime??new Date})}async readFile(t){ue(t,"open");let s=this.resolvePathWithSymlinks(t),r=this.data.get(s);if(!r)throw new Error(`ENOENT: no such file or directory, open '${t}'`);if(r.type!=="file")throw new Error(`EISDIR: illegal operation on a directory, read '${t}'`);return ht(r.chunks)}async readRange(t,s,r){yt(s,r),ue(t,"open");let n=this.resolvePathWithSymlinks(t),i=this.data.get(n);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 cs(i.chunks,i.size,s,r)}async readFileText(t,s){ue(t,"open");let r=this.resolvePathWithSymlinks(t),n=this.data.get(r);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}'`);let i=_e(s);return ls(n.chunks,i)}async writeFile(t,s,r){ue(t,"write");let n=this.normalizePath(t);this.ensureParentDirs(n);let i=_e(r),{chunks:a,size:o}=await Ze(s,i);this.data.set(n,{type:"file",chunks:a,size:o,mode:420,mtime:new Date})}async appendFile(t,s,r){ue(t,"append");let n=this.normalizePath(t),i=this.data.get(n);if(i&&i.type==="directory")throw new Error(`EISDIR: illegal operation on a directory, write '${t}'`);let a=_e(r),{chunks:o,size:l}=await Ze(s,a);i?.type==="file"?this.data.set(n,{type:"file",chunks:[...i.chunks,...o],size:i.size+l,mode:i.mode,mtime:new Date}):(this.ensureParentDirs(n),this.data.set(n,{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){ue(t,"stat");let s=this.resolvePathWithSymlinks(t),r=this.data.get(s);if(!r)throw new Error(`ENOENT: no such file or directory, stat '${t}'`);let n=0;return r.type==="file"&&(n=r.size),{isFile:r.type==="file",isDirectory:r.type==="directory",isSymbolicLink:!1,mode:r.mode,size:n,mtime:r.mtime||new Date}}async lstat(t){ue(t,"lstat");let s=this.resolveIntermediateSymlinks(t),r=this.data.get(s);if(!r)throw new Error(`ENOENT: no such file or directory, lstat '${t}'`);if(r.type==="symlink")return{isFile:!1,isDirectory:!1,isSymbolicLink:!0,mode:r.mode,size:r.target.length,mtime:r.mtime||new Date};let n=0;return r.type==="file"&&(n=r.size),{isFile:r.type==="file",isDirectory:r.type==="directory",isSymbolicLink:!1,mode:r.mode,size:n,mtime:r.mtime||new Date}}resolveSymlink(t,s){if(s.startsWith("/"))return this.normalizePath(s);let r=this.dirname(t);return this.normalizePath(r==="/"?`/${s}`:`${r}/${s}`)}resolveIntermediateSymlinks(t){let s=this.normalizePath(t);if(s==="/")return"/";let r=s.slice(1).split("/");if(r.length<=1)return s;let n="",i=new Set;for(let a=0;a<r.length-1;a++){let o=r[a];n=`${n}/${o}`;let l=this.data.get(n),c=0,u=40;for(;l&&l.type==="symlink"&&c<u;){if(i.has(n))throw new Error(`ELOOP: too many levels of symbolic links, lstat '${t}'`);i.add(n),n=this.resolveSymlink(n,l.target),l=this.data.get(n),c++}if(c>=u)throw new Error(`ELOOP: too many levels of symbolic links, lstat '${t}'`)}return`${n}/${r[r.length-1]}`}resolvePathWithSymlinks(t){let s=this.normalizePath(t);if(s==="/")return"/";let r=s.slice(1).split("/"),n="",i=new Set;for(let a of r){n=`${n}/${a}`;let o=this.data.get(n),l=0,c=40;for(;o&&o.type==="symlink"&&l<c;){if(i.has(n))throw new Error(`ELOOP: too many levels of symbolic links, open '${t}'`);i.add(n),n=this.resolveSymlink(n,o.target),o=this.data.get(n),l++}if(l>=c)throw new Error(`ELOOP: too many levels of symbolic links, open '${t}'`)}return n}async mkdir(t,s){this.mkdirSync(t,s)}mkdirSync(t,s){ue(t,"mkdir");let r=this.normalizePath(t);if(this.data.has(r)){if(this.data.get(r)?.type==="file")throw new Error(`EEXIST: file already exists, mkdir '${t}'`);if(!s?.recursive)throw new Error(`EEXIST: directory already exists, mkdir '${t}'`);return}let n=this.dirname(r);if(n!=="/"&&!this.data.has(n))if(s?.recursive)this.mkdirSync(n,{recursive:!0});else throw new Error(`ENOENT: no such file or directory, mkdir '${t}'`);this.data.set(r,{type:"directory",mode:493,mtime:new Date})}async readdir(t){return(await this.readdirWithFileTypes(t)).map(r=>r.name)}async readdirWithFileTypes(t){ue(t,"scandir");let s=this.normalizePath(t),r=this.data.get(s);if(!r)throw new Error(`ENOENT: no such file or directory, scandir '${t}'`);let n=new Set;for(;r&&r.type==="symlink";){if(n.has(s))throw new Error(`ELOOP: too many levels of symbolic links, scandir '${t}'`);n.add(s),s=this.resolveSymlink(s,r.target),r=this.data.get(s)}if(!r)throw new Error(`ENOENT: no such file or directory, scandir '${t}'`);if(r.type!=="directory")throw new Error(`ENOTDIR: not a directory, scandir '${t}'`);let i=s==="/"?"/":`${s}/`,a=new Map;for(let[o,l]of this.data.entries())if(o!==s&&o.startsWith(i)){let c=o.slice(i.length),u=c.split("/")[0];u&&!c.includes("/",u.length)&&!a.has(u)&&a.set(u,{name:u,isFile:l.type==="file",isDirectory:l.type==="directory",isSymbolicLink:l.type==="symlink"})}return Array.from(a.values()).sort((o,l)=>o.name<l.name?-1:o.name>l.name?1:0)}async rm(t,s){ue(t,"rm");let r=this.normalizePath(t),n=this.data.get(r);if(!n){if(s?.force)return;throw new Error(`ENOENT: no such file or directory, rm '${t}'`)}if(n.type==="directory"){let i=await this.readdir(r);if(i.length>0){if(!s?.recursive)throw new Error(`ENOTEMPTY: directory not empty, rm '${t}'`);for(let a of i){let o=r==="/"?`/${a}`:`${r}/${a}`;await this.rm(o,s)}}}this.data.delete(r)}async cp(t,s,r){ue(t,"cp"),ue(s,"cp");let n=this.normalizePath(t),i=this.normalizePath(s),a=this.data.get(n);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(!r?.recursive)throw new Error(`EISDIR: is a directory, cp '${t}'`);await this.mkdir(i,{recursive:!0});let o=await this.readdir(n);for(let l of o){let c=n==="/"?`/${l}`:`${n}/${l}`,u=i==="/"?`/${l}`:`${i}/${l}`;await this.cp(c,u,r)}}}async mv(t,s){await this.cp(t,s,{recursive:!0}),await this.rm(t,{recursive:!0})}getAllPaths(){return Array.from(this.data.keys())}resolvePath(t,s){if(s.startsWith("/"))return this.normalizePath(s);let r=t==="/"?`/${s}`:`${t}/${s}`;return this.normalizePath(r)}async chmod(t,s){ue(t,"chmod");let r=this.normalizePath(t),n=this.data.get(r);if(!n)throw new Error(`ENOENT: no such file or directory, chmod '${t}'`);n.mode=s}async symlink(t,s){ue(s,"symlink");let r=this.normalizePath(s);if(this.data.has(r))throw new Error(`EEXIST: file already exists, symlink '${s}'`);this.ensureParentDirs(r),this.data.set(r,{type:"symlink",target:t,mode:511,mtime:new Date})}async link(t,s){ue(t,"link"),ue(s,"link");let r=this.normalizePath(t),n=this.normalizePath(s),i=this.data.get(r);if(!i)throw new Error(`ENOENT: no such file or directory, link '${t}'`);if(i.type!=="file")throw new Error(`EPERM: operation not permitted, link '${t}'`);if(this.data.has(n))throw new Error(`EEXIST: file already exists, link '${s}'`);this.ensureParentDirs(n),this.data.set(n,{type:"file",chunks:[...i.chunks],size:i.size,mode:i.mode,mtime:i.mtime})}async readlink(t){ue(t,"readlink");let s=this.normalizePath(t),r=this.data.get(s);if(!r)throw new Error(`ENOENT: no such file or directory, readlink '${t}'`);if(r.type!=="symlink")throw new Error(`EINVAL: invalid argument, readlink '${t}'`);return r.target}async realpath(t){ue(t,"realpath");let s=this.resolvePathWithSymlinks(t);if(!this.data.has(s))throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);return s}async utimes(t,s,r){ue(t,"utimes");let n=this.normalizePath(t),i=this.resolvePathWithSymlinks(n),a=this.data.get(i);if(!a)throw new Error(`ENOENT: no such file or directory, utimes '${t}'`);a.mtime=r}};function Po(e){let t=e;return typeof t.mkdirSync=="function"&&typeof t.writeFileSync=="function"}function Ao(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 Co(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 ko(e){e.mkdirSync("/proc/self/fd",{recursive:!0}),e.writeFileSync("/proc/version",`${hn}
2
2
  `),e.writeFileSync("/proc/self/exe","/bin/bash"),e.writeFileSync("/proc/self/cmdline","bash\0"),e.writeFileSync("/proc/self/comm",`bash
3
- `),e.writeFileSync("/proc/self/status",pn()),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 Fn(e,t){Po(e)&&(Co(e,t),Ao(e),ko(e))}var xo=["allexport","errexit","noglob","noclobber","noexec","nounset","pipefail","posix","verbose","xtrace"],_o=["braceexpand","hashall","interactive-comments"];function Qs(e){let t=[],s=[..._o.map(r=>({name:r,enabled:!0})),...xo.map(r=>({name:r,enabled:e[r]}))].sort((r,n)=>r.name.localeCompare(n.name));for(let r of s)r.enabled&&t.push(r.name);return t.join(":")}function gt(e){g(e.state.env,"SHELLOPTS",Qs(e.state.options))}var To=["dotglob","expand_aliases","extglob","failglob","globskipdots","globstar","lastpipe","nocaseglob","nocasematch","nullglob","xpg_echo"];function er(e){let t=[];for(let s of To)e[s]&&t.push(s);return t.join(":")}function tr(e){g(e.state.env,"BASHOPTS",er(e.state.shoptOptions))}var No="BASH_ALIAS_";function Wn(e){return e.parts.length!==1?!1:e.parts[0].type==="Literal"}function Vn(e){if(e.parts.length!==1)return null;let t=e.parts[0];return t.type==="Literal"?t.value:null}function zn(e,t){let s=e.env.get(`${No}${t}`);return s!==void 0?B(s):void 0}function sr(e,t,s){if(!t.name||!Wn(t.name))return t;let r=Vn(t.name);if(!r)return t;let n=zn(e,r);if(!n||s.has(r))return t;try{s.add(r);let i=new X,a=n,o=n.endsWith(" ");if(!o)for(let f of t.args){let d=Bn(f);a+=` ${d}`}let l;try{l=i.parse(a)}catch(f){if(f instanceof ts)throw f;return t}if(l.statements.length!==1||l.statements[0].pipelines.length!==1||l.statements[0].pipelines[0].commands.length!==1)return jn(t,n);let u=l.statements[0].pipelines[0].commands[0];if(u.type!=="SimpleCommand")return jn(t,n);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(Wn(f)){let d=Vn(f);if(d&&zn(e,d)){let p={type:"SimpleCommand",name:f,args:c.args.slice(1),assignments:[],redirections:[]},m=sr(e,p,s);m!==p&&(c={...c,name:m.name,args:[...m.args]})}}}return c}catch(i){throw s.delete(r),i}}function jn(e,t){let s=t;for(let a of e.args){let o=Bn(a);s+=` ${o}`}let r=new X,n=r.parseWordFromString("eval",!1,!1),i=r.parseWordFromString(`'${s.replace(/'/g,"'\\''")}'`,!1,!1);return{type:"SimpleCommand",name:n,args:[i],assignments:e.assignments,redirections:e.redirections,line:e.line}}function Bn(e){let t="";for(let s of e.parts)switch(s.type){case"Literal":t+=s.value.replace(/([\s"'$`\\*?[\]{}()<>|&;#!])/g,"\\$1");break;case"SingleQuoted":t+=`'${s.value}'`;break;case"DoubleQuoted":t+=`"${s.parts.map(r=>r.type==="Literal"?r.value:`$${r.type}`).join("")}"`;break;case"ParameterExpansion":t+=`\${${s.parameter}}`;break;case"CommandSubstitution":t+="$(...)";break;case"ArithmeticExpansion":t+=`$((${s.expression}))`;break;case"Glob":t+=s.pattern;break;default:break}return t}async function Un(e,t){let s=t.parts.map(c=>c.type==="Literal"?c.value:"\0").join(""),r=s.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\(/);if(!r||!s.endsWith(")"))return null;let n=r[1],i=[],a=!1,o="",l=!1;for(let 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+=rs({type:"Word",parts:[c]});else{(o||l)&&(i.push(o),o="",l=!1);let d=await je(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`${n}=(${u.join(" ")})`}async function Gn(e,t){let s=-1,r=-1,n=!1;for(let h=0;h<t.parts.length;h++){let b=t.parts[h];if(b.type==="Literal"){let E=b.value.indexOf("+=");if(E!==-1){let y=b.value.slice(0,E);if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(y)){s=h,r=E,n=!0;break}if(/^[a-zA-Z_][a-zA-Z0-9_]*\[[^\]]+\]$/.test(y)){s=h,r=E,n=!0;break}}let $=b.value.indexOf("=");if($!==-1&&($===0||b.value[$-1]!=="+")){let y=b.value.slice(0,$);if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(y)||/^[a-zA-Z_][a-zA-Z0-9_]*\[[^\]]+\]$/.test(y)){s=h,r=$;break}}}}if(s===-1)return null;let i=t.parts.slice(0,s),a=t.parts[s];if(a.type!=="Literal")return null;let o=n?2:1,l=a.value.slice(0,r),u=a.value.slice(r+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}${n?"+=":"="}${p}`}var Oo=["tar","yq","xan","sqlite3","python3","python"];function Hn(e){return Oo.includes(e)}function U(){return{stdout:S(),stderr:S(),exitCode:0}}var wt={get stdout(){return S()},get stderr(){return S()},exitCode:0};function Ne(e=S()){return{stdout:e,stderr:S(),exitCode:0}}function H(e){return{stdout:V(e),stderr:S(),exitCode:0}}function P(e,t=1){return{stdout:S(),stderr:V(e),exitCode:t}}function F(e,t,s){return{stdout:e instanceof Uint8Array?fe(e):e,stderr:t instanceof Uint8Array?fe(t):t,exitCode:s}}function le(e){return{stdout:S(),stderr:S(),exitCode:e?0:1}}function Me(e,t){throw new ae(e,t)}async function rr(e,t){if(e.state.loopDepth===0){if(e.state.parentHasLoopContext)throw new Ge;return U()}if(t.length>1)throw await G(e,2,`bash: break: too many arguments
4
- `,!0),new q(1);let s=1;if(t.length>0){let r=Number.parseInt(t[0],10);if(Number.isNaN(r)||r<1)throw await G(e,2,`bash: break: ${t[0]}: numeric argument required
5
- `,!0),new q(128);s=r}throw new Ce(s)}async function nr(e,t){let s,r=!1,n=!1,i=0;for(;i<t.length;)if(t[i]==="--"){i++;break}else if(t[i]==="-L")n=!1,i++;else if(t[i]==="-P")n=!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,r=!0):s=a[0],!s.startsWith("/")&&!s.startsWith("./")&&!s.startsWith("../")&&s!=="."&&s!==".."){let f=e.state.env.get("CDPATH");if(f){let d=B(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,r=!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 P(`bash: cd: ${s}: Not a directory
6
- `)}catch{return P(`bash: cd: ${s}: No such file or directory
7
- `)}}let c=u||"/";if(n)try{c=await e.fs.realpath(c)}catch{}return e.state.previousDir=e.state.cwd,e.state.cwd=c,g(e.state.env,"PWD",e.state.cwd),g(e.state.env,"OLDPWD",e.state.previousDir),r?H(`${c}
8
- `):Ne()}function ir(e,t){return e.fs.resolvePath(e.state.cwd,t)}var Do=["-e","-a","-f","-d","-r","-w","-x","-s","-L","-h","-k","-g","-u","-G","-O","-b","-c","-p","-S","-t","-N"];function ls(e){return Do.includes(e)}async function cs(e,t,s){let r=ir(e,s);switch(t){case"-e":case"-a":return e.fs.exists(r);case"-f":return await e.fs.exists(r)?(await e.fs.stat(r)).isFile:!1;case"-d":return await e.fs.exists(r)?(await e.fs.stat(r)).isDirectory:!1;case"-r":return await e.fs.exists(r)?((await e.fs.stat(r)).mode&256)!==0:!1;case"-w":return await e.fs.exists(r)?((await e.fs.stat(r)).mode&128)!==0:!1;case"-x":return await e.fs.exists(r)?((await e.fs.stat(r)).mode&64)!==0:!1;case"-s":return await e.fs.exists(r)?(await e.fs.stat(r)).size>0:!1;case"-L":case"-h":try{return(await e.fs.lstat(r)).isSymbolicLink}catch{return!1}case"-k":return await e.fs.exists(r)?((await e.fs.stat(r)).mode&512)!==0:!1;case"-g":return await e.fs.exists(r)?((await e.fs.stat(r)).mode&1024)!==0:!1;case"-u":return await e.fs.exists(r)?((await e.fs.stat(r)).mode&2048)!==0:!1;case"-G":case"-O":return e.fs.exists(r);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=>r===i||r.endsWith(i));case"-p":return!1;case"-S":return!1;case"-t":return!1;case"-N":return e.fs.exists(r);default:return!1}}var Io=["-nt","-ot","-ef"];function us(e){return Io.includes(e)}async function fs(e,t,s,r){let n=ir(e,s),i=ir(e,r);switch(t){case"-nt":try{let a=await e.fs.stat(n),o=await e.fs.stat(i);return a.mtime>o.mtime}catch{return!1}case"-ot":try{let a=await e.fs.stat(n),o=await e.fs.stat(i);return a.mtime<o.mtime}catch{return!1}case"-ef":try{if(!await e.fs.exists(n)||!await e.fs.exists(i))return!1;let a=e.fs.resolvePath(e.state.cwd,n),o=e.fs.resolvePath(e.state.cwd,i);return a===o}catch{return!1}default:return!1}}var Ro=new Set(["-eq","-ne","-lt","-le","-gt","-ge"]);function ds(e){return Ro.has(e)}function hs(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 Vt(e){return e==="="||e==="=="||e==="!="}function ps(e,t,s,r=!1,n=!1,i=!1){if(r){let o=vt(t,s,n,i);return e==="!="?!o:o}if(n){let o=t.toLowerCase()===s.toLowerCase();return e==="!="?!o:o}let a=t===s;return e==="!="?!a:a}var Mo=new Set(["-z","-n"]);function ms(e){return Mo.has(e)}function ys(e,t){switch(e){case"-z":return t==="";case"-n":return t!==""}}async function gs(e,t){let s=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(s){let r=s[1],n=s[2];if(e.state.associativeArrays?.has(r)){let o=n;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(`${r}_${o}`)}let a;try{let o=new X,l=ce(o,n);a=await ee(e,l.expression)}catch{if(/^-?\d+$/.test(n))a=Number.parseInt(n,10);else{let o=T(e.state.env,n);a=o?Number.parseInt(o,10):0}}if(a<0){let o=me(e,r),l=e.state.currentLine;if(o.length===0)return await G(e,2,`bash: line ${l}: ${r}: bad array subscript
9
- `),!1;if(a=Math.max(...o)+1+a,a<0)return await G(e,2,`bash: line ${l}: ${r}: bad array subscript
10
- `),!1}return e.state.env.has(`${r}_${a}`)}return e.state.env.has(t)?!0:e.state.associativeArrays?.has(t)?et(e,t).length>0:me(e,t).length>0}async function tt(e,t){switch(t.type){case"CondBinary":{let s=await z(e,t.left),r=t.right.parts.length>0&&t.right.parts.every(i=>i.type==="SingleQuoted"||i.type==="DoubleQuoted"||i.type==="Escaped"&&t.operator!=="=~"),n;if(t.operator==="=~")if(r){let i=await z(e,t.right);n=$n(i)}else n=await Cn(e,t.right);else Vt(t.operator)&&!r?n=await An(e,t.right):n=await z(e,t.right);if(Vt(t.operator)){let i=e.state.shoptOptions.nocasematch;return ps(t.operator,s,n,!r,i,!0)}if(ds(t.operator))return hs(t.operator,await Zn(e,s),await Zn(e,n));if(us(t.operator))return fs(e,t.operator,s,n);switch(t.operator){case"=~":try{let i=e.state.shoptOptions.nocasematch,a=Vo(n),l=Rt(a,i?"i":"").match(s);if(Ve(e,"BASH_REMATCH"),l)for(let u=0;u<l.length;u++)g(e.state.env,`BASH_REMATCH_${u}`,l[u]||"");return l!==null}catch{throw new Error("syntax error in regular expression")}case"<":return s<n;case">":return s>n;default:return!1}}case"CondUnary":{let s=await z(e,t.operand);return ls(t.operator)?cs(e,t.operator,s):ms(t.operator)?ys(t.operator,s):t.operator==="-v"?await gs(e,s):t.operator==="-o"?ar(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 tt(e,t.operand);case"CondAnd":return await tt(e,t.left)?await tt(e,t.right):!1;case"CondOr":return await tt(e,t.left)?!0:await tt(e,t.right);case"CondGroup":return await tt(e,t.expression);case"CondWord":return await z(e,t.word)!=="";default:return!1}}async function zt(e,t){if(t.length===0)return F(R,R,1);if(t.length===1)return le(!!t[0]);if(t.length===2){let r=t[0],n=t[1];return r==="("?P(`test: '(' without matching ')'
11
- `,2):ls(r)?le(await cs(e,r,n)):ms(r)?le(ys(r,n)):r==="!"?le(!n):r==="-v"?le(await gs(e,n)):r==="-o"?le(ar(e,n)):r==="="||r==="=="||r==="!="||r==="<"||r===">"||r==="-eq"||r==="-ne"||r==="-lt"||r==="-le"||r==="-gt"||r==="-ge"||r==="-nt"||r==="-ot"||r==="-ef"?P(`test: ${r}: unary operator expected
12
- `,2):F(R,R,1)}if(t.length===3){let r=t[0],n=t[1],i=t[2];if(Vt(n))return le(ps(n,r,i));if(ds(n)){let a=ws(r),o=ws(i);return!a.valid||!o.valid?F(R,R,2):le(hs(n,a.value,o.value))}if(us(n))return le(await fs(e,n,r,i));switch(n){case"-a":return le(r!==""&&i!=="");case"-o":return le(r!==""||i!=="");case">":return le(r>i);case"<":return le(r<i)}if(r==="!"){let a=await zt(e,[n,i]);return F(R,a.stderr,a.exitCode===0?1:a.exitCode===1?0:a.exitCode)}if(r==="("&&i===")")return le(n!=="")}if(t.length===4){if(t[0]==="!"){let r=await zt(e,t.slice(1));return F(R,r.stderr,r.exitCode===0?1:r.exitCode===1?0:r.exitCode)}if(t[0]==="("&&t[3]===")")return zt(e,[t[1],t[2]])}let s=await Jn(e,t,0);return s.pos<t.length?P(`test: too many arguments
13
- `,2):le(s.value)}async function Jn(e,t,s){return Lo(e,t,s)}async function Lo(e,t,s){let{value:r,pos:n}=await qn(e,t,s);for(;t[n]==="-o";){let i=await qn(e,t,n+1);r=r||i.value,n=i.pos}return{value:r,pos:n}}async function qn(e,t,s){let{value:r,pos:n}=await or(e,t,s);for(;t[n]==="-a";){let i=await or(e,t,n+1);r=r&&i.value,n=i.pos}return{value:r,pos:n}}async function or(e,t,s){if(t[s]==="!"){let{value:r,pos:n}=await or(e,t,s+1);return{value:!r,pos:n}}return Fo(e,t,s)}async function Fo(e,t,s){let r=t[s];if(r==="("){let{value:i,pos:a}=await Jn(e,t,s+1);return{value:i,pos:t[a]===")"?a+1:a}}let n=t[s+1];if(Vt(n)){let i=r,a=t[s+2]??"";return{value:ps(n,i,a),pos:s+3}}if(ds(n)){let i=ws(r),a=ws(t[s+2]??"0");return!i.valid||!a.valid?{value:!1,pos:s+3}:{value:hs(n,i.value,a.value),pos:s+3}}if(us(n)){let i=r,a=t[s+2]??"";return{value:await fs(e,n,i,a),pos:s+3}}if(ls(r)){let i=t[s+1]??"";return{value:await cs(e,r,i),pos:s+2}}if(ms(r)){let i=t[s+1]??"";return{value:ys(r,i),pos:s+2}}if(r==="-v"){let i=t[s+1]??"";return{value:await gs(e,i),pos:s+2}}if(r==="-o"){let i=t[s+1]??"";return{value:ar(e,i),pos:s+2}}return{value:r!==void 0&&r!=="",pos:s+1}}function vt(e,t,s=!1,r=!1){let n=`^${Kn(t,r)}$`;return Rt(n,s?"is":"s").test(e)}function Kn(e,t){let s="";for(let r=0;r<e.length;r++){let n=e[r];if(t&&(n==="@"||n==="*"||n==="+"||n==="?"||n==="!")&&r+1<e.length&&e[r+1]==="("){let i=Yn(e,r+1);if(i!==-1){let a=e.slice(r+2,i),o=Qn(a),l=o.map(c=>Kn(c,t)),u=l.length>0?l.join("|"):"(?:)";if(n==="@")s+=`(?:${u})`;else if(n==="*")s+=`(?:${u})*`;else if(n==="+")s+=`(?:${u})+`;else if(n==="?")s+=`(?:${u})?`;else if(n==="!")if(i<e.length-1){let f=o.map(p=>ei(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})$).*`;r=i;continue}}if(n==="\\")if(r+1<e.length){let i=e[r+1];/[\\^$.|+(){}[\]*?]/.test(i)?s+=`\\${i}`:s+=i,r++}else s+="\\\\";else if(n==="*")s+=".*";else if(n==="?")s+=".";else if(n==="["){let i=e.indexOf("]",r+1);i!==-1?(s+=e.slice(r,i+1),r=i):s+="\\["}else/[\\^$.|+(){}]/.test(n)?s+=`\\${n}`:s+=n}return s}function Yn(e,t){let s=1,r=t+1;for(;r<e.length&&s>0;){let n=e[r];if(n==="\\"){r+=2;continue}if(n==="(")s++;else if(n===")"&&(s--,s===0))return r;r++}return-1}function Qn(e){let t=[],s="",r=0,n=0;for(;n<e.length;){let i=e[n];if(i==="\\"){s+=i,n+1<e.length?(s+=e[n+1],n+=2):n++;continue}i==="("?(r++,s+=i):i===")"?(r--,s+=i):i==="|"&&r===0?(t.push(s),s=""):s+=i,n++}return t.push(s),t}function ei(e,t){let s=0,r=0;for(;r<e.length;){let n=e[r];if(t&&(n==="@"||n==="*"||n==="+"||n==="?"||n==="!")&&r+1<e.length&&e[r+1]==="("){let i=Yn(e,r+1);if(i!==-1){if(n==="@"){let a=e.slice(r+2,i),l=Qn(a).map(u=>ei(u,t));if(l.every(u=>u!==null)&&l.every(u=>u===l[0])){s+=l[0],r=i+1;continue}return null}return null}}if(n==="*")return null;if(n==="?"){s+=1,r++;continue}if(n==="["){let i=e.indexOf("]",r+1);if(i!==-1){s+=1,r=i+1;continue}s+=1,r++;continue}if(n==="\\"){s+=1,r+=2;continue}s+=1,r++}return s}function ar(e,t){let r=new Map([["errexit",()=>e.state.options.errexit===!0],["nounset",()=>e.state.options.nounset===!0],["pipefail",()=>e.state.options.pipefail===!0],["xtrace",()=>e.state.options.xtrace===!0],["e",()=>e.state.options.errexit===!0],["u",()=>e.state.options.nounset===!0],["x",()=>e.state.options.xtrace===!0]]).get(t);return r?r():!1}async function Zn(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 Xn(t);try{let s=new X,r=ce(s,t);return await ee(e,r.expression)}catch{return Xn(t)}}function Wo(e,t){let s=0;for(let r of e){let n;if(r>="0"&&r<="9")n=r.charCodeAt(0)-48;else if(r>="a"&&r<="z")n=r.charCodeAt(0)-97+10;else if(r>="A"&&r<="Z")n=r.charCodeAt(0)-65+36;else if(r==="@")n=62;else if(r==="_")n=63;else return Number.NaN;if(n>=t)return Number.NaN;s=s*t+n}return s}function Xn(e){if(e=e.trim(),e==="")return 0;let t=!1;e.startsWith("-")?(t=!0,e=e.slice(1)):e.startsWith("+")&&(e=e.slice(1));let s,r=e.match(/^(\d+)#([a-zA-Z0-9@_]+)$/);if(r){let n=Number.parseInt(r[1],10);n>=2&&n<=64?s=Wo(r[2],n):s=0}else/^0[xX][0-9a-fA-F]+$/.test(e)?s=Number.parseInt(e,16):/^0[0-7]+$/.test(e)?s=Number.parseInt(e,8):s=Number.parseInt(e,10);return Number.isNaN(s)&&(s=0),t?-s:s}function ws(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 Vo(e){let t="",s=0;for(;s<e.length;)if(e[s]==="\\"&&s+1<e.length)t+=e[s]+e[s+1],s+=2;else if(e[s]==="["){let r=zo(e,s);t+=r.converted,s=r.endIndex}else t+=e[s],s++;return t}function zo(e,t){let s=t+1,r="[";s<e.length&&(e[s]==="^"||e[s]==="!")&&(r+="^",s++);let n=!1;s<e.length&&e[s]==="]"&&(n=!0,s++);let i=!1;s<e.length&&e[s]==="["&&s+1<e.length&&e[s+1]!==":"&&(i=!0,s++);let a="",o=!1;for(;s<e.length;){let l=e[s];if(l==="]"){o=!0,s++;break}if(l==="["&&s+1<e.length&&e[s+1]===":"){let u=e.indexOf(":]",s+2);if(u!==-1){let c=e.slice(s+2,u);a+=jo(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?(n&&(r+="\\]"),i&&(r+="\\["),r+=a,r+="]",{converted:r,endIndex:s}):{converted:"\\[",endIndex:t+1}}function jo(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 Be(e){let t=[],s="",r=!1,n=!1,i=!1,a=!1;for(let o of e){if(i){s+=o,i=!1,a=!0;continue}if(o==="\\"){i=!0;continue}if(o==="'"&&!n){r||(a=!0),r=!r;continue}if(o==='"'&&!r){n||(a=!0),n=!n;continue}if((o===" "||o===" "||o===`
14
- `)&&!r&&!n){a&&(t.push(s),s="",a=!1);continue}s+=o,a=!0}return a&&t.push(s),t}function vs(e){let t=[],s=0;for(;s<e.length;){for(;s<e.length&&/\s/.test(e[s]);)s++;if(s>=e.length)break;if(e[s]!=="["){s++;continue}s++;let r="";if(e[s]==="'"||e[s]==='"'){let i=e[s];for(s++;s<e.length&&e[s]!==i;)r+=e[s],s++;e[s]===i&&s++}else for(;s<e.length&&e[s]!=="]"&&e[s]!=="=";)r+=e[s],s++;for(;s<e.length&&e[s]!=="]";)s++;if(e[s]==="]"&&s++,e[s]!=="=")continue;s++;let n="";if(e[s]==="'"||e[s]==='"'){let i=e[s];for(s++;s<e.length&&e[s]!==i;)e[s]==="\\"&&s+1<e.length&&s++,n+=e[s],s++;e[s]===i&&s++}else for(;s<e.length&&!/\s/.test(e[s]);)n+=e[s],s++;t.push([r,n])}return t}function ti(e){let t=e.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\((.*)\)$/s);if(t)return{name:t[1],isArray:!0,arrayElements:Be(t[2])};let s=e.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([^\]]+)\]=(.*)$/s);if(s)return{name:s[1],isArray:!1,arrayIndex:s[2],value:s[3]};if(e.includes("=")){let r=e.indexOf("=");return{name:e.slice(0,r),isArray:!1,value:e.slice(r+1)}}return{name:e,isArray:!1}}async function Bo(e,t){try{let s=new X,r=ce(s,t);return await ee(e,r.expression)}catch{let s=parseInt(t,10);return Number.isNaN(s)?0:s}}async function si(e,t,s={}){let{name:r,isArray:n,arrayElements:i,value:a,arrayIndex:o}=t,{makeReadonly:l=!1,checkReadonly:u=!0}=s;if(u){let c=await de(e,r);if(c)return c}if(n&&i){for(let c=0;c<i.length;c++)g(e.state.env,`${r}_${c}`,i[c]);g(e.state.env,`${r}__length`,String(i.length))}else if(o!==void 0&&a!==void 0){let c=await Bo(e,o);g(e.state.env,`${r}_${c}`,a);let f=parseInt(T(e.state.env,`${r}__length`,"0"),10);c>=f&&g(e.state.env,`${r}__length`,String(c+1))}else a!==void 0&&g(e.state.env,r,a);return l&&Se(e,r),null}function st(e,t){e.state.localVarDepth=e.state.localVarDepth||new Map,e.state.localVarDepth.set(t,e.state.callDepth)}function bt(e,t){return e.state.localVarDepth?.get(t)}function bs(e,t){e.state.localVarDepth?.delete(t)}function ri(e,t,s){e.state.localVarStack=e.state.localVarStack||new Map;let r=e.state.localVarStack.get(t)||[];r.push({value:s,scopeIndex:e.state.localScopes.length-1}),e.state.localVarStack.set(t,r)}function Es(e,t){let s=e.state.localVarStack?.get(t);if(!(!s||s.length===0))return s.pop()}function ni(e,t){if(e.state.localVarStack)for(let[s,r]of e.state.localVarStack.entries()){for(;r.length>0&&r[r.length-1].scopeIndex===t;)r.pop();r.length===0&&e.state.localVarStack.delete(s)}}var lr=new Set([":",".","break","continue","eval","exec","exit","export","readonly","return","set","shift","trap","unset"]);function ii(e){return lr.has(e)}var cr=new Set(["if","then","else","elif","fi","case","esac","for","select","while","until","do","done","in","function","{","}","time","[[","]]","!"]),Je=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 jt(e,t){if(e.parts.length!==1)return!1;let s=e.parts[0];return s.type!=="Literal"?!1:t.includes(s.value)}function Ss(e){if(!e.startsWith("__rw__:"))return null;let t=e.slice(7),s=t.indexOf(":");if(s===-1)return null;let r=Number.parseInt(t.slice(0,s),10);if(Number.isNaN(r)||r<0)return null;let n=s+1,i=t.slice(n,n+r),a=n+r+1,o=t.slice(a),l=o.indexOf(":");if(l===-1)return null;let 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 oi(e,t,s,r){try{if((await e.fs.stat(t)).isDirectory)return`bash: ${s}: Is a directory
3
+ `),e.writeFileSync("/proc/self/status",pn()),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 Fn(e,t){Po(e)&&(Ao(e,t),Co(e),ko(e))}var To=["allexport","errexit","noglob","noclobber","noexec","nounset","pipefail","posix","verbose","xtrace"],xo=["braceexpand","hashall","interactive-comments"];function er(e){let t=[],s=[...xo.map(r=>({name:r,enabled:!0})),...To.map(r=>({name:r,enabled:e[r]}))].sort((r,n)=>r.name.localeCompare(n.name));for(let r of s)r.enabled&&t.push(r.name);return t.join(":")}function gt(e){g(e.state.env,"SHELLOPTS",er(e.state.options))}var _o=["dotglob","expand_aliases","extglob","failglob","globskipdots","globstar","lastpipe","nocaseglob","nocasematch","nullglob","xpg_echo"];function tr(e){let t=[];for(let s of _o)e[s]&&t.push(s);return t.join(":")}function sr(e){g(e.state.env,"BASHOPTS",tr(e.state.shoptOptions))}var No="BASH_ALIAS_";function Wn(e){return e.parts.length!==1?!1:e.parts[0].type==="Literal"}function Vn(e){if(e.parts.length!==1)return null;let t=e.parts[0];return t.type==="Literal"?t.value:null}function zn(e,t){let s=e.env.get(`${No}${t}`);return s!==void 0?B(s):void 0}function rr(e,t,s){if(!t.name||!Wn(t.name))return t;let r=Vn(t.name);if(!r)return t;let n=zn(e,r);if(!n||s.has(r))return t;try{s.add(r);let i=new X,a=n,o=n.endsWith(" ");if(!o)for(let f of t.args){let d=Bn(f);a+=` ${d}`}let l;try{l=i.parse(a)}catch(f){if(f instanceof rs)throw f;return t}if(l.statements.length!==1||l.statements[0].pipelines.length!==1||l.statements[0].pipelines[0].commands.length!==1)return jn(t,n);let c=l.statements[0].pipelines[0].commands[0];if(c.type!=="SimpleCommand")return jn(t,n);let u={...c,assignments:[...t.assignments,...c.assignments],redirections:[...c.redirections,...t.redirections],line:t.line};if(o&&t.args.length>0&&(u={...u,args:[...u.args,...t.args]},u.args.length>0)){let f=u.args[0];if(Wn(f)){let d=Vn(f);if(d&&zn(e,d)){let p={type:"SimpleCommand",name:f,args:u.args.slice(1),assignments:[],redirections:[]},m=rr(e,p,s);m!==p&&(u={...u,name:m.name,args:[...m.args]})}}}return u}catch(i){throw s.delete(r),i}}function jn(e,t){let s=t;for(let a of e.args){let o=Bn(a);s+=` ${o}`}let r=new X,n=r.parseWordFromString("eval",!1,!1),i=r.parseWordFromString(`'${s.replace(/'/g,"'\\''")}'`,!1,!1);return{type:"SimpleCommand",name:n,args:[i],assignments:e.assignments,redirections:e.redirections,line:e.line}}function Bn(e){let t="";for(let s of e.parts)switch(s.type){case"Literal":t+=s.value.replace(/([\s"'$`\\*?[\]{}()<>|&;#!])/g,"\\$1");break;case"SingleQuoted":t+=`'${s.value}'`;break;case"DoubleQuoted":t+=`"${s.parts.map(r=>r.type==="Literal"?r.value:`$${r.type}`).join("")}"`;break;case"ParameterExpansion":t+=`\${${s.parameter}}`;break;case"CommandSubstitution":t+="$(...)";break;case"ArithmeticExpansion":t+=`$((${s.expression}))`;break;case"Glob":t+=s.pattern;break;default:break}return t}async function Un(e,t){let s=t.parts.map(u=>u.type==="Literal"?u.value:"\0").join(""),r=s.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\(/);if(!r||!s.endsWith(")"))return null;let n=r[1],i=[],a=!1,o="",l=!1;for(let u of t.parts)if(u.type==="Literal"){let f=u.value;if(!a){let d=f.indexOf("=(");d!==-1&&(a=!0,f=f.slice(d+2))}if(a){f.endsWith(")")&&(f=f.slice(0,-1));let d=f.split(/(\s+)/);for(let 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+=is({type:"Word",parts:[u]});else{(o||l)&&(i.push(o),o="",l=!1);let d=await je(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`${n}=(${c.join(" ")})`}async function Hn(e,t){let s=-1,r=-1,n=!1;for(let h=0;h<t.parts.length;h++){let v=t.parts[h];if(v.type==="Literal"){let E=v.value.indexOf("+=");if(E!==-1){let b=v.value.slice(0,E);if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(b)){s=h,r=E,n=!0;break}if(/^[a-zA-Z_][a-zA-Z0-9_]*\[[^\]]+\]$/.test(b)){s=h,r=E,n=!0;break}}let S=v.value.indexOf("=");if(S!==-1&&(S===0||v.value[S-1]!=="+")){let b=v.value.slice(0,S);if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(b)||/^[a-zA-Z_][a-zA-Z0-9_]*\[[^\]]+\]$/.test(b)){s=h,r=S;break}}}}if(s===-1)return null;let i=t.parts.slice(0,s),a=t.parts[s];if(a.type!=="Literal")return null;let o=n?2:1,l=a.value.slice(0,r),c=a.value.slice(r+o),u=t.parts.slice(s+1),f="";for(let 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}${n?"+=":"="}${p}`}var Oo=["tar","yq","xan","sqlite3","python3","python"];function Gn(e){return Oo.includes(e)}function U(){return{stdout:P(),stderr:P(),exitCode:0}}var wt={get stdout(){return P()},get stderr(){return P()},exitCode:0};function Ne(e=P()){return{stdout:e,stderr:P(),exitCode:0}}function G(e){return{stdout:V(e),stderr:P(),exitCode:0}}function A(e,t=1){return{stdout:P(),stderr:V(e),exitCode:t}}function F(e,t,s){return{stdout:e instanceof Uint8Array?fe(e):e,stderr:t instanceof Uint8Array?fe(t):t,exitCode:s}}function le(e){return{stdout:P(),stderr:P(),exitCode:e?0:1}}function Me(e,t){throw new ae(e,t)}async function nr(e,t){if(e.state.loopDepth===0){if(e.state.parentHasLoopContext)throw new He;return U()}if(t.length>1)throw await H(e,2,`bash: break: too many arguments
4
+ `,!0),new q(1);let s=1;if(t.length>0){let r=Number.parseInt(t[0],10);if(Number.isNaN(r)||r<1)throw await H(e,2,`bash: break: ${t[0]}: numeric argument required
5
+ `,!0),new q(128);s=r}throw new Ae(s)}async function ir(e,t){let s,r=!1,n=!1,i=0;for(;i<t.length;)if(t[i]==="--"){i++;break}else if(t[i]==="-L")n=!1,i++;else if(t[i]==="-P")n=!0,i++;else if(t[i].startsWith("-")&&t[i]!=="-")i++;else break;let a=t.slice(i);if(a.length===0?s=N(e.state.env,"HOME","/"):a[0]==="~"?s=N(e.state.env,"HOME","/"):a[0]==="-"?(s=e.state.previousDir,r=!0):s=a[0],!s.startsWith("/")&&!s.startsWith("./")&&!s.startsWith("../")&&s!=="."&&s!==".."){let f=e.state.env.get("CDPATH");if(f){let d=B(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,r=!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 A(`bash: cd: ${s}: Not a directory
6
+ `)}catch{return A(`bash: cd: ${s}: No such file or directory
7
+ `)}}let u=c||"/";if(n)try{u=await e.fs.realpath(u)}catch{}return e.state.previousDir=e.state.cwd,e.state.cwd=u,g(e.state.env,"PWD",e.state.cwd),g(e.state.env,"OLDPWD",e.state.previousDir),r?G(`${u}
8
+ `):Ne()}function or(e,t){return e.fs.resolvePath(e.state.cwd,t)}var Do=["-e","-a","-f","-d","-r","-w","-x","-s","-L","-h","-k","-g","-u","-G","-O","-b","-c","-p","-S","-t","-N"];function us(e){return Do.includes(e)}async function fs(e,t,s){let r=or(e,s);switch(t){case"-e":case"-a":return e.fs.exists(r);case"-f":return await e.fs.exists(r)?(await e.fs.stat(r)).isFile:!1;case"-d":return await e.fs.exists(r)?(await e.fs.stat(r)).isDirectory:!1;case"-r":return await e.fs.exists(r)?((await e.fs.stat(r)).mode&256)!==0:!1;case"-w":return await e.fs.exists(r)?((await e.fs.stat(r)).mode&128)!==0:!1;case"-x":return await e.fs.exists(r)?((await e.fs.stat(r)).mode&64)!==0:!1;case"-s":return await e.fs.exists(r)?(await e.fs.stat(r)).size>0:!1;case"-L":case"-h":try{return(await e.fs.lstat(r)).isSymbolicLink}catch{return!1}case"-k":return await e.fs.exists(r)?((await e.fs.stat(r)).mode&512)!==0:!1;case"-g":return await e.fs.exists(r)?((await e.fs.stat(r)).mode&1024)!==0:!1;case"-u":return await e.fs.exists(r)?((await e.fs.stat(r)).mode&2048)!==0:!1;case"-G":case"-O":return e.fs.exists(r);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=>r===i||r.endsWith(i));case"-p":return!1;case"-S":return!1;case"-t":return!1;case"-N":return e.fs.exists(r);default:return!1}}var Io=["-nt","-ot","-ef"];function ds(e){return Io.includes(e)}async function hs(e,t,s,r){let n=or(e,s),i=or(e,r);switch(t){case"-nt":try{let a=await e.fs.stat(n),o=await e.fs.stat(i);return a.mtime>o.mtime}catch{return!1}case"-ot":try{let a=await e.fs.stat(n),o=await e.fs.stat(i);return a.mtime<o.mtime}catch{return!1}case"-ef":try{if(!await e.fs.exists(n)||!await e.fs.exists(i))return!1;let a=e.fs.resolvePath(e.state.cwd,n),o=e.fs.resolvePath(e.state.cwd,i);return a===o}catch{return!1}default:return!1}}var Ro=new Set(["-eq","-ne","-lt","-le","-gt","-ge"]);function ps(e){return Ro.has(e)}function ms(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 Vt(e){return e==="="||e==="=="||e==="!="}function ys(e,t,s,r=!1,n=!1,i=!1){if(r){let o=vt(t,s,n,i);return e==="!="?!o:o}if(n){let o=t.toLowerCase()===s.toLowerCase();return e==="!="?!o:o}let a=t===s;return e==="!="?!a:a}var Mo=new Set(["-z","-n"]);function gs(e){return Mo.has(e)}function ws(e,t){switch(e){case"-z":return t==="";case"-n":return t!==""}}async function vs(e,t){let s=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(s){let r=s[1],n=s[2];if(e.state.associativeArrays?.has(r)){let o=n;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)=>N(e.state.env,c)),e.state.env.has(`${r}_${o}`)}let a;try{let o=new X,l=ce(o,n);a=await ee(e,l.expression)}catch{if(/^-?\d+$/.test(n))a=Number.parseInt(n,10);else{let o=N(e.state.env,n);a=o?Number.parseInt(o,10):0}}if(a<0){let o=me(e,r),l=e.state.currentLine;if(o.length===0)return await H(e,2,`bash: line ${l}: ${r}: bad array subscript
9
+ `),!1;if(a=Math.max(...o)+1+a,a<0)return await H(e,2,`bash: line ${l}: ${r}: bad array subscript
10
+ `),!1}return e.state.env.has(`${r}_${a}`)}return e.state.env.has(t)?!0:e.state.associativeArrays?.has(t)?et(e,t).length>0:me(e,t).length>0}async function tt(e,t){switch(t.type){case"CondBinary":{let s=await z(e,t.left),r=t.right.parts.length>0&&t.right.parts.every(i=>i.type==="SingleQuoted"||i.type==="DoubleQuoted"||i.type==="Escaped"&&t.operator!=="=~"),n;if(t.operator==="=~")if(r){let i=await z(e,t.right);n=$n(i)}else n=await An(e,t.right);else Vt(t.operator)&&!r?n=await Cn(e,t.right):n=await z(e,t.right);if(Vt(t.operator)){let i=e.state.shoptOptions.nocasematch;return ys(t.operator,s,n,!r,i,!0)}if(ps(t.operator))return ms(t.operator,await Zn(e,s),await Zn(e,n));if(ds(t.operator))return hs(e,t.operator,s,n);switch(t.operator){case"=~":try{let i=e.state.shoptOptions.nocasematch,a=Vo(n),l=Rt(a,i?"i":"").match(s);if(Ve(e,"BASH_REMATCH"),l)for(let c=0;c<l.length;c++)g(e.state.env,`BASH_REMATCH_${c}`,l[c]||"");return l!==null}catch{throw new Error("syntax error in regular expression")}case"<":return s<n;case">":return s>n;default:return!1}}case"CondUnary":{let s=await z(e,t.operand);return us(t.operator)?fs(e,t.operator,s):gs(t.operator)?ws(t.operator,s):t.operator==="-v"?await vs(e,s):t.operator==="-o"?lr(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 tt(e,t.operand);case"CondAnd":return await tt(e,t.left)?await tt(e,t.right):!1;case"CondOr":return await tt(e,t.left)?!0:await tt(e,t.right);case"CondGroup":return await tt(e,t.expression);case"CondWord":return await z(e,t.word)!=="";default:return!1}}async function zt(e,t){if(t.length===0)return F(R,R,1);if(t.length===1)return le(!!t[0]);if(t.length===2){let r=t[0],n=t[1];return r==="("?A(`test: '(' without matching ')'
11
+ `,2):us(r)?le(await fs(e,r,n)):gs(r)?le(ws(r,n)):r==="!"?le(!n):r==="-v"?le(await vs(e,n)):r==="-o"?le(lr(e,n)):r==="="||r==="=="||r==="!="||r==="<"||r===">"||r==="-eq"||r==="-ne"||r==="-lt"||r==="-le"||r==="-gt"||r==="-ge"||r==="-nt"||r==="-ot"||r==="-ef"?A(`test: ${r}: unary operator expected
12
+ `,2):F(R,R,1)}if(t.length===3){let r=t[0],n=t[1],i=t[2];if(Vt(n))return le(ys(n,r,i));if(ps(n)){let a=bs(r),o=bs(i);return!a.valid||!o.valid?F(R,R,2):le(ms(n,a.value,o.value))}if(ds(n))return le(await hs(e,n,r,i));switch(n){case"-a":return le(r!==""&&i!=="");case"-o":return le(r!==""||i!=="");case">":return le(r>i);case"<":return le(r<i)}if(r==="!"){let a=await zt(e,[n,i]);return F(R,a.stderr,a.exitCode===0?1:a.exitCode===1?0:a.exitCode)}if(r==="("&&i===")")return le(n!=="")}if(t.length===4){if(t[0]==="!"){let r=await zt(e,t.slice(1));return F(R,r.stderr,r.exitCode===0?1:r.exitCode===1?0:r.exitCode)}if(t[0]==="("&&t[3]===")")return zt(e,[t[1],t[2]])}let s=await Jn(e,t,0);return s.pos<t.length?A(`test: too many arguments
13
+ `,2):le(s.value)}async function Jn(e,t,s){return Lo(e,t,s)}async function Lo(e,t,s){let{value:r,pos:n}=await qn(e,t,s);for(;t[n]==="-o";){let i=await qn(e,t,n+1);r=r||i.value,n=i.pos}return{value:r,pos:n}}async function qn(e,t,s){let{value:r,pos:n}=await ar(e,t,s);for(;t[n]==="-a";){let i=await ar(e,t,n+1);r=r&&i.value,n=i.pos}return{value:r,pos:n}}async function ar(e,t,s){if(t[s]==="!"){let{value:r,pos:n}=await ar(e,t,s+1);return{value:!r,pos:n}}return Fo(e,t,s)}async function Fo(e,t,s){let r=t[s];if(r==="("){let{value:i,pos:a}=await Jn(e,t,s+1);return{value:i,pos:t[a]===")"?a+1:a}}let n=t[s+1];if(Vt(n)){let i=r,a=t[s+2]??"";return{value:ys(n,i,a),pos:s+3}}if(ps(n)){let i=bs(r),a=bs(t[s+2]??"0");return!i.valid||!a.valid?{value:!1,pos:s+3}:{value:ms(n,i.value,a.value),pos:s+3}}if(ds(n)){let i=r,a=t[s+2]??"";return{value:await hs(e,n,i,a),pos:s+3}}if(us(r)){let i=t[s+1]??"";return{value:await fs(e,r,i),pos:s+2}}if(gs(r)){let i=t[s+1]??"";return{value:ws(r,i),pos:s+2}}if(r==="-v"){let i=t[s+1]??"";return{value:await vs(e,i),pos:s+2}}if(r==="-o"){let i=t[s+1]??"";return{value:lr(e,i),pos:s+2}}return{value:r!==void 0&&r!=="",pos:s+1}}function vt(e,t,s=!1,r=!1){let n=`^${Kn(t,r)}$`;return Rt(n,s?"is":"s").test(e)}function Kn(e,t){let s="";for(let r=0;r<e.length;r++){let n=e[r];if(t&&(n==="@"||n==="*"||n==="+"||n==="?"||n==="!")&&r+1<e.length&&e[r+1]==="("){let i=Yn(e,r+1);if(i!==-1){let a=e.slice(r+2,i),o=Qn(a),l=o.map(u=>Kn(u,t)),c=l.length>0?l.join("|"):"(?:)";if(n==="@")s+=`(?:${c})`;else if(n==="*")s+=`(?:${c})*`;else if(n==="+")s+=`(?:${c})+`;else if(n==="?")s+=`(?:${c})?`;else if(n==="!")if(i<e.length-1){let f=o.map(p=>ei(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})$).*`;r=i;continue}}if(n==="\\")if(r+1<e.length){let i=e[r+1];/[\\^$.|+(){}[\]*?]/.test(i)?s+=`\\${i}`:s+=i,r++}else s+="\\\\";else if(n==="*")s+=".*";else if(n==="?")s+=".";else if(n==="["){let i=e.indexOf("]",r+1);i!==-1?(s+=e.slice(r,i+1),r=i):s+="\\["}else/[\\^$.|+(){}]/.test(n)?s+=`\\${n}`:s+=n}return s}function Yn(e,t){let s=1,r=t+1;for(;r<e.length&&s>0;){let n=e[r];if(n==="\\"){r+=2;continue}if(n==="(")s++;else if(n===")"&&(s--,s===0))return r;r++}return-1}function Qn(e){let t=[],s="",r=0,n=0;for(;n<e.length;){let i=e[n];if(i==="\\"){s+=i,n+1<e.length?(s+=e[n+1],n+=2):n++;continue}i==="("?(r++,s+=i):i===")"?(r--,s+=i):i==="|"&&r===0?(t.push(s),s=""):s+=i,n++}return t.push(s),t}function ei(e,t){let s=0,r=0;for(;r<e.length;){let n=e[r];if(t&&(n==="@"||n==="*"||n==="+"||n==="?"||n==="!")&&r+1<e.length&&e[r+1]==="("){let i=Yn(e,r+1);if(i!==-1){if(n==="@"){let a=e.slice(r+2,i),l=Qn(a).map(c=>ei(c,t));if(l.every(c=>c!==null)&&l.every(c=>c===l[0])){s+=l[0],r=i+1;continue}return null}return null}}if(n==="*")return null;if(n==="?"){s+=1,r++;continue}if(n==="["){let i=e.indexOf("]",r+1);if(i!==-1){s+=1,r=i+1;continue}s+=1,r++;continue}if(n==="\\"){s+=1,r+=2;continue}s+=1,r++}return s}function lr(e,t){let r=new Map([["errexit",()=>e.state.options.errexit===!0],["nounset",()=>e.state.options.nounset===!0],["pipefail",()=>e.state.options.pipefail===!0],["xtrace",()=>e.state.options.xtrace===!0],["e",()=>e.state.options.errexit===!0],["u",()=>e.state.options.nounset===!0],["x",()=>e.state.options.xtrace===!0]]).get(t);return r?r():!1}async function Zn(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 Xn(t);try{let s=new X,r=ce(s,t);return await ee(e,r.expression)}catch{return Xn(t)}}function Wo(e,t){let s=0;for(let r of e){let n;if(r>="0"&&r<="9")n=r.charCodeAt(0)-48;else if(r>="a"&&r<="z")n=r.charCodeAt(0)-97+10;else if(r>="A"&&r<="Z")n=r.charCodeAt(0)-65+36;else if(r==="@")n=62;else if(r==="_")n=63;else return Number.NaN;if(n>=t)return Number.NaN;s=s*t+n}return s}function Xn(e){if(e=e.trim(),e==="")return 0;let t=!1;e.startsWith("-")?(t=!0,e=e.slice(1)):e.startsWith("+")&&(e=e.slice(1));let s,r=e.match(/^(\d+)#([a-zA-Z0-9@_]+)$/);if(r){let n=Number.parseInt(r[1],10);n>=2&&n<=64?s=Wo(r[2],n):s=0}else/^0[xX][0-9a-fA-F]+$/.test(e)?s=Number.parseInt(e,16):/^0[0-7]+$/.test(e)?s=Number.parseInt(e,8):s=Number.parseInt(e,10);return Number.isNaN(s)&&(s=0),t?-s:s}function bs(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 Vo(e){let t="",s=0;for(;s<e.length;)if(e[s]==="\\"&&s+1<e.length)t+=e[s]+e[s+1],s+=2;else if(e[s]==="["){let r=zo(e,s);t+=r.converted,s=r.endIndex}else t+=e[s],s++;return t}function zo(e,t){let s=t+1,r="[";s<e.length&&(e[s]==="^"||e[s]==="!")&&(r+="^",s++);let n=!1;s<e.length&&e[s]==="]"&&(n=!0,s++);let i=!1;s<e.length&&e[s]==="["&&s+1<e.length&&e[s+1]!==":"&&(i=!0,s++);let a="",o=!1;for(;s<e.length;){let l=e[s];if(l==="]"){o=!0,s++;break}if(l==="["&&s+1<e.length&&e[s+1]===":"){let c=e.indexOf(":]",s+2);if(c!==-1){let u=e.slice(s+2,c);a+=jo(u),s=c+2;continue}}if(l==="["&&s+1<e.length){let c=e[s+1];if(c==="."||c==="="){let u=`${c}]`,f=e.indexOf(u,s+2);if(f!==-1){let d=e.slice(s+2,f);a+=d,s=f+2;continue}}}if(l==="\\"&&s+1<e.length){a+=l+e[s+1],s+=2;continue}a+=l,s++}return o?(n&&(r+="\\]"),i&&(r+="\\["),r+=a,r+="]",{converted:r,endIndex:s}):{converted:"\\[",endIndex:t+1}}function jo(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 Be(e){let t=[],s="",r=!1,n=!1,i=!1,a=!1;for(let o of e){if(i){s+=o,i=!1,a=!0;continue}if(o==="\\"){i=!0;continue}if(o==="'"&&!n){r||(a=!0),r=!r;continue}if(o==='"'&&!r){n||(a=!0),n=!n;continue}if((o===" "||o===" "||o===`
14
+ `)&&!r&&!n){a&&(t.push(s),s="",a=!1);continue}s+=o,a=!0}return a&&t.push(s),t}function Es(e){let t=[],s=0;for(;s<e.length;){for(;s<e.length&&/\s/.test(e[s]);)s++;if(s>=e.length)break;if(e[s]!=="["){s++;continue}s++;let r="";if(e[s]==="'"||e[s]==='"'){let i=e[s];for(s++;s<e.length&&e[s]!==i;)r+=e[s],s++;e[s]===i&&s++}else for(;s<e.length&&e[s]!=="]"&&e[s]!=="=";)r+=e[s],s++;for(;s<e.length&&e[s]!=="]";)s++;if(e[s]==="]"&&s++,e[s]!=="=")continue;s++;let n="";if(e[s]==="'"||e[s]==='"'){let i=e[s];for(s++;s<e.length&&e[s]!==i;)e[s]==="\\"&&s+1<e.length&&s++,n+=e[s],s++;e[s]===i&&s++}else for(;s<e.length&&!/\s/.test(e[s]);)n+=e[s],s++;t.push([r,n])}return t}function ti(e){let t=e.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\((.*)\)$/s);if(t)return{name:t[1],isArray:!0,arrayElements:Be(t[2])};let s=e.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([^\]]+)\]=(.*)$/s);if(s)return{name:s[1],isArray:!1,arrayIndex:s[2],value:s[3]};if(e.includes("=")){let r=e.indexOf("=");return{name:e.slice(0,r),isArray:!1,value:e.slice(r+1)}}return{name:e,isArray:!1}}async function Bo(e,t){try{let s=new X,r=ce(s,t);return await ee(e,r.expression)}catch{let s=parseInt(t,10);return Number.isNaN(s)?0:s}}async function si(e,t,s={}){let{name:r,isArray:n,arrayElements:i,value:a,arrayIndex:o}=t,{makeReadonly:l=!1,checkReadonly:c=!0}=s;if(c){let u=await de(e,r);if(u)return u}if(n&&i){for(let u=0;u<i.length;u++)g(e.state.env,`${r}_${u}`,i[u]);g(e.state.env,`${r}__length`,String(i.length))}else if(o!==void 0&&a!==void 0){let u=await Bo(e,o);g(e.state.env,`${r}_${u}`,a);let f=parseInt(N(e.state.env,`${r}__length`,"0"),10);u>=f&&g(e.state.env,`${r}__length`,String(u+1))}else a!==void 0&&g(e.state.env,r,a);return l&&Se(e,r),null}function st(e,t){e.state.localVarDepth=e.state.localVarDepth||new Map,e.state.localVarDepth.set(t,e.state.callDepth)}function bt(e,t){return e.state.localVarDepth?.get(t)}function Ss(e,t){e.state.localVarDepth?.delete(t)}function ri(e,t,s){e.state.localVarStack=e.state.localVarStack||new Map;let r=e.state.localVarStack.get(t)||[];r.push({value:s,scopeIndex:e.state.localScopes.length-1}),e.state.localVarStack.set(t,r)}function $s(e,t){let s=e.state.localVarStack?.get(t);if(!(!s||s.length===0))return s.pop()}function ni(e,t){if(e.state.localVarStack)for(let[s,r]of e.state.localVarStack.entries()){for(;r.length>0&&r[r.length-1].scopeIndex===t;)r.pop();r.length===0&&e.state.localVarStack.delete(s)}}var cr=new Set([":",".","break","continue","eval","exec","exit","export","readonly","return","set","shift","trap","unset"]);function ii(e){return cr.has(e)}var ur=new Set(["if","then","else","elif","fi","case","esac","for","select","while","until","do","done","in","function","{","}","time","[[","]]","!"]),Je=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 jt(e,t){if(e.parts.length!==1)return!1;let s=e.parts[0];return s.type!=="Literal"?!1:t.includes(s.value)}function Ps(e){if(!e.startsWith("__rw__:"))return null;let t=e.slice(7),s=t.indexOf(":");if(s===-1)return null;let r=Number.parseInt(t.slice(0,s),10);if(Number.isNaN(r)||r<0)return null;let n=s+1,i=t.slice(n,n+r),a=n+r+1,o=t.slice(a),l=o.indexOf(":");if(l===-1)return null;let c=Number.parseInt(o.slice(0,l),10);if(Number.isNaN(c)||c<0)return null;let u=o.slice(l+1);return{path:i,position:c,content:u}}async function oi(e,t,s,r){try{if((await e.fs.stat(t)).isDirectory)return`bash: ${s}: Is a directory
15
15
  `;if(r.checkNoclobber&&e.state.options.noclobber&&!r.isClobber&&s!=="/dev/null")return`bash: ${s}: cannot overwrite existing file
16
- `}catch{}return null}async function $s(e,t){if(t.target.type==="HereDoc")throw new Error("Here-document targets are not words");return t.operator===">&"||t.operator==="<&"?kn(e,t.target)?{error:`bash: $@: ambiguous redirect
17
- `}:{target:await z(e,t.target)}:xn(e,t.target)}function ur(e){return e.includes("\0")?`bash: ${e.replace(/\0/g,"")}: No such file or directory
16
+ `}catch{}return null}async function As(e,t){if(t.target.type==="HereDoc")throw new Error("Here-document targets are not words");return t.operator===">&"||t.operator==="<&"?kn(e,t.target)?{error:`bash: $@: ambiguous redirect
17
+ `}:{target:await z(e,t.target)}:Tn(e,t.target)}function fr(e){return e.includes("\0")?`bash: ${e.replace(/\0/g,"")}: No such file or directory
18
18
  `:null}function Ue(e){return`bash: ${e}: Bad file descriptor
19
- `}function fr(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 Et(e,t,s){for(let r of t){if(!r.fdVariable)continue;e.state.fileDescriptors||(e.state.fileDescriptors=new Map);let n;if((r.operator===">&"||r.operator==="<&")&&r.target.type==="Word"&&(n=await z(e,r.target),n==="-")){if(e.state.env.has(r.fdVariable)){let a=Number.parseInt(T(e.state.env,r.fdVariable),10);Number.isNaN(a)||e.state.fileDescriptors.delete(a)}continue}let i=fr(e,s);if(g(e.state.env,r.fdVariable,String(i)),r.target.type==="Word"){let a=n??await z(e,r.target);if(r.operator===">&"||r.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 F(S(),V(Ue(o)),1);continue}}if(r.operator===">"||r.operator===">>"||r.operator===">|"||r.operator==="&>"||r.operator==="&>>"){let o=e.fs.resolvePath(e.state.cwd,a);(r.operator===">"||r.operator===">|"||r.operator==="&>")&&await e.fs.writeFile(o,""),e.state.fileDescriptors.set(i,`__file__:${o}`)}else if(r.operator==="<<<")e.state.fileDescriptors.set(i,`${a}
20
- `);else if(r.operator==="<"||r.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 F(S(),V(`bash: ${a}: No such file or directory
21
- `),1)}}}return null}var Uo={write(){}},Go={write(){let e=new Error(`bash: echo: write error: No space left on device
22
- `);return e.code="ENOSPC",Promise.reject(e)}};function Ho(e){return e.target.type==="HereDoc"||e.operator==="<"||e.operator==="<>"||e.operator==="<<<"||e.operator==="<<"||e.operator==="<<-"}function dr(e,t){return{...e,target:{type:"Word",parts:[{type:"Literal",value:t}]}}}function Cs(e,t){let s=Promise.resolve();return{write(r){let n=s.then(()=>e.fs.appendFile(t,r));return s=n.catch(()=>{}),n}}}function li(e,t,s,r=new Set){let n=t.bindings.get(s),i=n?.sink;if(i)return i;if(r.has(s))return;r.add(s);let a=n?.descriptor,o;if(a?.startsWith("__file__:"))o=Cs(e,a.slice(9));else if(a?.startsWith("__file_append__:"))o=Cs(e,a.slice(16));else if(a?.startsWith("__rw__:")){let l=Ss(a);l&&(o=Cs(e,l.path))}else if(a?.startsWith("__dupout__:")){let l=Number.parseInt(a.slice(11),10);Number.isNaN(l)||(o=li(e,t,l,r))}return o&&t.bindings.set(s,{...n,sink:o}),o}async function ai(e,t,s,r,n=!1){if(s==="/dev/null")return{sink:Uo,descriptor:"__file__:/dev/null"};if(s==="/dev/full")return{sink:Go,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:Ue(o)}}let i=e.fs.resolvePath(e.state.cwd,s),a=await oi(e,i,s,{checkNoclobber:r==="truncate",isClobber:n});return a?{error:a}:(r==="truncate"?await e.fs.writeFile(i,""):await e.fs.appendFile(i,new Uint8Array),{sink:Cs(e,i),descriptor:r==="append"?`__file_append__:${i}`:`__file__:${i}`})}function lt(e,t,s){e.state.fileDescriptors||(e.state.fileDescriptors=new Map),e.state.fileDescriptors.set(t,s)}function qo(e,t){return e.bindings.get(t)?.descriptor??`__dupout__:${t}`}function hr(e,t,s,r,n){if(!(!n&&!t.fdVariable)){if(t.fdVariable&&r.startsWith("__file_append__:")){lt(e,s,`__file__:${r.slice(16)}`);return}lt(e,s,r)}}function Ps(e,t,s,r,n,i=!0){let a=e.state.fileDescriptors?.get(s),o=n?.startsWith("__file_append__:")?`__file__:${n.slice(16)}`:n;(r||t.fdVariable)&&i&&a!==void 0&&a===o&&e.state.fileDescriptors?.delete(s)}function Oe(e,t,s){return{channels:e,legacyRedirections:t,error:P(s)}}async function De(e,t,s,r={}){let n={bindings:new Map(t.bindings),parent:t,overrides:new Set};for(let[o,l]of e.state.fileDescriptors??[]){let u=n.bindings.get(o);u?.descriptor===void 0&&n.bindings.set(o,{...u,descriptor:l})}let i=[],a=r.persistent===!0;for(let o of s){let l;if(o.operator==="<&"&&o.target.type==="Word"){let E=await $s(e,o);if("error"in E)return Oe(n,i,E.error);l=E.target;let $=l.startsWith("&")?l.slice(1):l,y=/^\d+-?$/.test($);if(l!=="-"&&!y)return Oe(n,i,`bash: ${l}: ambiguous redirect
23
- `);if(!o.fdVariable&&(o.fd??0)===0){i.push(dr(o,l));continue}}if(o.operator==="<"&&!o.fdVariable&&o.target.type==="Word"){let E=await $s(e,o);if("error"in E)return Oe(n,i,E.error);let $=ur(E.target);if($)return Oe(n,i,$);try{let y=e.fs.resolvePath(e.state.cwd,E.target);await e.fs.readFile(y)}catch{return Oe(n,i,`bash: ${E.target}: No such file or directory
24
- `)}i.push(dr(o,E.target));continue}if(Ho(o)){if(o.fdVariable&&o.target.type==="Word"){let E=await Et(e,[o],v=>Hs(n,v));if(E)return{channels:n,legacyRedirections:i,error:E};let $=Number.parseInt(T(e.state.env,o.fdVariable),10),y=e.state.fileDescriptors?.get($);if(!Number.isNaN($)&&y!==void 0){let v=n.bindings.get($);n.bindings.set($,{...v,descriptor:y})}}else i.push(o);continue}let u;if(l!==void 0)u=l;else{let E=await $s(e,o);if("error"in E)return Oe(n,i,E.error);u=E.target}let c=ur(u);if(c)return Oe(n,i,c);if((o.operator===">&"||o.operator==="<&")&&u==="-"&&o.fdVariable){if(e.state.env.has(o.fdVariable)){let E=Number.parseInt(T(e.state.env,o.fdVariable),10);if(!Number.isNaN(E)){let $=n.bindings.get(E)?.descriptor,y=Ft(n,E);Ps(e,o,E,a,$,y)}}continue}let f=o.fdVariable?fr(e,E=>Hs(n,E)):o.fd??(o.operator==="<&"?0:1);if(o.fdVariable&&g(e.state.env,o.fdVariable,String(f)),!Number.isInteger(f)||f<0)return Oe(n,i,Ue(f));if(o.operator===">"||o.operator===">|"||o.operator===">>"||o.operator==="&>"||o.operator==="&>>"){let E=o.operator===">>"||o.operator==="&>>",$=await ai(e,n,u,E?"append":"truncate",o.operator===">|");if("error"in $)return Oe(n,i,$.error);o.operator==="&>"||o.operator==="&>>"?(n.bindings.set(1,{sink:$.sink,descriptor:$.descriptor}),n.bindings.set(2,{sink:$.sink,descriptor:$.descriptor}),n.overrides?.add(1),n.overrides?.add(2),a&&(lt(e,1,$.descriptor),lt(e,2,$.descriptor))):(o.fdVariable?Lt(n,f,$.sink,$.descriptor):(n.bindings.set(f,{sink:$.sink,descriptor:$.descriptor}),n.overrides?.add(f)),hr(e,o,f,$.descriptor,a));continue}if(o.operator!==">&"&&o.operator!=="<&"){i.push(o);continue}if(u==="-"){let E=n.bindings.get(f)?.descriptor;n.overrides?.add(f),n.bindings.set(f,{descriptor:ss}),Ps(e,o,f,a,E);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 E=li(e,n,h);if(!E){let y=n.bindings.get(h)?.descriptor;if(y===ss)return Oe(n,i,Ue(h));if(o.operator==="<&"&&o.fdVariable&&y!==void 0){if(n.bindings.set(f,{descriptor:y}),lt(e,f,y),d){let v=Ft(n,h);Ps(e,o,h,a,y,v)}continue}if(o.operator==="<&"&&!o.fdVariable){i.push(dr(o,u));continue}return Oe(n,i,Ue(h))}let $=qo(n,h);if(o.fdVariable?Lt(n,f,E,$):n.bindings.set(f,{sink:E,descriptor:$}),hr(e,o,f,$,a),d){let y=!0;o.fdVariable?y=Ft(n,h):(n.overrides?.add(h),n.bindings.set(h,{descriptor:ss}),r.persistMovedSource&&n.parent&&(y=Ft(n.parent,h))),Ps(e,o,h,a||r.persistMovedSource===!0,$,y)}o.fdVariable||n.overrides?.add(f);continue}if(o.operator==="<&")return Oe(n,i,`bash: ${u}: ambiguous redirect
25
- `);let b=await ai(e,n,u,"truncate");if("error"in b)return Oe(n,i,b.error);o.fd==null&&!o.fdVariable?(n.bindings.set(1,{sink:b.sink,descriptor:b.descriptor}),n.bindings.set(2,{sink:b.sink,descriptor:b.descriptor}),n.overrides?.add(1),n.overrides?.add(2),a&&(lt(e,1,b.descriptor),lt(e,2,b.descriptor))):(o.fdVariable?Lt(n,f,b.sink,b.descriptor):(n.bindings.set(f,{sink:b.sink,descriptor:b.descriptor}),n.overrides?.add(f)),hr(e,o,f,b.descriptor,a))}return{channels:n,legacyRedirections:i}}async function ci(e,t){let s=e.outputChannels,r=await De(e,s,t,{persistent:!0});if(r.error)return r;for(let n of r.channels.overrides??[]){let i=r.channels.bindings.get(n);i?.descriptor!==void 0&&Lt(s,n,i.sink,i.descriptor)}return{...r,channels:s}}async function ui(e,t){if(e.state.options.posix&&lr.has(t.name)){let r=`bash: line ${e.state.currentLine}: \`${t.name}': is a special builtin
26
- `;throw await G(e,2,r,!0),new q(2)}let s={...t,sourceFile:t.sourceFile??e.state.currentSource??"main"};return e.state.functions.set(t.name,s),U()}async function Zo(e,t){let s=S(),r=!1;for(let n of t)if(!n.fdVariable){if((n.operator==="<<"||n.operator==="<<-")&&n.target.type==="HereDoc"){let i=n.target,a=await z(e,i.content);i.stripTabs&&(a=a.split(`
19
+ `}async function Bt(e,t){try{if((await e.fs.stat(e.fs.resolvePath(e.state.cwd,t))).isDirectory)return`bash: ${t}: Is a directory
20
+ `}catch{}return`bash: ${t}: No such file or directory
21
+ `}function dr(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 Et(e,t,s){for(let r of t){if(!r.fdVariable)continue;e.state.fileDescriptors||(e.state.fileDescriptors=new Map);let n;if((r.operator===">&"||r.operator==="<&")&&r.target.type==="Word"&&(n=await z(e,r.target),n==="-")){if(e.state.env.has(r.fdVariable)){let a=Number.parseInt(N(e.state.env,r.fdVariable),10);Number.isNaN(a)||e.state.fileDescriptors.delete(a)}continue}let i=dr(e,s);if(g(e.state.env,r.fdVariable,String(i)),r.target.type==="Word"){let a=n??await z(e,r.target);if(r.operator===">&"||r.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 F(P(),V(Ue(o)),1);continue}}if(r.operator===">"||r.operator===">>"||r.operator===">|"||r.operator==="&>"||r.operator==="&>>"){let o=e.fs.resolvePath(e.state.cwd,a);(r.operator===">"||r.operator===">|"||r.operator==="&>")&&await e.fs.writeFile(o,""),e.state.fileDescriptors.set(i,`__file__:${o}`)}else if(r.operator==="<<<")e.state.fileDescriptors.set(i,`${a}
22
+ `);else if(r.operator==="<"||r.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 F(P(),V(`bash: ${a}: No such file or directory
23
+ `),1)}}}return null}var Uo={write(){}},Ho={write(){let e=new Error(`bash: echo: write error: No space left on device
24
+ `);return e.code="ENOSPC",Promise.reject(e)}};function Go(e){return e.target.type==="HereDoc"||e.operator==="<"||e.operator==="<>"||e.operator==="<<<"||e.operator==="<<"||e.operator==="<<-"}function hr(e,t){return{...e,target:{type:"Word",parts:[{type:"Literal",value:t}]}}}function ks(e,t){let s=Promise.resolve();return{write(r){let n=s.then(()=>e.fs.appendFile(t,r));return s=n.catch(()=>{}),n}}}function li(e,t,s,r=new Set){let n=t.bindings.get(s),i=n?.sink;if(i)return i;if(r.has(s))return;r.add(s);let a=n?.descriptor,o;if(a?.startsWith("__file__:"))o=ks(e,a.slice(9));else if(a?.startsWith("__file_append__:"))o=ks(e,a.slice(16));else if(a?.startsWith("__rw__:")){let l=Ps(a);l&&(o=ks(e,l.path))}else if(a?.startsWith("__dupout__:")){let l=Number.parseInt(a.slice(11),10);Number.isNaN(l)||(o=li(e,t,l,r))}return o&&t.bindings.set(s,{...n,sink:o}),o}async function ai(e,t,s,r,n=!1){if(s==="/dev/null")return{sink:Uo,descriptor:"__file__:/dev/null"};if(s==="/dev/full")return{sink:Ho,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:Ue(o)}}let i=e.fs.resolvePath(e.state.cwd,s),a=await oi(e,i,s,{checkNoclobber:r==="truncate",isClobber:n});return a?{error:a}:(r==="truncate"?await e.fs.writeFile(i,""):await e.fs.appendFile(i,new Uint8Array),{sink:ks(e,i),descriptor:r==="append"?`__file_append__:${i}`:`__file__:${i}`})}function lt(e,t,s){e.state.fileDescriptors||(e.state.fileDescriptors=new Map),e.state.fileDescriptors.set(t,s)}function qo(e,t){return e.bindings.get(t)?.descriptor??`__dupout__:${t}`}function pr(e,t,s,r,n){if(!(!n&&!t.fdVariable)){if(t.fdVariable&&r.startsWith("__file_append__:")){lt(e,s,`__file__:${r.slice(16)}`);return}lt(e,s,r)}}function Cs(e,t,s,r,n,i=!0){let a=e.state.fileDescriptors?.get(s),o=n?.startsWith("__file_append__:")?`__file__:${n.slice(16)}`:n;(r||t.fdVariable)&&i&&a!==void 0&&a===o&&e.state.fileDescriptors?.delete(s)}function Oe(e,t,s){return{channels:e,legacyRedirections:t,error:A(s)}}async function De(e,t,s,r={}){let n={bindings:new Map(t.bindings),parent:t,overrides:new Set};for(let[o,l]of e.state.fileDescriptors??[]){let c=n.bindings.get(o);c?.descriptor===void 0&&n.bindings.set(o,{...c,descriptor:l})}let i=[],a=r.persistent===!0;for(let o of s){let l;if(o.operator==="<&"&&o.target.type==="Word"){let E=await As(e,o);if("error"in E)return Oe(n,i,E.error);l=E.target;let S=l.startsWith("&")?l.slice(1):l,b=/^\d+-?$/.test(S);if(l!=="-"&&!b)return Oe(n,i,`bash: ${l}: ambiguous redirect
25
+ `);if(!o.fdVariable&&(o.fd??0)===0){i.push(hr(o,l));continue}}if(o.operator==="<"&&!o.fdVariable&&o.target.type==="Word"){let E=await As(e,o);if("error"in E)return Oe(n,i,E.error);let S=fr(E.target);if(S)return Oe(n,i,S);try{let b=e.fs.resolvePath(e.state.cwd,E.target),y=await e.fs.stat(b)}catch{return Oe(n,i,`bash: ${E.target}: No such file or directory
26
+ `)}i.push(hr(o,E.target));continue}if(Go(o)){if(o.fdVariable&&o.target.type==="Word"){let E=await Et(e,[o],y=>qs(n,y));if(E)return{channels:n,legacyRedirections:i,error:E};let S=Number.parseInt(N(e.state.env,o.fdVariable),10),b=e.state.fileDescriptors?.get(S);if(!Number.isNaN(S)&&b!==void 0){let y=n.bindings.get(S);n.bindings.set(S,{...y,descriptor:b})}}else i.push(o);continue}let c;if(l!==void 0)c=l;else{let E=await As(e,o);if("error"in E)return Oe(n,i,E.error);c=E.target}let u=fr(c);if(u)return Oe(n,i,u);if((o.operator===">&"||o.operator==="<&")&&c==="-"&&o.fdVariable){if(e.state.env.has(o.fdVariable)){let E=Number.parseInt(N(e.state.env,o.fdVariable),10);if(!Number.isNaN(E)){let S=n.bindings.get(E)?.descriptor,b=Ft(n,E);Cs(e,o,E,a,S,b)}}continue}let f=o.fdVariable?dr(e,E=>qs(n,E)):o.fd??(o.operator==="<&"?0:1);if(o.fdVariable&&g(e.state.env,o.fdVariable,String(f)),!Number.isInteger(f)||f<0)return Oe(n,i,Ue(f));if(o.operator===">"||o.operator===">|"||o.operator===">>"||o.operator==="&>"||o.operator==="&>>"){let E=o.operator===">>"||o.operator==="&>>",S=await ai(e,n,c,E?"append":"truncate",o.operator===">|");if("error"in S)return Oe(n,i,S.error);o.operator==="&>"||o.operator==="&>>"?(n.bindings.set(1,{sink:S.sink,descriptor:S.descriptor}),n.bindings.set(2,{sink:S.sink,descriptor:S.descriptor}),n.overrides?.add(1),n.overrides?.add(2),a&&(lt(e,1,S.descriptor),lt(e,2,S.descriptor))):(o.fdVariable?Lt(n,f,S.sink,S.descriptor):(n.bindings.set(f,{sink:S.sink,descriptor:S.descriptor}),n.overrides?.add(f)),pr(e,o,f,S.descriptor,a));continue}if(o.operator!==">&"&&o.operator!=="<&"){i.push(o);continue}if(c==="-"){let E=n.bindings.get(f)?.descriptor;n.overrides?.add(f),n.bindings.set(f,{descriptor:ns}),Cs(e,o,f,a,E);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 E=li(e,n,h);if(!E){let b=n.bindings.get(h)?.descriptor;if(b===ns)return Oe(n,i,Ue(h));if(o.operator==="<&"&&o.fdVariable&&b!==void 0){if(n.bindings.set(f,{descriptor:b}),lt(e,f,b),d){let y=Ft(n,h);Cs(e,o,h,a,b,y)}continue}if(o.operator==="<&"&&!o.fdVariable){i.push(hr(o,c));continue}return Oe(n,i,Ue(h))}let S=qo(n,h);if(o.fdVariable?Lt(n,f,E,S):n.bindings.set(f,{sink:E,descriptor:S}),pr(e,o,f,S,a),d){let b=!0;o.fdVariable?b=Ft(n,h):(n.overrides?.add(h),n.bindings.set(h,{descriptor:ns}),r.persistMovedSource&&n.parent&&(b=Ft(n.parent,h))),Cs(e,o,h,a||r.persistMovedSource===!0,S,b)}o.fdVariable||n.overrides?.add(f);continue}if(o.operator==="<&")return Oe(n,i,`bash: ${c}: ambiguous redirect
27
+ `);let v=await ai(e,n,c,"truncate");if("error"in v)return Oe(n,i,v.error);o.fd==null&&!o.fdVariable?(n.bindings.set(1,{sink:v.sink,descriptor:v.descriptor}),n.bindings.set(2,{sink:v.sink,descriptor:v.descriptor}),n.overrides?.add(1),n.overrides?.add(2),a&&(lt(e,1,v.descriptor),lt(e,2,v.descriptor))):(o.fdVariable?Lt(n,f,v.sink,v.descriptor):(n.bindings.set(f,{sink:v.sink,descriptor:v.descriptor}),n.overrides?.add(f)),pr(e,o,f,v.descriptor,a))}return{channels:n,legacyRedirections:i}}async function ci(e,t){let s=e.outputChannels,r=await De(e,s,t,{persistent:!0});if(r.error)return r;for(let n of r.channels.overrides??[]){let i=r.channels.bindings.get(n);i?.descriptor!==void 0&&Lt(s,n,i.sink,i.descriptor)}return{...r,channels:s}}async function ui(e,t){if(e.state.options.posix&&cr.has(t.name)){let r=`bash: line ${e.state.currentLine}: \`${t.name}': is a special builtin
28
+ `;throw await H(e,2,r,!0),new q(2)}let s={...t,sourceFile:t.sourceFile??e.state.currentSource??"main"};return e.state.functions.set(t.name,s),U()}async function Zo(e,t){let s=P(),r=!1;for(let n of t)if(!n.fdVariable){if((n.operator==="<<"||n.operator==="<<-")&&n.target.type==="HereDoc"){let i=n.target,a=await z(e,i.content);i.stripTabs&&(a=a.split(`
27
29
  `).map(l=>l.replace(/^\t+/,"")).join(`
28
30
  `)),(n.fd??0)===0&&(s=V(a),r=!0)}else if(n.operator==="<<<"&&n.target.type==="Word")s=V(`${await z(e,n.target)}
29
- `),r=!0;else if(n.operator==="<"&&n.target.type==="Word"){let i=await z(e,n.target),a=e.fs.resolvePath(e.state.cwd,i);try{s=await e.fs.readFile(a),r=!0}catch{}}}return s}async function As(e,t,s,r=S(),n){e.state.callDepth++,e.state.callDepth>e.limits.maxCallDepth&&(e.state.callDepth--,Me(`${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(n??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))),g(e.state.env,String(o+1),s[o]);i.set("@",T(e.state.env,"@")),i.set("#",T(e.state.env,"#")),g(e.state.env,"@",s.join(" ")),g(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(ni(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):g(e.state.env,u,c);e.state.funcNameStack?.shift(),e.state.callLineStack?.shift(),e.state.sourceStack?.shift(),e.state.callDepth--};try{let o=await De(e,e.outputChannels,t.redirections);return o.error?await K(e,o.channels,()=>se(e,()=>Promise.resolve(o.error))):await K(e,o.channels,async()=>{try{let l=await Et(e,o.legacyRedirections);if(l)return await se(e,()=>Promise.resolve(l));let u=await re(r),c=u.length>0?fe(u):await Zo(e,o.legacyRedirections),f=await e.executeCommand(t.body,c);return await se(e,()=>Promise.resolve(f))}catch(l){let{writeFailure:u}=await Qe(e,l);if(u)return u;if(l instanceof ve)return F(S(),S(),l.exitCode);throw l}})}catch(o){throw await te(e,o),o}finally{a()}}var di=["!","[[","]]","case","do","done","elif","else","esac","fi","for","function","if","in","then","time","until","while","{","}"],mr=[".",":","[","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"],Xo=["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"],Jo=mr;async function yr(e,t){let s=[],r=null,n="",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 P(`compgen: -A: option requires an argument
30
- `,2);let N=t[v];if(!m.includes(N))return P(`compgen: ${N}: invalid action name
31
- `,2);s.push(N)}else if(C==="-W"){if(v++,v>=t.length)return P(`compgen: -W: option requires an argument
32
- `,2);r=t[v]}else if(C==="-P"){if(v++,v>=t.length)return P(`compgen: -P: option requires an argument
33
- `,2);n=t[v]}else if(C==="-S"){if(v++,v>=t.length)return P(`compgen: -S: option requires an argument
34
- `,2);i=t[v]}else if(C==="-o"){if(v++,v>=t.length)return P(`compgen: -o: option requires an argument
35
- `,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 P(`compgen: ${N}: invalid option name
36
- `,2)}else if(C==="-F"){if(v++,v>=t.length)return P(`compgen: -F: option requires an argument
37
- `,2);f=t[v]}else if(C==="-C"){if(v++,v>=t.length)return P(`compgen: -C: option requires an argument
38
- `,2);d=t[v]}else if(C==="-X"){if(v++,v>=t.length)return P(`compgen: -X: option requires an argument
39
- `,2);c=t[v]}else if(C==="-G"){if(v++,v>=t.length)return P(`compgen: -G: option requires an argument
40
- `,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 pr(e,a);h.push(...v)}if(u){let v=await fi(e,a);h.push(...v)}for(let v of s)if(v==="variable"){let C=Ko(e,a);h.push(...C)}else if(v==="export"){let C=Yo(e,a);h.push(...C)}else if(v==="function"){let C=Qo(e,a);h.push(...C)}else if(v==="builtin"){let C=ea(a);h.push(...C)}else if(v==="keyword"){let C=ta(a);h.push(...C)}else if(v==="alias"){let C=sa(e,a);h.push(...C)}else if(v==="shopt"){let C=ra(a);h.push(...C)}else if(v==="helptopic"){let C=na(a);h.push(...C)}else if(v==="directory"){let C=await pr(e,a);h.push(...C)}else if(v==="file"){let C=await fi(e,a);h.push(...C)}else if(v==="user"){let C=ia(a);h.push(...C)}else if(v==="command"){let C=await oa(e,a);h.push(...C)}if(r!==null)try{let v=await aa(e,r),C=la(e,v);for(let N of C)(a===null||N.startsWith(a))&&h.push(N)}catch{return F(R,R,1)}if(o){let v=await pr(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")),g(e.state.env,"COMP_WORDS__length","0"),C.set("COMP_CWORD",T(e.state.env,"COMP_CWORD")),g(e.state.env,"COMP_CWORD","-1"),C.set("COMP_LINE",T(e.state.env,"COMP_LINE")),g(e.state.env,"COMP_LINE",""),C.set("COMP_POINT",T(e.state.env,"COMP_POINT")),g(e.state.env,"COMP_POINT","0");let N=new Map;for(let k of e.state.env.keys())(k==="COMPREPLY"||k.startsWith("COMPREPLY_")||k==="COMPREPLY__length")&&(N.set(k,T(e.state.env,k)),e.state.env.delete(k));let I=["compgen",p[0]??"",""];try{let k=_e(),A=_e(),O=await K(e,{bindings:new Map([[1,{sink:k}],[2,{sink:A}]])},()=>As(e,v,I,S()));if(await Wt(e,O.stderr,A),O.exitCode!==0)return St(e,C),St(e,N),F(R,A.stream(),1);await Wt(e,O.stdout,k),b=B(await re(k.stream()));let M=ca(e);h.push(...M)}catch{return St(e,C),St(e,N),F(R,R,1)}St(e,C),St(e,N)}}if(d!==null)try{let v=Fe(d),C=_e(),N=_e(),I=await K(e,{bindings:new Map([[1,{sink:C}],[2,{sink:N}]])},()=>e.executeScript(v));if(await Wt(e,I.stderr,N),I.exitCode!==0)return F(R,N.stream(),I.exitCode);await Wt(e,I.stdout,C);let k=await re(C.stream());if(k.length>0){let A=B(k).split(`
41
- `);for(let O of A)O.length>0&&h.push(O)}}catch(v){if(v.name==="ParseException")return P(`compgen: -C: ${v.message}
42
- `,2);throw v}let E=h;if(c!==null){let v=c.startsWith("!"),C=v?c.slice(1):c;E=h.filter(N=>{let I=vt(N,C,!1,!0);return v?I:!I})}if(E.length===0&&a!==null)return F(W(b),R,1);let $=E.map(v=>`${n}${v}${i}`).join(`
43
- `),y=b+($?`${$}
44
- `:"");return H(y)}function Ko(e,t){let s=new Set;for(let n of e.state.env.keys()){if(n.includes("_")&&/^[a-zA-Z_][a-zA-Z0-9_]*_\d+$/.test(n)||n.endsWith("__length"))continue;let i=n.split("_")[0];/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(n)?s.add(n):i&&/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(i)&&e.state.env.has(`${i}__length`)&&s.add(i)}let r=Array.from(s);return t!==null&&(r=r.filter(n=>n.startsWith(t))),r.sort()}function Yo(e,t){let s=e.state.exportedVars??new Set,r=Array.from(s);return t!==null&&(r=r.filter(n=>n.startsWith(t))),r=r.filter(n=>n.includes("_")&&/^[a-zA-Z_][a-zA-Z0-9_]*_\d+$/.test(n)||n.endsWith("__length")?!1:e.state.env.has(n)),r.sort()}function Qo(e,t){let s=Array.from(e.state.functions.keys());return t!==null&&(s=s.filter(r=>r.startsWith(t))),s.sort()}function ea(e){let t=[...mr];return e!==null&&(t=t.filter(s=>s.startsWith(e))),t.sort()}function ta(e){let t=[...di];return e!==null&&(t=t.filter(s=>s.startsWith(e))),t.sort()}function sa(e,t){let s=[];for(let n of e.state.env.keys())if(n.startsWith("BASH_ALIAS_")){let i=n.slice(11);s.push(i)}let r=s;return t!==null&&(r=r.filter(n=>n.startsWith(t))),r.sort()}function ra(e){let t=[...Xo];return e!==null&&(t=t.filter(s=>s.startsWith(e))),t.sort()}function na(e){let t=[...Jo];return e!==null&&(t=t.filter(s=>s.startsWith(e))),t.sort()}async function pr(e,t){let s=[];try{let r=e.state.cwd,n=t??"";if(t){let a=t.lastIndexOf("/");if(a!==-1){let o=t.slice(0,a)||"/";n=t.slice(a+1),o.startsWith("/")?r=o:r=`${e.state.cwd}/${o}`}}let i=await e.fs.readdir(r);for(let a of i){let o=`${r}/${a}`;try{if((await e.fs.stat(o)).isDirectory&&(!n||a.startsWith(n)))if(t?.includes("/")){let u=t.lastIndexOf("/"),c=t.slice(0,u+1);s.push(c+a)}else s.push(a)}catch{}}}catch{}return s.sort()}async function fi(e,t){let s=[];try{let r=e.state.cwd,n=t??"";if(t){let a=t.lastIndexOf("/");if(a!==-1){let o=t.slice(0,a)||"/";n=t.slice(a+1),o.startsWith("/")?r=o:r=`${e.state.cwd}/${o}`}}let i=await e.fs.readdir(r);for(let a of i)if(!n||a.startsWith(n))if(t?.includes("/")){let o=t.lastIndexOf("/"),l=t.slice(0,o+1);s.push(l+a)}else s.push(a)}catch{}return s.sort()}function ia(e){return["root","nobody"]}async function oa(e,t){let s=new Set;for(let i of mr)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 di)s.add(i);let r=T(e.state.env,"PATH","/usr/bin:/bin");for(let i of r.split(":"))if(i)try{let a=await e.fs.readdir(i);for(let o of a)s.add(o)}catch{}let n=Array.from(s);return t!==null&&(n=n.filter(i=>i.startsWith(t))),n.sort()}async function aa(e,t){let r=new X().parseWordFromString(t,!1,!1);return await z(e,r)}function la(e,t){let s=T(e.state.env,"IFS",`
45
- `);if(s.length===0)return[t];let r=new Set(s.split("")),n=[],i="",a=0;for(;a<t.length;){let o=t[a];if(o==="\\"&&a+1<t.length){let l=t[a+1];i+=l,a+=2}else r.has(o)?(i.length>0&&(n.push(i),i=""),a++):(i+=o,a++)}return i.length>0&&n.push(i),n}function St(e,t){for(let[s,r]of t)r===void 0?e.state.env.delete(s):g(e.state.env,s,r)}function ca(e){let t=[];if(e.state.env.get("COMPREPLY__length")!==void 0){let n=Ie(e,"COMPREPLY");for(let[,i]of n)t.push(i)}else e.state.env.has("COMPREPLY")&&t.push(T(e.state.env,"COMPREPLY"));return t}var ua=["bashdefault","default","dirnames","filenames","noquote","nosort","nospace","plusdirs"];function wr(e,t){e.state.completionSpecs||(e.state.completionSpecs=new Map);let s=!1,r=!1,n=!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")r=!0;else if(d==="-D")n=!0;else if(d==="-W"){if(f++,f>=t.length)return P(`complete: -W: option requires an argument
46
- `,2);i=t[f]}else if(d==="-F"){if(f++,f>=t.length)return P(`complete: -F: option requires an argument
47
- `,2);a=t[f]}else if(d==="-o"){if(f++,f>=t.length)return P(`complete: -o: option requires an argument
48
- `,2);let p=t[f];if(!ua.includes(p))return P(`complete: ${p}: invalid option name
49
- `,2);l.push(p)}else if(d==="-A"){if(f++,f>=t.length)return P(`complete: -A: option requires an argument
50
- `,2);u.push(t[f])}else if(d==="-C"){if(f++,f>=t.length)return P(`complete: -C: option requires an argument
51
- `,2);o=t[f]}else if(d==="-G"){if(f++,f>=t.length)return P(`complete: -G: option requires an argument
52
- `,2)}else if(d==="-P"){if(f++,f>=t.length)return P(`complete: -P: option requires an argument
53
- `,2)}else if(d==="-S"){if(f++,f>=t.length)return P(`complete: -S: option requires an argument
54
- `,2)}else if(d==="-X"){if(f++,f>=t.length)return P(`complete: -X: option requires an argument
55
- `,2)}else if(d==="--"){c.push(...t.slice(f+1));break}else d.startsWith("-")||c.push(d)}if(r){if(c.length===0)return e.state.completionSpecs.clear(),Ne();for(let f of c)e.state.completionSpecs.delete(f);return Ne()}if(s)return c.length===0?gr(e):gr(e,c);if(t.length===0||c.length===0&&!i&&!a&&!o&&l.length===0&&u.length===0&&!n)return gr(e);if(a&&c.length===0&&!n)return P(`complete: -F: option requires a command name
56
- `,2);if(n){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),Ne()}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 Ne()}function gr(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
31
+ `),r=!0;else if(n.operator==="<"&&n.target.type==="Word"){let i=await z(e,n.target),a=e.fs.resolvePath(e.state.cwd,i);try{s=await e.fs.readFile(a),r=!0}catch{}}}return s}async function Ts(e,t,s,r=P(),n){e.state.callDepth++,e.state.callDepth>e.limits.maxCallDepth&&(e.state.callDepth--,Me(`${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(n??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),N(e.state.env,String(o+1))),g(e.state.env,String(o+1),s[o]);i.set("@",N(e.state.env,"@")),i.set("#",N(e.state.env,"#")),g(e.state.env,"@",s.join(" ")),g(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(ni(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):g(e.state.env,c,u);e.state.funcNameStack?.shift(),e.state.callLineStack?.shift(),e.state.sourceStack?.shift(),e.state.callDepth--};try{let o=await De(e,e.outputChannels,t.redirections);return o.error?await Y(e,o.channels,()=>se(e,()=>Promise.resolve(o.error))):await Y(e,o.channels,async()=>{try{let l=await Et(e,o.legacyRedirections);if(l)return await se(e,()=>Promise.resolve(l));let c=await re(r),u=c.length>0?fe(c):await Zo(e,o.legacyRedirections),f=await e.executeCommand(t.body,u);return await se(e,()=>Promise.resolve(f))}catch(l){let{writeFailure:c}=await Qe(e,l);if(c)return c;if(l instanceof ve)return F(P(),P(),l.exitCode);throw l}})}catch(o){throw await te(e,o),o}finally{a()}}var di=["!","[[","]]","case","do","done","elif","else","esac","fi","for","function","if","in","then","time","until","while","{","}"],yr=[".",":","[","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"],Xo=["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"],Jo=yr;async function gr(e,t){let s=[],r=null,n="",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 y=0;y<t.length;y++){let k=t[y];if(k==="-v")s.push("variable");else if(k==="-e")s.push("export");else if(k==="-f")s.push("file");else if(k==="-d")s.push("directory");else if(k==="-k")s.push("keyword");else if(k==="-A"){if(y++,y>=t.length)return A(`compgen: -A: option requires an argument
32
+ `,2);let _=t[y];if(!m.includes(_))return A(`compgen: ${_}: invalid action name
33
+ `,2);s.push(_)}else if(k==="-W"){if(y++,y>=t.length)return A(`compgen: -W: option requires an argument
34
+ `,2);r=t[y]}else if(k==="-P"){if(y++,y>=t.length)return A(`compgen: -P: option requires an argument
35
+ `,2);n=t[y]}else if(k==="-S"){if(y++,y>=t.length)return A(`compgen: -S: option requires an argument
36
+ `,2);i=t[y]}else if(k==="-o"){if(y++,y>=t.length)return A(`compgen: -o: option requires an argument
37
+ `,2);let _=t[y];if(_==="plusdirs")o=!0;else if(_==="dirnames")l=!0;else if(_==="default")c=!0;else if(!(_==="filenames"||_==="nospace"||_==="bashdefault"||_==="noquote"))return A(`compgen: ${_}: invalid option name
38
+ `,2)}else if(k==="-F"){if(y++,y>=t.length)return A(`compgen: -F: option requires an argument
39
+ `,2);f=t[y]}else if(k==="-C"){if(y++,y>=t.length)return A(`compgen: -C: option requires an argument
40
+ `,2);d=t[y]}else if(k==="-X"){if(y++,y>=t.length)return A(`compgen: -X: option requires an argument
41
+ `,2);u=t[y]}else if(k==="-G"){if(y++,y>=t.length)return A(`compgen: -G: option requires an argument
42
+ `,2)}else if(k==="--"){p.push(...t.slice(y+1));break}else k.startsWith("-")||p.push(k)}a=p[0]??null;let h=[];if(l){let y=await mr(e,a);h.push(...y)}if(c){let y=await fi(e,a);h.push(...y)}for(let y of s)if(y==="variable"){let k=Ko(e,a);h.push(...k)}else if(y==="export"){let k=Yo(e,a);h.push(...k)}else if(y==="function"){let k=Qo(e,a);h.push(...k)}else if(y==="builtin"){let k=ea(a);h.push(...k)}else if(y==="keyword"){let k=ta(a);h.push(...k)}else if(y==="alias"){let k=sa(e,a);h.push(...k)}else if(y==="shopt"){let k=ra(a);h.push(...k)}else if(y==="helptopic"){let k=na(a);h.push(...k)}else if(y==="directory"){let k=await mr(e,a);h.push(...k)}else if(y==="file"){let k=await fi(e,a);h.push(...k)}else if(y==="user"){let k=ia(a);h.push(...k)}else if(y==="command"){let k=await oa(e,a);h.push(...k)}if(r!==null)try{let y=await aa(e,r),k=la(e,y);for(let _ of k)(a===null||_.startsWith(a))&&h.push(_)}catch{return F(R,R,1)}if(o){let y=await mr(e,a);for(let k of y)h.includes(k)||h.push(k)}let v="";if(f!==null){let y=e.state.functions.get(f);if(y){let k=new Map;k.set("COMP_WORDS__length",N(e.state.env,"COMP_WORDS__length")),g(e.state.env,"COMP_WORDS__length","0"),k.set("COMP_CWORD",N(e.state.env,"COMP_CWORD")),g(e.state.env,"COMP_CWORD","-1"),k.set("COMP_LINE",N(e.state.env,"COMP_LINE")),g(e.state.env,"COMP_LINE",""),k.set("COMP_POINT",N(e.state.env,"COMP_POINT")),g(e.state.env,"COMP_POINT","0");let _=new Map;for(let $ of e.state.env.keys())($==="COMPREPLY"||$.startsWith("COMPREPLY_")||$==="COMPREPLY__length")&&(_.set($,N(e.state.env,$)),e.state.env.delete($));let L=["compgen",p[0]??"",""];try{let $=xe(),C=xe(),O=await Y(e,{bindings:new Map([[1,{sink:$}],[2,{sink:C}]])},()=>Ts(e,y,L,P()));if(await Wt(e,O.stderr,C),O.exitCode!==0)return St(e,k),St(e,_),F(R,C.stream(),1);await Wt(e,O.stdout,$),v=B(await re($.stream()));let I=ca(e);h.push(...I)}catch{return St(e,k),St(e,_),F(R,R,1)}St(e,k),St(e,_)}}if(d!==null)try{let y=Fe(d),k=xe(),_=xe(),L=await Y(e,{bindings:new Map([[1,{sink:k}],[2,{sink:_}]])},()=>e.executeScript(y));if(await Wt(e,L.stderr,_),L.exitCode!==0)return F(R,_.stream(),L.exitCode);await Wt(e,L.stdout,k);let $=await re(k.stream());if($.length>0){let C=B($).split(`
43
+ `);for(let O of C)O.length>0&&h.push(O)}}catch(y){if(y.name==="ParseException")return A(`compgen: -C: ${y.message}
44
+ `,2);throw y}let E=h;if(u!==null){let y=u.startsWith("!"),k=y?u.slice(1):u;E=h.filter(_=>{let L=vt(_,k,!1,!0);return y?L:!L})}if(E.length===0&&a!==null)return F(W(v),R,1);let S=E.map(y=>`${n}${y}${i}`).join(`
45
+ `),b=v+(S?`${S}
46
+ `:"");return G(b)}function Ko(e,t){let s=new Set;for(let n of e.state.env.keys()){if(n.includes("_")&&/^[a-zA-Z_][a-zA-Z0-9_]*_\d+$/.test(n)||n.endsWith("__length"))continue;let i=n.split("_")[0];/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(n)?s.add(n):i&&/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(i)&&e.state.env.has(`${i}__length`)&&s.add(i)}let r=Array.from(s);return t!==null&&(r=r.filter(n=>n.startsWith(t))),r.sort()}function Yo(e,t){let s=e.state.exportedVars??new Set,r=Array.from(s);return t!==null&&(r=r.filter(n=>n.startsWith(t))),r=r.filter(n=>n.includes("_")&&/^[a-zA-Z_][a-zA-Z0-9_]*_\d+$/.test(n)||n.endsWith("__length")?!1:e.state.env.has(n)),r.sort()}function Qo(e,t){let s=Array.from(e.state.functions.keys());return t!==null&&(s=s.filter(r=>r.startsWith(t))),s.sort()}function ea(e){let t=[...yr];return e!==null&&(t=t.filter(s=>s.startsWith(e))),t.sort()}function ta(e){let t=[...di];return e!==null&&(t=t.filter(s=>s.startsWith(e))),t.sort()}function sa(e,t){let s=[];for(let n of e.state.env.keys())if(n.startsWith("BASH_ALIAS_")){let i=n.slice(11);s.push(i)}let r=s;return t!==null&&(r=r.filter(n=>n.startsWith(t))),r.sort()}function ra(e){let t=[...Xo];return e!==null&&(t=t.filter(s=>s.startsWith(e))),t.sort()}function na(e){let t=[...Jo];return e!==null&&(t=t.filter(s=>s.startsWith(e))),t.sort()}async function mr(e,t){let s=[];try{let r=e.state.cwd,n=t??"";if(t){let a=t.lastIndexOf("/");if(a!==-1){let o=t.slice(0,a)||"/";n=t.slice(a+1),o.startsWith("/")?r=o:r=`${e.state.cwd}/${o}`}}let i=await e.fs.readdir(r);for(let a of i){let o=`${r}/${a}`;try{if((await e.fs.stat(o)).isDirectory&&(!n||a.startsWith(n)))if(t?.includes("/")){let c=t.lastIndexOf("/"),u=t.slice(0,c+1);s.push(u+a)}else s.push(a)}catch{}}}catch{}return s.sort()}async function fi(e,t){let s=[];try{let r=e.state.cwd,n=t??"";if(t){let a=t.lastIndexOf("/");if(a!==-1){let o=t.slice(0,a)||"/";n=t.slice(a+1),o.startsWith("/")?r=o:r=`${e.state.cwd}/${o}`}}let i=await e.fs.readdir(r);for(let a of i)if(!n||a.startsWith(n))if(t?.includes("/")){let o=t.lastIndexOf("/"),l=t.slice(0,o+1);s.push(l+a)}else s.push(a)}catch{}return s.sort()}function ia(e){return["root","nobody"]}async function oa(e,t){let s=new Set;for(let i of yr)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 di)s.add(i);let r=N(e.state.env,"PATH","/usr/bin:/bin");for(let i of r.split(":"))if(i)try{let a=await e.fs.readdir(i);for(let o of a)s.add(o)}catch{}let n=Array.from(s);return t!==null&&(n=n.filter(i=>i.startsWith(t))),n.sort()}async function aa(e,t){let r=new X().parseWordFromString(t,!1,!1);return await z(e,r)}function la(e,t){let s=N(e.state.env,"IFS",`
47
+ `);if(s.length===0)return[t];let r=new Set(s.split("")),n=[],i="",a=0;for(;a<t.length;){let o=t[a];if(o==="\\"&&a+1<t.length){let l=t[a+1];i+=l,a+=2}else r.has(o)?(i.length>0&&(n.push(i),i=""),a++):(i+=o,a++)}return i.length>0&&n.push(i),n}function St(e,t){for(let[s,r]of t)r===void 0?e.state.env.delete(s):g(e.state.env,s,r)}function ca(e){let t=[];if(e.state.env.get("COMPREPLY__length")!==void 0){let n=Ie(e,"COMPREPLY");for(let[,i]of n)t.push(i)}else e.state.env.has("COMPREPLY")&&t.push(N(e.state.env,"COMPREPLY"));return t}var ua=["bashdefault","default","dirnames","filenames","noquote","nosort","nospace","plusdirs"];function vr(e,t){e.state.completionSpecs||(e.state.completionSpecs=new Map);let s=!1,r=!1,n=!1,i,a,o,l=[],c=[],u=[];for(let f=0;f<t.length;f++){let d=t[f];if(d==="-p")s=!0;else if(d==="-r")r=!0;else if(d==="-D")n=!0;else if(d==="-W"){if(f++,f>=t.length)return A(`complete: -W: option requires an argument
48
+ `,2);i=t[f]}else if(d==="-F"){if(f++,f>=t.length)return A(`complete: -F: option requires an argument
49
+ `,2);a=t[f]}else if(d==="-o"){if(f++,f>=t.length)return A(`complete: -o: option requires an argument
50
+ `,2);let p=t[f];if(!ua.includes(p))return A(`complete: ${p}: invalid option name
51
+ `,2);l.push(p)}else if(d==="-A"){if(f++,f>=t.length)return A(`complete: -A: option requires an argument
52
+ `,2);c.push(t[f])}else if(d==="-C"){if(f++,f>=t.length)return A(`complete: -C: option requires an argument
53
+ `,2);o=t[f]}else if(d==="-G"){if(f++,f>=t.length)return A(`complete: -G: option requires an argument
54
+ `,2)}else if(d==="-P"){if(f++,f>=t.length)return A(`complete: -P: option requires an argument
55
+ `,2)}else if(d==="-S"){if(f++,f>=t.length)return A(`complete: -S: option requires an argument
56
+ `,2)}else if(d==="-X"){if(f++,f>=t.length)return A(`complete: -X: option requires an argument
57
+ `,2)}else if(d==="--"){u.push(...t.slice(f+1));break}else d.startsWith("-")||u.push(d)}if(r){if(u.length===0)return e.state.completionSpecs.clear(),Ne();for(let f of u)e.state.completionSpecs.delete(f);return Ne()}if(s)return u.length===0?wr(e):wr(e,u);if(t.length===0||u.length===0&&!i&&!a&&!o&&l.length===0&&c.length===0&&!n)return wr(e);if(a&&u.length===0&&!n)return A(`complete: -F: option requires a command name
58
+ `,2);if(n){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),Ne()}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 Ne()}function wr(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
57
59
  `;return F(R,W(i),1)}return Ne()}let r=[],n=t||Array.from(s.keys());for(let i of n){if(i==="__default__")continue;let a=s.get(i);if(!a){if(t)return F(W(r.join(`
58
60
  `)+(r.length>0?`
59
61
  `:"")),W(`complete: ${i}: no completion specification
60
- `),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}`,r.push(o)}return r.length===0?Ne():H(`${r.join(`
62
+ `),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}`,r.push(o)}return r.length===0?Ne():G(`${r.join(`
61
63
  `)}
62
- `)}var hi=["bashdefault","default","dirnames","filenames","noquote","nosort","nospace","plusdirs"];function vr(e,t){e.state.completionSpecs||(e.state.completionSpecs=new Map);let s=!1,r=!1,n=[],i=[],a=[];for(let o=0;o<t.length;o++){let l=t[o];if(l==="-D")s=!0;else if(l==="-E")r=!0;else if(l==="-o"){if(o++,o>=t.length)return P(`compopt: -o: option requires an argument
63
- `,2);let u=t[o];if(!hi.includes(u))return P(`compopt: ${u}: invalid option name
64
- `,2);n.push(u)}else if(l==="+o"){if(o++,o>=t.length)return P(`compopt: +o: option requires an argument
65
- `,2);let u=t[o];if(!hi.includes(u))return P(`compopt: ${u}: invalid option name
66
- `,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 n)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),Ne()}if(r){let o=e.state.completionSpecs.get("__empty__")??{},l=new Set(o.options??[]);for(let u of n)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),Ne()}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 n)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 Ne()}return P(`compopt: not currently executing completion function
67
- `,1)}async function br(e,t){if(e.state.loopDepth===0){if(e.state.parentHasLoopContext)throw new Ge;return U()}if(t.length>1)throw await G(e,2,`bash: continue: too many arguments
68
- `,!0),new q(1);let s=1;if(t.length>0){let r=Number.parseInt(t[0],10);if(Number.isNaN(r)||r<1)throw await G(e,2,`bash: continue: ${t[0]}: numeric argument required
69
- `,!0),new q(1);s=r}throw new Ae(s)}function ne(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 Er(e){for(let t=0;t<e.length;t++){let s=e.charCodeAt(t);if(s<32||s===127)return!0}return!1}function Sr(e){let t="$'";for(let s=0;s<e.length;s++){let r=e[s],n=e.charCodeAt(s);n===7?t+="\\a":n===8?t+="\\b":n===9?t+="\\t":n===10?t+="\\n":n===11?t+="\\v":n===12?t+="\\f":n===13?t+="\\r":n===27?t+="\\e":n===39?t+="\\'":n===92?t+="\\\\":n<32||n===127?t+=`\\${n.toString(8).padStart(3,"0")}`:t+=r}return t+="'",t}function ks(e){return Er(e)?Sr(e):/^[a-zA-Z0-9_/.:\-@%+,=]*$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}function ct(e){return Er(e)?Sr(e):`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function $r(e){return Er(e)?Sr(e):`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function pi(e,t){let s="";return e.state.integerVars?.has(t)&&(s+="i"),e.state.lowercaseVars?.has(t)&&(s+="l"),Ee(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 Pr(e){return e===""?"''":/[\s'\\]/.test(e)?`'${e.replace(/'/g,"'\\''")}'`:e}function mi(e,t){let s="",r="",n=!1;for(let i of t){let a=pi(e,i);if(e.state.associativeArrays?.has(i)){let u=et(e,i);if(u.length===0)s+=`declare -A ${i}=()
70
- `;else{let c=u.map(f=>{let d=T(e.state.env,`${i}_${f}`,""),p=Pr(d);return`['${f}']=${p}`});s+=`declare -A ${i}=(${c.join(" ")})
71
- `}continue}let l=me(e,i);if(l.length>0){let u=l.map(c=>{let f=T(e.state.env,`${i}_${c}`,"");return`[${c}]=${ct(f)}`});s+=`declare -a ${i}=(${u.join(" ")})
64
+ `)}var hi=["bashdefault","default","dirnames","filenames","noquote","nosort","nospace","plusdirs"];function br(e,t){e.state.completionSpecs||(e.state.completionSpecs=new Map);let s=!1,r=!1,n=[],i=[],a=[];for(let o=0;o<t.length;o++){let l=t[o];if(l==="-D")s=!0;else if(l==="-E")r=!0;else if(l==="-o"){if(o++,o>=t.length)return A(`compopt: -o: option requires an argument
65
+ `,2);let c=t[o];if(!hi.includes(c))return A(`compopt: ${c}: invalid option name
66
+ `,2);n.push(c)}else if(l==="+o"){if(o++,o>=t.length)return A(`compopt: +o: option requires an argument
67
+ `,2);let c=t[o];if(!hi.includes(c))return A(`compopt: ${c}: invalid option name
68
+ `,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 n)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),Ne()}if(r){let o=e.state.completionSpecs.get("__empty__")??{},l=new Set(o.options??[]);for(let c of n)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),Ne()}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 n)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 Ne()}return A(`compopt: not currently executing completion function
69
+ `,1)}async function Er(e,t){if(e.state.loopDepth===0){if(e.state.parentHasLoopContext)throw new He;return U()}if(t.length>1)throw await H(e,2,`bash: continue: too many arguments
70
+ `,!0),new q(1);let s=1;if(t.length>0){let r=Number.parseInt(t[0],10);if(Number.isNaN(r)||r<1)throw await H(e,2,`bash: continue: ${t[0]}: numeric argument required
71
+ `,!0),new q(1);s=r}throw new Ce(s)}function ne(e,t){let s=N(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 Sr(e){for(let t=0;t<e.length;t++){let s=e.charCodeAt(t);if(s<32||s===127)return!0}return!1}function $r(e){let t="$'";for(let s=0;s<e.length;s++){let r=e[s],n=e.charCodeAt(s);n===7?t+="\\a":n===8?t+="\\b":n===9?t+="\\t":n===10?t+="\\n":n===11?t+="\\v":n===12?t+="\\f":n===13?t+="\\r":n===27?t+="\\e":n===39?t+="\\'":n===92?t+="\\\\":n<32||n===127?t+=`\\${n.toString(8).padStart(3,"0")}`:t+=r}return t+="'",t}function xs(e){return Sr(e)?$r(e):/^[a-zA-Z0-9_/.:\-@%+,=]*$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}function ct(e){return Sr(e)?$r(e):`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function Pr(e){return Sr(e)?$r(e):`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function pi(e,t){let s="";return e.state.integerVars?.has(t)&&(s+="i"),e.state.lowercaseVars?.has(t)&&(s+="l"),Ee(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 Ar(e){return e===""?"''":/[\s'\\]/.test(e)?`'${e.replace(/'/g,"'\\''")}'`:e}function mi(e,t){let s="",r="",n=!1;for(let i of t){let a=pi(e,i);if(e.state.associativeArrays?.has(i)){let c=et(e,i);if(c.length===0)s+=`declare -A ${i}=()
72
+ `;else{let u=c.map(f=>{let d=N(e.state.env,`${i}_${f}`,""),p=Ar(d);return`['${f}']=${p}`});s+=`declare -A ${i}=(${u.join(" ")})
73
+ `}continue}let l=me(e,i);if(l.length>0){let c=l.map(u=>{let f=N(e.state.env,`${i}_${u}`,"");return`[${u}]=${ct(f)}`});s+=`declare -a ${i}=(${c.join(" ")})
72
74
  `;continue}if(e.state.env.has(`${i}__length`)){s+=`declare -a ${i}=()
73
- `;continue}if(e.state.env.has(i)){let u=T(e.state.env,i);s+=`declare ${a} ${i}=${$r(u)}
74
- `}else{let u=e.state.declaredVars?.has(i),c=e.state.localVarDepth?.has(i);u||c?s+=`declare ${a} ${i}
75
+ `;continue}if(e.state.env.has(i)){let c=N(e.state.env,i);s+=`declare ${a} ${i}=${Pr(c)}
76
+ `}else{let c=e.state.declaredVars?.has(i),u=e.state.localVarDepth?.has(i);c||u?s+=`declare ${a} ${i}
75
77
  `:(r+=`bash: declare: ${i}: not found
76
- `,n=!0)}}return F(W(s),W(r),n?1:0)}function yi(e,t){let{filterExport:s,filterReadonly:r,filterNameref:n,filterIndexedArray:i,filterAssocArray:a}=t,o=s||r||n||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=pi(e,f),p=e.state.associativeArrays?.has(f),m=me(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)||r&&!e.state.readonlyVars?.has(f)||n&&!Ee(e,f)))){if(p){let b=et(e,f);if(b.length===0)l+=`declare -A ${f}=()
77
- `;else{let E=b.map($=>{let y=T(e.state.env,`${f}_${$}`,""),v=Pr(y);return`['${$}']=${v}`});l+=`declare -A ${f}=(${E.join(" ")})
78
- `}continue}if(m.length>0){let b=m.map(E=>{let $=T(e.state.env,`${f}_${E}`,"");return`[${E}]=${ct($)}`});l+=`declare -a ${f}=(${b.join(" ")})
78
+ `,n=!0)}}return F(W(s),W(r),n?1:0)}function yi(e,t){let{filterExport:s,filterReadonly:r,filterNameref:n,filterIndexedArray:i,filterAssocArray:a}=t,o=s||r||n||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=pi(e,f),p=e.state.associativeArrays?.has(f),m=me(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)||r&&!e.state.readonlyVars?.has(f)||n&&!Ee(e,f)))){if(p){let v=et(e,f);if(v.length===0)l+=`declare -A ${f}=()
79
+ `;else{let E=v.map(S=>{let b=N(e.state.env,`${f}_${S}`,""),y=Ar(b);return`['${S}']=${y}`});l+=`declare -A ${f}=(${E.join(" ")})
80
+ `}continue}if(m.length>0){let v=m.map(E=>{let S=N(e.state.env,`${f}_${E}`,"");return`[${E}]=${ct(S)}`});l+=`declare -a ${f}=(${v.join(" ")})
79
81
  `;continue}if(e.state.env.has(`${f}__length`)){l+=`declare -a ${f}=()
80
- `;continue}if(e.state.env.has(f)){let b=T(e.state.env,f);l+=`declare ${d} ${f}=${$r(b)}
81
- `}}}return H(l)}function gi(e){let t="",s=Array.from(e.state.associativeArrays??[]).sort();for(let r of s){let n=et(e,r);if(n.length===0)t+=`declare -A ${r}=()
82
- `;else{let i=n.map(a=>{let o=T(e.state.env,`${r}_${a}`,""),l=Pr(o);return`['${a}']=${l}`});t+=`declare -A ${r}=(${i.join(" ")})
83
- `}}return H(t)}function wi(e){let t="",s=new Set;for(let n of e.state.env.keys()){if(n.startsWith("BASH_"))continue;if(n.endsWith("__length")){let a=n.slice(0,-8);e.state.associativeArrays?.has(a)||s.add(a);continue}let i=n.lastIndexOf("_");if(i>0){let a=n.slice(0,i),o=n.slice(i+1);/^\d+$/.test(o)&&(e.state.associativeArrays?.has(a)||s.add(a))}}let r=Array.from(s).sort();for(let n of r){let i=me(e,n);if(i.length===0)t+=`declare -a ${n}=()
84
- `;else{let a=i.map(o=>{let l=T(e.state.env,`${n}_${o}`,"");return`[${o}]=${ct(l)}`});t+=`declare -a ${n}=(${a.join(" ")})
85
- `}}return H(t)}function vi(e){let t="",s=new Set;for(let n of e.state.env.keys()){if(n.startsWith("BASH_"))continue;if(n.endsWith("__length")){let a=n.slice(0,-8);s.add(a);continue}let i=n.lastIndexOf("_");if(i>0){let a=n.slice(0,i),o=n.slice(i+1);if(/^\d+$/.test(o)||e.state.associativeArrays?.has(a)){s.add(a);continue}}s.add(n)}let r=Array.from(s).sort();for(let n of r)e.state.associativeArrays?.has(n)||me(e,n).length>0||e.state.env.has(`${n}__length`)||e.state.env.has(n)&&(t+=`${n}=${ks(T(e.state.env,n))}
86
- `);return H(t)}function Cr(e,t){e.state.integerVars??=new Set,e.state.integerVars.add(t)}function Bt(e,t){return e.state.integerVars?.has(t)??!1}function Ar(e,t){e.state.lowercaseVars??=new Set,e.state.lowercaseVars.add(t),e.state.uppercaseVars?.delete(t)}function fa(e,t){return e.state.lowercaseVars?.has(t)??!1}function kr(e,t){e.state.uppercaseVars??=new Set,e.state.uppercaseVars.add(t),e.state.lowercaseVars?.delete(t)}function da(e,t){return e.state.uppercaseVars?.has(t)??!1}function $t(e,t,s){return fa(e,t)?s.toLowerCase():da(e,t)?s.toUpperCase():s}async function bi(e,t){try{let s=new X,r=ce(s,t),n=await ee(e,r.expression);return String(n)}catch{return"0"}}function ha(e){let t=e.match(/^[a-zA-Z_][a-zA-Z0-9_]*/);if(!t)return null;let s=t[0],r=s.length;if(e[r]!=="[")return null;let n=0,i=r+1;for(;r<e.length;r++)if(e[r]==="[")n++;else if(e[r]==="]"&&(n--,n===0))break;if(n!==0)return null;let a=e.slice(i,r);if(r++,e[r]!=="=")return null;r++;let o=e.slice(r);return{name:s,indexExpr:a,value:o}}async function xr(e,t){let s=!1,r=!1,n=!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,E=[];for(let A=0;A<t.length;A++){let O=t[A];if(O==="-a")s=!0;else if(O==="-A")r=!0;else if(O==="-r")n=!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==="--"){E.push(...t.slice(A+1));break}else if(O.startsWith("+")){for(let M of O.slice(1))if(M==="n")l=!0;else if(M==="a")u=!0;else if(M==="x")c=!0;else if(M!=="r"){if(M!=="i"){if(!(M==="f"||M==="F"))return F(R,W(`bash: typeset: +${M}: invalid option
87
- `),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 M of O.slice(1))if(M==="a")s=!0;else if(M==="A")r=!0;else if(M==="r")n=!0;else if(M==="x")i=!0;else if(M==="p")a=!0;else if(M==="n")o=!0;else if(M==="i")f=!0;else if(M==="l")d=!0;else if(M==="u")p=!0;else if(M==="f")m=!0;else if(M==="F")h=!0;else if(M==="g")b=!0;else return F(R,W(`bash: typeset: -${M}: invalid option
88
- `),2);else E.push(O)}let y=e.state.localScopes.length>0&&!b,v=A=>{if(!y)return;let O=e.state.localScopes[e.state.localScopes.length-1];O.has(A)||O.set(A,e.state.env.get(A))},C=A=>{if(!y)return;let O=e.state.localScopes[e.state.localScopes.length-1];O.has(A)||O.set(A,e.state.env.get(A));let M=`${A}_`;for(let _ of e.state.env.keys())_.startsWith(M)&&!_.includes("__")&&(O.has(_)||O.set(_,e.state.env.get(_)));let x=`${A}__length`;e.state.env.has(x)&&!O.has(x)&&O.set(x,e.state.env.get(x))},N=A=>{y&&st(e,A)};if(h){if(E.length===0){let M=Array.from(e.state.functions.keys()).sort(),x="";for(let _ of M)x+=`declare -f ${_}
89
- `;return H(x)}let A=!0,O="";for(let M of E)e.state.functions.has(M)?O+=`${M}
90
- `:A=!1;return F(W(O),R,A?0:1)}if(m){if(E.length===0){let O="",M=Array.from(e.state.functions.keys()).sort();for(let x of M)O+=`${x} ()
82
+ `;continue}if(e.state.env.has(f)){let v=N(e.state.env,f);l+=`declare ${d} ${f}=${Pr(v)}
83
+ `}}}return G(l)}function gi(e){let t="",s=Array.from(e.state.associativeArrays??[]).sort();for(let r of s){let n=et(e,r);if(n.length===0)t+=`declare -A ${r}=()
84
+ `;else{let i=n.map(a=>{let o=N(e.state.env,`${r}_${a}`,""),l=Ar(o);return`['${a}']=${l}`});t+=`declare -A ${r}=(${i.join(" ")})
85
+ `}}return G(t)}function wi(e){let t="",s=new Set;for(let n of e.state.env.keys()){if(n.startsWith("BASH_"))continue;if(n.endsWith("__length")){let a=n.slice(0,-8);e.state.associativeArrays?.has(a)||s.add(a);continue}let i=n.lastIndexOf("_");if(i>0){let a=n.slice(0,i),o=n.slice(i+1);/^\d+$/.test(o)&&(e.state.associativeArrays?.has(a)||s.add(a))}}let r=Array.from(s).sort();for(let n of r){let i=me(e,n);if(i.length===0)t+=`declare -a ${n}=()
86
+ `;else{let a=i.map(o=>{let l=N(e.state.env,`${n}_${o}`,"");return`[${o}]=${ct(l)}`});t+=`declare -a ${n}=(${a.join(" ")})
87
+ `}}return G(t)}function vi(e){let t="",s=new Set;for(let n of e.state.env.keys()){if(n.startsWith("BASH_"))continue;if(n.endsWith("__length")){let a=n.slice(0,-8);s.add(a);continue}let i=n.lastIndexOf("_");if(i>0){let a=n.slice(0,i),o=n.slice(i+1);if(/^\d+$/.test(o)||e.state.associativeArrays?.has(a)){s.add(a);continue}}s.add(n)}let r=Array.from(s).sort();for(let n of r)e.state.associativeArrays?.has(n)||me(e,n).length>0||e.state.env.has(`${n}__length`)||e.state.env.has(n)&&(t+=`${n}=${xs(N(e.state.env,n))}
88
+ `);return G(t)}function Cr(e,t){e.state.integerVars??=new Set,e.state.integerVars.add(t)}function Ut(e,t){return e.state.integerVars?.has(t)??!1}function kr(e,t){e.state.lowercaseVars??=new Set,e.state.lowercaseVars.add(t),e.state.uppercaseVars?.delete(t)}function fa(e,t){return e.state.lowercaseVars?.has(t)??!1}function Tr(e,t){e.state.uppercaseVars??=new Set,e.state.uppercaseVars.add(t),e.state.lowercaseVars?.delete(t)}function da(e,t){return e.state.uppercaseVars?.has(t)??!1}function $t(e,t,s){return fa(e,t)?s.toLowerCase():da(e,t)?s.toUpperCase():s}async function bi(e,t){try{let s=new X,r=ce(s,t),n=await ee(e,r.expression);return String(n)}catch{return"0"}}function ha(e){let t=e.match(/^[a-zA-Z_][a-zA-Z0-9_]*/);if(!t)return null;let s=t[0],r=s.length;if(e[r]!=="[")return null;let n=0,i=r+1;for(;r<e.length;r++)if(e[r]==="[")n++;else if(e[r]==="]"&&(n--,n===0))break;if(n!==0)return null;let a=e.slice(i,r);if(r++,e[r]!=="=")return null;r++;let o=e.slice(r);return{name:s,indexExpr:a,value:o}}async function xr(e,t){let s=!1,r=!1,n=!1,i=!1,a=!1,o=!1,l=!1,c=!1,u=!1,f=!1,d=!1,p=!1,m=!1,h=!1,v=!1,E=[];for(let C=0;C<t.length;C++){let O=t[C];if(O==="-a")s=!0;else if(O==="-A")r=!0;else if(O==="-r")n=!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==="--"){E.push(...t.slice(C+1));break}else if(O.startsWith("+")){for(let I of O.slice(1))if(I==="n")l=!0;else if(I==="a")c=!0;else if(I==="x")u=!0;else if(I!=="r"){if(I!=="i"){if(!(I==="f"||I==="F"))return F(R,W(`bash: typeset: +${I}: invalid option
89
+ `),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 I of O.slice(1))if(I==="a")s=!0;else if(I==="A")r=!0;else if(I==="r")n=!0;else if(I==="x")i=!0;else if(I==="p")a=!0;else if(I==="n")o=!0;else if(I==="i")f=!0;else if(I==="l")d=!0;else if(I==="u")p=!0;else if(I==="f")m=!0;else if(I==="F")h=!0;else if(I==="g")v=!0;else return F(R,W(`bash: typeset: -${I}: invalid option
90
+ `),2);else E.push(O)}let b=e.state.localScopes.length>0&&!v,y=C=>{if(!b)return;let O=e.state.localScopes[e.state.localScopes.length-1];O.has(C)||O.set(C,e.state.env.get(C))},k=C=>{if(!b)return;let O=e.state.localScopes[e.state.localScopes.length-1];O.has(C)||O.set(C,e.state.env.get(C));let I=`${C}_`;for(let x of e.state.env.keys())x.startsWith(I)&&!x.includes("__")&&(O.has(x)||O.set(x,e.state.env.get(x)));let T=`${C}__length`;e.state.env.has(T)&&!O.has(T)&&O.set(T,e.state.env.get(T))},_=C=>{b&&st(e,C)};if(h){if(E.length===0){let I=Array.from(e.state.functions.keys()).sort(),T="";for(let x of I)T+=`declare -f ${x}
91
+ `;return G(T)}let C=!0,O="";for(let I of E)e.state.functions.has(I)?O+=`${I}
92
+ `:C=!1;return F(W(O),R,C?0:1)}if(m){if(E.length===0){let O="",I=Array.from(e.state.functions.keys()).sort();for(let T of I)O+=`${T} ()
91
93
  {
92
94
  # function body
93
95
  }
94
- `;return H(O)}let A=!0;for(let O of E)e.state.functions.has(O)||(A=!1);return F(R,R,A?0:1)}if(a&&E.length>0)return mi(e,E);if(a&&E.length===0)return yi(e,{filterExport:i,filterReadonly:n,filterNameref:o,filterIndexedArray:s,filterAssocArray:r});if(E.length===0&&r&&!a)return gi(e);if(E.length===0&&s&&!a)return wi(e);if(E.length===0&&!a)return vi(e);let I="",k=0;for(let A of E){let O=A.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\((.*)\)$/s);if(O&&!u){let w=O[1],D=O[2];if(r&&me(e,w).length>0){I+=`bash: declare: ${w}: cannot convert indexed to associative array
95
- `,k=1;continue}if((s||!r&&!s)&&e.state.associativeArrays?.has(w)){I+=`bash: declare: ${w}: cannot convert associative to indexed array
96
- `,k=1;continue}if(C(w),r&&(e.state.associativeArrays??=new Set,e.state.associativeArrays.add(w)),Ve(e,w),e.state.env.delete(w),e.state.env.delete(`${w}__length`),r&&D.includes("[")){let L=vs(D);for(let[J,j]of L){let Q=ne(e,j);g(e.state.env,`${w}_${J}`,Q)}}else if(r){let L=Be(D);for(let J=0;J<L.length;J+=2){let j=L[J],Q=J+1<L.length?ne(e,L[J+1]):"";g(e.state.env,`${w}_${j}`,Q)}}else{let L=Be(D);if(L.some(j=>/^\[[^\]]+\]=/.test(j))){let j=0;for(let Q of L){let oe=Q.match(/^\[([^\]]+)\]=(.*)$/);if(oe){let Pe=oe[1],ut=oe[2],lo=ne(e,ut),Ot;if(/^-?\d+$/.test(Pe))Ot=Number.parseInt(Pe,10);else try{let co=new X,uo=ce(co,Pe);Ot=await ee(e,uo.expression)}catch{Ot=0}g(e.state.env,`${w}_${Ot}`,lo),j=Ot+1}else{let Pe=ne(e,Q);g(e.state.env,`${w}_${j}`,Pe),j++}}}else{for(let j=0;j<L.length;j++)g(e.state.env,`${w}_${j}`,L[j]);g(e.state.env,`${w}__length`,String(L.length))}}N(w),n&&Se(e,w),i&&Re(e,w);continue}if(l){let w=A.includes("=")?A.slice(0,A.indexOf("=")):A;if(wn(e,w),!A.includes("="))continue}if(c){let w=A.includes("=")?A.slice(0,A.indexOf("=")):A;if(ns(e,w),!A.includes("="))continue}let M=ha(A);if(M){let{name:w,indexExpr:D,value:L}=M,J=await de(e,w);if(J)return J;C(w);let j;try{let oe=new X,Pe=ce(oe,D);j=await ee(e,Pe.expression)}catch{let oe=parseInt(D,10);j=Number.isNaN(oe)?0:oe}g(e.state.env,`${w}_${j}`,L);let Q=parseInt(T(e.state.env,`${w}__length`,"0"),10);j>=Q&&g(e.state.env,`${w}__length`,String(j+1)),N(w),n&&Se(e,w),i&&Re(e,w);continue}let x=A.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=\((.*)\)$/s);if(x&&!u){let w=x[1],D=x[2],L=await de(e,w);if(L)return L;C(w);let J=Be(D);if(e.state.associativeArrays?.has(w)){let j=vs(D);for(let[Q,oe]of j){let Pe=ne(e,oe);g(e.state.env,`${w}_${Q}`,Pe)}}else{let j=me(e,w),Q=0,oe=e.state.env.get(w);j.length===0&&oe!==void 0?(e.state.env.set(`${w}_0`,oe),e.state.env.delete(w),Q=1):j.length>0&&(Q=Math.max(...j)+1);for(let ut=0;ut<J.length;ut++)g(e.state.env,`${w}_${Q+ut}`,ne(e,J[ut]));let Pe=Q+J.length;g(e.state.env,`${w}__length`,String(Pe))}N(w),n&&Se(e,w),i&&Re(e,w);continue}let _=A.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=(.*)$/);if(_){let w=_[1],D=ne(e,_[2]),L=await de(e,w);if(L)return L;v(w),f&&Cr(e,w),d&&Ar(e,w),p&&kr(e,w);let j=me(e,w).length>0||e.state.associativeArrays?.has(w);if(Bt(e,w)){let Q=T(e.state.env,w,"0"),oe=parseInt(Q,10)||0,Pe=parseInt(await bi(e,D),10)||0;D=String(oe+Pe),g(e.state.env,w,D)}else if(j){D=$t(e,w,D);let Q=`${w}_0`,oe=T(e.state.env,Q);g(e.state.env,Q,oe+D)}else{D=$t(e,w,D);let Q=T(e.state.env,w);g(e.state.env,w,Q+D)}N(w),n&&Se(e,w),i&&Re(e,w),e.state.options.allexport&&!c&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(w));continue}if(A.includes("=")){let w=A.indexOf("="),D=A.slice(0,w),L=A.slice(w+1);if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(D)){I+=`bash: typeset: \`${D}': not a valid identifier
97
- `,k=1;continue}let J=await de(e,D);if(J)return J;if(v(D),o){if(L!==""&&!/^[a-zA-Z_][a-zA-Z0-9_]*(\[.+\])?$/.test(L)){I+=`bash: declare: \`${L}': invalid variable name for name reference
98
- `,k=1;continue}g(e.state.env,D,L),qe(e,D),L!==""&&Js(e,L)&&Xs(e,D),N(D),n&&Se(e,D),i&&Re(e,D);continue}if(f&&Cr(e,D),d&&Ar(e,D),p&&kr(e,D),Bt(e,D)&&(L=await bi(e,L)),L=$t(e,D,L),Ee(e,D)){let j=ze(e,D);j&&j!==D?g(e.state.env,j,L):g(e.state.env,D,L)}else g(e.state.env,D,L);N(D),n&&Se(e,D),i&&Re(e,D),e.state.options.allexport&&!c&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(D))}else{let w=A;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(w)){I+=`bash: typeset: \`${w}': not a valid identifier
99
- `,k=1;continue}if(s||r?C(w):v(w),o){qe(e,w);let L=T(e.state.env,w);L!==""&&!/^[a-zA-Z_][a-zA-Z0-9_]*(\[.+\])?$/.test(L)?vn(e,w):L&&Js(e,L)&&Xs(e,w),N(w),n&&Se(e,w),i&&Re(e,w);continue}if(f&&Cr(e,w),d&&Ar(e,w),p&&kr(e,w),r){if(me(e,w).length>0){I+=`bash: declare: ${w}: cannot convert indexed to associative array
100
- `,k=1;continue}e.state.associativeArrays??=new Set,e.state.associativeArrays.add(w)}let D=Array.from(e.state.env.keys()).some(L=>L.startsWith(`${w}_`)&&!L.startsWith(`${w}__length`));!e.state.env.has(w)&&!D&&(s||r?g(e.state.env,`${w}__length`,"0"):(e.state.declaredVars??=new Set,e.state.declaredVars.add(w))),N(w),n&&Se(e,w),i&&Re(e,w)}}return F(R,W(I),k)}async function _r(e,t){let s=!1,r=!1,n=!1,i=[];for(let a=0;a<t.length;a++){let o=t[a];if(o==="-a")s=!0;else if(o==="-A")r=!0;else if(o==="-p")n=!0;else if(o==="--"){i.push(...t.slice(a+1));break}else o.startsWith("-")||i.push(o)}if(i.length===0){let a="",o=Array.from(e.state.readonlyVars||[]).sort();for(let l of o){let u=e.state.env.get(l);if(u!==void 0){let c=B(u??R).replace(/\\/g,"\\\\").replace(/"/g,'\\"');a+=`declare -r ${l}="${c}"
101
- `}}return H(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 de(e,f);if(p)return p;let m=Be(d);if(e.state.associativeArrays?.has(f)){let h=vs(d);for(let[b,E]of h){let $=ne(e,E);g(e.state.env,`${f}_${b}`,$)}}else{let h=me(e,f),b=0,E=e.state.env.get(f);h.length===0&&E!==void 0?(e.state.env.set(`${f}_0`,E),e.state.env.delete(f),b=1):h.length>0&&(b=Math.max(...h)+1);for(let y=0;y<m.length;y++)g(e.state.env,`${f}_${b+y}`,ne(e,m[y]));let $=b+m.length;g(e.state.env,`${f}__length`,String($))}Se(e,f);continue}let l=a.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=(.*)$/);if(l){let f=l[1],d=ne(e,l[2]),p=await de(e,f);if(p)return p;let m=T(e.state.env,f);g(e.state.env,f,m+d),Se(e,f);continue}let u=ti(a);if(u.value===void 0&&!u.isArray){Se(e,u.name);continue}let c=await si(e,u,{makeReadonly:!0});if(c)return c}return wt}function Tr(e){return e.state.directoryStack??=[],e.state.directoryStack}function Ut(e,t){return t&&e===t?"~":t&&e.startsWith(`${t}/`)?`~${e.slice(t.length)}`:e}function pa(e){let t=e.split("/").filter(r=>r&&r!=="."),s=[];for(let r of t)r===".."?s.pop():s.push(r);return`/${s.join("/")}`}async function Nr(e,t){let s=Tr(e),r;for(let o=0;o<t.length;o++){let l=t[o];if(l==="--"){if(o+1<t.length){if(r!==void 0)return P(`bash: pushd: too many arguments
102
- `,2);r=t[o+1],o++}}else{if(l.startsWith("-")&&l!=="-")return P(`bash: pushd: ${l}: invalid option
103
- `,2);if(r!==void 0)return P(`bash: pushd: too many arguments
104
- `,2);r=l}}if(r===void 0){if(s.length<2)return P(`bash: pushd: no other directory
105
- `,1);let o=s[0];s[0]=s[1],s[1]=o,r=s[0]}let n;if(r.startsWith("/"))n=r;else if(r===".."){let o=e.state.cwd.split("/").filter(l=>l);o.pop(),n=`/${o.join("/")}`}else r==="."?n=e.state.cwd:r.startsWith("~")?n=T(e.state.env,"HOME","/")+r.slice(1):n=`${e.state.cwd}/${r}`;n=pa(n);try{if(!(await e.fs.stat(n)).isDirectory)return P(`bash: pushd: ${r}: Not a directory
106
- `,1)}catch{return P(`bash: pushd: ${r}: No such file or directory
107
- `,1)}s.unshift(e.state.cwd),e.state.previousDir=e.state.cwd,e.state.cwd=n,g(e.state.env,"PWD",n),g(e.state.env,"OLDPWD",e.state.previousDir);let i=T(e.state.env,"HOME",""),a=`${[n,...s].map(o=>Ut(o,i)).join(" ")}
108
- `;return H(a)}function Or(e,t){let s=Tr(e);for(let a of t)if(a!=="--")return a.startsWith("-")&&a!=="-"?P(`bash: popd: ${a}: invalid option
109
- `,2):P(`bash: popd: too many arguments
110
- `,2);if(s.length===0)return P(`bash: popd: directory stack empty
111
- `,1);let r=s.shift();if(!r)return P(`bash: popd: directory stack empty
112
- `,1);e.state.previousDir=e.state.cwd,e.state.cwd=r,g(e.state.env,"PWD",r),g(e.state.env,"OLDPWD",e.state.previousDir);let n=T(e.state.env,"HOME",""),i=`${[r,...s].map(a=>Ut(a,n)).join(" ")}
113
- `;return H(i)}function Dr(e,t){let s=Tr(e),r=!1,n=!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")r=!0;else if(f==="l")n=!0;else if(f==="p")i=!0;else if(f==="v")i=!0,a=!0;else return P(`bash: dirs: -${f}: invalid option
114
- `,2);else return P(`bash: dirs: too many arguments
115
- `,1);if(r)return e.state.directoryStack=[],wt;let o=[e.state.cwd,...s],l=T(e.state.env,"HOME",""),u;return a?(u=o.map((c,f)=>{let d=n?c:Ut(c,l);return` ${f} ${d}`}).join(`
116
- `),u+=`
117
- `):i?u=o.map(c=>n?c:Ut(c,l)).join(`
96
+ `;return G(O)}let C=!0;for(let O of E)e.state.functions.has(O)||(C=!1);return F(R,R,C?0:1)}if(a&&E.length>0)return mi(e,E);if(a&&E.length===0)return yi(e,{filterExport:i,filterReadonly:n,filterNameref:o,filterIndexedArray:s,filterAssocArray:r});if(E.length===0&&r&&!a)return gi(e);if(E.length===0&&s&&!a)return wi(e);if(E.length===0&&!a)return vi(e);let L="",$=0;for(let C of E){let O=C.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\((.*)\)$/s);if(O&&!c){let w=O[1],D=O[2];if(r&&me(e,w).length>0){L+=`bash: declare: ${w}: cannot convert indexed to associative array
97
+ `,$=1;continue}if((s||!r&&!s)&&e.state.associativeArrays?.has(w)){L+=`bash: declare: ${w}: cannot convert associative to indexed array
98
+ `,$=1;continue}if(k(w),r&&(e.state.associativeArrays??=new Set,e.state.associativeArrays.add(w)),Ve(e,w),e.state.env.delete(w),e.state.env.delete(`${w}__length`),r&&D.includes("[")){let M=Es(D);for(let[J,j]of M){let K=ne(e,j);g(e.state.env,`${w}_${J}`,K)}}else if(r){let M=Be(D);for(let J=0;J<M.length;J+=2){let j=M[J],K=J+1<M.length?ne(e,M[J+1]):"";g(e.state.env,`${w}_${j}`,K)}}else{let M=Be(D);if(M.some(j=>/^\[[^\]]+\]=/.test(j))){let j=0;for(let K of M){let oe=K.match(/^\[([^\]]+)\]=(.*)$/);if(oe){let Pe=oe[1],ut=oe[2],lo=ne(e,ut),Ot;if(/^-?\d+$/.test(Pe))Ot=Number.parseInt(Pe,10);else try{let co=new X,uo=ce(co,Pe);Ot=await ee(e,uo.expression)}catch{Ot=0}g(e.state.env,`${w}_${Ot}`,lo),j=Ot+1}else{let Pe=ne(e,K);g(e.state.env,`${w}_${j}`,Pe),j++}}}else{for(let j=0;j<M.length;j++)g(e.state.env,`${w}_${j}`,M[j]);g(e.state.env,`${w}__length`,String(M.length))}}_(w),n&&Se(e,w),i&&Re(e,w);continue}if(l){let w=C.includes("=")?C.slice(0,C.indexOf("=")):C;if(wn(e,w),!C.includes("="))continue}if(u){let w=C.includes("=")?C.slice(0,C.indexOf("=")):C;if(os(e,w),!C.includes("="))continue}let I=ha(C);if(I){let{name:w,indexExpr:D,value:M}=I,J=await de(e,w);if(J)return J;k(w);let j;try{let oe=new X,Pe=ce(oe,D);j=await ee(e,Pe.expression)}catch{let oe=parseInt(D,10);j=Number.isNaN(oe)?0:oe}g(e.state.env,`${w}_${j}`,M);let K=parseInt(N(e.state.env,`${w}__length`,"0"),10);j>=K&&g(e.state.env,`${w}__length`,String(j+1)),_(w),n&&Se(e,w),i&&Re(e,w);continue}let T=C.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=\((.*)\)$/s);if(T&&!c){let w=T[1],D=T[2],M=await de(e,w);if(M)return M;k(w);let J=Be(D);if(e.state.associativeArrays?.has(w)){let j=Es(D);for(let[K,oe]of j){let Pe=ne(e,oe);g(e.state.env,`${w}_${K}`,Pe)}}else{let j=me(e,w),K=0,oe=e.state.env.get(w);j.length===0&&oe!==void 0?(e.state.env.set(`${w}_0`,oe),e.state.env.delete(w),K=1):j.length>0&&(K=Math.max(...j)+1);for(let ut=0;ut<J.length;ut++)g(e.state.env,`${w}_${K+ut}`,ne(e,J[ut]));let Pe=K+J.length;g(e.state.env,`${w}__length`,String(Pe))}_(w),n&&Se(e,w),i&&Re(e,w);continue}let x=C.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=(.*)$/);if(x){let w=x[1],D=ne(e,x[2]),M=await de(e,w);if(M)return M;y(w),f&&Cr(e,w),d&&kr(e,w),p&&Tr(e,w);let j=me(e,w).length>0||e.state.associativeArrays?.has(w);if(Ut(e,w)){let K=N(e.state.env,w,"0"),oe=parseInt(K,10)||0,Pe=parseInt(await bi(e,D),10)||0;D=String(oe+Pe),g(e.state.env,w,D)}else if(j){D=$t(e,w,D);let K=`${w}_0`,oe=N(e.state.env,K);g(e.state.env,K,oe+D)}else{D=$t(e,w,D);let K=N(e.state.env,w);g(e.state.env,w,K+D)}_(w),n&&Se(e,w),i&&Re(e,w),e.state.options.allexport&&!u&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(w));continue}if(C.includes("=")){let w=C.indexOf("="),D=C.slice(0,w),M=C.slice(w+1);if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(D)){L+=`bash: typeset: \`${D}': not a valid identifier
99
+ `,$=1;continue}let J=await de(e,D);if(J)return J;if(y(D),o){if(M!==""&&!/^[a-zA-Z_][a-zA-Z0-9_]*(\[.+\])?$/.test(M)){L+=`bash: declare: \`${M}': invalid variable name for name reference
100
+ `,$=1;continue}g(e.state.env,D,M),qe(e,D),M!==""&&Ks(e,M)&&Js(e,D),_(D),n&&Se(e,D),i&&Re(e,D);continue}if(f&&Cr(e,D),d&&kr(e,D),p&&Tr(e,D),Ut(e,D)&&(M=await bi(e,M)),M=$t(e,D,M),Ee(e,D)){let j=ze(e,D);j&&j!==D?g(e.state.env,j,M):g(e.state.env,D,M)}else g(e.state.env,D,M);_(D),n&&Se(e,D),i&&Re(e,D),e.state.options.allexport&&!u&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(D))}else{let w=C;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(w)){L+=`bash: typeset: \`${w}': not a valid identifier
101
+ `,$=1;continue}if(s||r?k(w):y(w),o){qe(e,w);let M=N(e.state.env,w);M!==""&&!/^[a-zA-Z_][a-zA-Z0-9_]*(\[.+\])?$/.test(M)?vn(e,w):M&&Ks(e,M)&&Js(e,w),_(w),n&&Se(e,w),i&&Re(e,w);continue}if(f&&Cr(e,w),d&&kr(e,w),p&&Tr(e,w),r){if(me(e,w).length>0){L+=`bash: declare: ${w}: cannot convert indexed to associative array
102
+ `,$=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||r?g(e.state.env,`${w}__length`,"0"):(e.state.declaredVars??=new Set,e.state.declaredVars.add(w))),_(w),n&&Se(e,w),i&&Re(e,w)}}return F(R,W(L),$)}async function _r(e,t){let s=!1,r=!1,n=!1,i=[];for(let a=0;a<t.length;a++){let o=t[a];if(o==="-a")s=!0;else if(o==="-A")r=!0;else if(o==="-p")n=!0;else if(o==="--"){i.push(...t.slice(a+1));break}else o.startsWith("-")||i.push(o)}if(i.length===0){let a="",o=Array.from(e.state.readonlyVars||[]).sort();for(let l of o){let c=e.state.env.get(l);if(c!==void 0){let u=B(c??R).replace(/\\/g,"\\\\").replace(/"/g,'\\"');a+=`declare -r ${l}="${u}"
103
+ `}}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 de(e,f);if(p)return p;let m=Be(d);if(e.state.associativeArrays?.has(f)){let h=Es(d);for(let[v,E]of h){let S=ne(e,E);g(e.state.env,`${f}_${v}`,S)}}else{let h=me(e,f),v=0,E=e.state.env.get(f);h.length===0&&E!==void 0?(e.state.env.set(`${f}_0`,E),e.state.env.delete(f),v=1):h.length>0&&(v=Math.max(...h)+1);for(let b=0;b<m.length;b++)g(e.state.env,`${f}_${v+b}`,ne(e,m[b]));let S=v+m.length;g(e.state.env,`${f}__length`,String(S))}Se(e,f);continue}let l=a.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=(.*)$/);if(l){let f=l[1],d=ne(e,l[2]),p=await de(e,f);if(p)return p;let m=N(e.state.env,f);g(e.state.env,f,m+d),Se(e,f);continue}let c=ti(a);if(c.value===void 0&&!c.isArray){Se(e,c.name);continue}let u=await si(e,c,{makeReadonly:!0});if(u)return u}return wt}function Nr(e){return e.state.directoryStack??=[],e.state.directoryStack}function Ht(e,t){return t&&e===t?"~":t&&e.startsWith(`${t}/`)?`~${e.slice(t.length)}`:e}function pa(e){let t=e.split("/").filter(r=>r&&r!=="."),s=[];for(let r of t)r===".."?s.pop():s.push(r);return`/${s.join("/")}`}async function Or(e,t){let s=Nr(e),r;for(let o=0;o<t.length;o++){let l=t[o];if(l==="--"){if(o+1<t.length){if(r!==void 0)return A(`bash: pushd: too many arguments
104
+ `,2);r=t[o+1],o++}}else{if(l.startsWith("-")&&l!=="-")return A(`bash: pushd: ${l}: invalid option
105
+ `,2);if(r!==void 0)return A(`bash: pushd: too many arguments
106
+ `,2);r=l}}if(r===void 0){if(s.length<2)return A(`bash: pushd: no other directory
107
+ `,1);let o=s[0];s[0]=s[1],s[1]=o,r=s[0]}let n;if(r.startsWith("/"))n=r;else if(r===".."){let o=e.state.cwd.split("/").filter(l=>l);o.pop(),n=`/${o.join("/")}`}else r==="."?n=e.state.cwd:r.startsWith("~")?n=N(e.state.env,"HOME","/")+r.slice(1):n=`${e.state.cwd}/${r}`;n=pa(n);try{if(!(await e.fs.stat(n)).isDirectory)return A(`bash: pushd: ${r}: Not a directory
108
+ `,1)}catch{return A(`bash: pushd: ${r}: No such file or directory
109
+ `,1)}s.unshift(e.state.cwd),e.state.previousDir=e.state.cwd,e.state.cwd=n,g(e.state.env,"PWD",n),g(e.state.env,"OLDPWD",e.state.previousDir);let i=N(e.state.env,"HOME",""),a=`${[n,...s].map(o=>Ht(o,i)).join(" ")}
110
+ `;return G(a)}function Dr(e,t){let s=Nr(e);for(let a of t)if(a!=="--")return a.startsWith("-")&&a!=="-"?A(`bash: popd: ${a}: invalid option
111
+ `,2):A(`bash: popd: too many arguments
112
+ `,2);if(s.length===0)return A(`bash: popd: directory stack empty
113
+ `,1);let r=s.shift();if(!r)return A(`bash: popd: directory stack empty
114
+ `,1);e.state.previousDir=e.state.cwd,e.state.cwd=r,g(e.state.env,"PWD",r),g(e.state.env,"OLDPWD",e.state.previousDir);let n=N(e.state.env,"HOME",""),i=`${[r,...s].map(a=>Ht(a,n)).join(" ")}
115
+ `;return G(i)}function Ir(e,t){let s=Nr(e),r=!1,n=!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")r=!0;else if(f==="l")n=!0;else if(f==="p")i=!0;else if(f==="v")i=!0,a=!0;else return A(`bash: dirs: -${f}: invalid option
116
+ `,2);else return A(`bash: dirs: too many arguments
117
+ `,1);if(r)return e.state.directoryStack=[],wt;let o=[e.state.cwd,...s],l=N(e.state.env,"HOME",""),c;return a?(c=o.map((u,f)=>{let d=n?u:Ht(u,l);return` ${f} ${d}`}).join(`
118
+ `),c+=`
119
+ `):i?c=o.map(u=>n?u:Ht(u,l)).join(`
118
120
  `)+`
119
- `:u=o.map(c=>n?c:Ut(c,l)).join(" ")+`
120
- `,H(u)}async function xs(e,t,s){let r=t;if(r.length>0){let o=r[0];if(o==="--")r=r.slice(1);else if(o.startsWith("-")&&o!=="-"&&o.length>1)return P(`bash: eval: ${o}: invalid option
121
+ `:c=o.map(u=>n?u:Ht(u,l)).join(" ")+`
122
+ `,G(c)}async function _s(e,t,s){let r=t;if(r.length>0){let o=r[0];if(o==="--")r=r.slice(1);else if(o.startsWith("-")&&o!=="-"&&o.length>1)return A(`bash: eval: ${o}: invalid option
121
123
  eval: usage: eval [arg ...]
122
- `,2)}if(r.length===0)return U();let n=r.join(" ");if(n.trim()==="")return U();let i=e.state.groupStdin,a=s??e.state.groupStdin;a!==void 0&&(e.state.groupStdin=a);try{let o=Fe(n),l=await e.executeScript(o);return await Y(e,l)}catch(o){if(await te(e,o),o instanceof Ce||o instanceof Ae||o instanceof ve||o instanceof q)throw o;if(o.name==="ParseException")return P(`bash: eval: ${o.message}
123
- `);throw o}finally{e.state.groupStdin=i}}async function Ir(e,t){let s,r;if(t.length===0)s=e.state.lastExitCode;else{let n=t[0],i=Number.parseInt(n,10);n===""||Number.isNaN(i)||!/^-?\d+$/.test(n)?(r=`bash: exit: ${n}: numeric argument required
124
- `,s=2):s=(i%256+256)%256}throw r&&await G(e,2,r,!0),new q(s)}function Rr(e,t){let s=!1,r=[];for(let a of t)a==="-n"?s=!0:a==="-p"||a==="--"||r.push(a);if(r.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=B(c??R).replace(/\\/g,"\\\\").replace(/"/g,'\\"');a+=`declare -x ${u}="${f}"
125
- `}}return H(a)}if(s){for(let a of r){let o,l;if(a.includes("=")){let u=a.indexOf("=");o=a.slice(0,u),l=ne(e,a.slice(u+1)),g(e.state.env,o,l)}else o=a;ns(e,o)}return wt}let n="",i=0;for(let a of r){let o,l,u=!1,c=a.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=(.*)$/);if(c)o=c[1],l=ne(e,c[2]),u=!0;else if(a.includes("=")){let f=a.indexOf("=");o=a.slice(0,f),l=ne(e,a.slice(f+1))}else o=a;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(o)){n+=`bash: export: \`${a}': not a valid identifier
126
- `,i=1;continue}if(l!==void 0)if(u){let f=T(e.state.env,o);g(e.state.env,o,f+l)}else g(e.state.env,o,l);else e.state.env.has(o)||g(e.state.env,o,"");Re(e,o)}return F(R,W(n),i)}function _s(e,t){if(t.length<2)return P(`bash: getopts: usage: getopts optstring name [arg ...]
127
- `);let s=t[0],r=t[1],n=!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(r),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(g(e.state.env,"OPTARG",""),l>o.length)return n||g(e.state.env,r,"?"),g(e.state.env,"OPTIND",String(o.length+1)),g(e.state.env,"__GETOPTS_CHARINDEX","0"),{exitCode:n?2:1,stdout:S(),stderr:S()};let c=o[l-1];if(!c||c==="-"||!c.startsWith("-"))return n||g(e.state.env,r,"?"),{exitCode:n?2:1,stdout:S(),stderr:S()};if(c==="--")return g(e.state.env,"OPTIND",String(l+1)),g(e.state.env,"__GETOPTS_CHARINDEX","0"),n||g(e.state.env,r,"?"),{exitCode:n?2:1,stdout:S(),stderr:S()};let f=u===0?1:u,d=c[f];if(!d)return g(e.state.env,"OPTIND",String(l+1)),g(e.state.env,"__GETOPTS_CHARINDEX","0"),_s(e,t);let p=a.indexOf(d);if(p===-1){let h="";return i?g(e.state.env,"OPTARG",d):h=`bash: illegal option -- ${d}
128
- `,n||g(e.state.env,r,"?"),f+1<c.length?(g(e.state.env,"__GETOPTS_CHARINDEX",String(f+1)),g(e.state.env,"OPTIND",String(l))):(g(e.state.env,"OPTIND",String(l+1)),g(e.state.env,"__GETOPTS_CHARINDEX","0")),{exitCode:n?2:0,stdout:S(),stderr:V(h)}}if(p+1<a.length&&a[p+1]===":")if(f+1<c.length)g(e.state.env,"OPTARG",c.slice(f+1)),g(e.state.env,"OPTIND",String(l+1)),g(e.state.env,"__GETOPTS_CHARINDEX","0");else{if(l>=o.length){let h="";return i?(g(e.state.env,"OPTARG",d),n||g(e.state.env,r,":")):(h=`bash: option requires an argument -- ${d}
129
- `,n||g(e.state.env,r,"?")),g(e.state.env,"OPTIND",String(l+1)),g(e.state.env,"__GETOPTS_CHARINDEX","0"),{exitCode:n?2:0,stdout:S(),stderr:V(h)}}g(e.state.env,"OPTARG",o[l]),g(e.state.env,"OPTIND",String(l+2)),g(e.state.env,"__GETOPTS_CHARINDEX","0")}else f+1<c.length?(g(e.state.env,"__GETOPTS_CHARINDEX",String(f+1)),g(e.state.env,"OPTIND",String(l))):(g(e.state.env,"OPTIND",String(l+1)),g(e.state.env,"__GETOPTS_CHARINDEX","0"));return n||g(e.state.env,r,d),{exitCode:n?2:0,stdout:S(),stderr:S()}}async function Mr(e,t){e.state.hashTable||(e.state.hashTable=new Map);let s=!1,r=!1,n=!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")r=!0,u++;else if(m==="-l")n=!0,u++;else if(m==="-t")a=!0,u++;else if(m==="-p"){if(i=!0,u++,u>=t.length)return P(`bash: hash: -p: option requires an argument
130
- `,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")r=!0;else if(h==="l")n=!0;else if(h==="t")a=!0;else return h==="p"?P(`bash: hash: -p: option requires an argument
131
- `,1):P(`bash: hash: -${h}: invalid option
132
- `,1);u++}else l.push(m),u++}if(s)return e.state.hashTable.clear(),U();if(r){if(l.length===0)return P(`bash: hash: -d: option requires an argument
133
- `,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
134
- `,m=!0);return m?P(h,1):U()}if(a){if(l.length===0)return P(`bash: hash: -t: option requires an argument
135
- `,1);let m="",h=!1,b="";for(let E of l){let $=e.state.hashTable.get(E);$?l.length>1?m+=`${E} ${$}
136
- `:m+=`${$}
137
- `:(b+=`bash: hash: ${E}: not found
138
- `,h=!0)}return h?{exitCode:1,stdout:V(m),stderr:V(b)}:H(m)}if(i){if(l.length===0)return P(`bash: hash: usage: hash [-lr] [-p pathname] [-dt] [name ...]
139
- `,1);let m=l[0];return e.state.hashTable.set(m,o),U()}if(l.length===0){if(e.state.hashTable.size===0)return H(`hash: hash table empty
140
- `);let m="";if(n)for(let[h,b]of e.state.hashTable)m+=`builtin hash -p ${b} ${h}
124
+ `,2)}if(r.length===0)return U();let n=r.join(" ");if(n.trim()==="")return U();let i=e.state.groupStdin,a=s??e.state.groupStdin;a!==void 0&&(e.state.groupStdin=a);try{let o=Fe(n),l=await e.executeScript(o);return await Q(e,l)}catch(o){if(await te(e,o),o instanceof Ae||o instanceof Ce||o instanceof ve||o instanceof q)throw o;if(o.name==="ParseException")return A(`bash: eval: ${o.message}
125
+ `);throw o}finally{e.state.groupStdin=i}}async function Rr(e,t){let s,r;if(t.length===0)s=e.state.lastExitCode;else{let n=t[0],i=Number.parseInt(n,10);n===""||Number.isNaN(i)||!/^-?\d+$/.test(n)?(r=`bash: exit: ${n}: numeric argument required
126
+ `,s=2):s=(i%256+256)%256}throw r&&await H(e,2,r,!0),new q(s)}function Mr(e,t){let s=!1,r=[];for(let a of t)a==="-n"?s=!0:a==="-p"||a==="--"||r.push(a);if(r.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=B(u??R).replace(/\\/g,"\\\\").replace(/"/g,'\\"');a+=`declare -x ${c}="${f}"
127
+ `}}return G(a)}if(s){for(let a of r){let o,l;if(a.includes("=")){let c=a.indexOf("=");o=a.slice(0,c),l=ne(e,a.slice(c+1)),g(e.state.env,o,l)}else o=a;os(e,o)}return wt}let n="",i=0;for(let a of r){let o,l,c=!1,u=a.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=(.*)$/);if(u)o=u[1],l=ne(e,u[2]),c=!0;else if(a.includes("=")){let f=a.indexOf("=");o=a.slice(0,f),l=ne(e,a.slice(f+1))}else o=a;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(o)){n+=`bash: export: \`${a}': not a valid identifier
128
+ `,i=1;continue}if(l!==void 0)if(c){let f=N(e.state.env,o);g(e.state.env,o,f+l)}else g(e.state.env,o,l);else e.state.env.has(o)||g(e.state.env,o,"");Re(e,o)}return F(R,W(n),i)}function Ns(e,t){if(t.length<2)return A(`bash: getopts: usage: getopts optstring name [arg ...]
129
+ `);let s=t[0],r=t[1],n=!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(r),i=s.startsWith(":"),a=i?s.slice(1):s,o;if(t.length>2)o=t.slice(2);else{let h=Number.parseInt(N(e.state.env,"#","0"),10);o=[];for(let v=1;v<=h;v++)o.push(N(e.state.env,String(v))||"")}let l=Number.parseInt(N(e.state.env,"OPTIND","1"),10);l<1&&(l=1);let c=Number.parseInt(N(e.state.env,"__GETOPTS_CHARINDEX","0"),10);if(g(e.state.env,"OPTARG",""),l>o.length)return n||g(e.state.env,r,"?"),g(e.state.env,"OPTIND",String(o.length+1)),g(e.state.env,"__GETOPTS_CHARINDEX","0"),{exitCode:n?2:1,stdout:P(),stderr:P()};let u=o[l-1];if(!u||u==="-"||!u.startsWith("-"))return n||g(e.state.env,r,"?"),{exitCode:n?2:1,stdout:P(),stderr:P()};if(u==="--")return g(e.state.env,"OPTIND",String(l+1)),g(e.state.env,"__GETOPTS_CHARINDEX","0"),n||g(e.state.env,r,"?"),{exitCode:n?2:1,stdout:P(),stderr:P()};let f=c===0?1:c,d=u[f];if(!d)return g(e.state.env,"OPTIND",String(l+1)),g(e.state.env,"__GETOPTS_CHARINDEX","0"),Ns(e,t);let p=a.indexOf(d);if(p===-1){let h="";return i?g(e.state.env,"OPTARG",d):h=`bash: illegal option -- ${d}
130
+ `,n||g(e.state.env,r,"?"),f+1<u.length?(g(e.state.env,"__GETOPTS_CHARINDEX",String(f+1)),g(e.state.env,"OPTIND",String(l))):(g(e.state.env,"OPTIND",String(l+1)),g(e.state.env,"__GETOPTS_CHARINDEX","0")),{exitCode:n?2:0,stdout:P(),stderr:V(h)}}if(p+1<a.length&&a[p+1]===":")if(f+1<u.length)g(e.state.env,"OPTARG",u.slice(f+1)),g(e.state.env,"OPTIND",String(l+1)),g(e.state.env,"__GETOPTS_CHARINDEX","0");else{if(l>=o.length){let h="";return i?(g(e.state.env,"OPTARG",d),n||g(e.state.env,r,":")):(h=`bash: option requires an argument -- ${d}
131
+ `,n||g(e.state.env,r,"?")),g(e.state.env,"OPTIND",String(l+1)),g(e.state.env,"__GETOPTS_CHARINDEX","0"),{exitCode:n?2:0,stdout:P(),stderr:V(h)}}g(e.state.env,"OPTARG",o[l]),g(e.state.env,"OPTIND",String(l+2)),g(e.state.env,"__GETOPTS_CHARINDEX","0")}else f+1<u.length?(g(e.state.env,"__GETOPTS_CHARINDEX",String(f+1)),g(e.state.env,"OPTIND",String(l))):(g(e.state.env,"OPTIND",String(l+1)),g(e.state.env,"__GETOPTS_CHARINDEX","0"));return n||g(e.state.env,r,d),{exitCode:n?2:0,stdout:P(),stderr:P()}}async function Lr(e,t){e.state.hashTable||(e.state.hashTable=new Map);let s=!1,r=!1,n=!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")r=!0,c++;else if(m==="-l")n=!0,c++;else if(m==="-t")a=!0,c++;else if(m==="-p"){if(i=!0,c++,c>=t.length)return A(`bash: hash: -p: option requires an argument
132
+ `,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")r=!0;else if(h==="l")n=!0;else if(h==="t")a=!0;else return h==="p"?A(`bash: hash: -p: option requires an argument
133
+ `,1):A(`bash: hash: -${h}: invalid option
134
+ `,1);c++}else l.push(m),c++}if(s)return e.state.hashTable.clear(),U();if(r){if(l.length===0)return A(`bash: hash: -d: option requires an argument
135
+ `,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
136
+ `,m=!0);return m?A(h,1):U()}if(a){if(l.length===0)return A(`bash: hash: -t: option requires an argument
137
+ `,1);let m="",h=!1,v="";for(let E of l){let S=e.state.hashTable.get(E);S?l.length>1?m+=`${E} ${S}
138
+ `:m+=`${S}
139
+ `:(v+=`bash: hash: ${E}: not found
140
+ `,h=!0)}return h?{exitCode:1,stdout:V(m),stderr:V(v)}:G(m)}if(i){if(l.length===0)return A(`bash: hash: usage: hash [-lr] [-p pathname] [-dt] [name ...]
141
+ `,1);let m=l[0];return e.state.hashTable.set(m,o),U()}if(l.length===0){if(e.state.hashTable.size===0)return G(`hash: hash table empty
142
+ `);let m="";if(n)for(let[h,v]of e.state.hashTable)m+=`builtin hash -p ${v} ${h}
141
143
  `;else{m=`hits command
142
144
  `;for(let[,h]of e.state.hashTable)m+=` 1 ${h}
143
- `}return H(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
144
- `,c=!0;continue}let h=!1;for(let b of p){if(!b)continue;let E=`${b}/${m}`;if(await e.fs.exists(E)){e.state.hashTable.set(m,E),h=!0;break}}h||(f+=`bash: hash: ${m}: not found
145
- `,c=!0)}return c?P(f,1):U()}var Ei=new Map([[":",[": [arguments]",`Null command.
145
+ `}return G(m)}let u=!1,f="",p=N(e.state.env,"PATH","/usr/bin:/bin").split(":");for(let m of l){if(m.includes("/")){f+=`bash: hash: ${m}: cannot use / in name
146
+ `,u=!0;continue}let h=!1;for(let v of p){if(!v)continue;let E=`${v}/${m}`;if(await e.fs.exists(E)){e.state.hashTable.set(m,E),h=!0;break}}h||(f+=`bash: hash: ${m}: not found
147
+ `,u=!0)}return u?A(f,1):U()}var Ei=new Map([[":",[": [arguments]",`Null command.
146
148
  No effect; the command does nothing.
147
149
  Exit Status:
148
150
  Always succeeds.`]],[".",[". filename [arguments]",`Execute commands from a file in the current shell.
@@ -487,47 +489,48 @@ eval: usage: eval [arg ...]
487
489
  job specification. With no ID, waits for all known jobs.
488
490
  Exit Status:
489
491
  Returns the status of the last ID; fails if ID is invalid or an invalid
490
- option is given.`]]]),Si=[...Ei.keys()].sort();function Lr(e,t){let s=!1,r=[],n=0;for(;n<t.length;){let l=t[n];if(l==="--"){for(n++;n<t.length;)r.push(t[n]),n++;break}if(l.startsWith("-")&&l.length>1){for(let u=1;u<l.length;u++){let c=l[u];if(c==="s")s=!0;else return P(`bash: help: -${c}: invalid option
491
- `,2)}n++}else r.push(l),n++}if(r.length===0)return ya();let i="",a=!1,o="";for(let l of r){let u=ma(l);if(u.length===0){o+=`bash: help: no help topics match \`${l}'. Try \`help help' or \`man -k ${l}' or \`info ${l}'.
492
- `,a=!0;continue}for(let c of u){let f=Ei.get(c);if(!f)continue;let[d,p]=f;s?i+=`${c}: ${d}
493
- `:i+=`${c}: ${d}
492
+ option is given.`]]]),Si=[...Ei.keys()].sort();function Fr(e,t){let s=!1,r=[],n=0;for(;n<t.length;){let l=t[n];if(l==="--"){for(n++;n<t.length;)r.push(t[n]),n++;break}if(l.startsWith("-")&&l.length>1){for(let c=1;c<l.length;c++){let u=l[c];if(u==="s")s=!0;else return A(`bash: help: -${u}: invalid option
493
+ `,2)}n++}else r.push(l),n++}if(r.length===0)return ya();let i="",a=!1,o="";for(let l of r){let c=ma(l);if(c.length===0){o+=`bash: help: no help topics match \`${l}'. Try \`help help' or \`man -k ${l}' or \`info ${l}'.
494
+ `,a=!0;continue}for(let u of c){let f=Ei.get(u);if(!f)continue;let[d,p]=f;s?i+=`${u}: ${d}
495
+ `:i+=`${u}: ${d}
494
496
  ${p}
495
- `}}return{exitCode:a?1:0,stdout:V(i),stderr:V(o)}}function ma(e){let t=e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,"."),s=Rt(`^${t}$`);return Si.filter(r=>s.test(r))}function ya(){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=Si.slice(),r=Math.ceil(s.length/2);for(let n=0;n<r;n++){let i=s[n]||"",a=s[n+r]||"",o=i.padEnd(t);e.push(a?`${o}${a}`:i)}return H(`${e.join(`
497
+ `}}return{exitCode:a?1:0,stdout:V(i),stderr:V(o)}}function ma(e){let t=e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,"."),s=Rt(`^${t}$`);return Si.filter(r=>s.test(r))}function ya(){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=Si.slice(),r=Math.ceil(s.length/2);for(let n=0;n<r;n++){let i=s[n]||"",a=s[n+r]||"",o=i.padEnd(t);e.push(a?`${o}${a}`:i)}return G(`${e.join(`
496
498
  `)}
497
499
  `)}var ga=`jobs: usage: jobs [-lnprs] [jobspec ...] or jobs -x command [args]
498
- `;function wa(e){return{stdout:S(),stderr:V(`bash: jobs: ${e}: invalid option
499
- ${ga}`),exitCode:2}}async function Fr(e,t,s){if(t[0]==="-x"){let f=t[1];if(!f)return{stdout:S(),stderr:S(),exitCode:0};if(!s)return{stdout:S(),stderr:V(`bash: jobs: -x: command execution unavailable
500
- `),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:S(),stderr:V(`bash: ${p}: no such job
501
- `),exitCode:1};d.push(String(m))}return s(f,d)}let r={long:!1,pidsOnly:!1,runningOnly:!1,stoppedOnly:!1,changedOnly:!1},n=0;for(;n<t.length;n++){let f=t[n];if(f==="--"){n++;break}if(!f.startsWith("-")||f==="-")break;for(let d of f.slice(1))if(d==="l")r.long=!0;else if(d==="n")r.changedOnly=!0;else if(d==="p")r.pidsOnly=!0;else if(d==="r")r.runningOnly=!0;else if(d==="s")r.stoppedOnly=!0;else return wa(`-${d}`)}let i=t.slice(n),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
502
- `,u=1);let c=e.processes.listJobs(a,{changedOnly:r.changedOnly,runningOnly:r.runningOnly,stoppedOnly:r.stoppedOnly});for(let f of c){if(r.pidsOnly){o+=`${f.pid}
503
- `;continue}let d=f.state==="running"?"Running ":"Done ",p=r.long?`[${f.jobNumber}]${f.marker} ${f.pid} `:`[${f.jobNumber}]${f.marker} `;o+=`${p}${d}${f.command}
504
- `}return{stdout:V(o),stderr:V(l),exitCode:u}}var $i=`kill: usage: kill [-s sigspec | -n signum | -sigspec] pid | jobspec ... or kill -l [sigspec]
505
- `,Ts=typeof process<"u"&&process.platform==="darwin",Wr=[{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:Ts?30:10,delivery:"SIGTERM"},{name:"USR2",number:Ts?31:12,delivery:"SIGTERM"},{name:"STOP",number:Ts?17:19,delivery:"SIGSTOP"},{name:"CONT",number:Ts?19:18,delivery:"SIGCONT"}];function Ns(e){let t=e.toUpperCase().replace(/^SIG/,"");if(/^\d+$/.test(t)){let s=Number.parseInt(t,10);return Wr.find(r=>r.number===s)}return Wr.find(s=>s.name===t)}function Vr(e){return{stdout:S(),stderr:V(`bash: kill: ${e.replace(/^-/,"")}: invalid signal specification
506
- `),exitCode:1}}function va(e){if(e.length===0)return{stdout:V(`${Wr.map(s=>`${s.number}) SIG${s.name}`).join(" ")}
507
- `),stderr:S(),exitCode:0};let t="";for(let s of e){let r=/^\d+$/.test(s)?String(Number.parseInt(s,10)-(Number(s)>128?128:0)):s,n=Ns(r);if(!n)return Vr(s);t+=/^\d+$/.test(s)?`${n.name}
500
+ `;function wa(e){return{stdout:P(),stderr:V(`bash: jobs: ${e}: invalid option
501
+ ${ga}`),exitCode:2}}async function Wr(e,t,s){if(t[0]==="-x"){let d=t[1];if(!d)return{stdout:P(),stderr:P(),exitCode:0};if(!s)return{stdout:P(),stderr:V(`bash: jobs: -x: command execution unavailable
502
+ `),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 r={long:!1,pidsOnly:!1,runningOnly:!1,stoppedOnly:!1,changedOnly:!1},n=0;for(;n<t.length;n++){let d=t[n];if(d==="--"){n++;break}if(!d.startsWith("-")||d==="-")break;for(let p of d.slice(1))if(p==="l")r.long=!0;else if(p==="n")r.changedOnly=!0;else if(p==="p")r.pidsOnly=!0;else if(p==="r")r.runningOnly=!0;else if(p==="s")r.stoppedOnly=!0;else return wa(`-${p}`)}let i=t.slice(n),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
503
+ `,u=1);let f=e.processes.listJobs(o,{changedOnly:r.changedOnly,runningOnly:r.runningOnly,stoppedOnly:r.stoppedOnly});for(let d of f){if(r.pidsOnly){l+=`${d.pid}
504
+ `;continue}let p=d.state==="running"?"Running ":"Done ",m=r.long?`[${d.jobNumber}]${d.marker} ${d.pid} `:`[${d.jobNumber}]${d.marker} `;l+=`${m}${p}${d.command}
505
+ `}return{stdout:V(l),stderr:V(c),exitCode:u}}var $i=`kill: usage: kill [-s sigspec | -n signum | -sigspec] pid | jobspec ... or kill -l [sigspec]
506
+ `,va=typeof process<"u"&&process.platform==="darwin",ba=va?["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"],Ea=new Set(["STOP","TSTP","TTIN","TTOU","CONT","CHLD","URG","WINCH","INFO"]);function Sa(e){if(!Ea.has(e))return e==="KILL"?"SIGKILL":e==="INT"?"SIGINT":"SIGTERM"}var Vr=ba.map((e,t)=>({name:e,number:t+1,delivery:Sa(e)})),$a={name:"0",number:0};function Os(e){let t=e.toUpperCase().replace(/^SIG/,"");if(/^\d+$/.test(t)){let s=Number.parseInt(t,10);return s===0?$a:Vr.find(r=>r.number===s)}return Vr.find(s=>s.name===t)}function zr(e){return{stdout:P(),stderr:V(`bash: kill: ${e.replace(/^-/,"")}: invalid signal specification
507
+ `),exitCode:1}}function Pa(e){if(e.length===0){let s="";for(let r of Vr)s+=`${String(r.number).padStart(2)}) SIG${r.name} `,r.number%4===0&&(s=`${s.slice(0,-1)}
508
+ `);return{stdout:V(s.endsWith(`
509
+ `)?s:`${s}
510
+ `),stderr:P(),exitCode:0}}let t="";for(let s of e){let r=/^\d+$/.test(s)?String(Number.parseInt(s,10)-(Number(s)>128?128:0)):s,n=Os(r);if(!n)return zr(s);t+=/^\d+$/.test(s)?`${n.name}
508
511
  `:`${n.number}
509
- `}return{stdout:V(t),stderr:S(),exitCode:0}}function zr(e,t){let s=Ns("TERM"),r=0;if(t[0]==="-l")return va(t.slice(1));if(t[0]==="-s"||t[0]==="-n"){let o=t[1];if(!o)return{stdout:S(),stderr:V($i),exitCode:2};let l=Ns(o);if(!l)return Vr(o);s=l,r=2}else if(t[0]?.startsWith("-")&&t[0]!=="--"){let o=t[0].slice(1),l=Ns(o);if(!l)return Vr(o);s=l,r=1}else t[0]==="--"&&(r=1);let n=t.slice(r);if(n.length===0)return{stdout:S(),stderr:V($i),exitCode:2};let i="",a=0;for(let o of n){let l;if(o.startsWith("%")){if(l=e.processes.resolveJobSpec(o),l===void 0){i+=`bash: kill: ${o}: no such job
510
- `,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
511
- `,a=1;continue}e.processes.kill(l,s.delivery,s.number)||(i+=`bash: kill: (${l}) - No such process
512
- `,a=1)}return{stdout:S(),stderr:V(i),exitCode:a}}function ba(e){let t=[],s="",r=0;for(let n of e){for(let i of n)i==="("?r++:i===")"&&r--;s?s+=` ${n}`:s=n,r===0&&(t.push(s),s="")}return s&&t.push(s),t}async function jr(e,t){if(t.length===0)return P(`bash: let: expression expected
513
- `);let s=ba(t),r=0;for(let n of s)try{let a=Fe(`(( ${n} ))`).statements[0];if(a&&a.pipelines.length>0&&a.pipelines[0].commands.length>0){let o=a.pipelines[0].commands[0];o.type==="ArithmeticCommand"&&(r=await ee(e,o.expression.expression))}}catch(i){return P(`bash: let: ${n}: ${i.message}
514
- `)}return F(R,R,r===0?1:0)}async function Br(e,t){if(e.state.localScopes.length===0)return P(`bash: local: can only be used in a function
515
- `);let s=e.state.localScopes[e.state.localScopes.length-1],r="",n=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=B(d);u+=`${f}=${p}
516
- `}}return F(W(u),R,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 E=d[2];if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(c)){r+=`bash: local: \`${u}': not a valid identifier
517
- `,n=1;continue}if(await de(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 y=Be(E);for(let v=0;v<y.length;v++)g(e.state.env,`${c}_${v}`,y[v]);g(e.state.env,`${c}__length`,String(y.length)),st(e,c),i&&qe(e,c);continue}let p=u.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=\((.*)\)$/s);if(p){c=p[1];let E=p[2];if(await de(e,c,"bash"),!s.has(c)){s.set(c,e.state.env.get(c));let I=`${c}_`;for(let A of e.state.env.keys())A.startsWith(I)&&!A.includes("__")&&(s.has(A)||s.set(A,e.state.env.get(A)));let k=`${c}__length`;e.state.env.has(k)&&!s.has(k)&&s.set(k,e.state.env.get(k))}let $=Be(E),y=me(e,c),v=0,C=e.state.env.get(c);y.length===0&&C!==void 0?(e.state.env.set(`${c}_0`,C),e.state.env.delete(c),v=1):y.length>0&&(v=Math.max(...y)+1);for(let I=0;I<$.length;I++)g(e.state.env,`${c}_${v+I}`,ne(e,$[I]));let N=v+$.length;g(e.state.env,`${c}__length`,String(N)),st(e,c),i&&qe(e,c);continue}let m=u.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=(.*)$/);if(m){c=m[1];let E=ne(e,m[2]);await de(e,c,"bash"),s.has(c)||s.set(c,e.state.env.get(c));let $=T(e.state.env,c);g(e.state.env,c,$+E),st(e,c),i&&qe(e,c);continue}let h=u.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([^\]]+)\]=(.*)$/s);if(h){c=h[1];let E=h[2],$=ne(e,h[3]);if(await de(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 y;try{let C=new X,N=ce(C,E);y=await ee(e,N.expression)}catch{let C=parseInt(E,10);y=Number.isNaN(C)?0:C}g(e.state.env,`${c}_${y}`,$);let v=parseInt(T(e.state.env,`${c}__length`,"0"),10);y>=v&&g(e.state.env,`${c}__length`,String(y+1)),st(e,c),i&&qe(e,c);continue}if(u.includes("=")){let E=u.indexOf("=");c=u.slice(0,E),f=ne(e,u.slice(E+1))}else c=u;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(c)){r+=`bash: local: \`${u}': not a valid identifier
518
- `,n=1;continue}let b=s.has(c);if(f!==void 0){let E=e.state.env.get(c);if(e.state.tempEnvBindings){let $=e.state.accessedTempEnvVars?.has(c),y=e.state.mutatedTempEnvVars?.has(c);if(!$&&!y)for(let v=e.state.tempEnvBindings.length-1;v>=0;v--){let C=e.state.tempEnvBindings[v];if(C.has(c)){E=C.get(c);break}}}ri(e,c,E)}if(!b){let E=e.state.env.get(c);if(e.state.tempEnvBindings)for(let $=e.state.tempEnvBindings.length-1;$>=0;$--){let y=e.state.tempEnvBindings[$];if(y.has(c)){E=y.get(c);break}}if(s.set(c,E),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 y=`${c}__length`;e.state.env.has(y)&&!s.has(y)&&s.set(y,e.state.env.get(y))}}if(a&&f===void 0){let E=`${c}_`;for(let $ of e.state.env.keys())$.startsWith(E)&&!$.includes("__")&&e.state.env.delete($);g(e.state.env,`${c}__length`,"0")}else if(f!==void 0){if(await de(e,c,"bash"),i&&f!==""&&!/^[a-zA-Z_][a-zA-Z0-9_]*(\[.+\])?$/.test(f)){r+=`bash: local: \`${f}': invalid variable name for name reference
519
- `,n=1;continue}g(e.state.env,c,f),e.state.options.allexport&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(c))}else{let E=e.state.tempEnvBindings?.some($=>$.has(c));!b&&!E&&e.state.env.delete(c)}st(e,c),i&&qe(e,c)}return F(R,W(r),n)}async function Ur(e,t,s){let r=B(s),n=`
520
- `,i=0,a=0,o=0,l=!1,u="MAPFILE",c=0;for(;c<t.length;){let y=t[c];y==="-d"&&c+1<t.length?(n=t[c+1]===""?"\0":t[c+1]||`
521
- `,c+=2):y==="-n"&&c+1<t.length?(i=Number.parseInt(t[c+1],10)||0,c+=2):y==="-O"&&c+1<t.length?(a=Number.parseInt(t[c+1],10)||0,c+=2):y==="-s"&&c+1<t.length?(o=Number.parseInt(t[c+1],10)||0,c+=2):y==="-t"?(l=!0,c++):y==="-u"||y==="-C"||y==="-c"?c+=2:(y.startsWith("-")||(u=y),c++)}let f=r;!f&&e.state.groupStdin!==void 0&&(f=B(await re(e.state.groupStdin)));let d=[],p=f,m=0,h=0,b=e.limits?.maxArrayElements??1e5;for(;p.length>0;){let y=p.indexOf(n);if(y===-1){if(p.length>0){if(h<o)h++;else if(i===0||m<i){if(a+m>=b)return F(R,W(`mapfile: array element limit exceeded (${b})
522
- `),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,y),C=v.indexOf("\0");if(C!==-1&&(v=v.substring(0,C)),!l&&n!=="\0"&&(v+=n),p=p.substring(y+n.length),h<o){h++;continue}if(i>0&&m>=i)break;if(a+m>=b)return F(R,W(`mapfile: array element limit exceeded (${b})
523
- `),1);d.push(v),m++}a===0&&Ve(e,u);for(let y=0;y<d.length;y++)g(e.state.env,`${u}_${a+y}`,d[y]);let E=parseInt(T(e.state.env,`${u}__length`,"0"),10),$=a+d.length;return g(e.state.env,`${u}__length`,String(Math.max(E,$))),e.state.groupStdin!==void 0&&!r&&(e.state.groupStdin=S()),F(R,R,0)}function Ea(e){if(!e.startsWith("__rw__:"))return null;let t=e.slice(7),s=t.indexOf(":");if(s===-1)return null;let r=Number.parseInt(t.slice(0,s),10);if(Number.isNaN(r)||r<0)return null;let n=s+1,i=t.slice(n,n+r),a=n+r+1,o=t.slice(a),l=o.indexOf(":");if(l===-1)return null;let 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 Sa(e,t,s){return`__rw__:${e.length}:${e}:${t}:${s}`}async function Gr(e,t,s,r=-1){let n=B(s),i=!1,a=`
524
- `,o="",l=-1,u=-1,c=null,f=-1,d=-1,p=[],m=0,h=!1,b=(x,_)=>{let w=1;for(;w<x.length;){let D=x[w];if(D==="r")i=!0,w++;else if(D==="s")w++;else{if(D==="d")return w+1<x.length?(a=x.substring(w+1),{nextArgIndex:_+1}):_+1<t.length?(a=t[_+1],{nextArgIndex:_+2}):{nextArgIndex:_+1};if(D==="n"){if(w+1<x.length){let L=x.substring(w+1);return l=Number.parseInt(L,10),(Number.isNaN(l)||l<0)&&(h=!0,l=0),{nextArgIndex:_+1}}else if(_+1<t.length)return l=Number.parseInt(t[_+1],10),(Number.isNaN(l)||l<0)&&(h=!0,l=0),{nextArgIndex:_+2};return{nextArgIndex:_+1}}else if(D==="N"){if(w+1<x.length){let L=x.substring(w+1);return u=Number.parseInt(L,10),(Number.isNaN(u)||u<0)&&(h=!0,u=0),{nextArgIndex:_+1}}else if(_+1<t.length)return u=Number.parseInt(t[_+1],10),(Number.isNaN(u)||u<0)&&(h=!0,u=0),{nextArgIndex:_+2};return{nextArgIndex:_+1}}else{if(D==="a")return w+1<x.length?(c=x.substring(w+1),{nextArgIndex:_+1}):_+1<t.length?(c=t[_+1],{nextArgIndex:_+2}):{nextArgIndex:_+1};if(D==="p")return w+1<x.length?(o=x.substring(w+1),{nextArgIndex:_+1}):_+1<t.length?(o=t[_+1],{nextArgIndex:_+2}):{nextArgIndex:_+1};if(D==="u"){if(w+1<x.length){let L=x.substring(w+1);return f=Number.parseInt(L,10),Number.isNaN(f)||f<0?{nextArgIndex:-2}:{nextArgIndex:_+1}}else if(_+1<t.length)return f=Number.parseInt(t[_+1],10),Number.isNaN(f)||f<0?{nextArgIndex:-2}:{nextArgIndex:_+2};return{nextArgIndex:_+1}}else if(D==="t"){if(w+1<x.length){let L=x.substring(w+1);return d=Number.parseFloat(L),Number.isNaN(d)&&(d=0),{nextArgIndex:_+1}}else if(_+1<t.length)return d=Number.parseFloat(t[_+1]),Number.isNaN(d)&&(d=0),{nextArgIndex:_+2};return{nextArgIndex:_+1}}else if(D==="e"||D==="i"||D==="P"){if(D==="i"&&_+1<t.length)return{nextArgIndex:_+2};w++}else w++}}}return{nextArgIndex:_+1}};for(;m<t.length;){let x=t[m];if(x.startsWith("-")&&x.length>1&&x!=="--"){let _=b(x,m);if(_.nextArgIndex===-1)return{stdout:S(),stderr:S(),exitCode:2};if(_.nextArgIndex===-2)return{stdout:S(),stderr:S(),exitCode:1};m=_.nextArgIndex}else if(x==="--")for(m++;m<t.length;)p.push(t[m]),m++;else p.push(x),m++}if(h)return F(R,R,1);if(p.length===0&&c===null&&p.push("REPLY"),d===0){if(c)Ve(e,c);else{for(let x of p)g(e.state.env,x,"");p.length===0&&g(e.state.env,"REPLY","")}return F(R,R,0)}if(d<0&&d!==-1)return F(R,R,1);let E=n;f>=0?e.state.fileDescriptors?E=e.state.fileDescriptors.get(f)||"":E="":!E&&e.state.groupStdin!==void 0&&(E=B(await re(e.state.groupStdin)));let $=a===""?"\0":a,y="",v=0,C=!0,N=x=>{if(f>=0&&e.state.fileDescriptors)e.state.fileDescriptors.set(f,E.substring(x));else if(r>=0&&e.state.fileDescriptors){let _=e.state.fileDescriptors.get(r);if(_?.startsWith("__rw__:")){let w=Ea(_);if(w){let D=w.position+x;e.state.fileDescriptors.set(r,Sa(w.path,D,w.content))}}}else e.state.groupStdin!==void 0&&!n&&(e.state.groupStdin=fe(W(E.substring(x))))};if(u>=0){let x=Math.min(u,E.length);y=E.substring(0,x),v=x,C=x>=u,N(v);let _=p[0]||"REPLY";g(e.state.env,_,y);for(let w=1;w<p.length;w++)g(e.state.env,p[w],"");return F(R,R,C?0:1)}else if(l>=0){let x=0,_=0,w=!1;for(;_<E.length&&x<l;){let D=E[_];if(D===$){v=_+1,w=!0;break}if(!i&&D==="\\"&&_+1<E.length){let L=E[_+1];if(L===$&&$===`
525
- `){_+=2,v=_;continue}if(L===$){_+=2,x++,y+=L,v=_;continue}y+=L,_+=2,x++,v=_}else y+=D,_++,x++,v=_}C=x>=l||w,N(v)}else{v=0;let x=0;for(;x<E.length;){let _=E[x];if(_===$){v=x+$.length,C=!0;break}if(!i&&_==="\\"&&x+1<E.length){let w=E[x+1];if(w===`
526
- `){x+=2;continue}if(w===$){y+=w,x+=2;continue}y+=_,y+=w,x+=2;continue}y+=_,x++}if(x>=E.length&&(C=!1,v=x,y.length===0&&E.length===0)){for(let _ of p)g(e.state.env,_,"");return c&&Ve(e,c),F(R,R,1)}N(v)}$===`
527
- `&&y.endsWith(`
528
- `)&&(y=y.slice(0,-1));let I=x=>i?x:x.replace(/\\(.)/g,"$1");if(p.length===1&&p[0]==="REPLY")return g(e.state.env,"REPLY",I(y)),F(R,R,C?0:1);let k=yn(e.state.env);if(c){let{words:x}=Zs(y,k,void 0,i),_=e.limits?.maxArrayElements??1e5;if(x.length>_)return F(R,W(`read: array element limit exceeded (${_})
529
- `),1);Ve(e,c);for(let w=0;w<x.length;w++)g(e.state.env,`${c}_${w}`,I(x[w]));return F(R,R,C?0:1)}let A=p.length,{words:O,wordStarts:M}=Zs(y,k,A,i);for(let x=0;x<p.length;x++){let _=p[x];if(x<p.length-1)g(e.state.env,_,I(O[x]??""));else if(x<M.length){let w=y.substring(M[x]);w=gn(w,k,i),w=I(w),g(e.state.env,_,w)}else g(e.state.env,_,"")}return F(R,R,C?0:1)}function Hr(e,t){if(e.state.callDepth===0&&e.state.sourceDepth===0)return P("bash: return: can only `return' from a function or sourced script\n");let s=e.state.lastExitCode;if(t.length>0){let r=t[0],n=Number.parseInt(r,10);if(r===""||Number.isNaN(n)||!/^-?\d+$/.test(r))return P(`bash: return: ${r}: numeric argument required
530
- `,2);s=(n%256+256)%256}throw new ve(s)}var Os=`set: usage: set [-eux] [+eux] [-o option] [+o option]
512
+ `}return{stdout:V(t),stderr:P(),exitCode:0}}function jr(e,t){let s=Os("TERM"),r=0;if(t[0]==="-l")return Pa(t.slice(1));if(t[0]==="-s"||t[0]==="-n"){let l=t[1];if(!l)return{stdout:P(),stderr:V($i),exitCode:2};let c=Os(l);if(!c)return zr(l);s=c,r=2}else if(t[0]?.startsWith("-")&&t[0]!=="--"){let l=t[0].slice(1),c=Os(l);if(!c)return zr(l);s=c,r=1}else t[0]==="--"&&(r=1);let n=t.slice(r);if(n.length===0)return{stdout:P(),stderr:V($i),exitCode:1};let i="",a=0,o=0;for(let l of n){let c;if(l.startsWith("%")){if(c=e.processes.resolveJobSpec(l),c===void 0){i+=`bash: kill: ${l}: no such job
513
+ `,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
514
+ `,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
515
+ `,o++)}return{stdout:P(),stderr:V(i),exitCode:a>0||o===0?0:1}}function Aa(e){let t=[],s="",r=0;for(let n of e){for(let i of n)i==="("?r++:i===")"&&r--;s?s+=` ${n}`:s=n,r===0&&(t.push(s),s="")}return s&&t.push(s),t}async function Br(e,t){if(t.length===0)return A(`bash: let: expression expected
516
+ `);let s=Aa(t),r=0;for(let n of s)try{let a=Fe(`(( ${n} ))`).statements[0];if(a&&a.pipelines.length>0&&a.pipelines[0].commands.length>0){let o=a.pipelines[0].commands[0];o.type==="ArithmeticCommand"&&(r=await ee(e,o.expression.expression))}}catch(i){return A(`bash: let: ${n}: ${i.message}
517
+ `)}return F(R,R,r===0?1:0)}async function Ur(e,t){if(e.state.localScopes.length===0)return A(`bash: local: can only be used in a function
518
+ `);let s=e.state.localScopes[e.state.localScopes.length-1],r="",n=0,i=!1,a=!1,o=!1,l=[];for(let c of t)if(c==="-n")i=!0;else if(c==="-a")a=!0;else if(c==="-p")o=!0;else if(c.startsWith("-")&&!c.includes("="))for(let u of c.slice(1))u==="n"?i=!0:u==="a"?a=!0:u==="p"&&(o=!0);else l.push(c);if(l.length===0){let c="",u=Array.from(s.keys()).filter(f=>!f.includes("_")||!f.match(/_\d+$/)).filter(f=>!f.includes("__length")).sort();for(let f of u){let d=e.state.env.get(f);if(d!==void 0){let p=B(d);c+=`${f}=${p}
519
+ `}}return F(W(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 E=d[2];if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(u)){r+=`bash: local: \`${c}': not a valid identifier
520
+ `,n=1;continue}if(await de(e,u,"bash"),!s.has(u)){s.set(u,e.state.env.get(u));let y=`${u}_`;for(let k of e.state.env.keys())k.startsWith(y)&&!k.includes("__")&&(s.has(k)||s.set(k,e.state.env.get(k)))}let S=`${u}_`;for(let y of e.state.env.keys())y.startsWith(S)&&!y.includes("__")&&e.state.env.delete(y);let b=Be(E);for(let y=0;y<b.length;y++)g(e.state.env,`${u}_${y}`,b[y]);g(e.state.env,`${u}__length`,String(b.length)),st(e,u),i&&qe(e,u);continue}let p=c.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=\((.*)\)$/s);if(p){u=p[1];let E=p[2];if(await de(e,u,"bash"),!s.has(u)){s.set(u,e.state.env.get(u));let L=`${u}_`;for(let C of e.state.env.keys())C.startsWith(L)&&!C.includes("__")&&(s.has(C)||s.set(C,e.state.env.get(C)));let $=`${u}__length`;e.state.env.has($)&&!s.has($)&&s.set($,e.state.env.get($))}let S=Be(E),b=me(e,u),y=0,k=e.state.env.get(u);b.length===0&&k!==void 0?(e.state.env.set(`${u}_0`,k),e.state.env.delete(u),y=1):b.length>0&&(y=Math.max(...b)+1);for(let L=0;L<S.length;L++)g(e.state.env,`${u}_${y+L}`,ne(e,S[L]));let _=y+S.length;g(e.state.env,`${u}__length`,String(_)),st(e,u),i&&qe(e,u);continue}let m=c.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\+=(.*)$/);if(m){u=m[1];let E=ne(e,m[2]);await de(e,u,"bash"),s.has(u)||s.set(u,e.state.env.get(u));let S=N(e.state.env,u);g(e.state.env,u,S+E),st(e,u),i&&qe(e,u);continue}let h=c.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([^\]]+)\]=(.*)$/s);if(h){u=h[1];let E=h[2],S=ne(e,h[3]);if(await de(e,u,"bash"),!s.has(u)){s.set(u,e.state.env.get(u));let k=`${u}_`;for(let L of e.state.env.keys())L.startsWith(k)&&!L.includes("__")&&(s.has(L)||s.set(L,e.state.env.get(L)));let _=`${u}__length`;e.state.env.has(_)&&!s.has(_)&&s.set(_,e.state.env.get(_))}let b;try{let k=new X,_=ce(k,E);b=await ee(e,_.expression)}catch{let k=parseInt(E,10);b=Number.isNaN(k)?0:k}g(e.state.env,`${u}_${b}`,S);let y=parseInt(N(e.state.env,`${u}__length`,"0"),10);b>=y&&g(e.state.env,`${u}__length`,String(b+1)),st(e,u),i&&qe(e,u);continue}if(c.includes("=")){let E=c.indexOf("=");u=c.slice(0,E),f=ne(e,c.slice(E+1))}else u=c;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(u)){r+=`bash: local: \`${c}': not a valid identifier
521
+ `,n=1;continue}let v=s.has(u);if(f!==void 0){let E=e.state.env.get(u);if(e.state.tempEnvBindings){let S=e.state.accessedTempEnvVars?.has(u),b=e.state.mutatedTempEnvVars?.has(u);if(!S&&!b)for(let y=e.state.tempEnvBindings.length-1;y>=0;y--){let k=e.state.tempEnvBindings[y];if(k.has(u)){E=k.get(u);break}}}ri(e,u,E)}if(!v){let E=e.state.env.get(u);if(e.state.tempEnvBindings)for(let S=e.state.tempEnvBindings.length-1;S>=0;S--){let b=e.state.tempEnvBindings[S];if(b.has(u)){E=b.get(u);break}}if(s.set(u,E),a){let S=`${u}_`;for(let y of e.state.env.keys())y.startsWith(S)&&!y.includes("__")&&(s.has(y)||s.set(y,e.state.env.get(y)));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 E=`${u}_`;for(let S of e.state.env.keys())S.startsWith(E)&&!S.includes("__")&&e.state.env.delete(S);g(e.state.env,`${u}__length`,"0")}else if(f!==void 0){if(await de(e,u,"bash"),i&&f!==""&&!/^[a-zA-Z_][a-zA-Z0-9_]*(\[.+\])?$/.test(f)){r+=`bash: local: \`${f}': invalid variable name for name reference
522
+ `,n=1;continue}g(e.state.env,u,f),e.state.options.allexport&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(u))}else{let E=e.state.tempEnvBindings?.some(S=>S.has(u));!v&&!E&&e.state.env.delete(u)}st(e,u),i&&qe(e,u)}return F(R,W(r),n)}async function Hr(e,t,s){let r=B(s),n=`
523
+ `,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?(n=t[u+1]===""?"\0":t[u+1]||`
524
+ `,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=r;!f&&e.state.groupStdin!==void 0&&(f=B(await re(e.state.groupStdin)));let d=[],p=f,m=0,h=0,v=e.limits?.maxArrayElements??1e5;for(;p.length>0;){let b=p.indexOf(n);if(b===-1){if(p.length>0){if(h<o)h++;else if(i===0||m<i){if(a+m>=v)return F(R,W(`mapfile: array element limit exceeded (${v})
525
+ `),1);let _=p,L=_.indexOf("\0");L!==-1&&(_=_.substring(0,L)),d.push(_),m++}}break}let y=p.substring(0,b),k=y.indexOf("\0");if(k!==-1&&(y=y.substring(0,k)),!l&&n!=="\0"&&(y+=n),p=p.substring(b+n.length),h<o){h++;continue}if(i>0&&m>=i)break;if(a+m>=v)return F(R,W(`mapfile: array element limit exceeded (${v})
526
+ `),1);d.push(y),m++}a===0&&Ve(e,c);for(let b=0;b<d.length;b++)g(e.state.env,`${c}_${a+b}`,d[b]);let E=parseInt(N(e.state.env,`${c}__length`,"0"),10),S=a+d.length;return g(e.state.env,`${c}__length`,String(Math.max(E,S))),e.state.groupStdin!==void 0&&!r&&(e.state.groupStdin=P()),F(R,R,0)}function Ca(e){if(!e.startsWith("__rw__:"))return null;let t=e.slice(7),s=t.indexOf(":");if(s===-1)return null;let r=Number.parseInt(t.slice(0,s),10);if(Number.isNaN(r)||r<0)return null;let n=s+1,i=t.slice(n,n+r),a=n+r+1,o=t.slice(a),l=o.indexOf(":");if(l===-1)return null;let c=Number.parseInt(o.slice(0,l),10);if(Number.isNaN(c)||c<0)return null;let u=o.slice(l+1);return{path:i,position:c,content:u}}function ka(e,t,s){return`__rw__:${e.length}:${e}:${t}:${s}`}async function Gr(e,t,s,r=-1){let n=B(s),i=!1,a=`
527
+ `,o="",l=-1,c=-1,u=null,f=-1,d=-1,p=[],m=0,h=!1,v=(T,x)=>{let w=1;for(;w<T.length;){let D=T[w];if(D==="r")i=!0,w++;else if(D==="s")w++;else{if(D==="d")return w+1<T.length?(a=T.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<T.length){let M=T.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<T.length){let M=T.substring(w+1);return c=Number.parseInt(M,10),(Number.isNaN(c)||c<0)&&(h=!0,c=0),{nextArgIndex:x+1}}else if(x+1<t.length)return c=Number.parseInt(t[x+1],10),(Number.isNaN(c)||c<0)&&(h=!0,c=0),{nextArgIndex:x+2};return{nextArgIndex:x+1}}else{if(D==="a")return w+1<T.length?(u=T.substring(w+1),{nextArgIndex:x+1}):x+1<t.length?(u=t[x+1],{nextArgIndex:x+2}):{nextArgIndex:x+1};if(D==="p")return w+1<T.length?(o=T.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<T.length){let M=T.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<T.length){let M=T.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=t[m];if(T.startsWith("-")&&T.length>1&&T!=="--"){let x=v(T,m);if(x.nextArgIndex===-1)return{stdout:P(),stderr:P(),exitCode:2};if(x.nextArgIndex===-2)return{stdout:P(),stderr:P(),exitCode:1};m=x.nextArgIndex}else if(T==="--")for(m++;m<t.length;)p.push(t[m]),m++;else p.push(T),m++}if(h)return F(R,R,1);if(p.length===0&&u===null&&p.push("REPLY"),d===0){if(u)Ve(e,u);else{for(let T of p)g(e.state.env,T,"");p.length===0&&g(e.state.env,"REPLY","")}return F(R,R,0)}if(d<0&&d!==-1)return F(R,R,1);let E=n;f>=0?e.state.fileDescriptors?E=e.state.fileDescriptors.get(f)||"":E="":!E&&e.state.groupStdin!==void 0&&(E=B(await re(e.state.groupStdin)));let S=a===""?"\0":a,b="",y=0,k=!0,_=T=>{if(f>=0&&e.state.fileDescriptors)e.state.fileDescriptors.set(f,E.substring(T));else if(r>=0&&e.state.fileDescriptors){let x=e.state.fileDescriptors.get(r);if(x?.startsWith("__rw__:")){let w=Ca(x);if(w){let D=w.position+T;e.state.fileDescriptors.set(r,ka(w.path,D,w.content))}}}else e.state.groupStdin!==void 0&&!n&&(e.state.groupStdin=fe(W(E.substring(T))))};if(c>=0){let T=Math.min(c,E.length);b=E.substring(0,T),y=T,k=T>=c,_(y);let x=p[0]||"REPLY";g(e.state.env,x,b);for(let w=1;w<p.length;w++)g(e.state.env,p[w],"");return F(R,R,k?0:1)}else if(l>=0){let T=0,x=0,w=!1;for(;x<E.length&&T<l;){let D=E[x];if(D===S){y=x+1,w=!0;break}if(!i&&D==="\\"&&x+1<E.length){let M=E[x+1];if(M===S&&S===`
528
+ `){x+=2,y=x;continue}if(M===S){x+=2,T++,b+=M,y=x;continue}b+=M,x+=2,T++,y=x}else b+=D,x++,T++,y=x}k=T>=l||w,_(y)}else{y=0;let T=0;for(;T<E.length;){let x=E[T];if(x===S){y=T+S.length,k=!0;break}if(!i&&x==="\\"&&T+1<E.length){let w=E[T+1];if(w===`
529
+ `){T+=2;continue}if(w===S){b+=w,T+=2;continue}b+=x,b+=w,T+=2;continue}b+=x,T++}if(T>=E.length&&(k=!1,y=T,b.length===0&&E.length===0)){for(let x of p)g(e.state.env,x,"");return u&&Ve(e,u),F(R,R,1)}_(y)}S===`
530
+ `&&b.endsWith(`
531
+ `)&&(b=b.slice(0,-1));let L=T=>i?T:T.replace(/\\(.)/g,"$1");if(p.length===1&&p[0]==="REPLY")return g(e.state.env,"REPLY",L(b)),F(R,R,k?0:1);let $=yn(e.state.env);if(u){let{words:T}=Xs(b,$,void 0,i),x=e.limits?.maxArrayElements??1e5;if(T.length>x)return F(R,W(`read: array element limit exceeded (${x})
532
+ `),1);Ve(e,u);for(let w=0;w<T.length;w++)g(e.state.env,`${u}_${w}`,L(T[w]));return F(R,R,k?0:1)}let C=p.length,{words:O,wordStarts:I}=Xs(b,$,C,i);for(let T=0;T<p.length;T++){let x=p[T];if(T<p.length-1)g(e.state.env,x,L(O[T]??""));else if(T<I.length){let w=b.substring(I[T]);w=gn(w,$,i),w=L(w),g(e.state.env,x,w)}else g(e.state.env,x,"")}return F(R,R,k?0:1)}function qr(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 r=t[0],n=Number.parseInt(r,10);if(r===""||Number.isNaN(n)||!/^-?\d+$/.test(r))return A(`bash: return: ${r}: numeric argument required
533
+ `,2);s=(n%256+256)%256}throw new ve(s)}var Ds=`set: usage: set [-eux] [+eux] [-o option] [+o option]
531
534
  Options:
532
535
  -e Exit immediately if a command exits with non-zero status
533
536
  +e Disable -e
@@ -543,163 +546,160 @@ Options:
543
546
  +o pipefail Disable pipefail
544
547
  -o xtrace Same as -x
545
548
  +o xtrace Disable xtrace
546
- `,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]]),Ci=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]]),Ai=["errexit","nounset","pipefail","verbose","xtrace","posix","allexport","noclobber","noglob","noexec","vi","emacs"],ki=["braceexpand","errtrace","functrace","hashall","histexpand","history","ignoreeof","interactive-comments","keyword","monitor","nolog","notify","onecmd","physical","privileged"];function xi(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,gt(e))}function $a(e,t){return t+1<e.length&&!e[t+1].startsWith("-")&&!e[t+1].startsWith("+")}function Pa(e,t){let s=me(e,t);if(s.length===0)return`${t}=()`;let r=s.map(n=>{let i=T(e.state.env,`${t}_${n}`,"");return`[${n}]=${ct(i)}`});return`${t}=(${r.join(" ")})`}function Ca(e){return/^[a-zA-Z0-9_]+$/.test(e)?e:`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function Aa(e,t){let s=et(e,t);if(s.length===0)return`${t}=()`;let r=s.map(n=>{let i=T(e.state.env,`${t}_${n}`,"");return`[${Ca(n)}]=${ct(i)}`});return`${t}=(${r.join(" ")} )`}function ka(e){let t=new Set,s=e.state.associativeArrays??new Set;for(let r of e.state.env.keys()){let n=r.match(/^([a-zA-Z_][a-zA-Z0-9_]*)_(\d+)$/);if(n){let i=n[1];s.has(i)||t.add(i)}}return t}function xa(e){return e.state.associativeArrays??new Set}async function Zr(e,t){if(t.includes("--help"))return H(Os);if(t.length===0){let r=ka(e),n=xa(e),i=l=>{for(let u of n){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)||r.has(l)||n.has(l))continue;let c=l.match(/^([a-zA-Z_][a-zA-Z0-9_]*)_(\d+)$/);if(c&&r.has(c[1]))continue;let f=l.match(/^([a-zA-Z_][a-zA-Z0-9_]*)__length$/);f&&r.has(f[1])||i(l)||f&&n.has(f[1])||a.push([l,B(u)])}let o=[];for(let[l,u]of a.sort(([c],[f])=>c<f?-1:c>f?1:0))o.push(`${l}=${ks(u)}`);for(let l of[...r].sort((u,c)=>u<c?-1:u>c?1:0))o.push(Pa(e,l));for(let l of[...n].sort((u,c)=>u<c?-1:u>c?1:0))o.push(Aa(e,l));return o.sort((l,u)=>{let c=l.split("=")[0],f=u.split("=")[0];return c<f?-1:c>f?1:0}),H(o.length>0?`${o.join(`
549
+ `,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]]),Ai=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]]),Ci=["errexit","nounset","pipefail","verbose","xtrace","posix","allexport","noclobber","noglob","noexec","vi","emacs"],ki=["braceexpand","errtrace","functrace","hashall","histexpand","history","ignoreeof","interactive-comments","keyword","monitor","nolog","notify","onecmd","physical","privileged"];function Ti(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,gt(e))}function Ta(e,t){return t+1<e.length&&!e[t+1].startsWith("-")&&!e[t+1].startsWith("+")}function xa(e,t){let s=me(e,t);if(s.length===0)return`${t}=()`;let r=s.map(n=>{let i=N(e.state.env,`${t}_${n}`,"");return`[${n}]=${ct(i)}`});return`${t}=(${r.join(" ")})`}function _a(e){return/^[a-zA-Z0-9_]+$/.test(e)?e:`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function Na(e,t){let s=et(e,t);if(s.length===0)return`${t}=()`;let r=s.map(n=>{let i=N(e.state.env,`${t}_${n}`,"");return`[${_a(n)}]=${ct(i)}`});return`${t}=(${r.join(" ")} )`}function Oa(e){let t=new Set,s=e.state.associativeArrays??new Set;for(let r of e.state.env.keys()){let n=r.match(/^([a-zA-Z_][a-zA-Z0-9_]*)_(\d+)$/);if(n){let i=n[1];s.has(i)||t.add(i)}}return t}function Da(e){return e.state.associativeArrays??new Set}async function Xr(e,t){if(t.includes("--help"))return G(Ds);if(t.length===0){let r=Oa(e),n=Da(e),i=l=>{for(let c of n){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)||r.has(l)||n.has(l))continue;let u=l.match(/^([a-zA-Z_][a-zA-Z0-9_]*)_(\d+)$/);if(u&&r.has(u[1]))continue;let f=l.match(/^([a-zA-Z_][a-zA-Z0-9_]*)__length$/);f&&r.has(f[1])||i(l)||f&&n.has(f[1])||a.push([l,B(c)])}let o=[];for(let[l,c]of a.sort(([u],[f])=>u<f?-1:u>f?1:0))o.push(`${l}=${xs(c)}`);for(let l of[...r].sort((c,u)=>c<u?-1:c>u?1:0))o.push(xa(e,l));for(let l of[...n].sort((c,u)=>c<u?-1:c>u?1:0))o.push(Na(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(`
547
550
  `)}
548
- `:"")}let s=0;for(;s<t.length;){let r=t[s];if((r==="-o"||r==="+o")&&$a(t,s)){let n=t[s+1];if(!Ci.has(n)){let i=`bash: set: ${n}: invalid option name
549
- ${Os}`;if(e.state.options.posix)throw await G(e,2,i,!0),new be(1);return P(i)}xi(e,Ci.get(n)??null,r==="-o"),s+=2;continue}if(r==="-o"){let n=Ai.map(o=>`${o.padEnd(16)}${e.state.options[o]?"on":"off"}`),i=ki.map(o=>`${o.padEnd(16)}off`),a=[...n,...i].sort();return H(`${a.join(`
551
+ `:"")}let s=0;for(;s<t.length;){let r=t[s];if((r==="-o"||r==="+o")&&Ta(t,s)){let n=t[s+1];if(!Ai.has(n)){let i=`bash: set: ${n}: invalid option name
552
+ ${Ds}`;if(e.state.options.posix)throw await H(e,2,i,!0),new be(1);return A(i)}Ti(e,Ai.get(n)??null,r==="-o"),s+=2;continue}if(r==="-o"){let n=Ci.map(o=>`${o.padEnd(16)}${e.state.options[o]?"on":"off"}`),i=ki.map(o=>`${o.padEnd(16)}off`),a=[...n,...i].sort();return G(`${a.join(`
550
553
  `)}
551
- `)}if(r==="+o"){let n=Ai.map(o=>`set ${e.state.options[o]?"-o":"+o"} ${o}`),i=ki.map(o=>`set +o ${o}`),a=[...n,...i].sort();return H(`${a.join(`
554
+ `)}if(r==="+o"){let n=Ci.map(o=>`set ${e.state.options[o]?"-o":"+o"} ${o}`),i=ki.map(o=>`set +o ${o}`),a=[...n,...i].sort();return G(`${a.join(`
552
555
  `)}
553
556
  `)}if(r.length>1&&(r[0]==="-"||r[0]==="+")&&r[1]!=="-"){let n=r[0]==="-";for(let i=1;i<r.length;i++){let a=r[i];if(!Pi.has(a)){let o=`bash: set: ${r[0]}${a}: invalid option
554
- ${Os}`;if(e.state.options.posix)throw await G(e,2,o,!0),new be(1);return P(o)}xi(e,Pi.get(a)??null,n)}s++;continue}if(r==="--")return qr(e,t.slice(s+1)),U();if(r==="-"){if(e.state.options.xtrace=!1,e.state.options.verbose=!1,gt(e),s+1<t.length)return qr(e,t.slice(s+1)),U();s++;continue}if(r==="+"){s++;continue}if(r.startsWith("-")||r.startsWith("+")){let n=`bash: set: ${r}: invalid option
555
- ${Os}`;if(e.state.options.posix)throw await G(e,2,n,!0),new be(1);return P(n)}return qr(e,t.slice(s)),U()}return U()}function qr(e,t){let s=1;for(;e.state.env.has(String(s));)e.state.env.delete(String(s)),s++;for(let r=0;r<t.length;r++)g(e.state.env,String(r+1),t[r]);g(e.state.env,"#",String(t.length)),g(e.state.env,"@",t.join(" ")),g(e.state.env,"*",t.join(" "))}async function Xr(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
556
- `;if(e.state.options.posix)throw await G(e,2,o,!0),new be(1);return P(o)}s=a}let r=Number.parseInt(T(e.state.env,"#","0"),10);if(s>r){let a=`bash: shift: shift count out of range
557
- `;if(e.state.options.posix)throw await G(e,2,a,!0),new be(1);return P(a)}if(s===0)return U();let n=[];for(let a=1;a<=r;a++)n.push(T(e.state.env,String(a))||"");let i=n.slice(s);for(let a=1;a<=r;a++)e.state.env.delete(String(a));for(let a=0;a<i.length;a++)g(e.state.env,String(a+1),i[a]);return g(e.state.env,"#",String(i.length)),g(e.state.env,"@",i.join(" ")),U()}async function Jr(e,t){let s=t;if(s.length>0&&s[0]==="--"&&(s=s.slice(1)),s.length===0)return F(R,W(`bash: source: filename argument required
558
- `),2);let r=s[0],n=null,i=null;if(r.includes("/")){let u=e.fs.resolvePath(e.state.cwd,r);try{i=await e.fs.readFileText(u),n=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}/${r}`);try{if((await e.fs.stat(d)).isDirectory)continue;i=await e.fs.readFileText(d),n=d;break}catch{}}if(i===null){let f=e.fs.resolvePath(e.state.cwd,r);try{i=await e.fs.readFileText(f),n=f}catch{}}}if(i===null)return P(`bash: ${r}: No such file or directory
559
- `);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);g(e.state.env,"#",String(u.length)),g(e.state.env,"@",u.join(" "));for(let c=0;c<u.length&&c<9;c++)g(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):g(e.state.env,u,c)};e.state.sourceDepth++,e.state.currentSource=r;try{let u=Fe(i),c=await e.executeScript(u),f=await Y(e,c);return l(),f}catch(u){if(l(),await te(e,u),u instanceof q)throw u;if(u instanceof ve)return F(R,R,u.exitCode);if(u.name==="ParseException")return P(`bash: ${r}: ${u.message}
560
- `);throw u}}function _i(e){return/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e)}function _a(e){return e.startsWith("'")&&e.endsWith("'")||e.startsWith('"')&&e.endsWith('"')}async function Ti(e,t){if(_a(t))return null;try{let s=new X,r=ce(s,t);return await ee(e,r.expression)}catch{let s=parseInt(t,10);return Number.isNaN(s)?0:s}}function Ni(e,t){if(e.state.localVarStack?.has(t)){let r=Es(e,t);if(r){r.value===void 0?e.state.env.delete(t):e.state.env.set(t,r.value);let n=e.state.localVarStack?.get(t);if(!n||n.length===0)bs(e,t),e.state.localVarStack?.delete(t),e.state.fullyUnsetLocals=e.state.fullyUnsetLocals||new Map,e.state.fullyUnsetLocals.set(t,r.scopeIndex),Kr(e,t);else{let i=n[n.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),bs(e,t),e.state.localVarStack?.delete(t),e.state.fullyUnsetLocals=e.state.fullyUnsetLocals||new Map,e.state.fullyUnsetLocals.set(t,0),!0}for(let r=e.state.localScopes.length-1;r>=0;r--){let n=e.state.localScopes[r];if(n.has(t)){let i=n.get(t);i===void 0?e.state.env.delete(t):e.state.env.set(t,i),n.delete(t);let a=!1;for(let o=r-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||bs(e,t),!0}}return!1}function Kr(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 r=e.state.tempEnvBindings[s];if(r.has(t)){let n=r.get(t);return n===void 0?e.state.env.delete(t):e.state.env.set(t,n),r.delete(t),!0}}return!1}async function Oi(e,t){if(t.startsWith("'")&&t.endsWith("'"))return t.slice(1,-1);if(t.startsWith('"')&&t.endsWith('"')){let s=t.slice(1,-1),n=new X().parseWordFromString(s,!0,!1);return z(e,n)}if(t.includes("$")){let r=new X().parseWordFromString(t,!1,!1);return z(e,r)}return t}async function Yr(e,t){let s="both",r="",n=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 y=Ie(e,d);for(let[v]of y)e.state.env.delete(`${d}_${v}`);e.state.env.delete(d);continue}let m=e.state.associativeArrays?.has(d);if(m){let y=await Oi(e,p);e.state.env.delete(`${d}_${y}`);continue}let h=Ks(e,d),b=e.state.declaredVars?.has(d);if((e.state.env.has(d)||b)&&!h&&!m){r+=`bash: unset: ${d}: not an array variable
561
- `,n=1;continue}let $=await Ti(e,p);if($===null&&h){r+=`bash: unset: ${p}: not a valid identifier
562
- `,n=1;continue}if($===null)continue;if($<0){let y=Ie(e,d),v=y.length,C=e.state.currentLine;if(v===0){r+=`bash: line ${C}: unset: [${$}]: bad array subscript
563
- `,n=1;continue}let N=v+$;if(N<0){r+=`bash: line ${C}: unset: [${$}]: bad array subscript
564
- `,n=1;continue}let I=y[N][0];e.state.env.delete(`${d}_${I}`);continue}e.state.env.delete(`${d}_${$}`);continue}if(!_i(i)){r+=`bash: unset: \`${i}': not a valid identifier
565
- `,n=1;continue}let c=i;if(Ee(e,i)){let d=ze(e,i);d&&d!==i&&(c=d)}if(ot(e,c)){r+=`bash: unset: ${c}: cannot unset: readonly variable
566
- `,n=1;continue}let f=bt(e,c);if(f!==void 0&&f!==e.state.callDepth)Ni(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=Es(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 Kr(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=Ie(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 Oi(e,c);e.state.env.delete(`${u}_${h}`);continue}let d=Ks(e,u);if(e.state.env.has(u)&&!d&&!f){r+=`bash: unset: ${u}: not an array variable
567
- `,n=1;continue}let m=await Ti(e,c);if(m===null&&d){r+=`bash: unset: ${c}: not a valid identifier
568
- `,n=1;continue}if(m===null)continue;if(m<0){let h=Ie(e,u),b=h.length,E=e.state.currentLine;if(b===0){r+=`bash: line ${E}: unset: [${m}]: bad array subscript
569
- `,n=1;continue}let $=b+m;if($<0){r+=`bash: line ${E}: unset: [${m}]: bad array subscript
570
- `,n=1;continue}let y=h[$][0];e.state.env.delete(`${u}_${y}`);continue}e.state.env.delete(`${u}_${m}`);continue}if(!_i(i)){r+=`bash: unset: \`${i}': not a valid identifier
571
- `,n=1;continue}let o=i;if(Ee(e,i)){let u=ze(e,i);u&&u!==i&&(o=u)}if(ot(e,o)){r+=`bash: unset: ${o}: cannot unset: readonly variable
572
- `,n=1;continue}let l=bt(e,o);if(l!==void 0&&l!==e.state.callDepth)Ni(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=Es(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 Kr(e,o)||e.state.env.delete(o);e.state.exportedVars?.delete(o),e.state.functions.delete(i)}return F(R,W(r),n)}var Ta=`wait: usage: wait [id ...]
573
- `;async function Qr(e,t){let s=t.find(i=>i.startsWith("-"));if(s)return{stdout:S(),stderr:V(`bash: wait: ${s}: invalid option
574
- ${Ta}`),exitCode:2};if(Ke(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:S(),stderr:S(),exitCode:o}}finally{i&&e.signal?.removeEventListener("abort",i)}}let r=0,n="";for(let i of t){Ke(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)){n+=i.startsWith("%")?`bash: wait: ${i}: no such job
575
- `:`bash: wait: pid ${i} is not a child of this shell
576
- `,r=127;continue}let o,l=new Promise((u,c)=>{o=()=>c(new pe(e.signal?.reason)),e.signal?.addEventListener("abort",o,{once:!0})});try{r=await(e.signal?Promise.race([e.processes.wait(a),l]):e.processes.wait(a))}finally{o&&e.signal?.removeEventListener("abort",o)}}return{stdout:S(),stderr:V(n),exitCode:r}}var en=["extglob","dotglob","nullglob","failglob","globstar","globskipdots","nocaseglob","nocasematch","expand_aliases","lastpipe","xpg_echo"],Na=["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 Ds(e){return en.includes(e)}function Oa(e){return Na.includes(e)}function Di(e,t){let s=!1,r=!1,n=!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":r=!0;break;case"p":n=!0;break;case"q":i=!0;break;case"o":a=!0;break;default:return{exitCode:2,stdout:S(),stderr:V(`shopt: -${m}: invalid option
577
- `)}}}l++}else break}for(;l<t.length;)o.push(t[l]),l++;if(a)return Da(e,o,s,r,n,i);if(s&&r)return{exitCode:1,stdout:S(),stderr:V(`shopt: cannot set and unset shell options simultaneously
578
- `)};if(o.length===0){if(s||r){let p=[];for(let m of en){let h=e.state.shoptOptions[m];s&&h?p.push(n?`shopt -s ${m}`:`${m} on`):r&&!h&&p.push(n?`shopt -u ${m}`:`${m} off`)}return{exitCode:0,stdout:p.length>0?V(`${p.join(`
557
+ ${Ds}`;if(e.state.options.posix)throw await H(e,2,o,!0),new be(1);return A(o)}Ti(e,Pi.get(a)??null,n)}s++;continue}if(r==="--")return Zr(e,t.slice(s+1)),U();if(r==="-"){if(e.state.options.xtrace=!1,e.state.options.verbose=!1,gt(e),s+1<t.length)return Zr(e,t.slice(s+1)),U();s++;continue}if(r==="+"){s++;continue}if(r.startsWith("-")||r.startsWith("+")){let n=`bash: set: ${r}: invalid option
558
+ ${Ds}`;if(e.state.options.posix)throw await H(e,2,n,!0),new be(1);return A(n)}return Zr(e,t.slice(s)),U()}return U()}function Zr(e,t){let s=1;for(;e.state.env.has(String(s));)e.state.env.delete(String(s)),s++;for(let r=0;r<t.length;r++)g(e.state.env,String(r+1),t[r]);g(e.state.env,"#",String(t.length)),g(e.state.env,"@",t.join(" ")),g(e.state.env,"*",t.join(" "))}async function Jr(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
559
+ `;if(e.state.options.posix)throw await H(e,2,o,!0),new be(1);return A(o)}s=a}let r=Number.parseInt(N(e.state.env,"#","0"),10);if(s>r){let a=`bash: shift: shift count out of range
560
+ `;if(e.state.options.posix)throw await H(e,2,a,!0),new be(1);return A(a)}if(s===0)return U();let n=[];for(let a=1;a<=r;a++)n.push(N(e.state.env,String(a))||"");let i=n.slice(s);for(let a=1;a<=r;a++)e.state.env.delete(String(a));for(let a=0;a<i.length;a++)g(e.state.env,String(a+1),i[a]);return g(e.state.env,"#",String(i.length)),g(e.state.env,"@",i.join(" ")),U()}async function Kr(e,t){let s=t;if(s.length>0&&s[0]==="--"&&(s=s.slice(1)),s.length===0)return F(R,W(`bash: source: filename argument required
561
+ `),2);let r=s[0],n=null,i=null;if(r.includes("/")){let c=e.fs.resolvePath(e.state.cwd,r);try{i=await e.fs.readFileText(c),n=c}catch{}}else{let u=N(e.state.env,"PATH","").split(":").filter(f=>f);for(let f of u){let d=e.fs.resolvePath(e.state.cwd,`${f}/${r}`);try{if((await e.fs.stat(d)).isDirectory)continue;i=await e.fs.readFileText(d),n=d;break}catch{}}if(i===null){let f=e.fs.resolvePath(e.state.cwd,r);try{i=await e.fs.readFileText(f),n=f}catch{}}}if(i===null)return A(`bash: ${r}: No such file or directory
562
+ `);let a=new Map;if(s.length>1){for(let u=1;u<=9;u++)a.set(String(u),N(e.state.env,String(u)));a.set("#",N(e.state.env,"#")),a.set("@",N(e.state.env,"@"));let c=s.slice(1);g(e.state.env,"#",String(c.length)),g(e.state.env,"@",c.join(" "));for(let u=0;u<c.length&&u<9;u++)g(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):g(e.state.env,c,u)};e.state.sourceDepth++,e.state.currentSource=r;try{let c=Fe(i),u=await e.executeScript(c),f=await Q(e,u);return l(),f}catch(c){if(l(),await te(e,c),c instanceof q)throw c;if(c instanceof ve)return F(R,R,c.exitCode);if(c.name==="ParseException")return A(`bash: ${r}: ${c.message}
563
+ `);throw c}}function xi(e){return/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e)}function Ia(e){return e.startsWith("'")&&e.endsWith("'")||e.startsWith('"')&&e.endsWith('"')}async function _i(e,t){if(Ia(t))return null;try{let s=new X,r=ce(s,t);return await ee(e,r.expression)}catch{let s=parseInt(t,10);return Number.isNaN(s)?0:s}}function Ni(e,t){if(e.state.localVarStack?.has(t)){let r=$s(e,t);if(r){r.value===void 0?e.state.env.delete(t):e.state.env.set(t,r.value);let n=e.state.localVarStack?.get(t);if(!n||n.length===0)Ss(e,t),e.state.localVarStack?.delete(t),e.state.fullyUnsetLocals=e.state.fullyUnsetLocals||new Map,e.state.fullyUnsetLocals.set(t,r.scopeIndex),Yr(e,t);else{let i=n[n.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),Ss(e,t),e.state.localVarStack?.delete(t),e.state.fullyUnsetLocals=e.state.fullyUnsetLocals||new Map,e.state.fullyUnsetLocals.set(t,0),!0}for(let r=e.state.localScopes.length-1;r>=0;r--){let n=e.state.localScopes[r];if(n.has(t)){let i=n.get(t);i===void 0?e.state.env.delete(t):e.state.env.set(t,i),n.delete(t);let a=!1;for(let o=r-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||Ss(e,t),!0}}return!1}function Yr(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 r=e.state.tempEnvBindings[s];if(r.has(t)){let n=r.get(t);return n===void 0?e.state.env.delete(t):e.state.env.set(t,n),r.delete(t),!0}}return!1}async function Oi(e,t){if(t.startsWith("'")&&t.endsWith("'"))return t.slice(1,-1);if(t.startsWith('"')&&t.endsWith('"')){let s=t.slice(1,-1),n=new X().parseWordFromString(s,!0,!1);return z(e,n)}if(t.includes("$")){let r=new X().parseWordFromString(t,!1,!1);return z(e,r)}return t}async function Qr(e,t){let s="both",r="",n=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=Ie(e,d);for(let[y]of b)e.state.env.delete(`${d}_${y}`);e.state.env.delete(d);continue}let m=e.state.associativeArrays?.has(d);if(m){let b=await Oi(e,p);e.state.env.delete(`${d}_${b}`);continue}let h=Ys(e,d),v=e.state.declaredVars?.has(d);if((e.state.env.has(d)||v)&&!h&&!m){r+=`bash: unset: ${d}: not an array variable
564
+ `,n=1;continue}let S=await _i(e,p);if(S===null&&h){r+=`bash: unset: ${p}: not a valid identifier
565
+ `,n=1;continue}if(S===null)continue;if(S<0){let b=Ie(e,d),y=b.length,k=e.state.currentLine;if(y===0){r+=`bash: line ${k}: unset: [${S}]: bad array subscript
566
+ `,n=1;continue}let _=y+S;if(_<0){r+=`bash: line ${k}: unset: [${S}]: bad array subscript
567
+ `,n=1;continue}let L=b[_][0];e.state.env.delete(`${d}_${L}`);continue}e.state.env.delete(`${d}_${S}`);continue}if(!xi(i)){r+=`bash: unset: \`${i}': not a valid identifier
568
+ `,n=1;continue}let u=i;if(Ee(e,i)){let d=ze(e,i);d&&d!==i&&(u=d)}if(ot(e,u)){r+=`bash: unset: ${u}: cannot unset: readonly variable
569
+ `,n=1;continue}let f=bt(e,u);if(f!==void 0&&f!==e.state.callDepth)Ni(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=$s(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 Yr(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=Ie(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 Oi(e,u);e.state.env.delete(`${c}_${h}`);continue}let d=Ys(e,c);if(e.state.env.has(c)&&!d&&!f){r+=`bash: unset: ${c}: not an array variable
570
+ `,n=1;continue}let m=await _i(e,u);if(m===null&&d){r+=`bash: unset: ${u}: not a valid identifier
571
+ `,n=1;continue}if(m===null)continue;if(m<0){let h=Ie(e,c),v=h.length,E=e.state.currentLine;if(v===0){r+=`bash: line ${E}: unset: [${m}]: bad array subscript
572
+ `,n=1;continue}let S=v+m;if(S<0){r+=`bash: line ${E}: unset: [${m}]: bad array subscript
573
+ `,n=1;continue}let b=h[S][0];e.state.env.delete(`${c}_${b}`);continue}e.state.env.delete(`${c}_${m}`);continue}if(!xi(i)){r+=`bash: unset: \`${i}': not a valid identifier
574
+ `,n=1;continue}let o=i;if(Ee(e,i)){let c=ze(e,i);c&&c!==i&&(o=c)}if(ot(e,o)){r+=`bash: unset: ${o}: cannot unset: readonly variable
575
+ `,n=1;continue}let l=bt(e,o);if(l!==void 0&&l!==e.state.callDepth)Ni(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=$s(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 Yr(e,o)||e.state.env.delete(o);e.state.exportedVars?.delete(o),e.state.functions.delete(i)}return F(R,W(r),n)}var Ra=`wait: usage: wait [id ...]
576
+ `;async function en(e,t){let s=t.indexOf("--"),r=s===-1?t:t.slice(s+1),i=(s===-1?t:t.slice(0,s)).find(l=>l.startsWith("-"));if(i)return{stdout:P(),stderr:V(`bash: wait: ${i}: invalid option
577
+ ${Ra}`),exitCode:2};if(t=r,Ke(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:P(),stderr:P(),exitCode:u}}finally{l&&e.signal?.removeEventListener("abort",l)}}let a=0,o="";for(let l of t){Ke(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
578
+ `:`bash: wait: pid ${l} is not a child of this shell
579
+ `,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:P(),stderr:V(o),exitCode:a}}var tn=["extglob","dotglob","nullglob","failglob","globstar","globskipdots","nocaseglob","nocasematch","expand_aliases","lastpipe","xpg_echo"],Ma=["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 Is(e){return tn.includes(e)}function La(e){return Ma.includes(e)}function Di(e,t){let s=!1,r=!1,n=!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":r=!0;break;case"p":n=!0;break;case"q":i=!0;break;case"o":a=!0;break;default:return{exitCode:2,stdout:P(),stderr:V(`shopt: -${m}: invalid option
580
+ `)}}}l++}else break}for(;l<t.length;)o.push(t[l]),l++;if(a)return Fa(e,o,s,r,n,i);if(s&&r)return{exitCode:1,stdout:P(),stderr:V(`shopt: cannot set and unset shell options simultaneously
581
+ `)};if(o.length===0){if(s||r){let p=[];for(let m of tn){let h=e.state.shoptOptions[m];s&&h?p.push(n?`shopt -s ${m}`:`${m} on`):r&&!h&&p.push(n?`shopt -u ${m}`:`${m} off`)}return{exitCode:0,stdout:p.length>0?V(`${p.join(`
579
582
  `)}
580
- `):S(),stderr:S()}}let d=[];for(let p of en){let m=e.state.shoptOptions[p];d.push(n?`shopt ${m?"-s":"-u"} ${p}`:`${p} ${m?"on":"off"}`)}return{exitCode:0,stdout:V(`${d.join(`
583
+ `):P(),stderr:P()}}let d=[];for(let p of tn){let m=e.state.shoptOptions[p];d.push(n?`shopt ${m?"-s":"-u"} ${p}`:`${p} ${m?"on":"off"}`)}return{exitCode:0,stdout:V(`${d.join(`
581
584
  `)}
582
- `),stderr:S()}}let u=!1,c="",f=[];for(let d of o){if(!Ds(d)&&!Oa(d)){c+=`shopt: ${d}: invalid shell option name
583
- `,u=!0;continue}if(s)Ds(d)&&(e.state.shoptOptions[d]=!0,tr(e));else if(r)Ds(d)&&(e.state.shoptOptions[d]=!1,tr(e));else if(Ds(d)){let p=e.state.shoptOptions[d];i?p||(u=!0):n?(f.push(`shopt ${p?"-s":"-u"} ${d}`),p||(u=!0)):(f.push(`${d} ${p?"on":"off"}`),p||(u=!0))}else i?u=!0:n?(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(`
585
+ `),stderr:P()}}let c=!1,u="",f=[];for(let d of o){if(!Is(d)&&!La(d)){u+=`shopt: ${d}: invalid shell option name
586
+ `,c=!0;continue}if(s)Is(d)&&(e.state.shoptOptions[d]=!0,sr(e));else if(r)Is(d)&&(e.state.shoptOptions[d]=!1,sr(e));else if(Is(d)){let p=e.state.shoptOptions[d];i?p||(c=!0):n?(f.push(`shopt ${p?"-s":"-u"} ${d}`),p||(c=!0)):(f.push(`${d} ${p?"on":"off"}`),p||(c=!0))}else i?c=!0:n?(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(`
584
587
  `)}
585
- `):S(),stderr:V(c)}}function Da(e,t,s,r,n,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||r&&b||d.push(n?`set ${b?"-o":"+o"} ${p}`:`${p} ${b?"on":"off"}`)}return{exitCode:0,stdout:d.length>0?V(`${d.join(`
588
+ `):P(),stderr:V(u)}}function Fa(e,t,s,r,n,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||r&&v||d.push(n?`set ${v?"-o":"+o"} ${p}`:`${p} ${v?"on":"off"}`)}return{exitCode:0,stdout:d.length>0?V(`${d.join(`
586
589
  `)}
587
- `):S(),stderr:S()}}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
588
- `,u=!0;continue}if(m){s||r||(i?u=!0:n?(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,gt(e);else if(r)e.state.options[h]=!1,gt(e);else{let b=e.state.options[h];i?b||(u=!0):n?(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(`
590
+ `):P(),stderr:P()}}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
591
+ `,c=!0;continue}if(m){s||r||(i?c=!0:n?(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,gt(e);else if(r)e.state.options[h]=!1,gt(e);else{let v=e.state.options[h];i?v||(c=!0):n?(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(`
589
592
  `)}
590
- `):S(),stderr:V(c)}}async function Ii(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 n=(s??T(e.state.env,"PATH","/usr/bin:/bin")).split(":");for(let a of n){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 Is(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 n=T(e.state.env,"PATH","/usr/bin:/bin").split(":");for(let i of n){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 Fi(e,t,s,r){let n=!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"?n=!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 r(h);if(N.length>0){for(let I of N)c+=`${I}
591
- `;p=!0,b=!0}}else{let N=await s(h);N&&(c+=`${N}
592
- `,p=!0,b=!0)}b||(m=!0);continue}let E=!l&&e.state.functions.has(h);if(o&&E){if(!i)if(n)c+=`function
593
- `;else{let N=e.state.functions.get(h),I=N?Ri(h,N):`${h} is a function
594
- `;c+=I}b=!0}let $=e.state.env.get(`BASH_ALIAS_${h}`);if($!==void 0&&(o||!b)&&(i||(n?c+=`alias
595
- `:c+=`${h} is aliased to \`${B($)}'
596
- `),b=!0,!o)||cr.has(h)&&(o||!b)&&(i||(n?c+=`keyword
597
- `:c+=`${h} is a shell keyword
598
- `),b=!0,!o))continue;if(!o&&E&&!b){if(!i)if(n)c+=`function
599
- `;else{let N=e.state.functions.get(h),I=N?Ri(h,N):`${h} is a function
600
- `;c+=I}b=!0;continue}if(!(Je.has(h)&&(o||!b)&&(i||(n?c+=`builtin
601
- `:c+=`${h} is a shell builtin
602
- `),b=!0,!o))){if(o){let N=await r(h);for(let I of N)i?c+=`${I}
603
- `:n?c+=`file
604
- `:c+=`${h} is ${I}
605
- `,p=!0,b=!0}else if(!b){let N=await s(h);N&&(i?c+=`${N}
606
- `:n?c+=`file
607
- `:c+=`${h} is ${N}
608
- `,p=!0,b=!0)}if(!b&&(m=!0,!n&&!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
609
- `)}}}return i?d=m&&!p?1:0:d=m?1:0,F(W(c),W(f),d)}function Ri(e,t){let s;return t.body.type==="Group"?s=t.body.body.map(n=>Gt(n)).join("; "):s=Gt(t.body),`${e} is a function
593
+ `):P(),stderr:V(u)}}async function Ii(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 n=(s??N(e.state.env,"PATH","/usr/bin:/bin")).split(":");for(let a of n){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 Rs(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 n=N(e.state.env,"PATH","/usr/bin:/bin").split(":");for(let i of n){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 Fi(e,t,s,r){let n=!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"?n=!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 _=await r(h);if(_.length>0){for(let L of _)u+=`${L}
594
+ `;p=!0,v=!0}}else{let _=await s(h);_&&(u+=`${_}
595
+ `,p=!0,v=!0)}v||(m=!0);continue}let E=!l&&e.state.functions.has(h);if(o&&E){if(!i)if(n)u+=`function
596
+ `;else{let _=e.state.functions.get(h),L=_?Ri(h,_):`${h} is a function
597
+ `;u+=L}v=!0}let S=e.state.env.get(`BASH_ALIAS_${h}`);if(S!==void 0&&(o||!v)&&(i||(n?u+=`alias
598
+ `:u+=`${h} is aliased to \`${B(S)}'
599
+ `),v=!0,!o)||ur.has(h)&&(o||!v)&&(i||(n?u+=`keyword
600
+ `:u+=`${h} is a shell keyword
601
+ `),v=!0,!o))continue;if(!o&&E&&!v){if(!i)if(n)u+=`function
602
+ `;else{let _=e.state.functions.get(h),L=_?Ri(h,_):`${h} is a function
603
+ `;u+=L}v=!0;continue}if(!(Je.has(h)&&(o||!v)&&(i||(n?u+=`builtin
604
+ `:u+=`${h} is a shell builtin
605
+ `),v=!0,!o))){if(o){let _=await r(h);for(let L of _)i?u+=`${L}
606
+ `:n?u+=`file
607
+ `:u+=`${h} is ${L}
608
+ `,p=!0,v=!0}else if(!v){let _=await s(h);_&&(i?u+=`${_}
609
+ `:n?u+=`file
610
+ `:u+=`${h} is ${_}
611
+ `,p=!0,v=!0)}if(!v&&(m=!0,!n&&!i)){let _=!0;if(h.includes("/")){let L=e.fs.resolvePath(e.state.cwd,h);await e.fs.exists(L)&&(_=!1)}_&&(f+=`bash: type: ${h}: not found
612
+ `)}}}return i?d=m&&!p?1:0:d=m?1:0,F(W(u),W(f),d)}function Ri(e,t){let s;return t.body.type==="Group"?s=t.body.body.map(n=>Gt(n)).join("; "):s=Gt(t.body),`${e} is a function
610
613
  ${e} ()
611
614
  {
612
615
  ${s}
613
616
  }
614
- `}function Gt(e){if(Array.isArray(e))return e.map(t=>Gt(t)).join("; ");if(e.type==="Statement"){let t=[];for(let s=0;s<e.pipelines.length;s++){let r=e.pipelines[s];t.push(Ia(r)),e.operators[s]&&t.push(e.operators[s])}return t.join(" ")}if(e.type==="SimpleCommand"){let t=e,s=[];t.name&&s.push(Mi(t.name));for(let r of t.args)s.push(Mi(r));return s.join(" ")}return e.type==="Group"?`{ ${e.body.map(r=>Gt(r)).join("; ")}; }`:"..."}function Ia(e){let t=e.commands.map(s=>Gt(s));return(e.negated?"! ":"")+t.join(" | ")}function Mi(e){let t="";for(let s of e.parts)s.type==="Literal"?t+=s.value:s.type==="DoubleQuoted"?t+=`"${s.parts.map(r=>Li(r)).join("")}"`:s.type==="SingleQuoted"?t+=`'${s.value}'`:t+=Li(s);return t}function Li(e){let t=e;return t.type==="Literal"?t.value??"":t.type==="Variable"?`$${t.name}`:""}async function Wi(e,t,s,r){let n="",i="",a=0;for(let o of t){if(!o){a=1;continue}let l=e.state.env.get(`BASH_ALIAS_${o}`);if(l!==void 0)r?n+=`${o} is an alias for "${B(l)}"
617
+ `}function Gt(e){if(Array.isArray(e))return e.map(t=>Gt(t)).join("; ");if(e.type==="Statement"){let t=[];for(let s=0;s<e.pipelines.length;s++){let r=e.pipelines[s];t.push(Wa(r)),e.operators[s]&&t.push(e.operators[s])}return t.join(" ")}if(e.type==="SimpleCommand"){let t=e,s=[];t.name&&s.push(Mi(t.name));for(let r of t.args)s.push(Mi(r));return s.join(" ")}return e.type==="Group"?`{ ${e.body.map(r=>Gt(r)).join("; ")}; }`:"..."}function Wa(e){let t=e.commands.map(s=>Gt(s));return(e.negated?"! ":"")+t.join(" | ")}function Mi(e){let t="";for(let s of e.parts)s.type==="Literal"?t+=s.value:s.type==="DoubleQuoted"?t+=`"${s.parts.map(r=>Li(r)).join("")}"`:s.type==="SingleQuoted"?t+=`'${s.value}'`:t+=Li(s);return t}function Li(e){let t=e;return t.type==="Literal"?t.value??"":t.type==="Variable"?`$${t.name}`:""}async function Wi(e,t,s,r){let n="",i="",a=0;for(let o of t){if(!o){a=1;continue}let l=e.state.env.get(`BASH_ALIAS_${o}`);if(l!==void 0)r?n+=`${o} is an alias for "${B(l)}"
615
618
  `:n+=`alias ${o}='${B(l)}'
616
- `;else if(cr.has(o))r?n+=`${o} is a shell keyword
619
+ `;else if(ur.has(o))r?n+=`${o} is a shell keyword
617
620
  `:n+=`${o}
618
621
  `;else if(Je.has(o))r?n+=`${o} is a shell builtin
619
622
  `:n+=`${o}
620
623
  `;else if(e.state.functions.has(o))r?n+=`${o} is a function
621
624
  `:n+=`${o}
622
- `;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&&(r?n+=`${o} is ${o}
625
+ `;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&&(r?n+=`${o} is ${o}
623
626
  `:n+=`${o}
624
- `,c=!0)}catch{}c||(r&&(i+=`${o}: not found
625
- `),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}`),r?n+=`${o} is ${f}
627
+ `,u=!0)}catch{}u||(r&&(i+=`${o}: not found
628
+ `),a=1)}else if(e.commands.has(o)){let u=N(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}`),r?n+=`${o} is ${f}
626
629
  `:n+=`${f}
627
630
  `}else r&&(i+=`${o}: not found
628
- `),a=1}return F(W(n),W(i),a)}async function Vi(e,t){if(t.includes("/")){let n=e.fs.resolvePath(e.state.cwd,t);if(await e.fs.exists(n)){try{let i=await e.fs.stat(n);if(i.isDirectory||!((i.mode&73)!==0))return null}catch{return null}return t}return null}let r=T(e.state.env,"PATH","/usr/bin:/bin").split(":");for(let n of r){if(!n)continue;let a=`${n.startsWith("/")?n:e.fs.resolvePath(e.state.cwd,n)}/${t}`;if(await e.fs.exists(a)){try{if((await e.fs.stat(a)).isDirectory)continue}catch{continue}return`${n}/${t}`}}if(e.commands.has(t)){for(let n of r)if(n==="/usr/bin"||n==="/bin")return`${n}/${t}`;return`/usr/bin/${t}`}return null}async function zi(e,t,s,r,n,i,a,o){let{ctx:l,runCommand:u}=e,c=ft(s);if(l.coverage&&Je.has(t)&&l.coverage.hit(`bash:builtin:${t}`),t==="export")return Rr(l,c);if(t==="unset")return Yr(l,c);if(t==="exit")return Ir(l,c);if(t==="local")return Br(l,c);if(t==="set")return Zr(l,c);if(t==="break")return rr(l,c);if(t==="continue")return br(l,c);if(t==="return")return Hr(l,c);if(t==="eval"&&l.state.options.posix)return xs(l,c,n);if(t==="shift")return Xr(l,c);if(t==="getopts")return _s(l,c);if(t==="compgen")return yr(l,c);if(t==="complete")return wr(l,c);if(t==="compopt")return vr(l,c);if(t==="pushd")return await Nr(l,c);if(t==="popd")return Or(l,c);if(t==="dirs")return Dr(l,c);if(t==="source"||t===".")return Jr(l,c);if(t==="read")return await Gr(l,c,await re(n),o);if(t==="mapfile"||t==="readarray")return await Ur(l,c,await re(n));if(t==="declare"||t==="typeset")return xr(l,c);if(t==="readonly")return _r(l,c);if(!i){let f=l.state.functions.get(t);if(f)return As(l,f,c,n)}if(t==="eval")return xs(l,c,n);if(t==="cd")return await nr(l,c);if(t===":"||t==="true")return U();if(t==="false")return le(!1);if(t==="let")return jr(l,c);if(t==="command")return Ra(e,c,n);if(t==="builtin")return Ma(e,c,n);if(t==="shopt")return Di(l,c);if(t==="exec"){if(s.length===0)return U();let[f,...d]=s;return u(B(f),d,[],n,!1,!1,-1)}if(t==="wait")return await Qr(l,c);if(t==="jobs")return await Fr(l,c,(f,d)=>u(f,d.map(W),d.map(()=>!1),S()));if(t==="kill")return zr(l,c);if(t==="type")return await Fi(l,c,f=>Vi(l,f),f=>Is(l,f));if(t==="hash")return Mr(l,c);if(t==="help")return Lr(l,c);if(t==="["||t==="test"){let f=c;if(t==="["){if(c[c.length-1]!=="]")return P("[: missing `]'\n",2);f=c.slice(0,-1)}return zt(l,f)}return null}async function Ra(e,t,s){let{ctx:r,runCommand:n}=e;if(t.length===0)return U();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 U();if(o||a)return await Wi(r,l,o,a);let[u,...c]=l;return n(u,c.map(f=>W(f)),[],s,!0,i,-1)}async function Ma(e,t,s){let{runCommand:r}=e;if(t.length===0)return U();let n=t;if(n[0]==="--"&&(n=n.slice(1),n.length===0))return U();let i=n[0];if(!Je.has(i))return P(`bash: builtin: ${i}: not a shell builtin
629
- `);let[,...a]=n;return r(i,a.map(o=>W(o)),[],s,!0,!1,-1)}async function ji(e,t,s,r,n){let{buildExportedEnv:i,ctx:a,executeUserScript:o}=e,u=await Ii(a,t,n?"/usr/bin:/bin":void 0);if(!u)return Hn(t)?P(`bash: ${t}: command not available in browser environments. Exclude '${t}' from your commands or use the Node.js bundle.
630
- `,127):P(`bash: ${t}: command not found
631
- `,127);if("error"in u)return u.error==="permission_denied"?P(`bash: ${t}: Permission denied
632
- `,126):P(`bash: ${t}: No such file or directory
633
- `,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,r);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=r.getReader(),m=await p.read();p.releaseLock(),m.done||!m.value||m.value.length===0?a.state.groupStdin?d=a.state.groupStdin:d=S():d=rt(fe(m.value),r);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(E){if(E instanceof ae)throw E;return P(`${t}: ${He(E)}
634
- `)}}async function Rs(e,t){let s=e.state.inCondition;e.state.inCondition=!0;let r=0;try{for(let n of t){let i=await e.executeStatement(n);await Y(e,i),r=i.exitCode}}catch(n){throw await te(e,n),n}finally{e.state.inCondition=s}return{stdout:S(),stderr:S(),exitCode:r}}function Ht(e,t){return e instanceof Ce?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 ve||e instanceof ke||e instanceof q||e instanceof ae?{action:"rethrow",error:e}:{action:"error",exitCode:1,error:e}}async function Ms(e,t){let s=0;try{for(let r of t){let n=await e.executeStatement(r);await Y(e,n),s=n.exitCode}}catch(r){let n=await te(e,r);if(es(r)||r instanceof ke||r instanceof q||r instanceof ae||r instanceof Ge)throw r;if(!n){let i=He(r);await Y(e,P(i.endsWith(`
631
+ `),a=1}return F(W(n),W(i),a)}async function Vi(e,t){if(t.includes("/")){let n=e.fs.resolvePath(e.state.cwd,t);if(await e.fs.exists(n)){try{let i=await e.fs.stat(n);if(i.isDirectory||!((i.mode&73)!==0))return null}catch{return null}return t}return null}let r=N(e.state.env,"PATH","/usr/bin:/bin").split(":");for(let n of r){if(!n)continue;let a=`${n.startsWith("/")?n:e.fs.resolvePath(e.state.cwd,n)}/${t}`;if(await e.fs.exists(a)){try{if((await e.fs.stat(a)).isDirectory)continue}catch{continue}return`${n}/${t}`}}if(e.commands.has(t)){for(let n of r)if(n==="/usr/bin"||n==="/bin")return`${n}/${t}`;return`/usr/bin/${t}`}return null}async function zi(e,t,s,r,n,i,a,o){let{ctx:l,runCommand:c}=e,u=ft(s);if(l.coverage&&Je.has(t)&&l.coverage.hit(`bash:builtin:${t}`),t==="export")return Mr(l,u);if(t==="unset")return Qr(l,u);if(t==="exit")return Rr(l,u);if(t==="local")return Ur(l,u);if(t==="set")return Xr(l,u);if(t==="break")return nr(l,u);if(t==="continue")return Er(l,u);if(t==="return")return qr(l,u);if(t==="eval"&&l.state.options.posix)return _s(l,u,n);if(t==="shift")return Jr(l,u);if(t==="getopts")return Ns(l,u);if(t==="compgen")return gr(l,u);if(t==="complete")return vr(l,u);if(t==="compopt")return br(l,u);if(t==="pushd")return await Or(l,u);if(t==="popd")return Dr(l,u);if(t==="dirs")return Ir(l,u);if(t==="source"||t===".")return Kr(l,u);if(t==="read")return await Gr(l,u,await re(n),o);if(t==="mapfile"||t==="readarray")return await Hr(l,u,await re(n));if(t==="declare"||t==="typeset")return xr(l,u);if(t==="readonly")return _r(l,u);if(!i){let f=l.state.functions.get(t);if(f)return Ts(l,f,u,n)}if(t==="eval")return _s(l,u,n);if(t==="cd")return await ir(l,u);if(t===":"||t==="true")return U();if(t==="false")return le(!1);if(t==="let")return Br(l,u);if(t==="command")return Va(e,u,n);if(t==="builtin")return za(e,u,n);if(t==="shopt")return Di(l,u);if(t==="exec"){if(s.length===0)return U();let[f,...d]=s;return c(B(f),d,[],n,!1,!1,-1)}if(t==="wait")return await en(l,u);if(t==="jobs")return await Wr(l,u,(f,d)=>c(f,d.map(W),d.map(()=>!1),P()));if(t==="kill")return jr(l,u);if(t==="type")return await Fi(l,u,f=>Vi(l,f),f=>Rs(l,f));if(t==="hash")return Lr(l,u);if(t==="help")return Fr(l,u);if(t==="["||t==="test"){let f=u;if(t==="["){if(u[u.length-1]!=="]")return A("[: missing `]'\n",2);f=u.slice(0,-1)}return zt(l,f)}return null}async function Va(e,t,s){let{ctx:r,runCommand:n}=e;if(t.length===0)return U();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 U();if(o||a)return await Wi(r,l,o,a);let[c,...u]=l;return n(c,u.map(f=>W(f)),[],s,!0,i,-1)}async function za(e,t,s){let{runCommand:r}=e;if(t.length===0)return U();let n=t;if(n[0]==="--"&&(n=n.slice(1),n.length===0))return U();let i=n[0];if(!Je.has(i))return A(`bash: builtin: ${i}: not a shell builtin
632
+ `);let[,...a]=n;return r(i,a.map(o=>W(o)),[],s,!0,!1,-1)}async function ji(e,t,s,r,n){let{buildExportedEnv:i,ctx:a,executeUserScript:o}=e,c=await Ii(a,t,n?"/usr/bin:/bin":void 0);if(!c)return Gn(t)?A(`bash: ${t}: command not available in browser environments. Exclude '${t}' from your commands or use the Node.js bundle.
633
+ `,127):A(`bash: ${t}: command not found
634
+ `,127);if("error"in c)return c.error==="permission_denied"?A(`bash: ${t}: Permission denied
635
+ `,126):A(`bash: ${t}: No such file or directory
636
+ `,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,r);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=r.getReader(),m=await p.read();p.releaseLock(),m.done||!m.value||m.value.length===0?a.state.groupStdin?d=a.state.groupStdin:d=P():d=rt(fe(m.value),r);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(E){if(E instanceof ae)throw E;return A(`${t}: ${Ge(E)}
637
+ `)}}async function Ms(e,t){let s=e.state.inCondition;e.state.inCondition=!0;let r=0;try{for(let n of t){let i=await e.executeStatement(n);await Q(e,i),r=i.exitCode}}catch(n){throw await te(e,n),n}finally{e.state.inCondition=s}return{stdout:P(),stderr:P(),exitCode:r}}function qt(e,t){return e instanceof Ae?e.levels>1&&t>1?(e.levels--,{action:"rethrow",error:e}):{action:"break"}:e instanceof Ce?e.levels>1&&t>1?(e.levels--,{action:"rethrow",error:e}):{action:"continue"}:e instanceof ve||e instanceof ke||e instanceof q||e instanceof ae?{action:"rethrow",error:e}:{action:"error",exitCode:1,error:e}}async function Ls(e,t){let s=0;try{for(let r of t){let n=await e.executeStatement(r);await Q(e,n),s=n.exitCode}}catch(r){let n=await te(e,r);if(ss(r)||r instanceof ke||r instanceof q||r instanceof ae||r instanceof He)throw r;if(!n){let i=Ge(r);await Q(e,A(i.endsWith(`
635
638
  `)?i:`${i}
636
- `))}return{stdout:S(),stderr:S(),exitCode:1}}return{stdout:S(),stderr:S(),exitCode:s}}var La="+ ";async function Bi(e){let t=e.state.env.get("PS4"),s=e.substitutionDepth??0;if(t===void 0)return`${"+".repeat(s+1)} `;let r=B(t);if(r==="")return"";try{let i=new X().parseWordFromString(r,!1,!1),a=await z(e,i);return s>0&&a.length>0?`${a[0].repeat(s)}${a}`:a}catch{await G(e,2,`bash: ${r}: bad substitution
637
- `);let n=r||La;return s>0&&n.length>0?`${n[0].repeat(s)}${n}`:n}}function Fa(e){return e.map(t=>Wa(t)).join(" ")}function Wa(e){if(e==="")return"''";if(!/[\s'"\\$`!*?[\]{}|&;<>()~#\n\t]/.test(e))return e;let s=/[\x00-\x1f\x7f]/.test(e),r=e.includes(`
638
- `),n=e.includes(" "),i=e.includes("\\"),a=e.includes("'");if(s||r||n||i){let l="";for(let u of e){let c=u.charCodeAt(0);u===`
639
- `?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 Ls(e,t,s){if(!e.state.options.xtrace)return"";let r=await Bi(e),n=[t,...s],i=Fa(n);return`${r}${i}
639
+ `))}return{stdout:P(),stderr:P(),exitCode:1}}return{stdout:P(),stderr:P(),exitCode:s}}var ja="+ ";async function Bi(e){let t=e.state.env.get("PS4"),s=e.substitutionDepth??0;if(t===void 0)return`${"+".repeat(s+1)} `;let r=B(t);if(r==="")return"";try{let i=new X().parseWordFromString(r,!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: ${r}: bad substitution
640
+ `);let n=r||ja;return s>0&&n.length>0?`${n[0].repeat(s)}${n}`:n}}function Ba(e){return e.map(t=>Ua(t)).join(" ")}function Ua(e){if(e==="")return"''";if(!/[\s'"\\$`!*?[\]{}|&;<>()~#\n\t]/.test(e))return e;let s=/[\x00-\x1f\x7f]/.test(e),r=e.includes(`
641
+ `),n=e.includes(" "),i=e.includes("\\"),a=e.includes("'");if(s||r||n||i){let l="";for(let c of e){let u=c.charCodeAt(0);c===`
642
+ `?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 Fs(e,t,s){if(!e.state.options.xtrace)return"";let r=await Bi(e),n=[t,...s],i=Ba(n);return`${r}${i}
640
643
  `}async function Ui(e,t,s){return e.state.options.xtrace?`${await Bi(e)}${t}=${s}
641
- `:""}function qt(e){let t=He(e);return t.endsWith(`
644
+ `:""}function Zt(e){let t=Ge(e);return t.endsWith(`
642
645
  `)?t:`${t}
643
- `}async function Pt(e,t,s){let r=await De(e,e.outputChannels,t);return r.error?K(e,r.channels,()=>Y(e,r.error)):K(e,r.channels,async()=>{try{let n=await s(r.legacyRedirections);return{stdout:S(),stderr:S(),exitCode:n}}catch(n){let i=await te(e,n);if(n instanceof Error&&"code"in n&&n.code==="ENOSPC")return i?{stdout:S(),stderr:S(),exitCode:1}:await Y(e,P(qt(n)));throw n}})}async function Gi(e,t){return Pt(e,t.redirections,async()=>{for(let s of t.clauses)if((await Rs(e,s.condition)).exitCode===0)return(await Ms(e,s.body)).exitCode;return t.elseBody?(await Ms(e,t.elseBody)).exitCode:0})}async function Hi(e,t){return Pt(e,t.redirections,async()=>{let s=0,r=0;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t.variable))return await Y(e,P(`bash: \`${t.variable}': not a valid identifier
644
- `)),1;let n=[];if(t.words===null)n=T(e.state.env,"@","").split(" ").filter(Boolean);else if(t.words.length>0)try{for(let i of t.words){let a=await je(e,i);n.push(...a.values)}}catch(i){if(i instanceof Qt)return await te(e,i),1;throw i}e.state.loopDepth++;try{for(let i of n){if(r++,e.signal?.aborted)throw new pe(e.signal.reason);r>e.limits.maxLoopIterations&&Me(`for loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations"),g(e.state.env,t.variable,i),e.state.options.xtrace&&await G(e,2,await Ls(e,"for",[t.variable,"in",...n]));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 te(e,a),l=Ht(a,e.state.loopDepth);if(l.action==="break")break;if(l.action==="continue")continue;if(l.action==="error")return o||await Y(e,P(qt(l.error))),l.exitCode??1;throw l.error}}}finally{e.state.loopDepth--}return s})}async function qi(e,t){return Pt(e,t.redirections,async()=>{let s=t.line;s!==void 0&&(e.state.currentLine=s);let r=0,n=0;t.init&&await ee(e,t.init.expression),e.state.loopDepth++;try{for(;;){if(n++,e.signal?.aborted)throw new pe(e.signal.reason);if(n>e.limits.maxLoopIterations&&Me(`for loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations"),t.condition&&(s!==void 0&&(e.state.currentLine=s),await ee(e,t.condition.expression)===0))break;try{for(let i of t.body){let a=await e.executeStatement(i);await Y(e,a),r=a.exitCode}}catch(i){let a=await te(e,i),o=Ht(i,e.state.loopDepth);if(o.action==="break")break;if(o.action==="continue"){t.update&&await ee(e,t.update.expression);continue}if(o.action==="error")return a||await Y(e,P(qt(o.error))),o.exitCode??1;throw o.error}t.update&&await ee(e,t.update.expression)}}finally{e.state.loopDepth--}return r})}async function Zi(e,t,s=S()){return Pt(e,t.redirections,async r=>{let n=0,i=0,a=s,o=!1;for(let u of r)if((u.operator==="<<"||u.operator==="<<-")&&u.target.type==="HereDoc"){let c=u.target,f=await z(e,c.content);c.stripTabs&&(f=f.split(`
646
+ `}async function Pt(e,t,s){let r=await De(e,e.outputChannels,t);return r.error?Y(e,r.channels,()=>Q(e,r.error)):Y(e,r.channels,async()=>{try{let n=await s(r.legacyRedirections);return{stdout:P(),stderr:P(),exitCode:n}}catch(n){let i=await te(e,n);if(n instanceof Error&&"code"in n&&n.code==="ENOSPC")return i?{stdout:P(),stderr:P(),exitCode:1}:await Q(e,A(Zt(n)));throw n}})}async function Hi(e,t){return Pt(e,t.redirections,async()=>{for(let s of t.clauses)if((await Ms(e,s.condition)).exitCode===0)return(await Ls(e,s.body)).exitCode;return t.elseBody?(await Ls(e,t.elseBody)).exitCode:0})}async function Gi(e,t){return Pt(e,t.redirections,async()=>{let s=0,r=0;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t.variable))return await Q(e,A(`bash: \`${t.variable}': not a valid identifier
647
+ `)),1;let n=[];if(t.words===null)n=N(e.state.env,"@","").split(" ").filter(Boolean);else if(t.words.length>0)try{for(let i of t.words){let a=await je(e,i);n.push(...a.values)}}catch(i){if(i instanceof es)return await te(e,i),1;throw i}e.state.loopDepth++;try{for(let i of n){if(r++,e.signal?.aborted)throw new pe(e.signal.reason);r>e.limits.maxLoopIterations&&Me(`for loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations"),g(e.state.env,t.variable,i),e.state.options.xtrace&&await H(e,2,await Fs(e,"for",[t.variable,"in",...n]));try{for(let a of t.body){let o=await e.executeStatement(a);await Q(e,o),s=o.exitCode}}catch(a){let o=await te(e,a),l=qt(a,e.state.loopDepth);if(l.action==="break")break;if(l.action==="continue")continue;if(l.action==="error")return o||await Q(e,A(Zt(l.error))),l.exitCode??1;throw l.error}}}finally{e.state.loopDepth--}return s})}async function qi(e,t){return Pt(e,t.redirections,async()=>{let s=t.line;s!==void 0&&(e.state.currentLine=s);let r=0,n=0;t.init&&await ee(e,t.init.expression),e.state.loopDepth++;try{for(;;){if(n++,e.signal?.aborted)throw new pe(e.signal.reason);if(n>e.limits.maxLoopIterations&&Me(`for loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations"),t.condition&&(s!==void 0&&(e.state.currentLine=s),await ee(e,t.condition.expression)===0))break;try{for(let i of t.body){let a=await e.executeStatement(i);await Q(e,a),r=a.exitCode}}catch(i){let a=await te(e,i),o=qt(i,e.state.loopDepth);if(o.action==="break")break;if(o.action==="continue"){t.update&&await ee(e,t.update.expression);continue}if(o.action==="error")return a||await Q(e,A(Zt(o.error))),o.exitCode??1;throw o.error}t.update&&await ee(e,t.update.expression)}}finally{e.state.loopDepth--}return r})}async function Zi(e,t,s=P()){return Pt(e,t.redirections,async r=>{let n=0,i=0,a=s,o=!1;for(let c of r)if((c.operator==="<<"||c.operator==="<<-")&&c.target.type==="HereDoc"){let u=c.target,f=await z(e,u.content);u.stripTabs&&(f=f.split(`
645
648
  `).map(d=>d.replace(/^\t+/,"")).join(`
646
- `)),a=V(f),o=!0}else if(u.operator==="<<<"&&u.target.type==="Word")a=V(`${await z(e,u.target)}
647
- `),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 Y(e,P(`bash: ${c}: No such file or directory
648
- `)),1}}let l=e.state.groupStdin;if(o)e.state.groupStdin=a;else{let u=await re(s);u.length>0&&(e.state.groupStdin=fe(u))}e.state.loopDepth++;try{for(;;){if(i++,e.signal?.aborted)throw new pe(e.signal.reason);i>e.limits.maxLoopIterations&&Me(`while loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations");let u=0,c=!1,f=!1;try{u=(await Rs(e,t.condition)).exitCode}catch(d){if(await te(e,d),d instanceof Ce){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 Y(e,p),n=p.exitCode}}catch(d){let p=await te(e,d),m=Ht(d,e.state.loopDepth);if(m.action==="break")break;if(m.action==="continue")continue;if(m.action==="error")return p||await Y(e,P(qt(m.error))),m.exitCode??1;throw m.error}}}}finally{e.state.loopDepth--,e.state.groupStdin=l}return n})}async function Xi(e,t){return Pt(e,t.redirections,async()=>{let s=0,r=0;e.state.loopDepth++;try{for(;;){if(r++,e.signal?.aborted)throw new pe(e.signal.reason);if(r>e.limits.maxLoopIterations&&Me(`until loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations"),(await Rs(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 te(e,i),o=Ht(i,e.state.loopDepth);if(o.action==="break")break;if(o.action==="continue")continue;if(o.action==="error")return a||await Y(e,P(qt(o.error))),o.exitCode??1;throw o.error}}}finally{e.state.loopDepth--}return s})}async function Ji(e,t){return Pt(e,t.redirections,async()=>{let s=0,r=await z(e,t.word),n=!1;for(let i=0;i<t.items.length;i++){let a=t.items[i],o=n;if(!n)for(let l of a.patterns){let u=await z(e,l);Pn(l)&&(u=Sn(u));let c=e.state.shoptOptions.nocasematch,f=e.state.shoptOptions.extglob;if(vt(r,u,c,f)){o=!0;break}}if(o){if(s=(await Ms(e,a.body)).exitCode,a.terminator===";;")break;a.terminator===";&"?n=!0:n=!1}else n=!1}return s})}async function Va(e,t,s){let r=_e(),n=s?_e():void 0,i=it(e.outputChannels);Gs(i,1,r),n&&Gs(i,2,n);try{let a=await K(e,i,t);return{...a,stdout:rt(a.stdout,r.stream()),stderr:n?rt(a.stderr,n.stream()):a.stderr}}catch(a){await K(e,i,()=>te(e,a));let o=r.stream(),l=n?.stream()??S();if(a instanceof It)return{stdout:o,stderr:l,exitCode:1};if(a instanceof q)return{stdout:o,stderr:l,exitCode:a.exitCode};if(a instanceof ke)return{stdout:o,stderr:l,exitCode:a.exitCode};throw await Y(e,{stdout:o,stderr:l,exitCode:1},!1),a}}async function Ki(e,t,s){let r=t.timed?performance.now():0,n=S(),i=U(),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=W(""),h||(e.state.groupStdin=void 0));let E=l&&(!m||!e.state.shoptOptions.lastpipe),$=E?new Map(e.state.env):null,y;try{if(m){let v=()=>s(p,n);y=E?await K(e,it(e.outputChannels),v):await v()}else y=await Va(e,()=>s(p,n),b)}catch(v){if(await te(e,v),v instanceof It)y={stdout:S(),stderr:S(),exitCode:1};else if(v instanceof q&&t.commands.length>1)y={stdout:S(),stderr:S(),exitCode:v.exitCode};else if(v instanceof ke&&t.commands.length>1)y={stdout:S(),stderr:S(),exitCode:v.exitCode};else throw $&&(e.state.env=$),v}if($&&(e.state.env=$),e.signal?.aborted===!0&&y.exitCode===new pe(e.signal.reason).exitCode)throw await Y(e,y,!1),new pe(e.signal.reason);if(o.push(y.exitCode),y.exitCode!==0&&(a=y.exitCode),m)i=y;else if(b)n=rt(y.stderr,y.stdout),i={stdout:S(),stderr:S(),exitCode:y.exitCode};else{let v=y.stdout;await Y(e,y,!0,[2]),n=v,i={stdout:S(),stderr:S(),exitCode:y.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 Y(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++)g(e.state.env,`PIPESTATUS_${d}`,String(o[d]));g(e.state.env,"PIPESTATUS__length",String(o.length))}if(t.timed){let p=(performance.now()-r)/1e3,m=Math.floor(p/60),h=p%60,b;t.timePosix?b=`real ${p.toFixed(2)}
649
+ `)),a=V(f),o=!0}else if(c.operator==="<<<"&&c.target.type==="Word")a=V(`${await z(e,c.target)}
650
+ `),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 Q(e,A(await Bt(e,u))),1}}let l=e.state.groupStdin;if(o)e.state.groupStdin=a;else{let c=await re(s);c.length>0&&(e.state.groupStdin=fe(c))}e.state.loopDepth++;try{for(;;){if(i++,e.signal?.aborted)throw new pe(e.signal.reason);i>e.limits.maxLoopIterations&&Me(`while loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations");let c=0,u=!1,f=!1;try{c=(await Ms(e,t.condition)).exitCode}catch(d){if(await te(e,d),d instanceof Ae){if(d.levels>1&&e.state.loopDepth>1)throw d.levels--,d;u=!0}else if(d instanceof Ce){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 Q(e,p),n=p.exitCode}}catch(d){let p=await te(e,d),m=qt(d,e.state.loopDepth);if(m.action==="break")break;if(m.action==="continue")continue;if(m.action==="error")return p||await Q(e,A(Zt(m.error))),m.exitCode??1;throw m.error}}}}finally{e.state.loopDepth--,e.state.groupStdin=l}return n})}async function Xi(e,t){return Pt(e,t.redirections,async()=>{let s=0,r=0;e.state.loopDepth++;try{for(;;){if(r++,e.signal?.aborted)throw new pe(e.signal.reason);if(r>e.limits.maxLoopIterations&&Me(`until loop: too many iterations (${e.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations"),(await Ms(e,t.condition)).exitCode===0)break;try{for(let i of t.body){let a=await e.executeStatement(i);await Q(e,a),s=a.exitCode}}catch(i){let a=await te(e,i),o=qt(i,e.state.loopDepth);if(o.action==="break")break;if(o.action==="continue")continue;if(o.action==="error")return a||await Q(e,A(Zt(o.error))),o.exitCode??1;throw o.error}}}finally{e.state.loopDepth--}return s})}async function Ji(e,t){return Pt(e,t.redirections,async()=>{let s=0,r=await z(e,t.word),n=!1;for(let i=0;i<t.items.length;i++){let a=t.items[i],o=n;if(!n)for(let l of a.patterns){let c=await z(e,l);Pn(l)&&(c=Sn(c));let u=e.state.shoptOptions.nocasematch,f=e.state.shoptOptions.extglob;if(vt(r,c,u,f)){o=!0;break}}if(o){if(s=(await Ls(e,a.body)).exitCode,a.terminator===";;")break;a.terminator===";&"?n=!0:n=!1}else n=!1}return s})}async function Ha(e,t,s){let r=xe(),n=s?xe():void 0,i=it(e.outputChannels);Gs(i,1,r),n&&Gs(i,2,n);try{let a=await Y(e,i,t);return{...a,stdout:rt(a.stdout,r.stream()),stderr:n?rt(a.stderr,n.stream()):a.stderr}}catch(a){await Y(e,i,()=>te(e,a));let o=r.stream(),l=n?.stream()??P();if(a instanceof It)return{stdout:o,stderr:l,exitCode:1};if(a instanceof q)return{stdout:o,stderr:l,exitCode:a.exitCode};if(a instanceof ke)return{stdout:o,stderr:l,exitCode:a.exitCode};throw await Q(e,{stdout:o,stderr:l,exitCode:1},!1),a}}async function Ki(e,t,s){let r=t.timed?performance.now():0,n=P(),i=U(),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=W(""),h||(e.state.groupStdin=void 0));let E=l&&(!m||!e.state.shoptOptions.lastpipe),S=E?new Map(e.state.env):null,b;try{if(m){let y=()=>s(p,n);b=E?await Y(e,it(e.outputChannels),y):await y()}else b=await Ha(e,()=>s(p,n),v)}catch(y){if(await te(e,y),y instanceof It)b={stdout:P(),stderr:P(),exitCode:1};else if(y instanceof q&&t.commands.length>1)b={stdout:P(),stderr:P(),exitCode:y.exitCode};else if(y instanceof ke&&t.commands.length>1)b={stdout:P(),stderr:P(),exitCode:y.exitCode};else throw S&&(e.state.env=S),y}if(S&&(e.state.env=S),e.signal?.aborted===!0&&b.exitCode===new pe(e.signal.reason).exitCode)throw await Q(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)n=rt(b.stderr,b.stdout),i={stdout:P(),stderr:P(),exitCode:b.exitCode};else{let y=b.stdout;await Q(e,b,!0,[2]),n=y,i={stdout:P(),stderr:P(),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 Q(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++)g(e.state.env,`PIPESTATUS_${d}`,String(o[d]));g(e.state.env,"PIPESTATUS__length",String(o.length))}if(t.timed){let p=(performance.now()-r)/1e3,m=Math.floor(p/60),h=p%60,v;t.timePosix?v=`real ${p.toFixed(2)}
649
651
  user 0.00
650
652
  sys 0.00
651
- `:b=`
653
+ `:v=`
652
654
  real ${`${m}m${h.toFixed(3)}s`}
653
655
  user 0m0.000s
654
656
  sys 0m0.000s
655
- `,await G(e,2,b)}return l&&!e.state.shoptOptions.lastpipe&&(e.state.lastArg=u),i}async function Yi(e,t){let s=new Map,r="";for(let n of t.assignments){let i=n.name;if(n.array){let f=await za(e,t,i,n.array,n.append,s);if(f.error)return{continueToNext:!1,xtraceOutput:r,tempAssignments:s,error:f.error};if(r+=f.xtraceOutput,f.continueToNext)continue}let a=n.value?await pt(e,n.value):R,o=n.value?B(a):"";if(o.length>e.limits.maxStringLength&&Me(`word expansion: string length limit exceeded (${e.limits.maxStringLength} bytes)`,"iterations"),i.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[\]$/))return{continueToNext:!1,xtraceOutput:r,tempAssignments:s,error:P(`bash: ${i}: bad array subscript
656
- `)};let u=i.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(u){let f=await Ha(e,t,u[1],u[2],o,n.append,s);if(f.error)return{continueToNext:!1,xtraceOutput:r,tempAssignments:s,error:f.error};if(f.continueToNext)continue}let c=await Za(e,t,i,o,n.append,s,a);if(c.error)return{continueToNext:!1,xtraceOutput:r,tempAssignments:s,error:c.error};r+=c.xtraceOutput,c.continueToNext}return{continueToNext:!1,xtraceOutput:r,tempAssignments:s}}async function za(e,t,s,r,n,i){let a="";if(/\[.+\]$/.test(s))return{continueToNext:!1,xtraceOutput:"",error:P(`bash: ${s}: cannot assign list to array member
657
- `)};if(Ee(e,s)){let c=bn(e,s);if(c===void 0||c==="")throw new q(1);let f=ze(e,s);if(f&&/^[a-zA-Z_][a-zA-Z0-9_]*\[@\]$/.test(f))return{continueToNext:!1,xtraceOutput:"",error:P(`bash: ${s}: cannot assign list to array member
657
+ `,await H(e,2,v)}return l&&!e.state.shoptOptions.lastpipe&&(e.state.lastArg=c),i}async function Yi(e,t){let s=new Map,r="";for(let n of t.assignments){let i=n.name;if(n.array){let f=await Ga(e,t,i,n.array,n.append,s);if(f.error)return{continueToNext:!1,xtraceOutput:r,tempAssignments:s,error:f.error};if(r+=f.xtraceOutput,f.continueToNext)continue}let a=n.value?await pt(e,n.value):R,o=n.value?B(a):"";if(o.length>e.limits.maxStringLength&&Me(`word expansion: string length limit exceeded (${e.limits.maxStringLength} bytes)`,"iterations"),i.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[\]$/))return{continueToNext:!1,xtraceOutput:r,tempAssignments:s,error:A(`bash: ${i}: bad array subscript
658
+ `)};let c=i.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(c){let f=await Ka(e,t,c[1],c[2],o,n.append,s);if(f.error)return{continueToNext:!1,xtraceOutput:r,tempAssignments:s,error:f.error};if(f.continueToNext)continue}let u=await Qa(e,t,i,o,n.append,s,a);if(u.error)return{continueToNext:!1,xtraceOutput:r,tempAssignments:s,error:u.error};r+=u.xtraceOutput,u.continueToNext}return{continueToNext:!1,xtraceOutput:r,tempAssignments:s}}async function Ga(e,t,s,r,n,i){let a="";if(/\[.+\]$/.test(s))return{continueToNext:!1,xtraceOutput:"",error:A(`bash: ${s}: cannot assign list to array member
659
+ `)};if(Ee(e,s)){let u=bn(e,s);if(u===void 0||u==="")throw new q(1);let f=ze(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
660
  `)}}if(ot(e,s)){if(t.name)return a+=`bash: ${s}: readonly variable
659
- `,{continueToNext:!0,xtraceOutput:a};let c=await de(e,s);if(c)return{continueToNext:!1,xtraceOutput:"",error:c}}let o=e.state.associativeArrays?.has(s),l=ja(r),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 Ba(e,t,s,r,n,u,c=>{a+=c}):l?await Ua(e,s,r,n,u):await Ga(e,s,r,n,u),t.name){i.set(s,e.state.env.get(s));let f=`(${r.map(d=>rs(d)).join(" ")})`;g(e.state.env,s,f)}return{continueToNext:!0,xtraceOutput:a}}function ja(e){return e.some(t=>{if(t.parts.length>=2){let s=t.parts[0],r=t.parts[1];if(s.type!=="Glob"||!s.pattern.startsWith("["))return!1;if(s.pattern==="["&&(r.type==="DoubleQuoted"||r.type==="SingleQuoted")){if(t.parts.length<3)return!1;let n=t.parts[2];return n.type!=="Literal"?!1:n.value.startsWith("]=")||n.value.startsWith("]+=")}return r.type!=="Literal"?!1:r.value.startsWith("]")?r.value.startsWith("]=")||r.value.startsWith("]+="):s.pattern.endsWith("]")?r.value.startsWith("=")||r.value.startsWith("+="):!1}return!1})}async function Ba(e,t,s,r,n,i,a){let o=[];for(let l of r){let u=qs(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=ne(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})}}n||i();for(let l of o)if(l.type==="keyed")if(l.append){let u=T(e.state.env,`${s}_${l.key}`,"");g(e.state.env,`${s}_${l.key}`,u+l.value)}else g(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
660
- `)}}async function Ua(e,t,s,r,n){let i=[];for(let o of s){let l=qs(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=ne(e,d),i.push({type:"keyed",indexExpr:u,value:d,append:f})}else{let u=await je(e,o);i.push({type:"non-keyed",values:u.values})}}r||n();let a=0;for(let o of i)if(o.type==="keyed"){let l;try{let u=new X,c=ce(u,o.indexExpr);l=await ee(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}`,"");g(e.state.env,`${t}_${l}`,u+o.value)}else g(e.state.env,`${t}_${l}`,o.value);a=l+1}else for(let l of o.values)g(e.state.env,`${t}_${a++}`,l)}async function Ga(e,t,s,r,n){let i=[];for(let o of s){let l=await je(e,o);i.push(...l.values)}let a=0;if(r){let o=Ie(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 n();for(let o=0;o<i.length;o++)g(e.state.env,`${t}_${a+o}`,i[o]);r||g(e.state.env,`${t}__length`,String(i.length))}async function Ha(e,t,s,r,n,i,a){let o=s;if(Ee(e,s)){let f=ze(e,s);if(f&&f!==s){if(f.includes("["))return{continueToNext:!1,xtraceOutput:"",error:P(`bash: \`${f}': not a valid identifier
661
- `)};o=f}}if(ot(e,o)){if(t.name)return{continueToNext:!0,xtraceOutput:""};let f=await de(e,o);if(f)return{continueToNext:!1,xtraceOutput:"",error:f}}let l=e.state.associativeArrays?.has(o),u;if(l)u=await Qi(e,o,r);else{let f=await qa(e,o,r);if(f.error)return{continueToNext:!1,xtraceOutput:"",error:f.error};u=`${o}_${f.index}`}let c=i?T(e.state.env,u)+n:n;if(t.name)a.set(u,e.state.env.get(u)),g(e.state.env,u,c);else{let f=bt(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))}g(e.state.env,u,c)}return{continueToNext:!0,xtraceOutput:""}}async function Qi(e,t,s){let r;if(s.startsWith("'")&&s.endsWith("'"))r=s.slice(1,-1);else if(s.startsWith('"')&&s.endsWith('"')){let n=s.slice(1,-1),a=new X().parseWordFromString(n,!0,!1);r=await z(e,a)}else if(s.includes("$")){let i=new X().parseWordFromString(s,!1,!1);r=await z(e,i)}else r=s;return`${t}_${r}`}async function qa(e,t,s){let r=s;s.startsWith('"')&&s.endsWith('"')&&s.length>=2&&(r=s.slice(1,-1));let n;if(/^-?\d+$/.test(r))n=Number.parseInt(r,10);else{try{let i=new X,a=ce(i,r);n=await ee(e,a.expression,!1)}catch(i){if(i instanceof nt){let l=`bash: line ${e.state.currentLine}: ${s}: ${i.message}
662
- `;if(i.fatal)throw await G(e,2,l,!0),new q(1);return{index:0,error:P(l)}}let a=T(e.state.env,s);n=a?Number.parseInt(a,10):0}Number.isNaN(n)&&(n=0)}if(n<0){let i=Ie(e,t);if(i.length===0){let o=e.state.currentLine;return{index:0,error:P(`bash: line ${o}: ${t}[${s}]: bad array subscript
663
- `)}}if(n=Math.max(...i.map(([o])=>typeof o=="number"?o:0))+1+n,n<0){let o=e.state.currentLine;return{index:0,error:P(`bash: line ${o}: ${t}[${s}]: bad array subscript
664
- `)}}}return{index:n}}async function Za(e,t,s,r,n,i,a){let o="",l=s,u=null;if(Ee(e,s)){let h=En(e,s,r);if(h===void 0)return{continueToNext:!1,xtraceOutput:"",error:P(`bash: ${s}: circular name reference
665
- `)};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(ot(e,l)){if(t.name)return o+=`bash: ${l}: readonly variable
666
- `,{continueToNext:!0,xtraceOutput:o};let h=await de(e,l);if(h)return{continueToNext:!1,xtraceOutput:"",error:h}}let c,f=!!a&&!n&&!u;if(Bt(e,l)){f=!1;try{let h=new X;if(n){let E=`(${T(e.state.env,l,"0")}) + (${r})`,$=ce(h,E);c=String(await ee(e,$.expression))}else{let b=ce(h,r);c=String(await ee(e,b.expression))}}catch{c="0"}}else{let{isArray:h}=await import("./chunks/expansion-QM4WQBBG.js"),b=h(e,l);b&&(f=!1);let E=b?`${l}_0`:l;c=n?T(e.state.env,E)+r:r}let d=$t(e,l,c);d!==c&&(f=!1),c=d,o+=await Ui(e,l,c);let p=l;if(u)p=await Xa(e,u);else{let{isArray:h}=await import("./chunks/expansion-QM4WQBBG.js");h(e,l)&&(p=`${l}_0`,f=!1)}let m=f?()=>e.state.env.set(p,a):()=>g(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 Xa(e,t){let{arrayName:s,subscriptExpr:r}=t;if(e.state.associativeArrays?.has(s))return Qi(e,s,r);let i;if(/^-?\d+$/.test(r))i=Number.parseInt(r,10);else{try{let a=new X,o=ce(a,r);i=await ee(e,o.expression,!1)}catch{let a=T(e.state.env,r);i=a?Number.parseInt(a,10):0}Number.isNaN(i)&&(i=0)}if(i<0){let a=Ie(e,s);a.length>0&&(i=Math.max(...a.map(l=>l[0]))+1+i)}return`${s}_${i}`}async function eo(e,t,s,r){let n=it(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 E=e.state.lastArg,$=e.state.bashPid;e.state.bashPid=e.state.nextVirtualPid++;let y=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=y,e.state.bashPid=$,e.state.lastArg=E};try{let C=t.redirections.length===0?{channels:n,legacyRedirections:[]}:await De(e,n,t.redirections);return C.error?await K(e,C.channels,()=>se(e,()=>Promise.resolve(C.error))):await K(e,C.channels,async()=>{let N=I=>F(S(),S(),I);try{let I=await re(s);I.length>0&&(e.state.groupStdin=fe(I));let k=0;for(let A of t.body){let O=await r(A);k=(await se(e,()=>Promise.resolve(O))).exitCode}return await N(k)}catch(I){let{diagnosticWritten:k,writeFailure:A}=await Qe(e,I);if(A)return A;if(I instanceof ae)throw I;return I instanceof Ge||I instanceof Ce||I instanceof Ae?await N(0):I instanceof q||I instanceof ve||I instanceof ke||I instanceof be?await N(I.exitCode):(k||await se(e,()=>Promise.resolve(P(`${He(I)}
667
- `))),await N(1))}})}catch(C){throw await K(e,n,()=>te(e,C)),C}finally{v()}}async function to(e,t,s,r){let n=t.redirections.length===0?{channels:e.outputChannels,legacyRedirections:[]}:await De(e,e.outputChannels,t.redirections);return n.error?K(e,n.channels,()=>se(e,()=>Promise.resolve(n.error))):K(e,n.channels,async()=>{let i=e.state.groupStdin;try{let a=await Et(e,n.legacyRedirections);if(a)return await se(e,()=>Promise.resolve(a));let o=await re(s),l=fe(o),u=!1;for(let f of n.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(`
661
+ `,{continueToNext:!0,xtraceOutput:a};let u=await de(e,s);if(u)return{continueToNext:!1,xtraceOutput:"",error:u}}let o=e.state.associativeArrays?.has(s),l=qa(r),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 Za(e,t,s,r,n,c,u=>{a+=u}):l?await Xa(e,s,r,n,c):await Ja(e,s,r,n,c),t.name){i.set(s,e.state.env.get(s));let f=`(${r.map(d=>is(d)).join(" ")})`;g(e.state.env,s,f)}return{continueToNext:!0,xtraceOutput:a}}function qa(e){return e.some(t=>{if(t.parts.length>=2){let s=t.parts[0],r=t.parts[1];if(s.type!=="Glob"||!s.pattern.startsWith("["))return!1;if(s.pattern==="["&&(r.type==="DoubleQuoted"||r.type==="SingleQuoted")){if(t.parts.length<3)return!1;let n=t.parts[2];return n.type!=="Literal"?!1:n.value.startsWith("]=")||n.value.startsWith("]+=")}return r.type!=="Literal"?!1:r.value.startsWith("]")?r.value.startsWith("]=")||r.value.startsWith("]+="):s.pattern.endsWith("]")?r.value.startsWith("=")||r.value.startsWith("+="):!1}return!1})}async function Za(e,t,s,r,n,i,a){let o=[];for(let l of r){let c=Zs(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=ne(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})}}n||i();for(let l of o)if(l.type==="keyed")if(l.append){let c=N(e.state.env,`${s}_${l.key}`,"");g(e.state.env,`${s}_${l.key}`,c+l.value)}else g(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
662
+ `)}}async function Xa(e,t,s,r,n){let i=[];for(let o of s){let l=Zs(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=ne(e,d),i.push({type:"keyed",indexExpr:c,value:d,append:f})}else{let c=await je(e,o);i.push({type:"non-keyed",values:c.values})}}r||n();let a=0;for(let o of i)if(o.type==="keyed"){let l;try{let c=new X,u=ce(c,o.indexExpr);l=await ee(e,u.expression,!1)}catch{if(/^-?\d+$/.test(o.indexExpr))l=Number.parseInt(o.indexExpr,10);else{let c=N(e.state.env,o.indexExpr);l=c?Number.parseInt(c,10):0,Number.isNaN(l)&&(l=0)}}if(o.append){let c=N(e.state.env,`${t}_${l}`,"");g(e.state.env,`${t}_${l}`,c+o.value)}else g(e.state.env,`${t}_${l}`,o.value);a=l+1}else for(let l of o.values)g(e.state.env,`${t}_${a++}`,l)}async function Ja(e,t,s,r,n){let i=[];for(let o of s){let l=await je(e,o);i.push(...l.values)}let a=0;if(r){let o=Ie(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 n();for(let o=0;o<i.length;o++)g(e.state.env,`${t}_${a+o}`,i[o]);r||g(e.state.env,`${t}__length`,String(i.length))}async function Ka(e,t,s,r,n,i,a){let o=s;if(Ee(e,s)){let f=ze(e,s);if(f&&f!==s){if(f.includes("["))return{continueToNext:!1,xtraceOutput:"",error:A(`bash: \`${f}': not a valid identifier
663
+ `)};o=f}}if(ot(e,o)){if(t.name)return{continueToNext:!0,xtraceOutput:""};let f=await de(e,o);if(f)return{continueToNext:!1,xtraceOutput:"",error:f}}let l=e.state.associativeArrays?.has(o),c;if(l)c=await Qi(e,o,r);else{let f=await Ya(e,o,r);if(f.error)return{continueToNext:!1,xtraceOutput:"",error:f.error};c=`${o}_${f.index}`}let u=i?N(e.state.env,c)+n:n;if(t.name)a.set(c,e.state.env.get(c)),g(e.state.env,c,u);else{let f=bt(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))}g(e.state.env,c,u)}return{continueToNext:!0,xtraceOutput:""}}async function Qi(e,t,s){let r;if(s.startsWith("'")&&s.endsWith("'"))r=s.slice(1,-1);else if(s.startsWith('"')&&s.endsWith('"')){let n=s.slice(1,-1),a=new X().parseWordFromString(n,!0,!1);r=await z(e,a)}else if(s.includes("$")){let i=new X().parseWordFromString(s,!1,!1);r=await z(e,i)}else r=s;return`${t}_${r}`}async function Ya(e,t,s){let r=s;s.startsWith('"')&&s.endsWith('"')&&s.length>=2&&(r=s.slice(1,-1));let n;if(/^-?\d+$/.test(r))n=Number.parseInt(r,10);else{try{let i=new X,a=ce(i,r);n=await ee(e,a.expression,!1)}catch(i){if(i instanceof nt){let l=`bash: line ${e.state.currentLine}: ${s}: ${i.message}
664
+ `;if(i.fatal)throw await H(e,2,l,!0),new q(1);return{index:0,error:A(l)}}let a=N(e.state.env,s);n=a?Number.parseInt(a,10):0}Number.isNaN(n)&&(n=0)}if(n<0){let i=Ie(e,t);if(i.length===0){let o=e.state.currentLine;return{index:0,error:A(`bash: line ${o}: ${t}[${s}]: bad array subscript
665
+ `)}}if(n=Math.max(...i.map(([o])=>typeof o=="number"?o:0))+1+n,n<0){let o=e.state.currentLine;return{index:0,error:A(`bash: line ${o}: ${t}[${s}]: bad array subscript
666
+ `)}}}return{index:n}}async function Qa(e,t,s,r,n,i,a){let o="",l=s,c=null;if(Ee(e,s)){let h=En(e,s,r);if(h===void 0)return{continueToNext:!1,xtraceOutput:"",error:A(`bash: ${s}: circular name reference
667
+ `)};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(ot(e,l)){if(t.name)return o+=`bash: ${l}: readonly variable
668
+ `,{continueToNext:!0,xtraceOutput:o};let h=await de(e,l);if(h)return{continueToNext:!1,xtraceOutput:"",error:h}}let u,f=!!a&&!n&&!c;if(Ut(e,l)){f=!1;try{let h=new X;if(n){let E=`(${N(e.state.env,l,"0")}) + (${r})`,S=ce(h,E);u=String(await ee(e,S.expression))}else{let v=ce(h,r);u=String(await ee(e,v.expression))}}catch{u="0"}}else{let{isArray:h}=await import("./chunks/expansion-QM4WQBBG.js"),v=h(e,l);v&&(f=!1);let E=v?`${l}_0`:l;u=n?N(e.state.env,E)+r:r}let d=$t(e,l,u);d!==u&&(f=!1),u=d,o+=await Ui(e,l,u);let p=l;if(c)p=await el(e,c);else{let{isArray:h}=await import("./chunks/expansion-QM4WQBBG.js");h(e,l)&&(p=`${l}_0`,f=!1)}let m=f?()=>e.state.env.set(p,a):()=>g(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 el(e,t){let{arrayName:s,subscriptExpr:r}=t;if(e.state.associativeArrays?.has(s))return Qi(e,s,r);let i;if(/^-?\d+$/.test(r))i=Number.parseInt(r,10);else{try{let a=new X,o=ce(a,r);i=await ee(e,o.expression,!1)}catch{let a=N(e.state.env,r);i=a?Number.parseInt(a,10):0}Number.isNaN(i)&&(i=0)}if(i<0){let a=Ie(e,s);a.length>0&&(i=Math.max(...a.map(l=>l[0]))+1+i)}return`${s}_${i}`}async function eo(e,t,s,r){let n=it(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(_=>new Map(_)),d){e.state.localVarStack=new Map;for(let[_,L]of d.entries())e.state.localVarStack.set(_,L.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 E=e.state.lastArg,S=e.state.bashPid;e.state.bashPid=e.state.nextVirtualPid++;let b=e.state.groupStdin,y=e.lineageId;e.lineageId=e.processes.createLineageId();let k=()=>{e.lineageId=y,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=S,e.state.lastArg=E};try{let _=t.redirections.length===0?{channels:n,legacyRedirections:[]}:await De(e,n,t.redirections);return _.error?await Y(e,_.channels,()=>se(e,()=>Promise.resolve(_.error))):await Y(e,_.channels,async()=>{let L=$=>F(P(),P(),$);try{let $=await re(s);$.length>0&&(e.state.groupStdin=fe($));let C=0;for(let O of t.body){let I=await r(O);C=(await se(e,()=>Promise.resolve(I))).exitCode}return await L(C)}catch($){let{diagnosticWritten:C,writeFailure:O}=await Qe(e,$);if(O)return O;if($ instanceof ae)throw $;return $ instanceof He||$ instanceof Ae||$ instanceof Ce?await L(0):$ instanceof q||$ instanceof ve||$ instanceof ke||$ instanceof be?await L($.exitCode):(C||await se(e,()=>Promise.resolve(A(`${Ge($)}
669
+ `))),await L(1))}})}catch(_){throw await Y(e,n,()=>te(e,_)),_}finally{k()}}async function to(e,t,s,r){let n=t.redirections.length===0?{channels:e.outputChannels,legacyRedirections:[]}:await De(e,e.outputChannels,t.redirections);return n.error?Y(e,n.channels,()=>se(e,()=>Promise.resolve(n.error))):Y(e,n.channels,async()=>{let i=e.state.groupStdin;try{let a=await Et(e,n.legacyRedirections);if(a)return await se(e,()=>Promise.resolve(a));let o=await re(s),l=fe(o),c=!1;for(let f of n.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(`
668
670
  `).map(h=>h.replace(/^\t+/,"")).join(`
669
- `));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)}
670
- `),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 se(e,()=>Promise.resolve(P(`bash: ${d}: No such file or directory
671
- `)))}}}(u||o.length>0)&&(e.state.groupStdin=l);let c=0;for(let f of t.body){let d=await r(f);c=(await se(e,()=>Promise.resolve(d))).exitCode}return F(S(),S(),c)}catch(a){let{diagnosticWritten:o,writeFailure:l}=await Qe(e,a);if(l)return l;if(es(a)||a instanceof ke||a instanceof q||a instanceof be||a instanceof Ge||a instanceof ae)throw a;return o||await se(e,()=>Promise.resolve(P(`${He(a)}
672
- `))),F(S(),S(),1)}finally{e.state.groupStdin=i}})}async function so(e,t,s,r,n){let i;try{i=await e.fs.readFileText(t)}catch{return P(`bash: ${t}: No such file or directory
673
- `,127)}if(i.startsWith("#!")){let b=i.indexOf(`
674
- `);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 re(r);b.length>0&&(e.state.groupStdin=fe(b)),e.state.currentSource=t,g(e.state.env,"0",t),g(e.state.env,"#",String(s.length)),g(e.state.env,"@",s.join(" ")),g(e.state.env,"*",s.join(" "));for(let v=0;v<s.length&&v<9;v++)g(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 X().parse(i),y=await n($);return await se(e,()=>Promise.resolve(y))}catch(b){let{writeFailure:E}=await Qe(e,b);if(E)return E;if(b instanceof q||b instanceof ae)throw b;if(b.name==="ParseException")return P(`bash: ${t}: ${b.message}
675
- `);throw b}finally{h()}}function Ja(e,t){for(let s of t.parts)switch(s.type){case"Bytes":case"Literal":case"SingleQuoted":case"Escaped":continue;case"DoubleQuoted":for(let r of s.parts)switch(r.type){case"Bytes":case"Literal":case"SingleQuoted":case"Escaped":continue;case"ParameterExpansion":if(r.operation||r.parameter==="@"||r.parameter==="*"||r.parameter.endsWith("[@]")||r.parameter.endsWith("[*]"))return!1;if(Ee(e,r.parameter)){let n=ze(e,r.parameter);if(n&&(n.endsWith("[@]")||n.endsWith("[*]")))return!1}continue;case"CommandSubstitution":continue;default:return!1}continue;case"ParameterExpansion":return!1;default:return!1}return t.parts.length>0}var Zt=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,r=new Set;if(t)for(let i of t)r.add(i);if(s)for(let i of s)r.add(i);if(r.size===0)return Object.create(null);let n=Object.create(null);for(let i of r)this.ctx.state.env.has(i)&&(n[i]=T(this.ctx.state.env,i));return n}async executeRootScript(t){let s=await this.executeScript(t);return Ke(this.ctx.signal),Y(this.ctx,s)}async executeScript(t){let s=0;for(let r of t.statements)try{let n=await this.executeStatement(r),i=this.ctx.signal?.aborted===!0&&n.exitCode===new pe(this.ctx.signal.reason).exitCode;await Y(this.ctx,n,!i),s=n.exitCode,this.ctx.state.lastExitCode=s,g(this.ctx.state.env,"?",String(s))}catch(n){if(await te(this.ctx,n),n instanceof q)throw n;if(n instanceof be)return s=n.exitCode,this.ctx.state.lastExitCode=s,g(this.ctx.state.env,"?",String(s)),{stdout:S(),stderr:S(),exitCode:s,env:Ye(this.ctx.state.env)};if(n instanceof ae)throw n;if(n instanceof ke)return s=n.exitCode,this.ctx.state.lastExitCode=s,g(this.ctx.state.env,"?",String(s)),{stdout:S(),stderr:S(),exitCode:s,env:Ye(this.ctx.state.env)};if(n instanceof cn)return s=1,this.ctx.state.lastExitCode=s,g(this.ctx.state.env,"?",String(s)),{stdout:S(),stderr:S(),exitCode:s,env:Ye(this.ctx.state.env)};if(n instanceof It)return s=1,this.ctx.state.lastExitCode=s,g(this.ctx.state.env,"?",String(s)),{stdout:S(),stderr:S(),exitCode:s,env:Ye(this.ctx.state.env)};if(n instanceof nt){s=1,this.ctx.state.lastExitCode=s,g(this.ctx.state.env,"?",String(s));continue}if(n instanceof un){s=1,this.ctx.state.lastExitCode=s,g(this.ctx.state.env,"?",String(s));continue}if(n instanceof Ce||n instanceof Ae){if(this.ctx.state.loopDepth>0)throw n;continue}throw n instanceof ve,n}return{stdout:S(),stderr:S(),exitCode:s,env:Ye(this.ctx.state.env)}}async executeUserScript(t,s,r=S()){return so(this.ctx,t,ft(s),r,n=>this.executeScript(n))}async executeStatement(t){if(Ke(this.ctx.signal),this.ctx.state.commandCount++,this.ctx.state.commandCount>this.ctx.limits.maxCommandCount&&Me(`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)),Ke(this.ctx.signal)),t.deferredError)throw new ts(t.deferredError.message,t.line??1,1);if(this.ctx.state.options.noexec)return U();if(this.ctx.state.errexitSafe=!1,this.ctx.state.options.verbose&&!this.ctx.state.suppressVerbose&&t.sourceText&&await G(this.ctx,2,`${t.sourceText}
676
- `),t.background){if(this.ctx.processes.runningCount>=this.ctx.limits.maxConcurrentJobs)return this.ctx.jobTracker.limitExceeded=!0,await G(this.ctx,2,`bash: maximum concurrent jobs (${this.ctx.limits.maxConcurrentJobs}) exceeded
677
- `),P("",ae.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=>it(c,(h,b)=>u.observesOutput?_e({write(E){return u.observeOutput(m,h,E),b.write(E)}},!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 E=Mt(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:(y,v)=>this.ctx.execFn(y,{...v,signal:Mt(E,v?.signal)}),fetch:this.ctx.fetch,sleep:this.ctx.sleep,trace:this.ctx.trace,coverage:this.ctx.coverage,signal:E},l);try{return(await $.executeRootScript({type:"Script",statements:[{...t,background:!1,sourceText:void 0}]})).exitCode}catch(y){if(y instanceof pe||y instanceof q)return y.exitCode;if(y instanceof ae)return this.ctx.jobTracker.limitExceeded=!0,ae.EXIT_CODE;throw y}},this.ctx.lineageId),this.ctx.jobTracker.started=!0}catch(m){return await G(this.ctx,2,`bash: ${m instanceof Error?m.message:String(m)}
678
- `),P("",1)}return this.ctx.state.lastBackgroundPid=p,U()}let s=0,r=-1,n=!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,r=o,n=l.negated,this.ctx.state.lastExitCode=s,g(this.ctx.state.env,"?",String(s))}let i=r<t.pipelines.length-1,a=this.ctx.state.errexitSafe;if(this.ctx.state.errexitSafe=i||n||a,this.ctx.state.options.errexit&&s!==0&&r===t.pipelines.length-1&&!n&&!this.ctx.state.inCondition&&!a)throw new ke(s);return{stdout:S(),stderr:S(),exitCode:s}}async executePipeline(t){return Ki(this.ctx,t,(s,r)=>this.executeCommand(s,r))}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 Gi(this.ctx,t);case"For":return Hi(this.ctx,t);case"CStyleFor":return qi(this.ctx,t);case"While":return Zi(this.ctx,t,s);case"Until":return Xi(this.ctx,t);case"Case":return Ji(this.ctx,t);case"Subshell":return this.executeSubshell(t,s);case"Group":return this.executeGroup(t,s);case"FunctionDef":return ui(this.ctx,t);case"ArithmeticCommand":return this.executeArithmeticCommand(t);case"ConditionalCommand":return this.executeConditionalCommand(t);default:return U()}}async executeSimpleCommand(t,s){this.ctx.reportedDiagnostics=new WeakSet;try{return await this.executeSimpleCommandInner(t,s)}catch(r){if(r instanceof Qt)return await te(this.ctx,r),{stdout:S(),stderr:S(),exitCode:1};throw r}}async executeSimpleCommandInner(t,s){if(t.line!==void 0&&(this.ctx.state.currentLine=t.line),this.ctx.state.shoptOptions.expand_aliases&&t.name){let k=t,A=100;for(;A>0;){let O=this.expandAlias(k);if(O===k)break;k=O,A--}this.aliasExpansionStack.clear(),k!==t&&(t=k)}let r=await Yi(this.ctx,t);if(r.error)return r.error;let n=r.tempAssignments,i=r.xtraceOutput;if(!t.name){if(await G(this.ctx,2,i),t.redirections.length>0){let k=this.ctx.outputChannels,A=await De(this.ctx,k,t.redirections);if(A.error)return await K(this.ctx,A.channels,()=>se(this.ctx,()=>Promise.resolve(A.error)));let O={stdout:S(),stderr:S(),exitCode:0},M=[1,2].filter(x=>{let _=k.bindings.get(x),w=A.channels.bindings.get(x);return _?.sink!==w?.sink||We(k,x)!==We(A.channels,x)});return await K(this.ctx,A.channels,()=>se(this.ctx,()=>Promise.resolve(O),M))}return this.ctx.state.lastArg=W(""),{stdout:S(),stderr:S(),exitCode:this.ctx.state.lastExitCode}}let a=t.name&&jt(t.name,["local","declare","typeset","export","readonly"]),o=Array.from(n.keys());if(o.length>0&&!a){this.ctx.state.tempExportedVars=this.ctx.state.tempExportedVars||new Set;for(let k of o)this.ctx.state.tempExportedVars.add(k)}let l=-1,u=jt(t.name,["exec"])&&(t.args.length===0||t.args.length===1&&jt(t.args[0],["--"])),c=await z(this.ctx,t.name),f=[],d=[];if(jt(t.name,["local","declare","typeset","export","readonly"])&&(c==="local"||c==="declare"||c==="typeset"||c==="export"||c==="readonly"))for(let k of t.args){let A=await Un(this.ctx,k);if(A)f.push(W(A)),d.push(!0);else{let O=await Gn(this.ctx,k);if(O!==null)f.push(W(O)),d.push(!0);else{let M=await je(this.ctx,k);for(let x of M.values)f.push(W(x)),d.push(M.quoted)}}}else for(let k of t.args)if(Ja(this.ctx,k))f.push(await pt(this.ctx,k)),d.push(!0);else{let A=await je(this.ctx,k);for(let O of A.values)f.push(W(O)),d.push(A.quoted)}let m=this.ctx.outputChannels,h=!u&&t.redirections.length>0?await De(this.ctx,m,t.redirections,{persistMovedSource:Je.has(c)}):void 0;if(h?.error){await G(this.ctx,2,i);for(let[k,A]of n)A===void 0?this.ctx.state.env.delete(k):this.ctx.state.env.set(k,A);return await K(this.ctx,h.channels,()=>se(this.ctx,()=>Promise.resolve(h.error)))}let b=t.redirections.some(k=>{if(u&&(k.operator==="<"||k.operator==="<&")||k.fdVariable)return!1;if(k.operator==="<<"||k.operator==="<<-"||k.operator==="<<<")return!0;let A=k.fd??0;return(k.operator==="<"||k.operator==="<&")&&A===0}),E=null,$=R;b?$=await re(s):E=s;let y=h?.legacyRedirections??t.redirections;for(let k of y)if(!(k.fdVariable||u&&(k.operator==="<"||k.operator==="<&"))){if((k.operator==="<<"||k.operator==="<<-")&&k.target.type==="HereDoc"){let A=k.target,O=k.fd??0;if(O===0&&!A.stripTabs)$=await pt(this.ctx,A.content);else{let M=await z(this.ctx,A.content);A.stripTabs&&(M=M.split(`
679
- `).map(x=>x.replace(/^\t+/,"")).join(`
680
- `)),O!==0?(this.ctx.state.fileDescriptors||(this.ctx.state.fileDescriptors=new Map),this.ctx.state.fileDescriptors.set(O,M)):$=W(M)}continue}if(k.operator==="<<<"&&k.target.type==="Word"){let A=await pt(this.ctx,k.target);$=an(A,W(`
681
- `));continue}if(k.operator==="<"&&k.target.type==="Word")try{let A=await z(this.ctx,k.target),O=this.ctx.fs.resolvePath(this.ctx.state.cwd,A);$=await re(await this.ctx.fs.readFile(O))}catch{let A=await z(this.ctx,k.target);for(let[O,M]of n)M===void 0?this.ctx.state.env.delete(O):this.ctx.state.env.set(O,M);return P(`bash: ${A}: No such file or directory
682
- `)}if(k.operator==="<&"&&(k.fd??0)===0&&k.target.type==="Word"){let A=await z(this.ctx,k.target),O=A.startsWith("&")?A.slice(1):A;if(O!=="-"&&!/^\d+-?$/.test(O)){for(let[x,_]of n)_===void 0?this.ctx.state.env.delete(x):this.ctx.state.env.set(x,_);return P(`bash: ${A}: ambiguous redirect
683
- `)}let M=Number.parseInt(O,10);if(!Number.isNaN(M)&&We(this.ctx.outputChannels,M)){for(let[x,_]of n)_===void 0?this.ctx.state.env.delete(x):this.ctx.state.env.set(x,_);return P(Ue(M))}if(!Number.isNaN(M)&&this.ctx.state.fileDescriptors){let x=this.ctx.state.fileDescriptors.get(M);if(x!==void 0)if(x.startsWith("__rw__:")){let _=Ss(x);_&&($=W(_.content.slice(_.position)),l=M)}else x.startsWith("__file__:")||x.startsWith("__file_append__:")||($=W(x));else if(M>=3&&!this.ctx.outputChannels.bindings.get(M)?.sink){for(let[_,w]of n)w===void 0?this.ctx.state.env.delete(_):this.ctx.state.env.set(_,w);return P(Ue(M))}}else if(!Number.isNaN(M)&&M>=3&&!this.ctx.outputChannels.bindings.get(M)?.sink){for(let[x,_]of n)_===void 0?this.ctx.state.env.delete(x):this.ctx.state.env.set(x,_);return P(Ue(M))}}}if(!c){if(t.name.parts.every(A=>A.type==="CommandSubstitution"||A.type==="ParameterExpansion"||A.type==="ArithmeticExpansion")){if(f.length>0){let A=B(f.shift());return d.shift(),await this.runCommand(A,f,d,E??fe($),!1,!1,l)}return{stdout:S(),stderr:S(),exitCode:this.ctx.state.lastExitCode}}return P(`bash: : command not found
684
- `,127)}await G(this.ctx,2,i);let v=await Ls(this.ctx,c,f.map(k=>B(k)));if(await G(this.ctx,2,v),c==="exec"&&(f.length===0||B(f[0])==="--")){let k=[],A=this.ctx.outputChannels;for(;A;)k.push([A,new Map(A.bindings)]),A=A.parent;let O=this.ctx.state.fileDescriptors?new Map(this.ctx.state.fileDescriptors):void 0,M=this.ctx.state.nextFd,x=new Map;for(let w of t.redirections)w.fdVariable&&!x.has(w.fdVariable)&&x.set(w.fdVariable,this.ctx.state.env.get(w.fdVariable));let _=await ci(this.ctx,t.redirections);if(_.error){let w;try{w=await K(this.ctx,_.channels,()=>se(this.ctx,()=>Promise.resolve(_.error)))}finally{for(let[D,L]of k)D.bindings=new Map(L);this.ctx.state.fileDescriptors=O,this.ctx.state.nextFd=M;for(let[D,L]of x)L===void 0?this.ctx.state.env.delete(D):this.ctx.state.env.set(D,L)}return w}for(let w of _.legacyRedirections){if(w.target.type==="HereDoc"||w.fdVariable)continue;let D=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,D);try{let j=await this.ctx.fs.readFileText(J);this.ctx.state.fileDescriptors.set(L,j)}catch{let j;try{j=await se(this.ctx,()=>Promise.resolve(P(`bash: ${D}: No such file or directory
685
- `)))}finally{for(let[Q,oe]of k)Q.bindings=new Map(oe);this.ctx.state.fileDescriptors=O,this.ctx.state.nextFd=M;for(let[Q,oe]of x)oe===void 0?this.ctx.state.env.delete(Q):this.ctx.state.env.set(Q,oe)}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(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(D==="-")this.ctx.state.fileDescriptors.delete(L);else{let J=D.endsWith("-"),j=Number.parseInt(J?D.slice(0,-1):D,10);if(!Number.isNaN(j)){let Q=this.ctx.state.fileDescriptors.get(j)??`__dupin__:${j}`;this.ctx.state.fileDescriptors.set(L,Q),J&&this.ctx.state.fileDescriptors.delete(j)}}}for(let[w,D]of n)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 n.keys())this.ctx.state.tempExportedVars.delete(w);return U()}n.size>0&&(this.ctx.state.tempEnvBindings=this.ctx.state.tempEnvBindings||[],this.ctx.state.tempEnvBindings.push(new Map(n)));let C,N=null,I=h?[1,2].filter(k=>{let A=m.bindings.get(k),O=h.channels.bindings.get(k);return A?.sink!==O?.sink||We(m,k)!==We(h.channels,k)}):[];try{try{let k=()=>this.runCommand(c,f,d,E??fe($),!1,!1,l);C=h?await K(this.ctx,h.channels,k):await k()}catch(k){let A=null;if(h&&(A=(await K(this.ctx,h.channels,()=>Qe(this.ctx,k,I))).writeFailure,A&&(C=A)),!A)if(k instanceof Ce||k instanceof Ae)N=k,C=U();else throw k}if(C.exitCode===127&&Je.has(c)&&h?.channels.bindings.get(1)?.descriptor==="__file__:/dev/full"&&(C=H(`
686
- `)),h&&I.length>0&&(C=await K(this.ctx,h.channels,()=>se(this.ctx,()=>Promise.resolve(C),I))),N)throw N;if(f.length>0){let k=B(f[f.length-1]);if((c==="declare"||c==="local"||c==="typeset")&&/^[a-zA-Z_][a-zA-Z0-9_]*=\(/.test(k)){let A=k.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\(/);A&&(k=A[1])}this.ctx.state.lastArg=W(k)}else this.ctx.state.lastArg=W(c)}finally{let k=ii(c)&&c!=="unset"&&c!=="eval";if(!this.ctx.state.options.posix||!k)for(let[O,M]of n)this.ctx.state.fullyUnsetLocals?.has(O)||(M===void 0?this.ctx.state.env.delete(O):this.ctx.state.env.set(O,M));if(this.ctx.state.tempExportedVars)for(let O of n.keys())this.ctx.state.tempExportedVars.delete(O);n.size>0&&this.ctx.state.tempEnvBindings&&this.ctx.state.tempEnvBindings.pop()}return C}async runCommand(t,s,r,n,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??S())},u=await zi(l,t,s,r,n,i,a,o);return u!==null?u:ji(l,t,s,n,a)}aliasExpansionStack=new Set;expandAlias(t){return sr(this.ctx.state,t,this.aliasExpansionStack)}async findCommandInPath(t){return Is(this.ctx,t)}async executeSubshell(t,s=S()){return eo(this.ctx,t,s,r=>this.executeStatement(r))}async executeGroup(t,s=S()){return to(this.ctx,t,s,r=>this.executeStatement(r))}async executeArithmeticCommand(t){t.line!==void 0&&(this.ctx.state.currentLine=t.line);let s=this.ctx.outputChannels,r=await De(this.ctx,s,t.redirections);if(r.error)return K(this.ctx,r.channels,()=>se(this.ctx,()=>Promise.resolve(r.error)));let n=[1,2].filter(i=>{let a=s.bindings.get(i),o=r.channels.bindings.get(i);return a?.sink!==o?.sink||We(s,i)!==We(r.channels,i)});return K(this.ctx,r.channels,async()=>{let i;try{let a=await ee(this.ctx,t.expression.expression);i=le(a!==0)}catch(a){i=P(`bash: arithmetic expression: ${a.message}
687
- `)}return n.length>0?se(this.ctx,()=>Promise.resolve(i),n):i})}async executeConditionalCommand(t){t.line!==void 0&&(this.ctx.state.currentLine=t.line);let s=this.ctx.outputChannels,r=await De(this.ctx,s,t.redirections);if(r.error)return K(this.ctx,r.channels,()=>se(this.ctx,()=>Promise.resolve(r.error)));let n=[1,2].filter(i=>{let a=s.bindings.get(i),o=r.channels.bindings.get(i);return a?.sink!==o?.sink||We(s,i)!==We(r.channels,i)});return K(this.ctx,r.channels,async()=>{let i;try{let a=await tt(this.ctx,t.expression);i=le(a)}catch(a){let o=a instanceof nt?1:2;i=P(`bash: conditional expression: ${a.message}
688
- `,o)}return n.length>0?se(this.ctx,()=>Promise.resolve(i),n):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 ro(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 no(e){try{let t=new URL(e);return{origin:t.origin,pathname:t.pathname,href:t.href}}catch{return null}}function Ka(e){let t=no(e);return t?{origin:t.origin,pathPrefix:t.pathname}:null}function Ya(e,t){let s=no(e);if(!s)return!1;let r=Ka(t);return!r||s.origin!==r.origin?!1:r.pathPrefix==="/"||r.pathPrefix===""?!0:s.pathname.startsWith(r.pathPrefix)}function tn(e,t){return!t||t.length===0?!1:t.some(s=>Ya(e,s))}var Ct=class extends Error{constructor(t){super(`Network access denied: URL not in allow-list: ${t}`),this.name="NetworkAccessDeniedError"}},At=class extends Error{constructor(t){super(`Too many redirects (max: ${t})`),this.name="TooManyRedirectsError"}},kt=class extends Error{constructor(t){super(`Redirect target not in allow-list: ${t}`),this.name="RedirectNotAllowedError"}},Fs=class extends Error{constructor(t,s){super(`HTTP method '${t}' not allowed. Allowed methods: ${s.join(", ")}`),this.name="MethodNotAllowedError"}},Xt=class extends Error{constructor(t){super(`Response body too large (max: ${t} bytes)`),this.name="ResponseTooLargeError"}};var Qa=20,el=3e4,tl=10485760,sl=["GET","HEAD"],rl=new Set(["GET","HEAD","OPTIONS"]),nl=new Set([301,302,303,307,308]);function sn(e){let t=e.maxRedirects??Qa,s=e.timeoutMs??el,r=e.maxResponseSize??tl,n=e.dangerouslyAllowFullInternetAccess?["GET","HEAD","POST","PUT","DELETE","PATCH","OPTIONS"]:e.allowedMethods??sl;function i(l){if(!e.dangerouslyAllowFullInternetAccess&&!tn(l,e.allowedUrlPrefixes??[]))throw new Ct(l)}function a(l){if(e.dangerouslyAllowFullInternetAccess)return;let u=l.toUpperCase();if(!n.includes(u))throw new Fs(u,n)}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 E={method:c,headers:u.headers,signal:h.signal,redirect:"manual"};u.body&&!rl.has(c)&&(E.body=u.body);let $=await fetch(f,E);if(nl.has($.status)&&p){let y=$.headers.get("location");if(!y)return await io($,f,r);let v=new URL(y,f).href;if(!e.dangerouslyAllowFullInternetAccess&&!tn(v,e.allowedUrlPrefixes??[]))throw new kt(v);if(d++,d>t)throw new At(t);f=v;continue}return await io($,f,r)}finally{clearTimeout(b)}}}return o}async function io(e,t,s){let r=Object.create(null);if(e.headers.forEach((i,a)=>{r[a.toLowerCase()]=i}),s>0){let i=e.headers.get("content-length");if(i){let a=parseInt(i,10);if(!Number.isNaN(a)&&a>s)throw new Xt(s)}}let n;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 Xt(s);o.push(a.decode(c,{stream:!0}))}o.push(a.decode()),n=o.join("")}else n=await e.text();return{status:e.status,statusText:e.statusText,headers:r,body:n,url:t}}var il=1e3,ol=64,al=globalThis.setTimeout.bind(globalThis),ll=globalThis.clearTimeout.bind(globalThis),Le=class{jobs=new Map;reapedWaitStatuses=new Map;reapedWaitLineages=new Map;options;nextPid=il;nextLineageId=1;highestJobNumber=0;runningJobs=0;disposed=!1;disposePromise;constructor(t={}){this.options=t}start(t,s,r){if(this.disposed)throw new Error("Cannot start a job on a disposed ProcessTable");let n=this.nextPid++,i=new AbortController,a=this.highestJobNumber+1,o={info:{pid:n,command:t,startedAt:Date.now(),state:"running"},jobNumber:a,lineageId:r,controller:i,promise:Promise.resolve(0)};return this.jobs.set(n,o),this.highestJobNumber=a,this.runningJobs++,o.promise=Promise.resolve().then(()=>s(n,i.signal)).catch(()=>i.signal.aborted?fn(i.signal.reason):1).then(l=>{this.jobs.get(n)===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?.(n,l)).catch(()=>{})}catch{}return l}),n}list(){return[...this.jobs.values()].sort((t,s)=>t.jobNumber-s.jobNumber).map(t=>({...t.info}))}listJobs(t,s={}){let r=[...this.jobs.values()].sort((l,u)=>l.jobNumber-u.jobNumber),n=r.at(-1)?.info.pid,i=r.at(-2)?.info.pid,a=[],o=[];for(let l of r)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===n?"+":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,r){let n=this.jobs.get(t);return!n||n.info.state==="done"?!1:(s!=="SIGSTOP"&&s!=="SIGCONT"&&n.controller?.abort(r??s),!0)}async wait(t){if(t!==void 0){let n=this.jobs.get(t);if(!n)return this.reapedWaitStatuses.get(t)??127;let i=n.info.state==="done"?n.info.exitCode??1:await(n.promise??Promise.resolve(1));return this.jobs.get(t)===n&&(this.rememberWaitStatus(t,i,n.lineageId),this.deleteJobs([t])),i}let s=[...this.jobs.values()],r=new Set([...this.reapedWaitStatuses.keys(),...s.map(n=>n.info.pid)]);s.length>0&&(await Promise.all(s.map(n=>n.promise??Promise.resolve(n.info.exitCode??1))),this.deleteJobs(s.map(n=>n.info.pid)));for(let n of r)this.reapedWaitStatuses.delete(n),this.reapedWaitLineages.delete(n);return 0}async waitForLineage(t){let s=[...this.jobs.values()].filter(n=>n.lineageId===t),r=[...this.reapedWaitLineages.entries()].flatMap(([n,i])=>i===t?[n]:[]);s.length>0&&(await Promise.all(s.map(n=>n.promise??Promise.resolve(n.info.exitCode??1))),this.deleteJobs(s.map(n=>n.info.pid)));for(let n of[...r,...s.map(i=>i.info.pid)])this.reapedWaitStatuses.delete(n),this.reapedWaitLineages.delete(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(n=>{s=n}),this.abortAll("SIGKILL"),this.jobs.clear(),this.reapedWaitStatuses.clear(),this.reapedWaitLineages.clear(),this.highestJobNumber=0,this.runningJobs=0;let r=al(s,this.options.disposeTimeoutMs??1e3);return Promise.allSettled(t.flatMap(n=>n.promise?[n.promise]:[])).then(()=>{ll(r),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 r=/^%(\d+)$/.exec(t);if(!r)return;let n=Number.parseInt(r[1],10);return s.find(i=>i.jobNumber===n)?.info.pid}get observesOutput(){return this.options.onJobOutput!==void 0}observeOutput(t,s,r){try{Promise.resolve(this.options.onJobOutput?.(t,s,r)).catch(()=>{})}catch{}}rememberWaitStatus(t,s,r){if(this.reapedWaitStatuses.delete(t),this.reapedWaitLineages.delete(t),this.reapedWaitStatuses.set(t,s),this.reapedWaitLineages.set(t,r),this.reapedWaitStatuses.size>ol){let n=this.reapedWaitStatuses.keys().next().value;n!==void 0&&(this.reapedWaitStatuses.delete(n),this.reapedWaitLineages.delete(n))}}deleteJobs(t){let s=!1;for(let r of t){let n=this.jobs.get(r);n&&(this.jobs.delete(r),s||=n.jobNumber===this.highestJobNumber)}if(s){this.highestJobNumber=0;for(let r of this.jobs.values())this.highestJobNumber=Math.max(this.highestJobNumber,r.jobNumber)}}};function rn(){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 Jt=typeof __BROWSER__<"u"&&__BROWSER__;function oo(){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 on=null;if(!Jt)try{let e="node:module",{createRequire:t}=await import(e);on=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 cl=`
689
-
690
- This is a defense-in-depth measure and indicates a bug in just-bash. Please report this at security@vercel.com`,ye=class extends Error{violation;constructor(t,s){super(t+cl),this.violation=s,this.name="SecurityViolationError"}},$e=!Jt&&on?new on:null,ul=1e3,nn={enabled:!0,auditMode:!1};function fl(e){return e===void 0?{...nn,enabled:!1}:typeof e=="boolean"?{...nn,enabled:e}:{...nn,...e}}var xt=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(fl(t))),e.instance}static resetInstance(){e.instance&&(e.instance.forceDeactivate(),e.instance=null)}static isInSandboxedContext(){return $e?$e?.getStore()?.sandboxActive===!0:!1}static getCurrentExecutionId(){if($e)return $e?.getStore()?.executionId}updateConfig(t){this.config={...this.config,...t}}activate(){if(Jt||!this.config.enabled){let s=oo();return{run:r=>r(),deactivate:()=>{},executionId:s}}this.refCount++,this.refCount===1&&(this.applyPatches(),this.activationTime=Date.now());let t=oo();return{run:s=>$e.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 Jt||this.config.auditMode||!$e?!1:$e?.getStore()?.sandboxActive===!0}recordViolation(t,s,r){let n={timestamp:Date.now(),type:t,message:r,path:s,stack:new Error().stack,executionId:$e?.getStore()?.executionId};if(this.violations.length<ul&&this.violations.push(n),this.config.onViolation)try{this.config.onViolation(n)}catch(i){console.debug("[DefenseInDepthBox] onViolation callback threw:",i instanceof Error?i.message:i)}return n}createBlockingProxy(t,s,r){let n=this;return new Proxy(t,{apply(i,a,o){if(n.shouldBlock()){let l=`${s} is blocked during script execution`,u=n.recordViolation(r,s,l);throw new ye(l,u)}return n.config.auditMode&&$e?.getStore()?.sandboxActive===!0&&n.recordViolation(r,s,`${s} called (audit mode)`),Reflect.apply(i,a,o)},construct(i,a,o){if(n.shouldBlock()){let l=`${s} constructor is blocked during script execution`,u=n.recordViolation(r,s,l);throw new ye(l,u)}return n.config.auditMode&&$e?.getStore()?.sandboxActive===!0&&n.recordViolation(r,s,`${s} constructor called (audit mode)`),Reflect.construct(i,a,o)}})}createBlockingObjectProxy(t,s,r){let n=this;return new Proxy(t,{get(i,a,o){if(n.shouldBlock()){let l=`${s}.${String(a)}`,u=`${l} is blocked during script execution`,c=n.recordViolation(r,l,u);throw new ye(u,c)}if(n.config.auditMode&&$e?.getStore()?.sandboxActive===!0){let l=`${s}.${String(a)}`;n.recordViolation(r,l,`${l} accessed (audit mode)`)}return Reflect.get(i,a,o)},set(i,a,o,l){if(n.shouldBlock()){let u=`${s}.${String(a)}`,c=`${u} modification is blocked during script execution`,f=n.recordViolation(r,u,c);throw new ye(c,f)}return Reflect.set(i,a,o,l)},ownKeys(i){if(n.shouldBlock()){let a=`${s} enumeration is blocked during script execution`,o=n.recordViolation(r,s,a);throw new ye(a,o)}return Reflect.ownKeys(i)},getOwnPropertyDescriptor(i,a){if(n.shouldBlock()){let o=`${s}.${String(a)}`,l=`${o} descriptor access is blocked during script execution`,u=n.recordViolation(r,o,l);throw new ye(l,u)}return Reflect.getOwnPropertyDescriptor(i,a)},has(i,a){if(n.shouldBlock()){let o=`${s}.${String(a)}`,l=`${o} existence check is blocked during script execution`,u=n.recordViolation(r,o,l);throw new ye(l,u)}return Reflect.has(i,a)}})}applyPatches(){let t=rn();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 r=s?.value;Object.defineProperty(Error,"prepareStackTrace",{get(){return r},set(n){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 ye(i,a)}t.config.auditMode&&$e?.getStore()?.sandboxActive===!0&&t.recordViolation("error_prepare_stack_trace","Error.prepareStackTrace","Error.prepareStackTrace set (audit mode)"),r=n},configurable:!0})}catch(s){console.debug("[DefenseInDepthBox] Could not protect Error.prepareStackTrace:",s instanceof Error?s.message:s)}}patchPrototypeConstructor(t,s,r){let n=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(n.shouldBlock()){let o=`${s} access is blocked during script execution`,l=n.recordViolation(r,s,o);throw new ye(o,l)}return n.config.auditMode&&$e?.getStore()?.sandboxActive===!0&&n.recordViolation(r,s,`${s} accessed (audit mode)`),a},set(o){if(n.shouldBlock()){let l=`${s} modification is blocked during script execution`,u=n.recordViolation(r,s,l);throw new ye(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 r=s?.value;r!==void 0&&Object.defineProperty(process,"mainModule",{get(){if(t.shouldBlock()){let n="process.mainModule access is blocked during script execution",i=t.recordViolation("process_main_module","process.mainModule",n);throw new ye(n,i)}return t.config.auditMode&&$e?.getStore()?.sandboxActive===!0&&t.recordViolation("process_main_module","process.mainModule","process.mainModule accessed (audit mode)"),r},set(n){if(t.shouldBlock()){let i="process.mainModule modification is blocked during script execution",a=t.recordViolation("process_main_module","process.mainModule",i);throw new ye(i,a)}Object.defineProperty(process,"mainModule",{value:n,writable:!0,configurable:!0})},configurable:!0})}catch(s){console.debug("[DefenseInDepthBox] Could not protect process.mainModule:",s instanceof Error?s.message:s)}}protectModuleLoad(){if(!Jt)try{let t=null;if(typeof process<"u"){let a=process.mainModule;a&&typeof a=="object"&&(t=a.constructor)}if(!t&&typeof Dt<"u"&&typeof Dt.main<"u"&&(t=Dt.main.constructor),!t||typeof t._load!="function")return;let s=t._load,r=Object.getOwnPropertyDescriptor(t,"_load");this.originalDescriptors.push({target:t,prop:"_load",descriptor:r});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:r,violationType:n,strategy:i}=t;try{let a=s[r];if(a===void 0)return;let o=Object.getOwnPropertyDescriptor(s,r);if(this.originalDescriptors.push({target:s,prop:r,descriptor:o}),i==="freeze")typeof a=="object"&&a!==null&&Object.freeze(a);else{let l=this.getPathForTarget(s,r),u=typeof a=="function"?this.createBlockingProxy(a,l,n):this.createBlockingObjectProxy(a,l,n);Object.defineProperty(s,r,{value:u,writable:!0,configurable:!0})}}catch(a){let o=this.getPathForTarget(s,r);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:r,descriptor:n}=this.originalDescriptors[t];try{n?Object.defineProperty(s,r,n):delete s[r]}catch(i){let a=this.getPathForTarget(s,r);console.debug(`[DefenseInDepthBox] Could not restore ${a}:`,i instanceof Error?i.message:i)}}this.originalDescriptors=[]}};var dl=globalThis.setTimeout.bind(globalThis),Kt=class{fs;processes;commands=new Map;useDefaultLayout=!1;limits;secureFetch;sleepFn;traceFn;logger;defenseInDepthConfig;coverageWriter;state;constructor(t={}){let s=t.fs??new Xe(t.files);this.fs=s,this.processes=t.processes??new Le,this.useDefaultLayout=!t.cwd&&!t.files;let r=t.cwd||(this.useDefaultLayout?"/home/user":"/"),n=new Map,i=[["HOME",this.useDefaultLayout?"/home/user":"/"],["PATH","/usr/bin:/bin"],["IFS",`
691
- `],["OSTYPE","linux-gnu"],["MACHTYPE","x86_64-pc-linux-gnu"],["HOSTTYPE","x86_64"],["HOSTNAME","localhost"],["PWD",r],["OLDPWD",r],["OPTIND","1"]];for(let[a,o]of i)g(n,a,o);for(let[a,o]of Object.entries(t.env??{}))g(n,a,o);if(this.limits=ro({...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=sn(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:n,cwd:r,previousDir:"/home/user",functions:new Map,localScopes:[],callDepth:0,sourceDepth:0,commandCount:0,lastExitCode:0,lastArg:R,startTime:Date.now(),lastBackgroundPid:0,bashPid:Us().pid,nextVirtualPid:Us().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},g(this.state.env,"SHELLOPTS",Qs(this.state.options)),g(this.state.env,"BASHOPTS",er(this.state.shoptOptions)),Fn(s,this.useDefaultLayout),r!=="/"&&s instanceof Xe)try{s.mkdirSync(r,{recursive:!0})}catch{}for(let a of Nn(t.commands))this.registerCommand(a);if(t.network)for(let a of On())this.registerCommand(a);if(t.python)for(let a of Dn())this.registerCommand(a);if(t.customCommands)for(let a of t.customCommands)In(a)?this.registerCommand(Rn(a)):this.registerCommand(a)}registerCommand(t){this.commands.set(t.name,t);let s=this.fs;if(typeof s.writeFileSync=="function"){let r=`#!/bin/bash
671
+ `));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)}
672
+ `),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 se(e,()=>Promise.resolve(A(`bash: ${d}: No such file or directory
673
+ `)))}}}(c||o.length>0)&&(e.state.groupStdin=l);let u=0;for(let f of t.body){let d=await r(f);u=(await se(e,()=>Promise.resolve(d))).exitCode}return F(P(),P(),u)}catch(a){let{diagnosticWritten:o,writeFailure:l}=await Qe(e,a);if(l)return l;if(ss(a)||a instanceof ke||a instanceof q||a instanceof be||a instanceof He||a instanceof ae)throw a;return o||await se(e,()=>Promise.resolve(A(`${Ge(a)}
674
+ `))),F(P(),P(),1)}finally{e.state.groupStdin=i}})}async function so(e,t,s,r,n){let i;try{i=await e.fs.readFileText(t)}catch{return A(`bash: ${t}: No such file or directory
675
+ `,127)}if(i.startsWith("#!")){let v=i.indexOf(`
676
+ `);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 re(r);v.length>0&&(e.state.groupStdin=fe(v)),e.state.currentSource=t,g(e.state.env,"0",t),g(e.state.env,"#",String(s.length)),g(e.state.env,"@",s.join(" ")),g(e.state.env,"*",s.join(" "));for(let y=0;y<s.length&&y<9;y++)g(e.state.env,String(y+1),s[y]);for(let y=s.length+1;y<=9;y++)e.state.env.delete(String(y));let S=new X().parse(i),b=await n(S);return await se(e,()=>Promise.resolve(b))}catch(v){let{writeFailure:E}=await Qe(e,v);if(E)return E;if(v instanceof q||v instanceof ae)throw v;if(v.name==="ParseException")return A(`bash: ${t}: ${v.message}
677
+ `);throw v}finally{h()}}function tl(e,t){for(let s of t.parts)switch(s.type){case"Bytes":case"Literal":case"SingleQuoted":case"Escaped":continue;case"DoubleQuoted":for(let r of s.parts)switch(r.type){case"Bytes":case"Literal":case"SingleQuoted":case"Escaped":continue;case"ParameterExpansion":if(r.operation||r.parameter==="@"||r.parameter==="*"||r.parameter.endsWith("[@]")||r.parameter.endsWith("[*]"))return!1;if(Ee(e,r.parameter)){let n=ze(e,r.parameter);if(n&&(n.endsWith("[@]")||n.endsWith("[*]")))return!1}continue;case"CommandSubstitution":continue;default:return!1}continue;case"ParameterExpansion":return!1;default:return!1}return t.parts.length>0}var Xt=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,r=new Set;if(t)for(let i of t)r.add(i);if(s)for(let i of s)r.add(i);if(r.size===0)return Object.create(null);let n=Object.create(null);for(let i of r)this.ctx.state.env.has(i)&&(n[i]=N(this.ctx.state.env,i));return n}async executeRootScript(t){let s=await this.executeScript(t);return Ke(this.ctx.signal),Q(this.ctx,s)}async executeScript(t){let s=0;for(let r of t.statements)try{let n=await this.executeStatement(r),i=this.ctx.signal?.aborted===!0&&n.exitCode===new pe(this.ctx.signal.reason).exitCode;await Q(this.ctx,n,!i),s=n.exitCode,this.ctx.state.lastExitCode=s,g(this.ctx.state.env,"?",String(s))}catch(n){if(await te(this.ctx,n),n instanceof q)throw n;if(n instanceof be)return s=n.exitCode,this.ctx.state.lastExitCode=s,g(this.ctx.state.env,"?",String(s)),{stdout:P(),stderr:P(),exitCode:s,env:Ye(this.ctx.state.env)};if(n instanceof ae)throw n;if(n instanceof ke)return s=n.exitCode,this.ctx.state.lastExitCode=s,g(this.ctx.state.env,"?",String(s)),{stdout:P(),stderr:P(),exitCode:s,env:Ye(this.ctx.state.env)};if(n instanceof un)return s=1,this.ctx.state.lastExitCode=s,g(this.ctx.state.env,"?",String(s)),{stdout:P(),stderr:P(),exitCode:s,env:Ye(this.ctx.state.env)};if(n instanceof It)return s=1,this.ctx.state.lastExitCode=s,g(this.ctx.state.env,"?",String(s)),{stdout:P(),stderr:P(),exitCode:s,env:Ye(this.ctx.state.env)};if(n instanceof nt){s=1,this.ctx.state.lastExitCode=s,g(this.ctx.state.env,"?",String(s));continue}if(n instanceof fn){s=1,this.ctx.state.lastExitCode=s,g(this.ctx.state.env,"?",String(s));continue}if(n instanceof Ae||n instanceof Ce){if(this.ctx.state.loopDepth>0)throw n;continue}throw n instanceof ve,n}return{stdout:P(),stderr:P(),exitCode:s,env:Ye(this.ctx.state.env)}}async executeUserScript(t,s,r=P()){return so(this.ctx,t,ft(s),r,n=>this.executeScript(n))}async executeStatement(t){if(Ke(this.ctx.signal),this.ctx.state.commandCount++,this.ctx.state.commandCount>this.ctx.limits.maxCommandCount&&Me(`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)),Ke(this.ctx.signal)),t.deferredError)throw new rs(t.deferredError.message,t.line??1,1);if(this.ctx.state.options.noexec)return U();if(this.ctx.state.errexitSafe=!1,this.ctx.state.options.verbose&&!this.ctx.state.suppressVerbose&&t.sourceText&&await H(this.ctx,2,`${t.sourceText}
678
+ `),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
679
+ `),A("",ae.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,E])=>[v,E?.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(E=>({...E,value:E.value?.slice()}))]))}:{},...o.fullyUnsetLocals?{fullyUnsetLocals:new Map(o.fullyUnsetLocals)}:{},...o.tempEnvBindings?{tempEnvBindings:o.tempEnvBindings.map(h=>new Map([...h].map(([v,E])=>[v,E?.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=>it(u,(v,E)=>c.observesOutput?xe({write(S){return c.observeOutput(h,v,S),E.write(S)}},!1):E),d=t.sourceText?.trim()||"<background job>",p=c.createLineageId(),m;try{m=c.start(d,async(h,v)=>{let E=f(h);l.bashPid=h,l.nextVirtualPid=Math.max(l.nextVirtualPid,h+1);let S=Mt(this.ctx.signal,v),b=new e({fs:this.ctx.fs,commands:this.ctx.commands,processes:c,lineageId:p,outputChannels:E,limits:this.ctx.limits,jobTracker:this.ctx.jobTracker,exec:(y,k)=>this.ctx.execFn(y,{...k,signal:Mt(S,k?.signal)}),fetch:this.ctx.fetch,sleep:this.ctx.sleep,trace:this.ctx.trace,coverage:this.ctx.coverage,signal:S},l);try{return(await b.executeRootScript({type:"Script",statements:[{...t,background:!1,sourceText:void 0}]})).exitCode}catch(y){if(y instanceof pe||y instanceof q)return y.exitCode;if(y instanceof ae)return this.ctx.jobTracker.limitExceeded=!0,ae.EXIT_CODE;throw y}},this.ctx.lineageId),this.ctx.jobTracker.started=!0}catch(h){return await H(this.ctx,2,`bash: ${h instanceof Error?h.message:String(h)}
680
+ `),A("",1)}return this.ctx.state.lastBackgroundPid=m,U()}let s=0,r=-1,n=!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,r=o,n=l.negated,this.ctx.state.lastExitCode=s,g(this.ctx.state.env,"?",String(s))}let i=r<t.pipelines.length-1,a=this.ctx.state.errexitSafe;if(this.ctx.state.errexitSafe=i||n||a,this.ctx.state.options.errexit&&s!==0&&r===t.pipelines.length-1&&!n&&!this.ctx.state.inCondition&&!a)throw new ke(s);return{stdout:P(),stderr:P(),exitCode:s}}async executePipeline(t){return Ki(this.ctx,t,(s,r)=>this.executeCommand(s,r))}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 Hi(this.ctx,t);case"For":return Gi(this.ctx,t);case"CStyleFor":return qi(this.ctx,t);case"While":return Zi(this.ctx,t,s);case"Until":return Xi(this.ctx,t);case"Case":return Ji(this.ctx,t);case"Subshell":return this.executeSubshell(t,s);case"Group":return this.executeGroup(t,s);case"FunctionDef":return ui(this.ctx,t);case"ArithmeticCommand":return this.executeArithmeticCommand(t);case"ConditionalCommand":return this.executeConditionalCommand(t);default:return U()}}async executeSimpleCommand(t,s){this.ctx.reportedDiagnostics=new WeakSet;try{return await this.executeSimpleCommandInner(t,s)}catch(r){if(r instanceof es)return await te(this.ctx,r),{stdout:P(),stderr:P(),exitCode:1};throw r}}async executeSimpleCommandInner(t,s){if(t.line!==void 0&&(this.ctx.state.currentLine=t.line),this.ctx.state.shoptOptions.expand_aliases&&t.name){let $=t,C=100;for(;C>0;){let O=this.expandAlias($);if(O===$)break;$=O,C--}this.aliasExpansionStack.clear(),$!==t&&(t=$)}let r=await Yi(this.ctx,t);if(r.error)return r.error;let n=r.tempAssignments,i=r.xtraceOutput;if(!t.name){if(await H(this.ctx,2,i),t.redirections.length>0){let $=this.ctx.outputChannels,C=await De(this.ctx,$,t.redirections);if(C.error)return await Y(this.ctx,C.channels,()=>se(this.ctx,()=>Promise.resolve(C.error)));let O={stdout:P(),stderr:P(),exitCode:0},I=[1,2].filter(T=>{let x=$.bindings.get(T),w=C.channels.bindings.get(T);return x?.sink!==w?.sink||We($,T)!==We(C.channels,T)});return await Y(this.ctx,C.channels,()=>se(this.ctx,()=>Promise.resolve(O),I))}return this.ctx.state.lastArg=W(""),{stdout:P(),stderr:P(),exitCode:this.ctx.state.lastExitCode}}let a=t.name&&jt(t.name,["local","declare","typeset","export","readonly"]),o=Array.from(n.keys());if(o.length>0&&!a){this.ctx.state.tempExportedVars=this.ctx.state.tempExportedVars||new Set;for(let $ of o)this.ctx.state.tempExportedVars.add($)}let l=-1,c=jt(t.name,["exec"])&&(t.args.length===0||t.args.length===1&&jt(t.args[0],["--"])),u=await z(this.ctx,t.name),f=[],d=[];if(jt(t.name,["local","declare","typeset","export","readonly"])&&(u==="local"||u==="declare"||u==="typeset"||u==="export"||u==="readonly"))for(let $ of t.args){let C=await Un(this.ctx,$);if(C)f.push(W(C)),d.push(!0);else{let O=await Hn(this.ctx,$);if(O!==null)f.push(W(O)),d.push(!0);else{let I=await je(this.ctx,$);for(let T of I.values)f.push(W(T)),d.push(I.quoted)}}}else for(let $ of t.args)if(tl(this.ctx,$))f.push(await pt(this.ctx,$)),d.push(!0);else{let C=await je(this.ctx,$);for(let O of C.values)f.push(W(O)),d.push(C.quoted)}let m=this.ctx.outputChannels,h=!c&&t.redirections.length>0?await De(this.ctx,m,t.redirections,{persistMovedSource:Je.has(u)}):void 0;if(h?.error){await H(this.ctx,2,i);for(let[$,C]of n)C===void 0?this.ctx.state.env.delete($):this.ctx.state.env.set($,C);return await Y(this.ctx,h.channels,()=>se(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 C=$.fd??0;return($.operator==="<"||$.operator==="<&")&&C===0}),E=null,S=R;v?S=await re(s):E=s;let b=h?.legacyRedirections??t.redirections;for(let $ of b)if(!($.fdVariable||c&&($.operator==="<"||$.operator==="<&"))){if(($.operator==="<<"||$.operator==="<<-")&&$.target.type==="HereDoc"){let C=$.target,O=$.fd??0;if(O===0&&!C.stripTabs)S=await pt(this.ctx,C.content);else{let I=await z(this.ctx,C.content);C.stripTabs&&(I=I.split(`
681
+ `).map(T=>T.replace(/^\t+/,"")).join(`
682
+ `)),O!==0?(this.ctx.state.fileDescriptors||(this.ctx.state.fileDescriptors=new Map),this.ctx.state.fileDescriptors.set(O,I)):S=W(I)}continue}if($.operator==="<<<"&&$.target.type==="Word"){let C=await pt(this.ctx,$.target);S=ln(C,W(`
683
+ `));continue}if($.operator==="<"&&$.target.type==="Word")try{let C=await z(this.ctx,$.target),O=this.ctx.fs.resolvePath(this.ctx.state.cwd,C);S=await re(await this.ctx.fs.readFile(O))}catch{let C=await z(this.ctx,$.target);for(let[O,I]of n)I===void 0?this.ctx.state.env.delete(O):this.ctx.state.env.set(O,I);return A(await Bt(this.ctx,C))}if($.operator==="<&"&&($.fd??0)===0&&$.target.type==="Word"){let C=await z(this.ctx,$.target),O=C.startsWith("&")?C.slice(1):C;if(O!=="-"&&!/^\d+-?$/.test(O)){for(let[T,x]of n)x===void 0?this.ctx.state.env.delete(T):this.ctx.state.env.set(T,x);return A(`bash: ${C}: ambiguous redirect
684
+ `)}let I=Number.parseInt(O,10);if(!Number.isNaN(I)&&We(this.ctx.outputChannels,I)){for(let[T,x]of n)x===void 0?this.ctx.state.env.delete(T):this.ctx.state.env.set(T,x);return A(Ue(I))}if(!Number.isNaN(I)&&this.ctx.state.fileDescriptors){let T=this.ctx.state.fileDescriptors.get(I);if(T!==void 0)if(T.startsWith("__rw__:")){let x=Ps(T);x&&(S=W(x.content.slice(x.position)),l=I)}else T.startsWith("__file__:")||T.startsWith("__file_append__:")||(S=W(T));else if(I>=3&&!this.ctx.outputChannels.bindings.get(I)?.sink){for(let[x,w]of n)w===void 0?this.ctx.state.env.delete(x):this.ctx.state.env.set(x,w);return A(Ue(I))}}else if(!Number.isNaN(I)&&I>=3&&!this.ctx.outputChannels.bindings.get(I)?.sink){for(let[T,x]of n)x===void 0?this.ctx.state.env.delete(T):this.ctx.state.env.set(T,x);return A(Ue(I))}}}if(!u){if(t.name.parts.every(C=>C.type==="CommandSubstitution"||C.type==="ParameterExpansion"||C.type==="ArithmeticExpansion")){if(f.length>0){let C=B(f.shift());return d.shift(),await this.runCommand(C,f,d,E??fe(S),!1,!1,l)}return{stdout:P(),stderr:P(),exitCode:this.ctx.state.lastExitCode}}return A(`bash: : command not found
685
+ `,127)}await H(this.ctx,2,i);let y=await Fs(this.ctx,u,f.map($=>B($)));if(await H(this.ctx,2,y),u==="exec"&&(f.length===0||B(f[0])==="--")){let $=[],C=this.ctx.outputChannels;for(;C;)$.push([C,new Map(C.bindings)]),C=C.parent;let O=this.ctx.state.fileDescriptors?new Map(this.ctx.state.fileDescriptors):void 0,I=this.ctx.state.nextFd,T=new Map;for(let w of t.redirections)w.fdVariable&&!T.has(w.fdVariable)&&T.set(w.fdVariable,this.ctx.state.env.get(w.fdVariable));let x=await ci(this.ctx,t.redirections);if(x.error){let w;try{w=await Y(this.ctx,x.channels,()=>se(this.ctx,()=>Promise.resolve(x.error)))}finally{for(let[D,M]of $)D.bindings=new Map(M);this.ctx.state.fileDescriptors=O,this.ctx.state.nextFd=I;for(let[D,M]of T)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{let K=await Bt(this.ctx,D);j=await se(this.ctx,()=>Promise.resolve(A(K)))}finally{for(let[K,oe]of $)K.bindings=new Map(oe);this.ctx.state.fileDescriptors=O,this.ctx.state.nextFd=I;for(let[K,oe]of T)oe===void 0?this.ctx.state.env.delete(K):this.ctx.state.env.set(K,oe)}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 K=this.ctx.state.fileDescriptors.get(j)??`__dupin__:${j}`;this.ctx.state.fileDescriptors.set(M,K),J&&this.ctx.state.fileDescriptors.delete(j)}}}for(let[w,D]of n)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 n.keys())this.ctx.state.tempExportedVars.delete(w);return U()}n.size>0&&(this.ctx.state.tempEnvBindings=this.ctx.state.tempEnvBindings||[],this.ctx.state.tempEnvBindings.push(new Map(n)));let k,_=null,L=h?[1,2].filter($=>{let C=m.bindings.get($),O=h.channels.bindings.get($);return C?.sink!==O?.sink||We(m,$)!==We(h.channels,$)}):[];try{try{let $=()=>this.runCommand(u,f,d,E??fe(S),!1,!1,l);k=h?await Y(this.ctx,h.channels,$):await $()}catch($){let C=null;if(h&&(C=(await Y(this.ctx,h.channels,()=>Qe(this.ctx,$,L))).writeFailure,C&&(k=C)),!C)if($ instanceof Ae||$ instanceof Ce)_=$,k=U();else throw $}if(k.exitCode===127&&Je.has(u)&&h?.channels.bindings.get(1)?.descriptor==="__file__:/dev/full"&&(k=G(`
686
+ `)),h&&L.length>0&&(k=await Y(this.ctx,h.channels,()=>se(this.ctx,()=>Promise.resolve(k),L))),_)throw _;if(f.length>0){let $=B(f[f.length-1]);if((u==="declare"||u==="local"||u==="typeset")&&/^[a-zA-Z_][a-zA-Z0-9_]*=\(/.test($)){let C=$.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\(/);C&&($=C[1])}this.ctx.state.lastArg=W($)}else this.ctx.state.lastArg=W(u)}finally{let $=ii(u)&&u!=="unset"&&u!=="eval";if(!this.ctx.state.options.posix||!$)for(let[O,I]of n)this.ctx.state.fullyUnsetLocals?.has(O)||(I===void 0?this.ctx.state.env.delete(O):this.ctx.state.env.set(O,I));if(this.ctx.state.tempExportedVars)for(let O of n.keys())this.ctx.state.tempExportedVars.delete(O);n.size>0&&this.ctx.state.tempEnvBindings&&this.ctx.state.tempEnvBindings.pop()}return k}async runCommand(t,s,r,n,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??P())},c=await zi(l,t,s,r,n,i,a,o);return c!==null?c:ji(l,t,s,n,a)}aliasExpansionStack=new Set;expandAlias(t){return rr(this.ctx.state,t,this.aliasExpansionStack)}async findCommandInPath(t){return Rs(this.ctx,t)}async executeSubshell(t,s=P()){return eo(this.ctx,t,s,r=>this.executeStatement(r))}async executeGroup(t,s=P()){return to(this.ctx,t,s,r=>this.executeStatement(r))}async executeArithmeticCommand(t){t.line!==void 0&&(this.ctx.state.currentLine=t.line);let s=this.ctx.outputChannels,r=await De(this.ctx,s,t.redirections);if(r.error)return Y(this.ctx,r.channels,()=>se(this.ctx,()=>Promise.resolve(r.error)));let n=[1,2].filter(i=>{let a=s.bindings.get(i),o=r.channels.bindings.get(i);return a?.sink!==o?.sink||We(s,i)!==We(r.channels,i)});return Y(this.ctx,r.channels,async()=>{let i;try{let a=await ee(this.ctx,t.expression.expression);i=le(a!==0)}catch(a){i=A(`bash: arithmetic expression: ${a.message}
687
+ `)}return n.length>0?se(this.ctx,()=>Promise.resolve(i),n):i})}async executeConditionalCommand(t){t.line!==void 0&&(this.ctx.state.currentLine=t.line);let s=this.ctx.outputChannels,r=await De(this.ctx,s,t.redirections);if(r.error)return Y(this.ctx,r.channels,()=>se(this.ctx,()=>Promise.resolve(r.error)));let n=[1,2].filter(i=>{let a=s.bindings.get(i),o=r.channels.bindings.get(i);return a?.sink!==o?.sink||We(s,i)!==We(r.channels,i)});return Y(this.ctx,r.channels,async()=>{let i;try{let a=await tt(this.ctx,t.expression);i=le(a)}catch(a){let o=a instanceof nt?1:2;i=A(`bash: conditional expression: ${a.message}
688
+ `,o)}return n.length>0?se(this.ctx,()=>Promise.resolve(i),n):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 ro(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 no(e){try{let t=new URL(e);return{origin:t.origin,pathname:t.pathname,href:t.href}}catch{return null}}function sl(e){let t=no(e);return t?{origin:t.origin,pathPrefix:t.pathname}:null}function rl(e,t){let s=no(e);if(!s)return!1;let r=sl(t);return!r||s.origin!==r.origin?!1:r.pathPrefix==="/"||r.pathPrefix===""?!0:s.pathname.startsWith(r.pathPrefix)}function sn(e,t){return!t||t.length===0?!1:t.some(s=>rl(e,s))}var At=class extends Error{constructor(t){super(`Network access denied: URL not in allow-list: ${t}`),this.name="NetworkAccessDeniedError"}},Ct=class extends Error{constructor(t){super(`Too many redirects (max: ${t})`),this.name="TooManyRedirectsError"}},kt=class extends Error{constructor(t){super(`Redirect target not in allow-list: ${t}`),this.name="RedirectNotAllowedError"}},Ws=class extends Error{constructor(t,s){super(`HTTP method '${t}' not allowed. Allowed methods: ${s.join(", ")}`),this.name="MethodNotAllowedError"}},Jt=class extends Error{constructor(t){super(`Response body too large (max: ${t} bytes)`),this.name="ResponseTooLargeError"}};var nl=20,il=3e4,ol=10485760,al=["GET","HEAD"],ll=new Set(["GET","HEAD","OPTIONS"]),cl=new Set([301,302,303,307,308]);function rn(e){let t=e.maxRedirects??nl,s=e.timeoutMs??il,r=e.maxResponseSize??ol,n=e.dangerouslyAllowFullInternetAccess?["GET","HEAD","POST","PUT","DELETE","PATCH","OPTIONS"]:e.allowedMethods??al;function i(l){if(!e.dangerouslyAllowFullInternetAccess&&!sn(l,e.allowedUrlPrefixes??[]))throw new At(l)}function a(l){if(e.dangerouslyAllowFullInternetAccess)return;let c=l.toUpperCase();if(!n.includes(c))throw new Ws(c,n)}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 E={method:u,headers:c.headers,signal:h.signal,redirect:"manual"};c.body&&!ll.has(u)&&(E.body=c.body);let S=await fetch(f,E);if(cl.has(S.status)&&p){let b=S.headers.get("location");if(!b)return await io(S,f,r);let y=new URL(b,f).href;if(!e.dangerouslyAllowFullInternetAccess&&!sn(y,e.allowedUrlPrefixes??[]))throw new kt(y);if(d++,d>t)throw new Ct(t);f=y;continue}return await io(S,f,r)}finally{clearTimeout(v)}}}return o}async function io(e,t,s){let r=Object.create(null);if(e.headers.forEach((i,a)=>{r[a.toLowerCase()]=i}),s>0){let i=e.headers.get("content-length");if(i){let a=parseInt(i,10);if(!Number.isNaN(a)&&a>s)throw new Jt(s)}}let n;if(s>0&&e.body){let i=e.body.getReader(),a=new TextDecoder,o=[],l=0;for(;;){let{done:c,value:u}=await i.read();if(c)break;if(l+=u.byteLength,l>s)throw i.cancel(),new Jt(s);o.push(a.decode(u,{stream:!0}))}o.push(a.decode()),n=o.join("")}else n=await e.text();return{status:e.status,statusText:e.statusText,headers:r,body:n,url:t}}var ul=1e3,fl=4096,dl=globalThis.setTimeout.bind(globalThis),hl=globalThis.clearTimeout.bind(globalThis),Le=class{jobs=new Map;reapedWaitStatuses=new Map;reapedWaitLineages=new Map;reapedJobNumbers=new Map;options;nextPid=ul;nextLineageId=1;highestJobNumber=0;runningJobs=0;disposed=!1;disposePromise;constructor(t={}){this.options=t}start(t,s,r){if(this.disposed)throw new Error("Cannot start a job on a disposed ProcessTable");let n=this.nextPid++,i=new AbortController,a=this.highestJobNumber+1,o={info:{pid:n,command:t,startedAt:Date.now(),state:"running"},jobNumber:a,lineageId:r,controller:i,promise:Promise.resolve(0)};return this.jobs.set(n,o),this.highestJobNumber=a,this.runningJobs++,o.promise=Promise.resolve().then(()=>s(n,i.signal)).catch(()=>i.signal.aborted?ts(i.signal.reason):1).then(l=>{let c=this.jobs.get(n)===o;c&&this.runningJobs--,o.info={...o.info,state:"done",exitCode:l},o.controller=void 0,o.promise=void 0,c&&(this.rememberWaitStatus(n,l,o.lineageId,o.jobNumber),this.deleteJobs([n]));try{Promise.resolve(this.options.onJobExit?.(n,l)).catch(()=>{})}catch{}return l}),n}list(){return[...this.jobs.values()].sort((t,s)=>t.jobNumber-s.jobNumber).map(t=>({...t.info}))}listJobs(t,s={}){let r=[...this.jobs.values()].sort((o,l)=>o.jobNumber-l.jobNumber),n=r.at(-1)?.info.pid,i=r.at(-2)?.info.pid,a=[];for(let o of r)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===n?"+":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,r){let n=this.jobs.get(t);return!n||n.info.state==="done"?!1:(s!=="SIGSTOP"&&s!=="SIGCONT"&&n.controller?.abort(r??s),!0)}async wait(t){if(t!==void 0){let n=this.jobs.get(t);if(!n)return this.reapedWaitStatuses.get(t)??127;let i=n.info.state==="done"?n.info.exitCode??1:await(n.promise??Promise.resolve(1));return this.jobs.get(t)===n&&(this.rememberWaitStatus(t,i,n.lineageId),this.deleteJobs([t])),i}let s=[...this.jobs.values()],r=new Set([...this.reapedWaitStatuses.keys(),...s.map(n=>n.info.pid)]);s.length>0&&(await Promise.all(s.map(n=>n.promise??Promise.resolve(n.info.exitCode??1))),this.deleteJobs(s.map(n=>n.info.pid)));for(let n of r)this.forgetWaitStatus(n);return 0}async waitForLineage(t){let s=new Set;for(;;){let r=[...this.jobs.values()].filter(n=>n.lineageId===t);if(r.length===0)break;await Promise.all(r.map(n=>n.promise??Promise.resolve(n.info.exitCode??1)));for(let n of r)s.add(n.info.pid);this.deleteJobs(r.map(n=>n.info.pid))}for(let[r,n]of this.reapedWaitLineages)n===t&&s.add(r);for(let r of s)this.forgetWaitStatus(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(n=>{s=n}),this.abortAll("SIGKILL"),this.jobs.clear(),this.reapedWaitStatuses.clear(),this.reapedWaitLineages.clear(),this.reapedJobNumbers.clear(),this.highestJobNumber=0,this.runningJobs=0;let r=dl(s,this.options.disposeTimeoutMs??1e3);return r.unref?.(),Promise.allSettled(t.flatMap(n=>n.promise?[n.promise]:[])).then(()=>{hl(r),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 r=/^%(\d+)$/.exec(t);if(!r)return;let n=Number.parseInt(r[1],10);return s.find(i=>i.jobNumber===n)?.info.pid??this.reapedJobNumbers.get(n)}get observesOutput(){return this.options.onJobOutput!==void 0}observeOutput(t,s,r){try{Promise.resolve(this.options.onJobOutput?.(t,s,r)).catch(()=>{})}catch{}}rememberWaitStatus(t,s,r,n){if(this.forgetWaitStatus(t),this.reapedWaitStatuses.set(t,s),this.reapedWaitLineages.set(t,r),n!==void 0&&this.reapedJobNumbers.set(n,t),this.reapedWaitStatuses.size>fl){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,r]of this.reapedJobNumbers)r===t&&this.reapedJobNumbers.delete(s)}deleteJobs(t){let s=!1;for(let r of t){let n=this.jobs.get(r);n&&(this.jobs.delete(r),s||=n.jobNumber===this.highestJobNumber)}if(s){this.highestJobNumber=0;for(let r of this.jobs.values())this.highestJobNumber=Math.max(this.highestJobNumber,r.jobNumber)}}};function nn(){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 Kt=typeof __BROWSER__<"u"&&__BROWSER__;function oo(){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 an=null;if(!Kt)try{let e="node:module",{createRequire:t}=await import(e);an=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 pl=`
689
+
690
+ This is a defense-in-depth measure and indicates a bug in just-bash. Please report this at security@vercel.com`,ye=class extends Error{violation;constructor(t,s){super(t+pl),this.violation=s,this.name="SecurityViolationError"}},$e=!Kt&&an?new an:null,ml=1e3,on={enabled:!0,auditMode:!1};function yl(e){return e===void 0?{...on,enabled:!1}:typeof e=="boolean"?{...on,enabled:e}:{...on,...e}}var Tt=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(yl(t))),e.instance}static resetInstance(){e.instance&&(e.instance.forceDeactivate(),e.instance=null)}static isInSandboxedContext(){return $e?$e?.getStore()?.sandboxActive===!0:!1}static getCurrentExecutionId(){if($e)return $e?.getStore()?.executionId}updateConfig(t){this.config={...this.config,...t}}activate(){if(Kt||!this.config.enabled){let s=oo();return{run:r=>r(),deactivate:()=>{},executionId:s}}this.refCount++,this.refCount===1&&(this.applyPatches(),this.activationTime=Date.now());let t=oo();return{run:s=>$e.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 Kt||this.config.auditMode||!$e?!1:$e?.getStore()?.sandboxActive===!0}recordViolation(t,s,r){let n={timestamp:Date.now(),type:t,message:r,path:s,stack:new Error().stack,executionId:$e?.getStore()?.executionId};if(this.violations.length<ml&&this.violations.push(n),this.config.onViolation)try{this.config.onViolation(n)}catch(i){console.debug("[DefenseInDepthBox] onViolation callback threw:",i instanceof Error?i.message:i)}return n}createBlockingProxy(t,s,r){let n=this;return new Proxy(t,{apply(i,a,o){if(n.shouldBlock()){let l=`${s} is blocked during script execution`,c=n.recordViolation(r,s,l);throw new ye(l,c)}return n.config.auditMode&&$e?.getStore()?.sandboxActive===!0&&n.recordViolation(r,s,`${s} called (audit mode)`),Reflect.apply(i,a,o)},construct(i,a,o){if(n.shouldBlock()){let l=`${s} constructor is blocked during script execution`,c=n.recordViolation(r,s,l);throw new ye(l,c)}return n.config.auditMode&&$e?.getStore()?.sandboxActive===!0&&n.recordViolation(r,s,`${s} constructor called (audit mode)`),Reflect.construct(i,a,o)}})}createBlockingObjectProxy(t,s,r){let n=this;return new Proxy(t,{get(i,a,o){if(n.shouldBlock()){let l=`${s}.${String(a)}`,c=`${l} is blocked during script execution`,u=n.recordViolation(r,l,c);throw new ye(c,u)}if(n.config.auditMode&&$e?.getStore()?.sandboxActive===!0){let l=`${s}.${String(a)}`;n.recordViolation(r,l,`${l} accessed (audit mode)`)}return Reflect.get(i,a,o)},set(i,a,o,l){if(n.shouldBlock()){let c=`${s}.${String(a)}`,u=`${c} modification is blocked during script execution`,f=n.recordViolation(r,c,u);throw new ye(u,f)}return Reflect.set(i,a,o,l)},ownKeys(i){if(n.shouldBlock()){let a=`${s} enumeration is blocked during script execution`,o=n.recordViolation(r,s,a);throw new ye(a,o)}return Reflect.ownKeys(i)},getOwnPropertyDescriptor(i,a){if(n.shouldBlock()){let o=`${s}.${String(a)}`,l=`${o} descriptor access is blocked during script execution`,c=n.recordViolation(r,o,l);throw new ye(l,c)}return Reflect.getOwnPropertyDescriptor(i,a)},has(i,a){if(n.shouldBlock()){let o=`${s}.${String(a)}`,l=`${o} existence check is blocked during script execution`,c=n.recordViolation(r,o,l);throw new ye(l,c)}return Reflect.has(i,a)}})}applyPatches(){let t=nn();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 r=s?.value;Object.defineProperty(Error,"prepareStackTrace",{get(){return r},set(n){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 ye(i,a)}t.config.auditMode&&$e?.getStore()?.sandboxActive===!0&&t.recordViolation("error_prepare_stack_trace","Error.prepareStackTrace","Error.prepareStackTrace set (audit mode)"),r=n},configurable:!0})}catch(s){console.debug("[DefenseInDepthBox] Could not protect Error.prepareStackTrace:",s instanceof Error?s.message:s)}}patchPrototypeConstructor(t,s,r){let n=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(n.shouldBlock()){let o=`${s} access is blocked during script execution`,l=n.recordViolation(r,s,o);throw new ye(o,l)}return n.config.auditMode&&$e?.getStore()?.sandboxActive===!0&&n.recordViolation(r,s,`${s} accessed (audit mode)`),a},set(o){if(n.shouldBlock()){let l=`${s} modification is blocked during script execution`,c=n.recordViolation(r,s,l);throw new ye(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 r=s?.value;r!==void 0&&Object.defineProperty(process,"mainModule",{get(){if(t.shouldBlock()){let n="process.mainModule access is blocked during script execution",i=t.recordViolation("process_main_module","process.mainModule",n);throw new ye(n,i)}return t.config.auditMode&&$e?.getStore()?.sandboxActive===!0&&t.recordViolation("process_main_module","process.mainModule","process.mainModule accessed (audit mode)"),r},set(n){if(t.shouldBlock()){let i="process.mainModule modification is blocked during script execution",a=t.recordViolation("process_main_module","process.mainModule",i);throw new ye(i,a)}Object.defineProperty(process,"mainModule",{value:n,writable:!0,configurable:!0})},configurable:!0})}catch(s){console.debug("[DefenseInDepthBox] Could not protect process.mainModule:",s instanceof Error?s.message:s)}}protectModuleLoad(){if(!Kt)try{let t=null;if(typeof process<"u"){let a=process.mainModule;a&&typeof a=="object"&&(t=a.constructor)}if(!t&&typeof Dt<"u"&&typeof Dt.main<"u"&&(t=Dt.main.constructor),!t||typeof t._load!="function")return;let s=t._load,r=Object.getOwnPropertyDescriptor(t,"_load");this.originalDescriptors.push({target:t,prop:"_load",descriptor:r});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:r,violationType:n,strategy:i}=t;try{let a=s[r];if(a===void 0)return;let o=Object.getOwnPropertyDescriptor(s,r);if(this.originalDescriptors.push({target:s,prop:r,descriptor:o}),i==="freeze")typeof a=="object"&&a!==null&&Object.freeze(a);else{let l=this.getPathForTarget(s,r),c=typeof a=="function"?this.createBlockingProxy(a,l,n):this.createBlockingObjectProxy(a,l,n);Object.defineProperty(s,r,{value:c,writable:!0,configurable:!0})}}catch(a){let o=this.getPathForTarget(s,r);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:r,descriptor:n}=this.originalDescriptors[t];try{n?Object.defineProperty(s,r,n):delete s[r]}catch(i){let a=this.getPathForTarget(s,r);console.debug(`[DefenseInDepthBox] Could not restore ${a}:`,i instanceof Error?i.message:i)}}this.originalDescriptors=[]}};var gl=globalThis.setTimeout.bind(globalThis),Yt=class{fs;processes;commands=new Map;useDefaultLayout=!1;limits;secureFetch;sleepFn;traceFn;logger;defenseInDepthConfig;coverageWriter;state;constructor(t={}){let s=t.fs??new Xe(t.files);this.fs=s,this.processes=t.processes??new Le,this.useDefaultLayout=!t.cwd&&!t.files;let r=t.cwd||(this.useDefaultLayout?"/home/user":"/"),n=new Map,i=[["HOME",this.useDefaultLayout?"/home/user":"/"],["PATH","/usr/bin:/bin"],["IFS",`
691
+ `],["OSTYPE","linux-gnu"],["MACHTYPE","x86_64-pc-linux-gnu"],["HOSTTYPE","x86_64"],["HOSTNAME","localhost"],["PWD",r],["OLDPWD",r],["OPTIND","1"]];for(let[a,o]of i)g(n,a,o);for(let[a,o]of Object.entries(t.env??{}))g(n,a,o);if(this.limits=ro({...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=rn(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:n,cwd:r,previousDir:"/home/user",functions:new Map,localScopes:[],callDepth:0,sourceDepth:0,commandCount:0,lastExitCode:0,lastArg:R,startTime:Date.now(),lastBackgroundPid:0,bashPid:Hs().pid,nextVirtualPid:Hs().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},g(this.state.env,"SHELLOPTS",er(this.state.options)),g(this.state.env,"BASHOPTS",tr(this.state.shoptOptions)),Fn(s,this.useDefaultLayout),r!=="/"&&s instanceof Xe)try{s.mkdirSync(r,{recursive:!0})}catch{}for(let a of Nn(t.commands))this.registerCommand(a);if(t.network)for(let a of On())this.registerCommand(a);if(t.python)for(let a of Dn())this.registerCommand(a);if(t.customCommands)for(let a of t.customCommands)In(a)?this.registerCommand(Rn(a)):this.registerCommand(a)}registerCommand(t){this.commands.set(t.name,t);let s=this.fs;if(typeof s.writeFileSync=="function"){let r=`#!/bin/bash
692
692
  # Built-in command: ${t.name}
693
- `;try{s.writeFileSync(`/bin/${t.name}`,r)}catch{}try{s.writeFileSync(`/usr/bin/${t.name}`,r)}catch{}}}logResult(t,s,r){try{let n=this.logger;if(n){let i=s.text(),a=r.text();i.length>0&&n.debug("stdout",{output:i}),a.length>0&&n.info("stderr",{output:a}),n.info("exit",{exitCode:t.exitCode})}return{...t,stdout:s.stream(),stderr:r.stream()}}finally{s.seal(),r.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:S(),stderr:V(`bash: maximum command count (${this.limits.maxCommandCount}) exceeded (possible infinite loop). Increase with executionLimits.maxCommandCount option.
694
- `),exitCode:1,env:xe(this.state.env,s?.env)};if(!t.trim())return{stdout:S(),stderr:S(),exitCode:0,env:xe(this.state.env,s?.env)};if(s?.signal?.aborted)return{stdout:S(),stderr:S(),exitCode:new pe(s.signal.reason).exitCode,env:xe(this.state.env,s?.env)};let r=new Set,n=y=>{if(y)return{async write(v){try{await y.write(v)}catch(C){throw r.add(C),C}}}},i=_e(n(s?.stdoutSink)),a=_e(n(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[y,v]of Object.entries(s.env))g(p,y,v);f!==void 0&&g(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=hl(t));let E=(this.defenseInDepthConfig?xt.getInstance(this.defenseInDepthConfig):null)?.activate(),$=!1;try{let y=async()=>{let v=Fe(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:(k,A)=>this.exec(k,{...A,jobTracker:u,processes:o,lineageId:l,signal:Mt(s?.signal,A?.signal)}),fetch:this.secureFetch,sleep:this.sleepFn,trace:this.traceFn,coverage:this.coverageWriter,signal:s?.signal},I=await new Zt(C,m).executeRootScript(v);return u.started&&(await new Promise(k=>dl(k,0)),u.limitExceeded&&(I={...I,exitCode:ae.EXIT_CODE})),this.logResult(I,i,a)};return E?await E.run(y):await y()}catch(y){if(r.has(y))throw y;if(y instanceof q)return this.logResult({exitCode:y.exitCode,env:xe(this.state.env,s?.env)},i,a);if(y instanceof be)return this.logResult({exitCode:y.exitCode,env:xe(this.state.env,s?.env)},i,a);if(y instanceof nt)return $||await a.write(W(`bash: ${y.message}
695
- `)),this.logResult({exitCode:1,env:xe(this.state.env,s?.env)},i,a);if(y instanceof pe)return this.logResult({exitCode:y.exitCode,env:xe(this.state.env,s?.env)},i,a);if(y instanceof ae)return this.logResult({exitCode:ae.EXIT_CODE,env:xe(this.state.env,s?.env)},i,a);if(y instanceof ye)return await a.write(W(`bash: security violation: ${y.message}
696
- `)),this.logResult({exitCode:1,env:xe(this.state.env,s?.env)},i,a);if(y.name==="ParseException")return await a.write(W(`bash: syntax error: ${y.message}
697
- `)),this.logResult({exitCode:2,env:xe(this.state.env,s?.env)},i,a);if(y instanceof mn)return await a.write(W(`bash: ${y.message}
698
- `)),this.logResult({exitCode:2,env:xe(this.state.env,s?.env)},i,a);if(y instanceof RangeError)return await a.write(W(`bash: ${y.message}
699
- `)),this.logResult({exitCode:1,env:xe(this.state.env,s?.env)},i,a);throw y}finally{E?.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 Ye(this.state.env)}};function hl(e){let t=e.split(`
700
- `),s=[],r=[];for(let n=0;n<t.length;n++){let i=t[n];if(r.length>0){let l=r[r.length-1];if((l.stripTabs?i.replace(/^\t+/,""):i)===l.delimiter){s.push(i.trimStart()),r.pop();continue}s.push(i);continue}let a=i.trimStart();s.push(a);let o=/<<(-?)\s*(['"]?)([\w-]+)\2/g;for(let l of a.matchAll(o)){let u=l[1]==="-",c=l[3];r.push({delimiter:c,stripTabs:u})}}return s.join(`
701
- `)}var Ws=class{baseFs;mounts=new Map;constructor(t){if(this.baseFs=t?.base??new Xe,t?.mounts)for(let{mountPoint:s,filesystem:r}of t.mounts)this.mount(s,r)}mount(t,s){this.validateMountPath(t);let r=this.normalizePath(t);this.validateMount(r),this.mounts.set(r,{mountPoint:r,filesystem:s})}unmount(t){let s=this.normalizePath(t);if(!this.mounts.has(s))throw new Error(`No filesystem mounted at '${t}'`);this.mounts.delete(s)}getMounts(){return Array.from(this.mounts.values()).map(t=>({mountPoint:t.mountPoint,filesystem:t.filesystem}))}isMountPoint(t){let s=this.normalizePath(t);return this.mounts.has(s)}validateMountPath(t){let s=t.split("/");for(let r of s)if(r==="."||r==="..")throw new Error(`Invalid mount point '${t}': contains '.' or '..' segments`)}validateMount(t){if(t==="/")throw new Error("Cannot mount at root '/'");for(let s of this.mounts.keys())if(s!==t){if(t.startsWith(`${s}/`))throw new Error(`Cannot mount at '${t}': inside existing mount '${s}'`);if(s.startsWith(`${t}/`))throw new Error(`Cannot mount at '${t}': would contain existing mount '${s}'`)}}normalizePath(t){if(!t||t==="/")return"/";let s=t.endsWith("/")&&t!=="/"?t.slice(0,-1):t;s.startsWith("/")||(s=`/${s}`);let r=s.split("/").filter(i=>i&&i!=="."),n=[];for(let i of r)i===".."?n.pop():n.push(i);return`/${n.join("/")}`}routePath(t){let s=this.normalizePath(t),r=null,n=0;for(let i of this.mounts.values()){let a=i.mountPoint;if(s===a)return{fs:i.filesystem,relativePath:"/"};s.startsWith(`${a}/`)&&a.length>n&&(r=i,n=a.length)}if(r){let i=s.slice(n);return{fs:r.filesystem,relativePath:i||"/"}}return{fs:this.baseFs,relativePath:s}}getChildMountPoints(t){let s=this.normalizePath(t),r=s==="/"?"/":`${s}/`,n=[];for(let i of this.mounts.keys())if(i.startsWith(r)){let o=i.slice(r.length).split("/")[0];o&&!n.includes(o)&&n.push(o)}return n}async readFile(t){let{fs:s,relativePath:r}=this.routePath(t);return s.readFile(r)}async readRange(t,s,r){let{fs:n,relativePath:i}=this.routePath(t);return n.readRange(i,s,r)}async readFileText(t,s){let{fs:r,relativePath:n}=this.routePath(t);return r.readFileText(n,s)}async writeFile(t,s,r){let{fs:n,relativePath:i}=this.routePath(t);return n.writeFile(i,s,r)}async appendFile(t,s,r){let{fs:n,relativePath:i}=this.routePath(t);return n.appendFile(i,s,r)}async exists(t){let s=this.normalizePath(t);if(this.mounts.has(s)||this.getChildMountPoints(s).length>0)return!0;let{fs:n,relativePath:i}=this.routePath(t);return n.exists(i)}async stat(t){let s=this.normalizePath(t),r=this.mounts.get(s);if(r)try{return await r.filesystem.stat("/")}catch{return{isFile:!1,isDirectory:!0,isSymbolicLink:!1,mode:493,size:0,mtime:new Date}}if(this.getChildMountPoints(s).length>0)try{return await this.baseFs.stat(s)}catch{return{isFile:!1,isDirectory:!0,isSymbolicLink:!1,mode:493,size:0,mtime:new Date}}let{fs:i,relativePath:a}=this.routePath(t);return i.stat(a)}async lstat(t){let s=this.normalizePath(t),r=this.mounts.get(s);if(r)try{return await r.filesystem.lstat("/")}catch{return{isFile:!1,isDirectory:!0,isSymbolicLink:!1,mode:493,size:0,mtime:new Date}}if(this.getChildMountPoints(s).length>0)try{return await this.baseFs.lstat(s)}catch{return{isFile:!1,isDirectory:!0,isSymbolicLink:!1,mode:493,size:0,mtime:new Date}}let{fs:i,relativePath:a}=this.routePath(t);return i.lstat(a)}async mkdir(t,s){let r=this.normalizePath(t);if(this.mounts.has(r)){if(s?.recursive)return;throw new Error(`EEXIST: directory already exists, mkdir '${t}'`)}if(this.getChildMountPoints(r).length>0&&s?.recursive)return;let{fs:i,relativePath:a}=this.routePath(t);return i.mkdir(a,s)}async readdir(t){let s=this.normalizePath(t),r=new Set,n=null,{fs:i,relativePath:a}=this.routePath(t);try{let l=await i.readdir(a);for(let u of l)r.add(u)}catch(l){let u=l.code,c=l.message||"";if(u!=="ENOENT"&&!c.includes("ENOENT"))throw l;n=l}let o=this.getChildMountPoints(s);for(let l of o)r.add(l);if(r.size===0&&n&&!this.mounts.has(s))throw n;return Array.from(r).sort()}async rm(t,s){let r=this.normalizePath(t);if(this.mounts.has(r))throw new Error(`EBUSY: mount point, cannot remove '${t}'`);if(this.getChildMountPoints(r).length>0)throw new Error(`EBUSY: contains mount points, cannot remove '${t}'`);let{fs:i,relativePath:a}=this.routePath(t);return i.rm(a,s)}async cp(t,s,r){let n=this.routePath(t),i=this.routePath(s);return n.fs===i.fs?n.fs.cp(n.relativePath,i.relativePath,r):this.crossMountCopy(t,s,r)}async mv(t,s){let r=this.normalizePath(t);if(this.mounts.has(r))throw new Error(`EBUSY: mount point, cannot move '${t}'`);let n=this.routePath(t),i=this.routePath(s);if(n.fs===i.fs)return n.fs.mv(n.relativePath,i.relativePath);await this.cp(t,s,{recursive:!0}),await this.rm(t,{recursive:!0})}resolvePath(t,s){if(s.startsWith("/"))return this.normalizePath(s);let r=t==="/"?`/${s}`:`${t}/${s}`;return this.normalizePath(r)}getAllPaths(){let t=new Set;for(let s of this.baseFs.getAllPaths())t.add(s);for(let s of this.mounts.keys()){let r=s.split("/").filter(Boolean),n="";for(let a of r)n=`${n}/${a}`,t.add(n);let i=this.mounts.get(s);if(i)for(let a of i.filesystem.getAllPaths())a==="/"?t.add(s):t.add(`${s}${a}`)}return Array.from(t).sort()}async chmod(t,s){let r=this.normalizePath(t),n=this.mounts.get(r);if(n)return n.filesystem.chmod("/",s);let{fs:i,relativePath:a}=this.routePath(t);return i.chmod(a,s)}async symlink(t,s){let{fs:r,relativePath:n}=this.routePath(s);return r.symlink(t,n)}async link(t,s){let r=this.routePath(t),n=this.routePath(s);if(r.fs!==n.fs)throw new Error(`EXDEV: cross-device link not permitted, link '${t}' -> '${s}'`);return r.fs.link(r.relativePath,n.relativePath)}async readlink(t){let{fs:s,relativePath:r}=this.routePath(t);return s.readlink(r)}async realpath(t){let s=this.normalizePath(t);if(this.mounts.get(s))return s;let{fs:n,relativePath:i}=this.routePath(t),a=await n.realpath(i);for(let[o,l]of this.mounts)if(s===o||s.startsWith(`${o}/`))return a==="/"?o:`${o}${a}`;return a}async crossMountCopy(t,s,r){let n=await this.lstat(t);if(n.isFile){let i=await this.readFile(t);await this.writeFile(s,i),await this.chmod(s,n.mode)}else if(n.isDirectory){if(!r?.recursive)throw new Error(`cp: ${t} is a directory (not copied)`);await this.mkdir(s,{recursive:!0});let i=await this.readdir(t);for(let a of i){let o=t==="/"?`/${a}`:`${t}/${a}`,l=s==="/"?`/${a}`:`${s}/${a}`;await this.crossMountCopy(o,l,r)}}else if(n.isSymbolicLink){let i=await this.readlink(t);await this.symlink(i,s)}}async utimes(t,s,r){let{fs:n,relativePath:i}=this.routePath(t);return n.utimes(i,s,r)}};import*as ie from"node:fs";import*as _t from"node:path";var pl="/home/user/project";function he(e,t){if(e.includes("\0"))throw new Error(`ENOENT: path contains null byte, ${t} '${e}'`)}var Tt=class{root;mountPoint;readOnly;maxFileReadSize;memory=new Map;deleted=new Set;constructor(t){this.root=_t.resolve(t.root);let s=t.mountPoint??pl;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,!ie.existsSync(this.root))throw new Error(`OverlayFs root does not exist: ${this.root}`);if(!ie.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 r of t)s+=`/${r}`,this.memory.has(s)||this.memory.set(s,{type:"directory",mode:493,mtime:new Date});this.memory.has("/")||this.memory.set("/",{type:"directory",mode:493,mtime:new Date})}getMountPoint(){return this.mountPoint}mkdirSync(t,s){let n=this.normalizePath(t).split("/").filter(Boolean),i="";for(let a of n)i+=`/${a}`,this.memory.has(i)||this.memory.set(i,{type:"directory",mode:493,mtime:new Date})}writeFileSync(t,s){let r=this.normalizePath(t),n=this.getDirname(r);n!=="/"&&this.mkdirSync(n);let{chunks:i,size:a}=mt(s);this.memory.set(r,{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 r=s.split("/").filter(i=>i&&i!=="."),n=[];for(let i of r)i===".."?n.pop():n.push(i);return`/${n.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),r=this.getRelativeToMount(s);if(r===null)return null;let n=_t.join(this.root,r),i=_t.resolve(n);return!i.startsWith(this.root)&&i!==this.root.replace(/\/$/,"")?null:i}dirname(t){let s=this.normalizePath(t);if(s==="/")return"/";let r=s.lastIndexOf("/");return r===0?"/":s.slice(0,r)}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 r=this.toRealPath(s);if(!r)return!1;try{return await ie.promises.access(r),!0}catch{return!1}}async readFile(t){let s=await this.readFileChunks(t);return ht(s)}async readRange(t,s,r){yt(s,r);let n=await this.resolveForRead(t);if(n.kind==="memory")return as(n.chunks,n.size,s,r);if(r===0||s>=n.size)return new Uint8Array(0);let i=Math.min(r,n.size-s),a=new Uint8Array(i),o=await ie.promises.open(n.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){he(t,"open");let r=this.normalizePath(t);if(s.has(r))throw new Error(`ELOOP: too many levels of symbolic links, open '${t}'`);if(s.add(r),this.deleted.has(r))throw new Error(`ENOENT: no such file or directory, open '${t}'`);let n=this.memory.get(r);if(n){if(n.type==="symlink"){let a=this.resolveSymlink(r,n.target);return this.resolveForRead(a,s)}if(n.type!=="file")throw new Error(`EISDIR: illegal operation on a directory, read '${t}'`);return{kind:"memory",chunks:n.chunks,size:n.size}}let i=this.toRealPath(r);if(!i)throw new Error(`ENOENT: no such file or directory, open '${t}'`);try{let a=await ie.promises.lstat(i);if(a.isSymbolicLink()){let o=await ie.promises.readlink(i),l=this.resolveSymlink(r,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 r=await this.readFileChunks(t),n=Te(s);return os(r,n)}async readFileChunks(t,s=new Set){he(t,"open");let r=this.normalizePath(t);if(s.has(r))throw new Error(`ELOOP: too many levels of symbolic links, open '${t}'`);if(s.add(r),this.deleted.has(r))throw new Error(`ENOENT: no such file or directory, open '${t}'`);let n=this.memory.get(r);if(n){if(n.type==="symlink"){let a=this.resolveSymlink(r,n.target);return this.readFileChunks(a,s)}if(n.type!=="file")throw new Error(`EISDIR: illegal operation on a directory, read '${t}'`);return n.chunks}let i=this.toRealPath(r);if(!i)throw new Error(`ENOENT: no such file or directory, open '${t}'`);try{let a=await ie.promises.lstat(i);if(a.isSymbolicLink()){let c=await ie.promises.readlink(i),f=this.resolveSymlink(r,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 ie.promises.readFile(i),l=new Uint8Array(o.buffer,o.byteOffset,o.byteLength),{chunks:u}=mt(l);return u}catch(a){throw a.code==="ENOENT"?new Error(`ENOENT: no such file or directory, open '${t}'`):a}}async writeFile(t,s,r){he(t,"write"),this.assertWritable(`write '${t}'`);let n=this.normalizePath(t);this.ensureParentDirs(n);let i=Te(r),{chunks:a,size:o}=await Ze(s,i);this.memory.set(n,{type:"file",chunks:a,size:o,mode:420,mtime:new Date}),this.deleted.delete(n)}async appendFile(t,s,r){he(t,"append"),this.assertWritable(`append '${t}'`);let n=this.normalizePath(t),i=Te(r),{chunks:a,size:o}=await Ze(s,i),l=[],u=0;try{l=await this.readFileChunks(n);for(let c of l)u+=c.length}catch{}this.ensureParentDirs(n),this.memory.set(n,{type:"file",chunks:[...l,...a],size:u+o,mode:420,mtime:new Date}),this.deleted.delete(n)}async exists(t){return t.includes("\0")?!1:this.existsInOverlay(t)}async stat(t,s=new Set){he(t,"stat");let r=this.normalizePath(t);if(s.has(r))throw new Error(`ELOOP: too many levels of symbolic links, stat '${t}'`);if(s.add(r),this.deleted.has(r))throw new Error(`ENOENT: no such file or directory, stat '${t}'`);let n=this.memory.get(r);if(n){if(n.type==="symlink"){let o=this.resolveSymlink(r,n.target);return this.stat(o,s)}let a=0;return n.type==="file"&&(a=n.size),{isFile:n.type==="file",isDirectory:n.type==="directory",isSymbolicLink:!1,mode:n.mode,size:a,mtime:n.mtime}}let i=this.toRealPath(r);if(!i)throw new Error(`ENOENT: no such file or directory, stat '${t}'`);try{let a=await ie.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){he(t,"lstat");let s=this.normalizePath(t);if(this.deleted.has(s))throw new Error(`ENOENT: no such file or directory, lstat '${t}'`);let r=this.memory.get(s);if(r){if(r.type==="symlink")return{isFile:!1,isDirectory:!1,isSymbolicLink:!0,mode:r.mode,size:r.target.length,mtime:r.mtime};let i=0;return r.type==="file"&&(i=r.size),{isFile:r.type==="file",isDirectory:r.type==="directory",isSymbolicLink:!1,mode:r.mode,size:i,mtime:r.mtime}}let n=this.toRealPath(s);if(!n)throw new Error(`ENOENT: no such file or directory, lstat '${t}'`);try{let i=await ie.promises.lstat(n);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 r=this.dirname(t);return this.normalizePath(r==="/"?`/${s}`:`${r}/${s}`)}async mkdir(t,s){he(t,"mkdir"),this.assertWritable(`mkdir '${t}'`);let r=this.normalizePath(t);if(await this.existsInOverlay(r)){if(!s?.recursive)throw new Error(`EEXIST: file already exists, mkdir '${t}'`);return}let i=this.dirname(r);if(i!=="/"&&!await this.existsInOverlay(i))if(s?.recursive)await this.mkdir(i,{recursive:!0});else throw new Error(`ENOENT: no such file or directory, mkdir '${t}'`);this.memory.set(r,{type:"directory",mode:493,mtime:new Date}),this.deleted.delete(r)}async readdirCore(t,s){if(this.deleted.has(s))throw new Error(`ENOENT: no such file or directory, scandir '${t}'`);let r=new Map,n=new Set,i=s==="/"?"/":`${s}/`;for(let o of this.deleted)if(o.startsWith(i)){let l=o.slice(i.length),u=l.split("/")[0];u&&!l.includes("/",u.length)&&n.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&&!n.has(c)&&!u.includes("/",1)&&r.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 ie.promises.readdir(a,{withFileTypes:!0});for(let l of o)!n.has(l.name)&&!r.has(l.name)&&r.set(l.name,{name:l.name,isFile:l.isFile(),isDirectory:l.isDirectory(),isSymbolicLink:l.isSymbolicLink()})}catch(o){if(o.code==="ENOENT"){if(!this.memory.has(s))throw new Error(`ENOENT: no such file or directory, scandir '${t}'`)}else if(o.code!=="ENOTDIR")throw o}return r}async resolveForReaddir(t,s=!1){let r=this.normalizePath(t),n=new Set,i=s,a=this.memory.get(r);for(;a&&a.type==="symlink";){if(n.has(r))throw new Error(`ELOOP: too many levels of symbolic links, scandir '${t}'`);n.add(r),i=!0,r=this.resolveSymlink(r,a.target),a=this.memory.get(r)}if(a)return{normalized:r,outsideOverlay:!1};if(this.getRelativeToMount(r)===null)return{normalized:r,outsideOverlay:!0};let l=this.toRealPath(r);if(!l)return{normalized:r,outsideOverlay:!0};try{if((await ie.promises.lstat(l)).isSymbolicLink()){let c=await ie.promises.readlink(l),f=this.resolveSymlink(r,c);return this.resolveForReaddir(f,!0)}return{normalized:r,outsideOverlay:!1}}catch{return i?{normalized:r,outsideOverlay:!0}:{normalized:r,outsideOverlay:!1}}}async readdir(t){he(t,"scandir");let{normalized:s,outsideOverlay:r}=await this.resolveForReaddir(t);if(r)return[];let n=await this.readdirCore(t,s);return Array.from(n.keys()).sort((i,a)=>i<a?-1:i>a?1:0)}async readdirWithFileTypes(t){he(t,"scandir");let{normalized:s,outsideOverlay:r}=await this.resolveForReaddir(t);if(r)return[];let n=await this.readdirCore(t,s);return Array.from(n.values()).sort((i,a)=>i.name<a.name?-1:i.name>a.name?1:0)}async rm(t,s){he(t,"rm"),this.assertWritable(`rm '${t}'`);let r=this.normalizePath(t);if(!await this.existsInOverlay(r)){if(s?.force)return;throw new Error(`ENOENT: no such file or directory, rm '${t}'`)}try{if((await this.stat(r)).isDirectory){let a=await this.readdir(r);if(a.length>0){if(!s?.recursive)throw new Error(`ENOTEMPTY: directory not empty, rm '${t}'`);for(let o of a){let l=r==="/"?`/${o}`:`${r}/${o}`;await this.rm(l,s)}}}}catch{}this.deleted.add(r),this.memory.delete(r)}async cp(t,s,r){he(t,"cp"),he(s,"cp"),this.assertWritable(`cp '${s}'`);let n=this.normalizePath(t),i=this.normalizePath(s);if(!await this.existsInOverlay(n))throw new Error(`ENOENT: no such file or directory, cp '${t}'`);let o=await this.stat(n);if(o.isFile){let l=await this.readFileChunks(n);await this.writeFile(i,ht(l))}else if(o.isDirectory){if(!r?.recursive)throw new Error(`EISDIR: is a directory, cp '${t}'`);await this.mkdir(i,{recursive:!0});let l=await this.readdir(n);for(let u of l){let c=n==="/"?`/${u}`:`${n}/${u}`,f=i==="/"?`/${u}`:`${i}/${u}`;await this.cp(c,f,r)}}}async mv(t,s){this.assertWritable(`mv '${s}'`),await this.cp(t,s,{recursive:!0}),await this.rm(t,{recursive:!0})}resolvePath(t,s){if(s.startsWith("/"))return this.normalizePath(s);let r=t==="/"?`/${s}`:`${t}/${s}`;return this.normalizePath(r)}getAllPaths(){let t=new Set(this.memory.keys());for(let s of this.deleted)t.delete(s);return this.scanRealFs("/",t),Array.from(t)}scanRealFs(t,s){if(this.deleted.has(t))return;let r=this.toRealPath(t);if(r)try{let n=ie.readdirSync(r);for(let i of n){let a=t==="/"?`/${i}`:`${t}/${i}`;if(this.deleted.has(a))continue;s.add(a);let o=_t.join(r,i);ie.statSync(o).isDirectory()&&this.scanRealFs(a,s)}}catch{}}async chmod(t,s){he(t,"chmod"),this.assertWritable(`chmod '${t}'`);let r=this.normalizePath(t);if(!await this.existsInOverlay(r))throw new Error(`ENOENT: no such file or directory, chmod '${t}'`);let i=this.memory.get(r);if(i){i.mode=s;return}let a=await this.stat(r);if(a.isFile){let o=await this.readFileChunks(r),l=0;for(let u of o)l+=u.length;this.memory.set(r,{type:"file",chunks:o,size:l,mode:s,mtime:new Date})}else a.isDirectory&&this.memory.set(r,{type:"directory",mode:s,mtime:new Date})}async symlink(t,s){he(s,"symlink"),this.assertWritable(`symlink '${s}'`);let r=this.normalizePath(s);if(await this.existsInOverlay(r))throw new Error(`EEXIST: file already exists, symlink '${s}'`);this.ensureParentDirs(r),this.memory.set(r,{type:"symlink",target:t,mode:511,mtime:new Date}),this.deleted.delete(r)}async link(t,s){he(t,"link"),he(s,"link"),this.assertWritable(`link '${s}'`);let r=this.normalizePath(t),n=this.normalizePath(s);if(!await this.existsInOverlay(r))throw new Error(`ENOENT: no such file or directory, link '${t}'`);let a=await this.stat(r);if(!a.isFile)throw new Error(`EPERM: operation not permitted, link '${t}'`);if(await this.existsInOverlay(n))throw new Error(`EEXIST: file already exists, link '${s}'`);let l=await this.readFileChunks(r),u=0;for(let c of l)u+=c.length;this.ensureParentDirs(n),this.memory.set(n,{type:"file",chunks:l,size:u,mode:a.mode,mtime:new Date}),this.deleted.delete(n)}async readlink(t){he(t,"readlink");let s=this.normalizePath(t);if(this.deleted.has(s))throw new Error(`ENOENT: no such file or directory, readlink '${t}'`);let r=this.memory.get(s);if(r){if(r.type!=="symlink")throw new Error(`EINVAL: invalid argument, readlink '${t}'`);return r.target}let n=this.toRealPath(s);if(!n)throw new Error(`ENOENT: no such file or directory, readlink '${t}'`);try{return await ie.promises.readlink(n)}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){he(t,"realpath");let s=this.normalizePath(t),r=new Set,n=async o=>{let l=o==="/"?[]:o.slice(1).split("/"),u="";for(let c of l){if(u=`${u}/${c}`,r.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(r.add(u),u=this.resolveSymlink(u,f.target),d++,r.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 ie.promises.lstat(m)).isSymbolicLink()){let b=await ie.promises.readlink(m);return r.add(u),u=this.resolveSymlink(u,b),n(u)}}catch(h){throw h.code==="ENOENT"?new Error(`ENOENT: no such file or directory, realpath '${t}'`):h}}}return u||"/"},i=await n(s);if(!await this.existsInOverlay(i))throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);return i}async utimes(t,s,r){he(t,"utimes"),this.assertWritable(`utimes '${t}'`);let n=this.normalizePath(t);if(!await this.existsInOverlay(n))throw new Error(`ENOENT: no such file or directory, utimes '${t}'`);let a=this.memory.get(n);if(a){a.mtime=r;return}let o=await this.stat(n);if(o.isFile){let l=await this.readFileChunks(n),u=0;for(let c of l)u+=c.length;this.memory.set(n,{type:"file",chunks:l,size:u,mode:o.mode,mtime:r})}else o.isDirectory&&this.memory.set(n,{type:"directory",mode:o.mode,mtime:r})}};import*as Z from"node:fs";import*as we from"node:path";import{Readable as ml}from"node:stream";var Vs=class{root;maxFileReadSize;constructor(t){if(this.root=we.resolve(t.root),this.maxFileReadSize=t.maxFileReadSize??10485760,!Z.existsSync(this.root))throw new Error(`ReadWriteFs root does not exist: ${this.root}`);if(!Z.statSync(this.root).isDirectory())throw new Error(`ReadWriteFs root is not a directory: ${this.root}`)}toRealPath(t){let s=this.normalizePath(t),r=we.join(this.root,s);return we.resolve(r)}normalizePath(t){if(!t||t==="/")return"/";let s=t.endsWith("/")&&t!=="/"?t.slice(0,-1):t;s.startsWith("/")||(s=`/${s}`);let r=s.split("/").filter(i=>i&&i!=="."),n=[];for(let i of r)i===".."?n.pop():n.push(i);return`/${n.join("/")}`||"/"}async readFile(t){let s=this.toRealPath(t);try{let n=await Z.promises.lstat(s);if(n.isDirectory())throw new Error(`EISDIR: illegal operation on a directory, read '${t}'`);if(this.maxFileReadSize>0&&n.size>this.maxFileReadSize)throw new Error(`EFBIG: file too large, read '${t}' (${n.size} bytes, max ${this.maxFileReadSize})`)}catch(n){throw n.code==="ENOENT"?new Error(`ENOENT: no such file or directory, open '${t}'`):n}let r=Z.createReadStream(s);return ml.toWeb(r)}async readRange(t,s,r){yt(s,r);let n=this.toRealPath(t),i;try{i=await Z.promises.lstat(n)}catch(u){throw u.code==="ENOENT"?new Error(`ENOENT: no such file or directory, open '${t}'`):u}if(i.isDirectory())throw new Error(`EISDIR: illegal operation on a directory, read '${t}'`);if(r===0||s>=i.size)return new Uint8Array(0);let a=Math.min(r,i.size-s),o=new Uint8Array(a),l=await Z.promises.open(n,"r");try{let{bytesRead:u}=await l.read(o,0,a,s);return u===a?o:o.subarray(0,u)}finally{await l.close()}}async readFileText(t,s){let r=await this.readFile(t),n=await re(r),i=Te(s)??"utf8";return i==="utf8"||i==="utf-8"?new TextDecoder().decode(n):typeof Buffer<"u"?Buffer.from(n).toString(i):new TextDecoder().decode(n)}async writeFile(t,s,r){let n=this.toRealPath(t),i=Te(r),a=we.dirname(n);await Z.promises.mkdir(a,{recursive:!0});let{chunks:o,size:l}=await Ze(s,i),u=new Uint8Array(l),c=0;for(let f of o)u.set(f,c),c+=f.length;await Z.promises.writeFile(n,u)}async appendFile(t,s,r){let n=this.toRealPath(t),i=Te(r),a=we.dirname(n);await Z.promises.mkdir(a,{recursive:!0});let{chunks:o,size:l}=await Ze(s,i),u=new Uint8Array(l),c=0;for(let f of o)u.set(f,c),c+=f.length;await Z.promises.appendFile(n,u)}async exists(t){let s=this.toRealPath(t);try{return await Z.promises.access(s),!0}catch{return!1}}async stat(t){let s=this.toRealPath(t);try{let r=await Z.promises.stat(s);return{isFile:r.isFile(),isDirectory:r.isDirectory(),isSymbolicLink:!1,mode:r.mode,size:r.size,mtime:r.mtime}}catch(r){throw r.code==="ENOENT"?new Error(`ENOENT: no such file or directory, stat '${t}'`):r}}async lstat(t){let s=this.toRealPath(t);try{let r=await Z.promises.lstat(s);return{isFile:r.isFile(),isDirectory:r.isDirectory(),isSymbolicLink:r.isSymbolicLink(),mode:r.mode,size:r.size,mtime:r.mtime}}catch(r){throw r.code==="ENOENT"?new Error(`ENOENT: no such file or directory, lstat '${t}'`):r}}async mkdir(t,s){let r=this.toRealPath(t);try{await Z.promises.mkdir(r,{recursive:s?.recursive})}catch(n){let i=n;throw i.code==="EEXIST"?new Error(`EEXIST: file already exists, mkdir '${t}'`):i.code==="ENOENT"?new Error(`ENOENT: no such file or directory, mkdir '${t}'`):n}}async readdir(t){return(await this.readdirWithFileTypes(t)).map(r=>r.name)}async readdirWithFileTypes(t){let s=this.toRealPath(t);try{return(await Z.promises.readdir(s,{withFileTypes:!0})).map(n=>({name:n.name,isFile:n.isFile(),isDirectory:n.isDirectory(),isSymbolicLink:n.isSymbolicLink()})).sort((n,i)=>n.name<i.name?-1:n.name>i.name?1:0)}catch(r){let n=r;throw n.code==="ENOENT"?new Error(`ENOENT: no such file or directory, scandir '${t}'`):n.code==="ENOTDIR"?new Error(`ENOTDIR: not a directory, scandir '${t}'`):r}}async rm(t,s){let r=this.toRealPath(t);try{await Z.promises.rm(r,{recursive:s?.recursive??!1,force:s?.force??!1})}catch(n){let i=n;throw i.code==="ENOENT"&&!s?.force?new Error(`ENOENT: no such file or directory, rm '${t}'`):i.code==="ENOTEMPTY"?new Error(`ENOTEMPTY: directory not empty, rm '${t}'`):n}}async cp(t,s,r){let n=this.toRealPath(t),i=this.toRealPath(s);try{await Z.promises.cp(n,i,{recursive:r?.recursive??!1})}catch(a){let o=a;throw o.code==="ENOENT"?new Error(`ENOENT: no such file or directory, cp '${t}'`):o.code==="EISDIR"?new Error(`EISDIR: is a directory, cp '${t}'`):a}}async mv(t,s){let r=this.toRealPath(t),n=this.toRealPath(s),i=we.dirname(n);await Z.promises.mkdir(i,{recursive:!0});try{await Z.promises.rename(r,n)}catch(a){let o=a;if(o.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, mv '${t}'`);if(o.code==="EXDEV"){await this.cp(t,s,{recursive:!0}),await this.rm(t,{recursive:!0});return}throw a}}resolvePath(t,s){if(s.startsWith("/"))return this.normalizePath(s);let r=t==="/"?`/${s}`:`${t}/${s}`;return this.normalizePath(r)}getAllPaths(){let t=[];return this.scanDir("/",t),t}scanDir(t,s){let r=this.toRealPath(t);try{let n=Z.readdirSync(r);for(let i of n){let a=t==="/"?`/${i}`:`${t}/${i}`;s.push(a);let o=we.join(r,i);Z.statSync(o).isDirectory()&&this.scanDir(a,s)}}catch{}}async chmod(t,s){let r=this.toRealPath(t);try{await Z.promises.chmod(r,s)}catch(n){throw n.code==="ENOENT"?new Error(`ENOENT: no such file or directory, chmod '${t}'`):n}}async symlink(t,s){let r=this.toRealPath(s),n=this.normalizePath(s),i=this.normalizePath(we.dirname(n)),a=t.startsWith("/")?this.normalizePath(t):this.normalizePath(i==="/"?`/${t}`:`${i}/${t}`),o=we.join(this.root,a),l=we.dirname(r),u=t.startsWith("/")?o:we.relative(l,o);try{await Z.promises.symlink(u,r)}catch(c){throw c.code==="EEXIST"?new Error(`EEXIST: file already exists, symlink '${s}'`):c}}async link(t,s){let r=this.toRealPath(t),n=this.toRealPath(s);try{await Z.promises.link(r,n)}catch(i){let a=i;throw a.code==="ENOENT"?new Error(`ENOENT: no such file or directory, link '${t}'`):a.code==="EEXIST"?new Error(`EEXIST: file already exists, link '${s}'`):a.code==="EPERM"?new Error(`EPERM: operation not permitted, link '${t}'`):i}}async readlink(t){let s=this.toRealPath(t);try{return await Z.promises.readlink(s)}catch(r){let n=r;throw n.code==="ENOENT"?new Error(`ENOENT: no such file or directory, readlink '${t}'`):n.code==="EINVAL"?new Error(`EINVAL: invalid argument, readlink '${t}'`):r}}async realpath(t){let s=this.toRealPath(t);try{let r=await Z.promises.realpath(s),n=await Z.promises.realpath(this.root);if(r.startsWith(n))return r.slice(n.length)||"/";throw new Error(`ENOENT: no such file or directory, realpath '${t}'`)}catch(r){let n=r;throw n.code==="ENOENT"?new Error(`ENOENT: no such file or directory, realpath '${t}'`):n.code==="ELOOP"?new Error(`ELOOP: too many levels of symbolic links, realpath '${t}'`):r}}async utimes(t,s,r){let n=this.toRealPath(t);try{await Z.promises.utimes(n,s,r)}catch(i){throw i.code==="ENOENT"?new Error(`ENOENT: no such file or directory, utimes '${t}'`):i}}};var Nt=class{cmdId;cwd;pid;startedAt;exitCode;bashEnv;cmdLine;env;explicitCwd;processes;shellProcesses;logMessages=[];logReaders=new Set;logsComplete=!1;stdoutDecoder=new TextDecoder;stderrDecoder=new TextDecoder;resultPromise;constructor(t,s,r,n,i=!1,a=new Le,o=t.processes){this.cmdId=crypto.randomUUID(),this.cwd=r,this.startedAt=new Date,this.bashEnv=t,this.processes=a,this.shellProcesses=o,this.cmdLine=s,this.env=n,this.explicitCwd=i;let l=()=>{},u=()=>{};this.resultPromise=new Promise((c,f)=>{l=c,u=f}),this.pid=a.start(this.cmdLine,async(c,f)=>{try{let d=await this.execute(f);return l(d),d.exitCode}catch(d){throw u(d),d}finally{this.appendLog("stdout",this.stdoutDecoder.decode(),new Date),this.appendLog("stderr",this.stderrDecoder.decode(),new Date),this.logsComplete=!0;let d=[...this.logReaders];this.logReaders.clear();for(let p of d)p()}}),a.wait(this.pid)}appendLog(t,s,r){if(s.length===0)return;this.logMessages.push({type:t,data:s,timestamp:r});let n=[...this.logReaders];this.logReaders.clear();for(let i of n)i()}async execute(t){let s={write:l=>{this.appendLog("stdout",this.stdoutDecoder.decode(l,{stream:!0}),new Date)}},r={write:l=>{this.appendLog("stderr",this.stderrDecoder.decode(l,{stream:!0}),new Date)}},n={cwd:this.explicitCwd?this.cwd:void 0,env:this.env,processes:this.shellProcesses,signal:t,stdoutSink:s,stderrSink:r},i=await this.bashEnv.exec(this.cmdLine,n);this.exitCode=i.exitCode;let[a,o]=await Promise.all([Yt(i.stdout),Yt(i.stderr)]);return{stdoutText:a,stderrText:o,exitCode:i.exitCode}}async*logs(){let t=0;for(;;){for(;t<this.logMessages.length;)yield this.logMessages[t++];if(this.logsComplete)return;await new Promise(s=>{this.logReaders.add(s)})}}async wait(){return await this.resultPromise,this}async output(){let t=await this.resultPromise;return t.stdoutText+t.stderrText}async stdout(){return(await this.resultPromise).stdoutText}async stderr(){return(await this.resultPromise).stderrText}async kill(t="SIGTERM"){this.processes.kill(this.pid,t)}};var zs=class e{bashEnv;commandProcesses;baseShellProcesses;commandShellProcesses=new Set;stopped=!1;stopPromise;constructor(t,s,r){this.bashEnv=t,this.commandProcesses=s,this.baseShellProcesses=r}static async create(t){let s=t?.fs;if(t?.overlayRoot){if(t?.fs)throw new Error("Cannot specify both 'fs' and 'overlayRoot' options");s=new Tt({root:t.overlayRoot})}let r=new Le,n=new Le,i=new Kt({env:t?.env,cwd:t?.cwd,fs:s,processes:n,maxCallDepth:t?.maxCallDepth,maxCommandCount:t?.maxCommandCount,maxLoopIterations:t?.maxLoopIterations,network:t?.network});return new e(i,r,n)}async runCommand(t,s){if(this.stopped)throw new Error("Cannot run commands after Sandbox.stop()");let r=s?.cwd??this.bashEnv.getCwd(),n=s?.cwd!==void 0,i=!1,a=()=>{!i||o.runningCount!==0||(this.commandShellProcesses.delete(o),o.dispose())},o=new Le({onJobExit:a});this.commandShellProcesses.add(o);let l=new Nt(this.bashEnv,t,r,s?.env,n,this.commandProcesses,o);return l.wait().then(()=>{i=!0,a()},()=>{i=!0,a()}),l}async writeFiles(t){for(let[s,r]of Object.entries(t)){let n;typeof r=="string"?n=r:r.encoding==="base64"?n=Buffer.from(r.content,"base64").toString("utf-8"):n=r.content;let i=s.substring(0,s.lastIndexOf("/"))||"/";i!=="/"&&await this.bashEnv.exec(`mkdir -p ${i}`),await this.bashEnv.writeFile(s,n)}}async readFile(t,s){let r=await this.bashEnv.readFile(t);return s==="base64"?Buffer.from(r).toString("base64"):r}async mkDir(t,s){let r=s?.recursive?"-p":"";await this.bashEnv.exec(`mkdir ${r} ${t}`)}async stop(){if(!this.stopPromise){this.stopped=!0;let t=new Set([this.commandProcesses,this.baseShellProcesses,...this.commandShellProcesses]);this.commandShellProcesses.clear(),this.stopPromise=Promise.all([...t].map(s=>s.dispose())).then(()=>{})}await this.stopPromise}async extendTimeout(t){}get domain(){}get bashEnvInstance(){return this.bashEnv}};var js=class{violations=[];violationsByType=new Map;options;constructor(t={}){this.options={maxViolationsPerType:t.maxViolationsPerType??100,includeStackTraces:t.includeStackTraces??!0,onViolation:t.onViolation??(()=>{}),logToConsole:t.logToConsole??!1}}record(t){let s=this.options.includeStackTraces?t:{...t,stack:void 0};this.violations.unshift(s);let r=this.violationsByType.get(t.type);r||(r=[],this.violationsByType.set(t.type,r)),r.length<this.options.maxViolationsPerType&&r.push(s),this.options.logToConsole&&console.warn(`[SecurityViolation] ${t.type}: ${t.message}`,t.path),this.options.onViolation(s)}getViolations(){return[...this.violations]}getViolationsByType(t){return[...this.violationsByType.get(t)??[]]}getSummary(){let t=[];for(let[s,r]of this.violationsByType){if(r.length===0)continue;let n=new Set,i=Number.POSITIVE_INFINITY,a=0;for(let o of r)n.add(o.path),i=Math.min(i,o.timestamp),a=Math.max(a,o.timestamp);t.push({type:s,count:r.length,firstSeen:i,lastSeen:a,paths:Array.from(n)})}return t.sort((s,r)=>r.count-s.count),t}getTotalCount(){return this.violations.length}hasViolations(){return this.violations.length>0}clear(){this.violations=[],this.violationsByType.clear()}createCallback(){return t=>this.record(t)}};function ao(){return e=>{console.warn("[DefenseInDepth] Security violation detected:",`
693
+ `;try{s.writeFileSync(`/bin/${t.name}`,r)}catch{}try{s.writeFileSync(`/usr/bin/${t.name}`,r)}catch{}}}logResult(t,s,r){try{let n=this.logger;if(n){let i=s.text(),a=r.text();i.length>0&&n.debug("stdout",{output:i}),a.length>0&&n.info("stderr",{output:a}),n.info("exit",{exitCode:t.exitCode})}return{...t,stdout:s.stream(),stderr:r.stream()}}finally{s.seal(),r.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:P(),stderr:V(`bash: maximum command count (${this.limits.maxCommandCount}) exceeded (possible infinite loop). Increase with executionLimits.maxCommandCount option.
694
+ `),exitCode:1,env:Te(this.state.env,s?.env)};if(!t.trim())return{stdout:P(),stderr:P(),exitCode:0,env:Te(this.state.env,s?.env)};if(s?.signal?.aborted)return{stdout:P(),stderr:P(),exitCode:new pe(s.signal.reason).exitCode,env:Te(this.state.env,s?.env)};let r=new Set,n=b=>{if(b)return{async write(y){try{await b.write(y)}catch(k){throw r.add(k),k}}}},i=xe(n(s?.stdoutSink)),a=xe(n(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,y]of Object.entries(s.env))g(p,b,y);f!==void 0&&g(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=wl(t));let E=(this.defenseInDepthConfig?Tt.getInstance(this.defenseInDepthConfig):null)?.activate(),S=!1;try{let b=async()=>{let y=Fe(h);S=!0;let k={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:($,C)=>this.exec($,{...C,jobTracker:c,processes:o,signal:Mt(s?.signal,C?.signal)}),fetch:this.secureFetch,sleep:this.sleepFn,trace:this.traceFn,coverage:this.coverageWriter,signal:s?.signal},L=await new Xt(k,m).executeRootScript(y);return c.started&&(await new Promise($=>gl($,0)),c.limitExceeded&&(L={...L,exitCode:ae.EXIT_CODE})),this.logResult(L,i,a)};return E?await E.run(b):await b()}catch(b){if(r.has(b))throw b;if(b instanceof q)return this.logResult({exitCode:b.exitCode,env:Te(this.state.env,s?.env)},i,a);if(b instanceof be)return this.logResult({exitCode:b.exitCode,env:Te(this.state.env,s?.env)},i,a);if(b instanceof nt)return S||await a.write(W(`bash: ${b.message}
695
+ `)),this.logResult({exitCode:1,env:Te(this.state.env,s?.env)},i,a);if(b instanceof pe)return this.logResult({exitCode:b.exitCode,env:Te(this.state.env,s?.env)},i,a);if(b instanceof ae)return this.logResult({exitCode:ae.EXIT_CODE,env:Te(this.state.env,s?.env)},i,a);if(b instanceof ye)return await a.write(W(`bash: security violation: ${b.message}
696
+ `)),this.logResult({exitCode:1,env:Te(this.state.env,s?.env)},i,a);if(b.name==="ParseException")return await a.write(W(`bash: syntax error: ${b.message}
697
+ `)),this.logResult({exitCode:2,env:Te(this.state.env,s?.env)},i,a);if(b instanceof mn)return await a.write(W(`bash: ${b.message}
698
+ `)),this.logResult({exitCode:2,env:Te(this.state.env,s?.env)},i,a);if(b instanceof RangeError)return await a.write(W(`bash: ${b.message}
699
+ `)),this.logResult({exitCode:1,env:Te(this.state.env,s?.env)},i,a);throw b}finally{E?.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 Ye(this.state.env)}};function wl(e){let t=e.split(`
700
+ `),s=[],r=[];for(let n=0;n<t.length;n++){let i=t[n];if(r.length>0){let l=r[r.length-1];if((l.stripTabs?i.replace(/^\t+/,""):i)===l.delimiter){s.push(i.trimStart()),r.pop();continue}s.push(i);continue}let a=i.trimStart();s.push(a);let o=/<<(-?)\s*(['"]?)([\w-]+)\2/g;for(let l of a.matchAll(o)){let c=l[1]==="-",u=l[3];r.push({delimiter:u,stripTabs:c})}}return s.join(`
701
+ `)}var Vs=class{baseFs;mounts=new Map;constructor(t){if(this.baseFs=t?.base??new Xe,t?.mounts)for(let{mountPoint:s,filesystem:r}of t.mounts)this.mount(s,r)}mount(t,s){this.validateMountPath(t);let r=this.normalizePath(t);this.validateMount(r),this.mounts.set(r,{mountPoint:r,filesystem:s})}unmount(t){let s=this.normalizePath(t);if(!this.mounts.has(s))throw new Error(`No filesystem mounted at '${t}'`);this.mounts.delete(s)}getMounts(){return Array.from(this.mounts.values()).map(t=>({mountPoint:t.mountPoint,filesystem:t.filesystem}))}isMountPoint(t){let s=this.normalizePath(t);return this.mounts.has(s)}validateMountPath(t){let s=t.split("/");for(let r of s)if(r==="."||r==="..")throw new Error(`Invalid mount point '${t}': contains '.' or '..' segments`)}validateMount(t){if(t==="/")throw new Error("Cannot mount at root '/'");for(let s of this.mounts.keys())if(s!==t){if(t.startsWith(`${s}/`))throw new Error(`Cannot mount at '${t}': inside existing mount '${s}'`);if(s.startsWith(`${t}/`))throw new Error(`Cannot mount at '${t}': would contain existing mount '${s}'`)}}normalizePath(t){if(!t||t==="/")return"/";let s=t.endsWith("/")&&t!=="/"?t.slice(0,-1):t;s.startsWith("/")||(s=`/${s}`);let r=s.split("/").filter(i=>i&&i!=="."),n=[];for(let i of r)i===".."?n.pop():n.push(i);return`/${n.join("/")}`}routePath(t){let s=this.normalizePath(t),r=null,n=0;for(let i of this.mounts.values()){let a=i.mountPoint;if(s===a)return{fs:i.filesystem,relativePath:"/"};s.startsWith(`${a}/`)&&a.length>n&&(r=i,n=a.length)}if(r){let i=s.slice(n);return{fs:r.filesystem,relativePath:i||"/"}}return{fs:this.baseFs,relativePath:s}}getChildMountPoints(t){let s=this.normalizePath(t),r=s==="/"?"/":`${s}/`,n=[];for(let i of this.mounts.keys())if(i.startsWith(r)){let o=i.slice(r.length).split("/")[0];o&&!n.includes(o)&&n.push(o)}return n}async readFile(t){let{fs:s,relativePath:r}=this.routePath(t);return s.readFile(r)}async readRange(t,s,r){let{fs:n,relativePath:i}=this.routePath(t);return n.readRange(i,s,r)}async readFileText(t,s){let{fs:r,relativePath:n}=this.routePath(t);return r.readFileText(n,s)}async writeFile(t,s,r){let{fs:n,relativePath:i}=this.routePath(t);return n.writeFile(i,s,r)}async appendFile(t,s,r){let{fs:n,relativePath:i}=this.routePath(t);return n.appendFile(i,s,r)}async exists(t){let s=this.normalizePath(t);if(this.mounts.has(s)||this.getChildMountPoints(s).length>0)return!0;let{fs:n,relativePath:i}=this.routePath(t);return n.exists(i)}async stat(t){let s=this.normalizePath(t),r=this.mounts.get(s);if(r)try{return await r.filesystem.stat("/")}catch{return{isFile:!1,isDirectory:!0,isSymbolicLink:!1,mode:493,size:0,mtime:new Date}}if(this.getChildMountPoints(s).length>0)try{return await this.baseFs.stat(s)}catch{return{isFile:!1,isDirectory:!0,isSymbolicLink:!1,mode:493,size:0,mtime:new Date}}let{fs:i,relativePath:a}=this.routePath(t);return i.stat(a)}async lstat(t){let s=this.normalizePath(t),r=this.mounts.get(s);if(r)try{return await r.filesystem.lstat("/")}catch{return{isFile:!1,isDirectory:!0,isSymbolicLink:!1,mode:493,size:0,mtime:new Date}}if(this.getChildMountPoints(s).length>0)try{return await this.baseFs.lstat(s)}catch{return{isFile:!1,isDirectory:!0,isSymbolicLink:!1,mode:493,size:0,mtime:new Date}}let{fs:i,relativePath:a}=this.routePath(t);return i.lstat(a)}async mkdir(t,s){let r=this.normalizePath(t);if(this.mounts.has(r)){if(s?.recursive)return;throw new Error(`EEXIST: directory already exists, mkdir '${t}'`)}if(this.getChildMountPoints(r).length>0&&s?.recursive)return;let{fs:i,relativePath:a}=this.routePath(t);return i.mkdir(a,s)}async readdir(t){let s=this.normalizePath(t),r=new Set,n=null,{fs:i,relativePath:a}=this.routePath(t);try{let l=await i.readdir(a);for(let c of l)r.add(c)}catch(l){let c=l.code,u=l.message||"";if(c!=="ENOENT"&&!u.includes("ENOENT"))throw l;n=l}let o=this.getChildMountPoints(s);for(let l of o)r.add(l);if(r.size===0&&n&&!this.mounts.has(s))throw n;return Array.from(r).sort()}async rm(t,s){let r=this.normalizePath(t);if(this.mounts.has(r))throw new Error(`EBUSY: mount point, cannot remove '${t}'`);if(this.getChildMountPoints(r).length>0)throw new Error(`EBUSY: contains mount points, cannot remove '${t}'`);let{fs:i,relativePath:a}=this.routePath(t);return i.rm(a,s)}async cp(t,s,r){let n=this.routePath(t),i=this.routePath(s);return n.fs===i.fs?n.fs.cp(n.relativePath,i.relativePath,r):this.crossMountCopy(t,s,r)}async mv(t,s){let r=this.normalizePath(t);if(this.mounts.has(r))throw new Error(`EBUSY: mount point, cannot move '${t}'`);let n=this.routePath(t),i=this.routePath(s);if(n.fs===i.fs)return n.fs.mv(n.relativePath,i.relativePath);await this.cp(t,s,{recursive:!0}),await this.rm(t,{recursive:!0})}resolvePath(t,s){if(s.startsWith("/"))return this.normalizePath(s);let r=t==="/"?`/${s}`:`${t}/${s}`;return this.normalizePath(r)}getAllPaths(){let t=new Set;for(let s of this.baseFs.getAllPaths())t.add(s);for(let s of this.mounts.keys()){let r=s.split("/").filter(Boolean),n="";for(let a of r)n=`${n}/${a}`,t.add(n);let i=this.mounts.get(s);if(i)for(let a of i.filesystem.getAllPaths())a==="/"?t.add(s):t.add(`${s}${a}`)}return Array.from(t).sort()}async chmod(t,s){let r=this.normalizePath(t),n=this.mounts.get(r);if(n)return n.filesystem.chmod("/",s);let{fs:i,relativePath:a}=this.routePath(t);return i.chmod(a,s)}async symlink(t,s){let{fs:r,relativePath:n}=this.routePath(s);return r.symlink(t,n)}async link(t,s){let r=this.routePath(t),n=this.routePath(s);if(r.fs!==n.fs)throw new Error(`EXDEV: cross-device link not permitted, link '${t}' -> '${s}'`);return r.fs.link(r.relativePath,n.relativePath)}async readlink(t){let{fs:s,relativePath:r}=this.routePath(t);return s.readlink(r)}async realpath(t){let s=this.normalizePath(t);if(this.mounts.get(s))return s;let{fs:n,relativePath:i}=this.routePath(t),a=await n.realpath(i);for(let[o,l]of this.mounts)if(s===o||s.startsWith(`${o}/`))return a==="/"?o:`${o}${a}`;return a}async crossMountCopy(t,s,r){let n=await this.lstat(t);if(n.isFile){let i=await this.readFile(t);await this.writeFile(s,i),await this.chmod(s,n.mode)}else if(n.isDirectory){if(!r?.recursive)throw new Error(`cp: ${t} is a directory (not copied)`);await this.mkdir(s,{recursive:!0});let i=await this.readdir(t);for(let a of i){let o=t==="/"?`/${a}`:`${t}/${a}`,l=s==="/"?`/${a}`:`${s}/${a}`;await this.crossMountCopy(o,l,r)}}else if(n.isSymbolicLink){let i=await this.readlink(t);await this.symlink(i,s)}}async utimes(t,s,r){let{fs:n,relativePath:i}=this.routePath(t);return n.utimes(i,s,r)}};import*as ie from"node:fs";import*as xt from"node:path";var vl="/home/user/project";function he(e,t){if(e.includes("\0"))throw new Error(`ENOENT: path contains null byte, ${t} '${e}'`)}var _t=class{root;mountPoint;readOnly;maxFileReadSize;memory=new Map;deleted=new Set;constructor(t){this.root=xt.resolve(t.root);let s=t.mountPoint??vl;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,!ie.existsSync(this.root))throw new Error(`OverlayFs root does not exist: ${this.root}`);if(!ie.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 r of t)s+=`/${r}`,this.memory.has(s)||this.memory.set(s,{type:"directory",mode:493,mtime:new Date});this.memory.has("/")||this.memory.set("/",{type:"directory",mode:493,mtime:new Date})}getMountPoint(){return this.mountPoint}mkdirSync(t,s){let n=this.normalizePath(t).split("/").filter(Boolean),i="";for(let a of n)i+=`/${a}`,this.memory.has(i)||this.memory.set(i,{type:"directory",mode:493,mtime:new Date})}writeFileSync(t,s){let r=this.normalizePath(t),n=this.getDirname(r);n!=="/"&&this.mkdirSync(n);let{chunks:i,size:a}=mt(s);this.memory.set(r,{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 r=s.split("/").filter(i=>i&&i!=="."),n=[];for(let i of r)i===".."?n.pop():n.push(i);return`/${n.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),r=this.getRelativeToMount(s);if(r===null)return null;let n=xt.join(this.root,r),i=xt.resolve(n);return!i.startsWith(this.root)&&i!==this.root.replace(/\/$/,"")?null:i}dirname(t){let s=this.normalizePath(t);if(s==="/")return"/";let r=s.lastIndexOf("/");return r===0?"/":s.slice(0,r)}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 r=this.toRealPath(s);if(!r)return!1;try{return await ie.promises.access(r),!0}catch{return!1}}async readFile(t){let s=await this.readFileChunks(t);return ht(s)}async readRange(t,s,r){yt(s,r);let n=await this.resolveForRead(t);if(n.kind==="memory")return cs(n.chunks,n.size,s,r);if(r===0||s>=n.size)return new Uint8Array(0);let i=Math.min(r,n.size-s),a=new Uint8Array(i),o=await ie.promises.open(n.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){he(t,"open");let r=this.normalizePath(t);if(s.has(r))throw new Error(`ELOOP: too many levels of symbolic links, open '${t}'`);if(s.add(r),this.deleted.has(r))throw new Error(`ENOENT: no such file or directory, open '${t}'`);let n=this.memory.get(r);if(n){if(n.type==="symlink"){let a=this.resolveSymlink(r,n.target);return this.resolveForRead(a,s)}if(n.type!=="file")throw new Error(`EISDIR: illegal operation on a directory, read '${t}'`);return{kind:"memory",chunks:n.chunks,size:n.size}}let i=this.toRealPath(r);if(!i)throw new Error(`ENOENT: no such file or directory, open '${t}'`);try{let a=await ie.promises.lstat(i);if(a.isSymbolicLink()){let o=await ie.promises.readlink(i),l=this.resolveSymlink(r,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 r=await this.readFileChunks(t),n=_e(s);return ls(r,n)}async readFileChunks(t,s=new Set){he(t,"open");let r=this.normalizePath(t);if(s.has(r))throw new Error(`ELOOP: too many levels of symbolic links, open '${t}'`);if(s.add(r),this.deleted.has(r))throw new Error(`ENOENT: no such file or directory, open '${t}'`);let n=this.memory.get(r);if(n){if(n.type==="symlink"){let a=this.resolveSymlink(r,n.target);return this.readFileChunks(a,s)}if(n.type!=="file")throw new Error(`EISDIR: illegal operation on a directory, read '${t}'`);return n.chunks}let i=this.toRealPath(r);if(!i)throw new Error(`ENOENT: no such file or directory, open '${t}'`);try{let a=await ie.promises.lstat(i);if(a.isSymbolicLink()){let u=await ie.promises.readlink(i),f=this.resolveSymlink(r,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 ie.promises.readFile(i),l=new Uint8Array(o.buffer,o.byteOffset,o.byteLength),{chunks:c}=mt(l);return c}catch(a){throw a.code==="ENOENT"?new Error(`ENOENT: no such file or directory, open '${t}'`):a}}async writeFile(t,s,r){he(t,"write"),this.assertWritable(`write '${t}'`);let n=this.normalizePath(t);this.ensureParentDirs(n);let i=_e(r),{chunks:a,size:o}=await Ze(s,i);this.memory.set(n,{type:"file",chunks:a,size:o,mode:420,mtime:new Date}),this.deleted.delete(n)}async appendFile(t,s,r){he(t,"append"),this.assertWritable(`append '${t}'`);let n=this.normalizePath(t),i=_e(r),{chunks:a,size:o}=await Ze(s,i),l=[],c=0;try{l=await this.readFileChunks(n);for(let u of l)c+=u.length}catch{}this.ensureParentDirs(n),this.memory.set(n,{type:"file",chunks:[...l,...a],size:c+o,mode:420,mtime:new Date}),this.deleted.delete(n)}async exists(t){return t.includes("\0")?!1:this.existsInOverlay(t)}async stat(t,s=new Set){he(t,"stat");let r=this.normalizePath(t);if(s.has(r))throw new Error(`ELOOP: too many levels of symbolic links, stat '${t}'`);if(s.add(r),this.deleted.has(r))throw new Error(`ENOENT: no such file or directory, stat '${t}'`);let n=this.memory.get(r);if(n){if(n.type==="symlink"){let o=this.resolveSymlink(r,n.target);return this.stat(o,s)}let a=0;return n.type==="file"&&(a=n.size),{isFile:n.type==="file",isDirectory:n.type==="directory",isSymbolicLink:!1,mode:n.mode,size:a,mtime:n.mtime}}let i=this.toRealPath(r);if(!i)throw new Error(`ENOENT: no such file or directory, stat '${t}'`);try{let a=await ie.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){he(t,"lstat");let s=this.normalizePath(t);if(this.deleted.has(s))throw new Error(`ENOENT: no such file or directory, lstat '${t}'`);let r=this.memory.get(s);if(r){if(r.type==="symlink")return{isFile:!1,isDirectory:!1,isSymbolicLink:!0,mode:r.mode,size:r.target.length,mtime:r.mtime};let i=0;return r.type==="file"&&(i=r.size),{isFile:r.type==="file",isDirectory:r.type==="directory",isSymbolicLink:!1,mode:r.mode,size:i,mtime:r.mtime}}let n=this.toRealPath(s);if(!n)throw new Error(`ENOENT: no such file or directory, lstat '${t}'`);try{let i=await ie.promises.lstat(n);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 r=this.dirname(t);return this.normalizePath(r==="/"?`/${s}`:`${r}/${s}`)}async mkdir(t,s){he(t,"mkdir"),this.assertWritable(`mkdir '${t}'`);let r=this.normalizePath(t);if(await this.existsInOverlay(r)){if(!s?.recursive)throw new Error(`EEXIST: file already exists, mkdir '${t}'`);return}let i=this.dirname(r);if(i!=="/"&&!await this.existsInOverlay(i))if(s?.recursive)await this.mkdir(i,{recursive:!0});else throw new Error(`ENOENT: no such file or directory, mkdir '${t}'`);this.memory.set(r,{type:"directory",mode:493,mtime:new Date}),this.deleted.delete(r)}async readdirCore(t,s){if(this.deleted.has(s))throw new Error(`ENOENT: no such file or directory, scandir '${t}'`);let r=new Map,n=new Set,i=s==="/"?"/":`${s}/`;for(let o of this.deleted)if(o.startsWith(i)){let l=o.slice(i.length),c=l.split("/")[0];c&&!l.includes("/",c.length)&&n.add(c)}for(let[o,l]of this.memory)if(o!==s&&o.startsWith(i)){let c=o.slice(i.length),u=c.split("/")[0];u&&!n.has(u)&&!c.includes("/",1)&&r.set(u,{name:u,isFile:l.type==="file",isDirectory:l.type==="directory",isSymbolicLink:l.type==="symlink"})}let a=this.toRealPath(s);if(a)try{let o=await ie.promises.readdir(a,{withFileTypes:!0});for(let l of o)!n.has(l.name)&&!r.has(l.name)&&r.set(l.name,{name:l.name,isFile:l.isFile(),isDirectory:l.isDirectory(),isSymbolicLink:l.isSymbolicLink()})}catch(o){if(o.code==="ENOENT"){if(!this.memory.has(s))throw new Error(`ENOENT: no such file or directory, scandir '${t}'`)}else if(o.code!=="ENOTDIR")throw o}return r}async resolveForReaddir(t,s=!1){let r=this.normalizePath(t),n=new Set,i=s,a=this.memory.get(r);for(;a&&a.type==="symlink";){if(n.has(r))throw new Error(`ELOOP: too many levels of symbolic links, scandir '${t}'`);n.add(r),i=!0,r=this.resolveSymlink(r,a.target),a=this.memory.get(r)}if(a)return{normalized:r,outsideOverlay:!1};if(this.getRelativeToMount(r)===null)return{normalized:r,outsideOverlay:!0};let l=this.toRealPath(r);if(!l)return{normalized:r,outsideOverlay:!0};try{if((await ie.promises.lstat(l)).isSymbolicLink()){let u=await ie.promises.readlink(l),f=this.resolveSymlink(r,u);return this.resolveForReaddir(f,!0)}return{normalized:r,outsideOverlay:!1}}catch{return i?{normalized:r,outsideOverlay:!0}:{normalized:r,outsideOverlay:!1}}}async readdir(t){he(t,"scandir");let{normalized:s,outsideOverlay:r}=await this.resolveForReaddir(t);if(r)return[];let n=await this.readdirCore(t,s);return Array.from(n.keys()).sort((i,a)=>i<a?-1:i>a?1:0)}async readdirWithFileTypes(t){he(t,"scandir");let{normalized:s,outsideOverlay:r}=await this.resolveForReaddir(t);if(r)return[];let n=await this.readdirCore(t,s);return Array.from(n.values()).sort((i,a)=>i.name<a.name?-1:i.name>a.name?1:0)}async rm(t,s){he(t,"rm"),this.assertWritable(`rm '${t}'`);let r=this.normalizePath(t);if(!await this.existsInOverlay(r)){if(s?.force)return;throw new Error(`ENOENT: no such file or directory, rm '${t}'`)}try{if((await this.stat(r)).isDirectory){let a=await this.readdir(r);if(a.length>0){if(!s?.recursive)throw new Error(`ENOTEMPTY: directory not empty, rm '${t}'`);for(let o of a){let l=r==="/"?`/${o}`:`${r}/${o}`;await this.rm(l,s)}}}}catch{}this.deleted.add(r),this.memory.delete(r)}async cp(t,s,r){he(t,"cp"),he(s,"cp"),this.assertWritable(`cp '${s}'`);let n=this.normalizePath(t),i=this.normalizePath(s);if(!await this.existsInOverlay(n))throw new Error(`ENOENT: no such file or directory, cp '${t}'`);let o=await this.stat(n);if(o.isFile){let l=await this.readFileChunks(n);await this.writeFile(i,ht(l))}else if(o.isDirectory){if(!r?.recursive)throw new Error(`EISDIR: is a directory, cp '${t}'`);await this.mkdir(i,{recursive:!0});let l=await this.readdir(n);for(let c of l){let u=n==="/"?`/${c}`:`${n}/${c}`,f=i==="/"?`/${c}`:`${i}/${c}`;await this.cp(u,f,r)}}}async mv(t,s){this.assertWritable(`mv '${s}'`),await this.cp(t,s,{recursive:!0}),await this.rm(t,{recursive:!0})}resolvePath(t,s){if(s.startsWith("/"))return this.normalizePath(s);let r=t==="/"?`/${s}`:`${t}/${s}`;return this.normalizePath(r)}getAllPaths(){let t=new Set(this.memory.keys());for(let s of this.deleted)t.delete(s);return this.scanRealFs("/",t),Array.from(t)}scanRealFs(t,s){if(this.deleted.has(t))return;let r=this.toRealPath(t);if(r)try{let n=ie.readdirSync(r);for(let i of n){let a=t==="/"?`/${i}`:`${t}/${i}`;if(this.deleted.has(a))continue;s.add(a);let o=xt.join(r,i);ie.statSync(o).isDirectory()&&this.scanRealFs(a,s)}}catch{}}async chmod(t,s){he(t,"chmod"),this.assertWritable(`chmod '${t}'`);let r=this.normalizePath(t);if(!await this.existsInOverlay(r))throw new Error(`ENOENT: no such file or directory, chmod '${t}'`);let i=this.memory.get(r);if(i){i.mode=s;return}let a=await this.stat(r);if(a.isFile){let o=await this.readFileChunks(r),l=0;for(let c of o)l+=c.length;this.memory.set(r,{type:"file",chunks:o,size:l,mode:s,mtime:new Date})}else a.isDirectory&&this.memory.set(r,{type:"directory",mode:s,mtime:new Date})}async symlink(t,s){he(s,"symlink"),this.assertWritable(`symlink '${s}'`);let r=this.normalizePath(s);if(await this.existsInOverlay(r))throw new Error(`EEXIST: file already exists, symlink '${s}'`);this.ensureParentDirs(r),this.memory.set(r,{type:"symlink",target:t,mode:511,mtime:new Date}),this.deleted.delete(r)}async link(t,s){he(t,"link"),he(s,"link"),this.assertWritable(`link '${s}'`);let r=this.normalizePath(t),n=this.normalizePath(s);if(!await this.existsInOverlay(r))throw new Error(`ENOENT: no such file or directory, link '${t}'`);let a=await this.stat(r);if(!a.isFile)throw new Error(`EPERM: operation not permitted, link '${t}'`);if(await this.existsInOverlay(n))throw new Error(`EEXIST: file already exists, link '${s}'`);let l=await this.readFileChunks(r),c=0;for(let u of l)c+=u.length;this.ensureParentDirs(n),this.memory.set(n,{type:"file",chunks:l,size:c,mode:a.mode,mtime:new Date}),this.deleted.delete(n)}async readlink(t){he(t,"readlink");let s=this.normalizePath(t);if(this.deleted.has(s))throw new Error(`ENOENT: no such file or directory, readlink '${t}'`);let r=this.memory.get(s);if(r){if(r.type!=="symlink")throw new Error(`EINVAL: invalid argument, readlink '${t}'`);return r.target}let n=this.toRealPath(s);if(!n)throw new Error(`ENOENT: no such file or directory, readlink '${t}'`);try{return await ie.promises.readlink(n)}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){he(t,"realpath");let s=this.normalizePath(t),r=new Set,n=async o=>{let l=o==="/"?[]:o.slice(1).split("/"),c="";for(let u of l){if(c=`${c}/${u}`,r.has(c))throw new Error(`ELOOP: too many levels of symbolic links, realpath '${t}'`);if(this.deleted.has(c))throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);let f=this.memory.get(c),d=0,p=40;for(;f&&f.type==="symlink"&&d<p;){if(r.add(c),c=this.resolveSymlink(c,f.target),d++,r.has(c))throw new Error(`ELOOP: too many levels of symbolic links, realpath '${t}'`);if(this.deleted.has(c))throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);f=this.memory.get(c)}if(d>=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 ie.promises.lstat(m)).isSymbolicLink()){let v=await ie.promises.readlink(m);return r.add(c),c=this.resolveSymlink(c,v),n(c)}}catch(h){throw h.code==="ENOENT"?new Error(`ENOENT: no such file or directory, realpath '${t}'`):h}}}return c||"/"},i=await n(s);if(!await this.existsInOverlay(i))throw new Error(`ENOENT: no such file or directory, realpath '${t}'`);return i}async utimes(t,s,r){he(t,"utimes"),this.assertWritable(`utimes '${t}'`);let n=this.normalizePath(t);if(!await this.existsInOverlay(n))throw new Error(`ENOENT: no such file or directory, utimes '${t}'`);let a=this.memory.get(n);if(a){a.mtime=r;return}let o=await this.stat(n);if(o.isFile){let l=await this.readFileChunks(n),c=0;for(let u of l)c+=u.length;this.memory.set(n,{type:"file",chunks:l,size:c,mode:o.mode,mtime:r})}else o.isDirectory&&this.memory.set(n,{type:"directory",mode:o.mode,mtime:r})}};import*as Z from"node:fs";import*as we from"node:path";import{Readable as bl}from"node:stream";var zs=class{root;maxFileReadSize;constructor(t){if(this.root=we.resolve(t.root),this.maxFileReadSize=t.maxFileReadSize??10485760,!Z.existsSync(this.root))throw new Error(`ReadWriteFs root does not exist: ${this.root}`);if(!Z.statSync(this.root).isDirectory())throw new Error(`ReadWriteFs root is not a directory: ${this.root}`)}toRealPath(t){let s=this.normalizePath(t),r=we.join(this.root,s);return we.resolve(r)}normalizePath(t){if(!t||t==="/")return"/";let s=t.endsWith("/")&&t!=="/"?t.slice(0,-1):t;s.startsWith("/")||(s=`/${s}`);let r=s.split("/").filter(i=>i&&i!=="."),n=[];for(let i of r)i===".."?n.pop():n.push(i);return`/${n.join("/")}`||"/"}async readFile(t){let s=this.toRealPath(t);try{let n=await Z.promises.lstat(s);if(n.isDirectory())throw new Error(`EISDIR: illegal operation on a directory, read '${t}'`);if(this.maxFileReadSize>0&&n.size>this.maxFileReadSize)throw new Error(`EFBIG: file too large, read '${t}' (${n.size} bytes, max ${this.maxFileReadSize})`)}catch(n){throw n.code==="ENOENT"?new Error(`ENOENT: no such file or directory, open '${t}'`):n}let r=Z.createReadStream(s);return bl.toWeb(r)}async readRange(t,s,r){yt(s,r);let n=this.toRealPath(t),i;try{i=await Z.promises.lstat(n)}catch(c){throw c.code==="ENOENT"?new Error(`ENOENT: no such file or directory, open '${t}'`):c}if(i.isDirectory())throw new Error(`EISDIR: illegal operation on a directory, read '${t}'`);if(r===0||s>=i.size)return new Uint8Array(0);let a=Math.min(r,i.size-s),o=new Uint8Array(a),l=await Z.promises.open(n,"r");try{let{bytesRead:c}=await l.read(o,0,a,s);return c===a?o:o.subarray(0,c)}finally{await l.close()}}async readFileText(t,s){let r=await this.readFile(t),n=await re(r),i=_e(s)??"utf8";return i==="utf8"||i==="utf-8"?new TextDecoder().decode(n):typeof Buffer<"u"?Buffer.from(n).toString(i):new TextDecoder().decode(n)}async writeFile(t,s,r){let n=this.toRealPath(t),i=_e(r),a=we.dirname(n);await Z.promises.mkdir(a,{recursive:!0});let{chunks:o,size:l}=await Ze(s,i),c=new Uint8Array(l),u=0;for(let f of o)c.set(f,u),u+=f.length;await Z.promises.writeFile(n,c)}async appendFile(t,s,r){let n=this.toRealPath(t),i=_e(r),a=we.dirname(n);await Z.promises.mkdir(a,{recursive:!0});let{chunks:o,size:l}=await Ze(s,i),c=new Uint8Array(l),u=0;for(let f of o)c.set(f,u),u+=f.length;await Z.promises.appendFile(n,c)}async exists(t){let s=this.toRealPath(t);try{return await Z.promises.access(s),!0}catch{return!1}}async stat(t){let s=this.toRealPath(t);try{let r=await Z.promises.stat(s);return{isFile:r.isFile(),isDirectory:r.isDirectory(),isSymbolicLink:!1,mode:r.mode,size:r.size,mtime:r.mtime}}catch(r){throw r.code==="ENOENT"?new Error(`ENOENT: no such file or directory, stat '${t}'`):r}}async lstat(t){let s=this.toRealPath(t);try{let r=await Z.promises.lstat(s);return{isFile:r.isFile(),isDirectory:r.isDirectory(),isSymbolicLink:r.isSymbolicLink(),mode:r.mode,size:r.size,mtime:r.mtime}}catch(r){throw r.code==="ENOENT"?new Error(`ENOENT: no such file or directory, lstat '${t}'`):r}}async mkdir(t,s){let r=this.toRealPath(t);try{await Z.promises.mkdir(r,{recursive:s?.recursive})}catch(n){let i=n;throw i.code==="EEXIST"?new Error(`EEXIST: file already exists, mkdir '${t}'`):i.code==="ENOENT"?new Error(`ENOENT: no such file or directory, mkdir '${t}'`):n}}async readdir(t){return(await this.readdirWithFileTypes(t)).map(r=>r.name)}async readdirWithFileTypes(t){let s=this.toRealPath(t);try{return(await Z.promises.readdir(s,{withFileTypes:!0})).map(n=>({name:n.name,isFile:n.isFile(),isDirectory:n.isDirectory(),isSymbolicLink:n.isSymbolicLink()})).sort((n,i)=>n.name<i.name?-1:n.name>i.name?1:0)}catch(r){let n=r;throw n.code==="ENOENT"?new Error(`ENOENT: no such file or directory, scandir '${t}'`):n.code==="ENOTDIR"?new Error(`ENOTDIR: not a directory, scandir '${t}'`):r}}async rm(t,s){let r=this.toRealPath(t);try{await Z.promises.rm(r,{recursive:s?.recursive??!1,force:s?.force??!1})}catch(n){let i=n;throw i.code==="ENOENT"&&!s?.force?new Error(`ENOENT: no such file or directory, rm '${t}'`):i.code==="ENOTEMPTY"?new Error(`ENOTEMPTY: directory not empty, rm '${t}'`):n}}async cp(t,s,r){let n=this.toRealPath(t),i=this.toRealPath(s);try{await Z.promises.cp(n,i,{recursive:r?.recursive??!1})}catch(a){let o=a;throw o.code==="ENOENT"?new Error(`ENOENT: no such file or directory, cp '${t}'`):o.code==="EISDIR"?new Error(`EISDIR: is a directory, cp '${t}'`):a}}async mv(t,s){let r=this.toRealPath(t),n=this.toRealPath(s),i=we.dirname(n);await Z.promises.mkdir(i,{recursive:!0});try{await Z.promises.rename(r,n)}catch(a){let o=a;if(o.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, mv '${t}'`);if(o.code==="EXDEV"){await this.cp(t,s,{recursive:!0}),await this.rm(t,{recursive:!0});return}throw a}}resolvePath(t,s){if(s.startsWith("/"))return this.normalizePath(s);let r=t==="/"?`/${s}`:`${t}/${s}`;return this.normalizePath(r)}getAllPaths(){let t=[];return this.scanDir("/",t),t}scanDir(t,s){let r=this.toRealPath(t);try{let n=Z.readdirSync(r);for(let i of n){let a=t==="/"?`/${i}`:`${t}/${i}`;s.push(a);let o=we.join(r,i);Z.statSync(o).isDirectory()&&this.scanDir(a,s)}}catch{}}async chmod(t,s){let r=this.toRealPath(t);try{await Z.promises.chmod(r,s)}catch(n){throw n.code==="ENOENT"?new Error(`ENOENT: no such file or directory, chmod '${t}'`):n}}async symlink(t,s){let r=this.toRealPath(s),n=this.normalizePath(s),i=this.normalizePath(we.dirname(n)),a=t.startsWith("/")?this.normalizePath(t):this.normalizePath(i==="/"?`/${t}`:`${i}/${t}`),o=we.join(this.root,a),l=we.dirname(r),c=t.startsWith("/")?o:we.relative(l,o);try{await Z.promises.symlink(c,r)}catch(u){throw u.code==="EEXIST"?new Error(`EEXIST: file already exists, symlink '${s}'`):u}}async link(t,s){let r=this.toRealPath(t),n=this.toRealPath(s);try{await Z.promises.link(r,n)}catch(i){let a=i;throw a.code==="ENOENT"?new Error(`ENOENT: no such file or directory, link '${t}'`):a.code==="EEXIST"?new Error(`EEXIST: file already exists, link '${s}'`):a.code==="EPERM"?new Error(`EPERM: operation not permitted, link '${t}'`):i}}async readlink(t){let s=this.toRealPath(t);try{return await Z.promises.readlink(s)}catch(r){let n=r;throw n.code==="ENOENT"?new Error(`ENOENT: no such file or directory, readlink '${t}'`):n.code==="EINVAL"?new Error(`EINVAL: invalid argument, readlink '${t}'`):r}}async realpath(t){let s=this.toRealPath(t);try{let r=await Z.promises.realpath(s),n=await Z.promises.realpath(this.root);if(r.startsWith(n))return r.slice(n.length)||"/";throw new Error(`ENOENT: no such file or directory, realpath '${t}'`)}catch(r){let n=r;throw n.code==="ENOENT"?new Error(`ENOENT: no such file or directory, realpath '${t}'`):n.code==="ELOOP"?new Error(`ELOOP: too many levels of symbolic links, realpath '${t}'`):r}}async utimes(t,s,r){let n=this.toRealPath(t);try{await Z.promises.utimes(n,s,r)}catch(i){throw i.code==="ENOENT"?new Error(`ENOENT: no such file or directory, utimes '${t}'`):i}}};var El=4*1024*1024,Nt=class{cmdId;cwd;pid;startedAt;exitCode;bashEnv;cmdLine;env;explicitCwd;processes;shellProcesses;logMessages=[];retainedLogBytes=0;droppedLogMessages=0;logReaders=new Set;logsComplete=!1;stdoutDecoder=new TextDecoder;stderrDecoder=new TextDecoder;resultPromise;constructor(t,s,r,n,i=!1,a=new Le,o=t.processes){this.cmdId=crypto.randomUUID(),this.cwd=r,this.startedAt=new Date,this.bashEnv=t,this.processes=a,this.shellProcesses=o,this.cmdLine=s,this.env=n,this.explicitCwd=i;let l=()=>{},c=()=>{};this.resultPromise=new Promise((u,f)=>{l=u,c=f}),this.pid=a.start(this.cmdLine,async(u,f)=>{try{let d=await Promise.race([this.execute(f),this.resultOnAbort(f)]);return this.exitCode=d.exitCode,l(d),d.exitCode}catch(d){throw c(d),d}finally{this.appendLog("stdout",this.stdoutDecoder.decode(),new Date),this.appendLog("stderr",this.stderrDecoder.decode(),new Date),this.logsComplete=!0;let d=[...this.logReaders];this.logReaders.clear();for(let p of d)p()}}),a.wait(this.pid)}resultOnAbort(t){let s=()=>({stdoutText:this.logMessages.filter(r=>r.type==="stdout").map(r=>r.data).join(""),stderrText:this.logMessages.filter(r=>r.type==="stderr").map(r=>r.data).join(""),exitCode:ts(t.reason)});return t.aborted?Promise.resolve(s()):new Promise(r=>{t.addEventListener("abort",()=>r(s()),{once:!0})})}appendLog(t,s,r){if(s.length===0||this.logsComplete)return;for(this.logMessages.push({type:t,data:s,timestamp:r}),this.retainedLogBytes+=s.length;this.retainedLogBytes>El&&this.logMessages.length>1;){let i=this.logMessages.shift();this.retainedLogBytes-=i?.data.length??0,this.droppedLogMessages++}let n=[...this.logReaders];this.logReaders.clear();for(let i of n)i()}async execute(t){let s={write:l=>{this.appendLog("stdout",this.stdoutDecoder.decode(l,{stream:!0}),new Date)}},r={write:l=>{this.appendLog("stderr",this.stderrDecoder.decode(l,{stream:!0}),new Date)}},n={cwd:this.explicitCwd?this.cwd:void 0,env:this.env,processes:this.shellProcesses,signal:t,stdoutSink:s,stderrSink:r},i=await this.bashEnv.exec(this.cmdLine,n);this.exitCode=i.exitCode;let[a,o]=await Promise.all([Qt(i.stdout),Qt(i.stderr)]);return{stdoutText:a,stderrText:o,exitCode:i.exitCode}}async*logs(){let t=0;for(;;){for(t<this.droppedLogMessages&&(t=this.droppedLogMessages);t-this.droppedLogMessages<this.logMessages.length;)yield this.logMessages[t-this.droppedLogMessages],t++;if(this.logsComplete)return;await new Promise(s=>{this.logReaders.add(s)})}}async wait(){return await this.resultPromise,this}async output(){let t=await this.resultPromise;return t.stdoutText+t.stderrText}async stdout(){return(await this.resultPromise).stdoutText}async stderr(){return(await this.resultPromise).stderrText}async kill(t="SIGTERM"){this.processes.kill(this.pid,t)}};var js=class e{bashEnv;commandProcesses;baseShellProcesses;commandShellProcesses=new Set;stopped=!1;stopPromise;constructor(t,s,r){this.bashEnv=t,this.commandProcesses=s,this.baseShellProcesses=r}static async create(t){let s=t?.fs;if(t?.overlayRoot){if(t?.fs)throw new Error("Cannot specify both 'fs' and 'overlayRoot' options");s=new _t({root:t.overlayRoot})}let r=new Le,n=new Le,i=new Yt({env:t?.env,cwd:t?.cwd,fs:s,processes:n,maxCallDepth:t?.maxCallDepth,maxCommandCount:t?.maxCommandCount,maxLoopIterations:t?.maxLoopIterations,network:t?.network});return new e(i,r,n)}async runCommand(t,s){if(this.stopped)throw new Error("Cannot run commands after Sandbox.stop()");let r=s?.cwd??this.bashEnv.getCwd(),n=s?.cwd!==void 0,i=!1,a=()=>{!i||o.runningCount!==0||(this.commandShellProcesses.delete(o),o.dispose())},o=new Le({onJobExit:a});this.commandShellProcesses.add(o);let l=new Nt(this.bashEnv,t,r,s?.env,n,this.commandProcesses,o);return l.wait().then(()=>{i=!0,a()},()=>{i=!0,a()}),l}async writeFiles(t){for(let[s,r]of Object.entries(t)){let n;typeof r=="string"?n=r:r.encoding==="base64"?n=Buffer.from(r.content,"base64").toString("utf-8"):n=r.content;let i=s.substring(0,s.lastIndexOf("/"))||"/";i!=="/"&&await this.bashEnv.exec(`mkdir -p ${i}`),await this.bashEnv.writeFile(s,n)}}async readFile(t,s){let r=await this.bashEnv.readFile(t);return s==="base64"?Buffer.from(r).toString("base64"):r}async mkDir(t,s){let r=s?.recursive?"-p":"";await this.bashEnv.exec(`mkdir ${r} ${t}`)}async stop(){if(!this.stopPromise){this.stopped=!0;let t=new Set([this.commandProcesses,this.baseShellProcesses,...this.commandShellProcesses]);this.commandShellProcesses.clear(),this.stopPromise=Promise.all([...t].map(s=>s.dispose())).then(()=>{})}await this.stopPromise}async extendTimeout(t){}get domain(){}get bashEnvInstance(){return this.bashEnv}};var Bs=class{violations=[];violationsByType=new Map;options;constructor(t={}){this.options={maxViolationsPerType:t.maxViolationsPerType??100,includeStackTraces:t.includeStackTraces??!0,onViolation:t.onViolation??(()=>{}),logToConsole:t.logToConsole??!1}}record(t){let s=this.options.includeStackTraces?t:{...t,stack:void 0};this.violations.unshift(s);let r=this.violationsByType.get(t.type);r||(r=[],this.violationsByType.set(t.type,r)),r.length<this.options.maxViolationsPerType&&r.push(s),this.options.logToConsole&&console.warn(`[SecurityViolation] ${t.type}: ${t.message}`,t.path),this.options.onViolation(s)}getViolations(){return[...this.violations]}getViolationsByType(t){return[...this.violationsByType.get(t)??[]]}getSummary(){let t=[];for(let[s,r]of this.violationsByType){if(r.length===0)continue;let n=new Set,i=Number.POSITIVE_INFINITY,a=0;for(let o of r)n.add(o.path),i=Math.min(i,o.timestamp),a=Math.max(a,o.timestamp);t.push({type:s,count:r.length,firstSeen:i,lastSeen:a,paths:Array.from(n)})}return t.sort((s,r)=>r.count-s.count),t}getTotalCount(){return this.violations.length}hasViolations(){return this.violations.length>0}clear(){this.violations=[],this.violationsByType.clear()}createCallback(){return t=>this.record(t)}};function ao(){return e=>{console.warn("[DefenseInDepth] Security violation detected:",`
702
702
  Type: ${e.type}`,`
703
703
  Path: ${e.path}`,`
704
704
  Message: ${e.message}`,e.executionId?`
705
- ExecutionId: ${e.executionId}`:"")}}export{pe as AbortExecutionError,Kt as Bash,dt as CHUNK_SIZE,xt as DefenseInDepthBox,R as EMPTY,Xe as InMemoryFs,Ws as MountableFs,Ct as NetworkAccessDeniedError,Tt as OverlayFs,Le as ProcessTable,Vs as ReadWriteFs,kt as RedirectNotAllowedError,zs as Sandbox,Nt as SandboxCommand,ye as SecurityViolationError,js as SecurityViolationLogger,At as TooManyRedirectsError,Ke as checkAborted,re as collectBytes,Yt as collectText,rt as concatStreams,ao as createConsoleViolationCallback,B as decode,vo as defineCommand,po as drain,S as emptyStream,W as encode,fe as fromBytes,ht as fromChunks,V as fromString,yo as getCommandNames,go as getNetworkCommandNames,wo as getPythonCommandNames,mo as mapChunks,Bs as streamChunks,ho as streamLines,fo as teeStream};
705
+ ExecutionId: ${e.executionId}`:"")}}export{pe as AbortExecutionError,Yt as Bash,dt as CHUNK_SIZE,Tt as DefenseInDepthBox,R as EMPTY,Xe as InMemoryFs,Vs as MountableFs,At as NetworkAccessDeniedError,_t as OverlayFs,Le as ProcessTable,zs as ReadWriteFs,kt as RedirectNotAllowedError,js as Sandbox,Nt as SandboxCommand,ye as SecurityViolationError,Bs as SecurityViolationLogger,Ct as TooManyRedirectsError,Ke as checkAborted,re as collectBytes,Qt as collectText,rt as concatStreams,ao as createConsoleViolationCallback,B as decode,vo as defineCommand,po as drain,P as emptyStream,W as encode,fe as fromBytes,ht as fromChunks,V as fromString,yo as getCommandNames,go as getNetworkCommandNames,wo as getPythonCommandNames,mo as mapChunks,Us as streamChunks,ho as streamLines,fo as teeStream};