just-bash 2.5.1 → 2.5.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin/chunks/chunk-UKYJ3JMW.js +17 -0
- package/dist/bin/chunks/file-LNCFDPQZ.js +23 -0
- package/dist/bin/chunks/grep-JUSJYJL4.js +9 -0
- package/dist/bin/chunks/rg-4VGBMMUO.js +33 -0
- package/dist/bin/just-bash.js +99 -99
- package/dist/bin/shell/chunks/chunk-UKYJ3JMW.js +17 -0
- package/dist/bin/shell/chunks/file-LNCFDPQZ.js +23 -0
- package/dist/bin/shell/chunks/grep-JUSJYJL4.js +9 -0
- package/dist/bin/shell/chunks/rg-4VGBMMUO.js +33 -0
- package/dist/bin/shell/shell.js +33 -33
- package/dist/bundle/browser.js +332 -332
- package/dist/bundle/chunks/chunk-PINJ2PBS.js +16 -0
- package/dist/bundle/chunks/file-XPA6O6H2.js +22 -0
- package/dist/bundle/chunks/grep-TKGBN6VV.js +8 -0
- package/dist/bundle/chunks/rg-QWPJPSNC.js +32 -0
- package/dist/bundle/index.js +116 -116
- package/dist/commands/search-engine/index.d.ts +1 -1
- package/dist/commands/search-engine/matcher.d.ts +2 -0
- package/dist/commands/search-engine/regex.d.ts +6 -1
- package/package.json +1 -1
- package/dist/bin/chunks/chunk-CTLU5QUH.js +0 -17
- package/dist/bin/chunks/file-XMPFXMUJ.js +0 -23
- package/dist/bin/chunks/grep-QCXXYC54.js +0 -9
- package/dist/bin/chunks/rg-GVIT6FTE.js +0 -33
- package/dist/bin/shell/chunks/chunk-CTLU5QUH.js +0 -17
- package/dist/bin/shell/chunks/file-XMPFXMUJ.js +0 -23
- package/dist/bin/shell/chunks/grep-QCXXYC54.js +0 -9
- package/dist/bin/shell/chunks/rg-GVIT6FTE.js +0 -33
- package/dist/bundle/chunks/chunk-OHJS5H37.js +0 -16
- package/dist/bundle/chunks/file-AWZ3TUFP.js +0 -22
- package/dist/bundle/chunks/grep-TUWLGQC2.js +0 -8
- package/dist/bundle/chunks/rg-KTCMPGU6.js +0 -32
package/dist/bundle/index.js
CHANGED
|
@@ -1,78 +1,78 @@
|
|
|
1
|
-
import{a as U,b as Y,c as G,d as te,e as J,f as R,g as W,h as Ee,i as B,j as ue,k as qe}from"./chunks/chunk-CG2HXOFG.js";import"./chunks/chunk-NUFRM6SI.js";import{a as le}from"./chunks/chunk-44UOCSGV.js";import"./chunks/chunk-DXB73IDG.js";var ge=[{name:"echo",load:async()=>(await import("./chunks/echo-VUHWYV6L.js")).echoCommand},{name:"cat",load:async()=>(await import("./chunks/cat-MV4K6AUA.js")).catCommand},{name:"printf",load:async()=>(await import("./chunks/printf-VG2POOXB.js")).printfCommand},{name:"ls",load:async()=>(await import("./chunks/ls-5W3NU5OJ.js")).lsCommand},{name:"mkdir",load:async()=>(await import("./chunks/mkdir-7UKY4B3B.js")).mkdirCommand},{name:"touch",load:async()=>(await import("./chunks/touch-MVQSKQKT.js")).touchCommand},{name:"rm",load:async()=>(await import("./chunks/rm-I2SRVF7H.js")).rmCommand},{name:"cp",load:async()=>(await import("./chunks/cp-PBJT3GBF.js")).cpCommand},{name:"mv",load:async()=>(await import("./chunks/mv-FXHEKRTB.js")).mvCommand},{name:"ln",load:async()=>(await import("./chunks/ln-Y7YB677N.js")).lnCommand},{name:"chmod",load:async()=>(await import("./chunks/chmod-FBHLEIY6.js")).chmodCommand},{name:"pwd",load:async()=>(await import("./chunks/pwd-AC4P3JKI.js")).pwdCommand},{name:"readlink",load:async()=>(await import("./chunks/readlink-EM4O3U4P.js")).readlinkCommand},{name:"head",load:async()=>(await import("./chunks/head-FZ6IQHYW.js")).headCommand},{name:"tail",load:async()=>(await import("./chunks/tail-PD4RZR6J.js")).tailCommand},{name:"wc",load:async()=>(await import("./chunks/wc-DFQKWSIZ.js")).wcCommand},{name:"stat",load:async()=>(await import("./chunks/stat-IVQBBOKN.js")).statCommand},{name:"grep",load:async()=>(await import("./chunks/grep-TUWLGQC2.js")).grepCommand},{name:"fgrep",load:async()=>(await import("./chunks/grep-TUWLGQC2.js")).fgrepCommand},{name:"egrep",load:async()=>(await import("./chunks/grep-TUWLGQC2.js")).egrepCommand},{name:"rg",load:async()=>(await import("./chunks/rg-KTCMPGU6.js")).rgCommand},{name:"sed",load:async()=>(await import("./chunks/sed-ZKODWZ6F.js")).sedCommand},{name:"awk",load:async()=>(await import("./chunks/awk2-46RTIZKB.js")).awkCommand2},{name:"sort",load:async()=>(await import("./chunks/sort-EJUT5LXD.js")).sortCommand},{name:"uniq",load:async()=>(await import("./chunks/uniq-47QVBRNC.js")).uniqCommand},{name:"comm",load:async()=>(await import("./chunks/comm-AXQM7FFF.js")).commCommand},{name:"cut",load:async()=>(await import("./chunks/cut-NVKWEAZF.js")).cutCommand},{name:"paste",load:async()=>(await import("./chunks/paste-QTGVEPH5.js")).pasteCommand},{name:"tr",load:async()=>(await import("./chunks/tr-EDGW5FG6.js")).trCommand},{name:"rev",load:async()=>(await import("./chunks/rev-FKUV5GH5.js")).rev},{name:"nl",load:async()=>(await import("./chunks/nl-KWQGFZH5.js")).nl},{name:"fold",load:async()=>(await import("./chunks/fold-6CFXIPYZ.js")).fold},{name:"expand",load:async()=>(await import("./chunks/expand-VSTNOVF5.js")).expand},{name:"unexpand",load:async()=>(await import("./chunks/unexpand-I7A2VXFD.js")).unexpand},{name:"strings",load:async()=>(await import("./chunks/strings-LRU5XCFP.js")).strings},{name:"split",load:async()=>(await import("./chunks/split-YBTFW7MT.js")).split},{name:"column",load:async()=>(await import("./chunks/column-XPDNNO5Y.js")).column},{name:"join",load:async()=>(await import("./chunks/join-X3QYPZUA.js")).join},{name:"tee",load:async()=>(await import("./chunks/tee-2QU4NRSJ.js")).teeCommand},{name:"find",load:async()=>(await import("./chunks/find-ACOAWALE.js")).findCommand},{name:"basename",load:async()=>(await import("./chunks/basename-CFA5ZIGT.js")).basenameCommand},{name:"dirname",load:async()=>(await import("./chunks/dirname-YPJLCQYA.js")).dirnameCommand},{name:"tree",load:async()=>(await import("./chunks/tree-MEM64BW3.js")).treeCommand},{name:"du",load:async()=>(await import("./chunks/du-NQXEC3EF.js")).duCommand},{name:"env",load:async()=>(await import("./chunks/env-EG5SQSAQ.js")).envCommand},{name:"printenv",load:async()=>(await import("./chunks/env-EG5SQSAQ.js")).printenvCommand},{name:"alias",load:async()=>(await import("./chunks/alias-4UGRF4DM.js")).aliasCommand},{name:"unalias",load:async()=>(await import("./chunks/alias-4UGRF4DM.js")).unaliasCommand},{name:"history",load:async()=>(await import("./chunks/history-MQDK2OPD.js")).historyCommand},{name:"xargs",load:async()=>(await import("./chunks/xargs-4FRA6OJ7.js")).xargsCommand},{name:"true",load:async()=>(await import("./chunks/true-CNJ54NE6.js")).trueCommand},{name:"false",load:async()=>(await import("./chunks/true-CNJ54NE6.js")).falseCommand},{name:"clear",load:async()=>(await import("./chunks/clear-VT2LJIDX.js")).clearCommand},{name:"bash",load:async()=>(await import("./chunks/bash-ZILV3VHA.js")).bashCommand},{name:"sh",load:async()=>(await import("./chunks/bash-ZILV3VHA.js")).shCommand},{name:"jq",load:async()=>(await import("./chunks/jq-3YU5HRKE.js")).jqCommand},{name:"base64",load:async()=>(await import("./chunks/base64-3BME25ON.js")).base64Command},{name:"diff",load:async()=>(await import("./chunks/diff-ZLJYSBRK.js")).diffCommand},{name:"date",load:async()=>(await import("./chunks/date-PN3CMG7K.js")).dateCommand},{name:"sleep",load:async()=>(await import("./chunks/sleep-AK4QE4WR.js")).sleepCommand},{name:"timeout",load:async()=>(await import("./chunks/timeout-X3X3N6IE.js")).timeoutCommand},{name:"seq",load:async()=>(await import("./chunks/seq-5VRIVQYP.js")).seqCommand},{name:"expr",load:async()=>(await import("./chunks/expr-DG4E7SIS.js")).exprCommand},{name:"md5sum",load:async()=>(await import("./chunks/md5sum-KLHZSRUA.js")).md5sumCommand},{name:"sha1sum",load:async()=>(await import("./chunks/sha1sum-WKWTIZGQ.js")).sha1sumCommand},{name:"sha256sum",load:async()=>(await import("./chunks/sha256sum-IUVNMBTA.js")).sha256sumCommand},{name:"file",load:async()=>(await import("./chunks/file-AWZ3TUFP.js")).fileCommand},{name:"html-to-markdown",load:async()=>(await import("./chunks/html-to-markdown-ZK6GQVSL.js")).htmlToMarkdownCommand},{name:"help",load:async()=>(await import("./chunks/help-75YOGKM4.js")).helpCommand},{name:"which",load:async()=>(await import("./chunks/which-M5MQ6QXQ.js")).whichCommand},{name:"tac",load:async()=>(await import("./chunks/tac-2X4JLF4W.js")).tac},{name:"hostname",load:async()=>(await import("./chunks/hostname-NWR32CGF.js")).hostname},{name:"od",load:async()=>(await import("./chunks/od-ECWXNUB4.js")).od},{name:"gzip",load:async()=>(await import("./chunks/gzip-L3NDJG3F.js")).gzipCommand},{name:"gunzip",load:async()=>(await import("./chunks/gzip-L3NDJG3F.js")).gunzipCommand},{name:"zcat",load:async()=>(await import("./chunks/gzip-L3NDJG3F.js")).zcatCommand}];(typeof __BROWSER__>"u"||!__BROWSER__)&&(ge.push({name:"tar",load:async()=>(await import("./chunks/tar-QWBXMF7K.js")).tarCommand}),ge.push({name:"yq",load:async()=>(await import("./chunks/yq-KANM4MD2.js")).yqCommand}),ge.push({name:"xan",load:async()=>(await import("./chunks/xan-2R2APJJ4.js")).xanCommand}),ge.push({name:"sqlite3",load:async()=>(await import("./chunks/sqlite3-5QVZOGER.js")).sqlite3Command}));var Ar=[{name:"curl",load:async()=>(await import("./chunks/curl-TVZH24MD.js")).curlCommand}],gr=new Map;function Sr(t){return{name:t.name,async execute(e,n){let r=gr.get(t.name);return r||(r=await t.load(),gr.set(t.name,r)),r.execute(e,n)}}}function jn(){return ge.map(t=>t.name)}function qn(){return Ar.map(t=>t.name)}function xr(t){return(t?ge.filter(n=>t.includes(n.name)):ge).map(Sr)}function br(){return Ar.map(Sr)}function Cr(t){return"load"in t&&typeof t.load=="function"}function Zn(t,e){return{name:t,execute:e}}function Nr(t){let e=null;return{name:t.name,async execute(n,r){return e||(e=await t.load()),e.execute(n,r)}}}var Qn=new TextEncoder,Kn=new TextDecoder;function re(t,e){if(t instanceof Uint8Array)return t;if(e==="base64")return Uint8Array.from(atob(t),n=>n.charCodeAt(0));if(e==="hex"){let n=new Uint8Array(t.length/2);for(let r=0;r<t.length;r+=2)n[r/2]=parseInt(t.slice(r,r+2),16);return n}return e==="binary"||e==="latin1"?Uint8Array.from(t,n=>n.charCodeAt(0)):Qn.encode(t)}function Ce(t,e){return e==="base64"?btoa(String.fromCharCode(...t)):e==="hex"?Array.from(t).map(n=>n.toString(16).padStart(2,"0")).join(""):e==="binary"||e==="latin1"?String.fromCharCode(...t):Kn.decode(t)}function q(t){if(t!=null)return typeof t=="string"?t:t.encoding??void 0}var Ze=new TextEncoder;function Xn(t){return typeof t=="object"&&t!==null&&!(t instanceof Uint8Array)&&"content"in t}var ne=class{data=new Map;constructor(e){if(this.data.set("/",{type:"directory",mode:493,mtime:new Date}),e)for(let[n,r]of Object.entries(e))Xn(r)?this.writeFileSync(n,r.content,void 0,{mode:r.mode,mtime:r.mtime}):this.writeFileSync(n,r)}normalizePath(e){if(!e||e==="/")return"/";let n=e.endsWith("/")&&e!=="/"?e.slice(0,-1):e;n.startsWith("/")||(n=`/${n}`);let r=n.split("/").filter(i=>i&&i!=="."),s=[];for(let i of r)i===".."?s.pop():s.push(i);return`/${s.join("/")}`||"/"}dirname(e){let n=this.normalizePath(e);if(n==="/")return"/";let r=n.lastIndexOf("/");return r===0?"/":n.slice(0,r)}ensureParentDirs(e){let n=this.dirname(e);n!=="/"&&(this.data.has(n)||(this.ensureParentDirs(n),this.data.set(n,{type:"directory",mode:493,mtime:new Date})))}writeFileSync(e,n,r,s){let i=this.normalizePath(e);this.ensureParentDirs(i);let o=q(r),a=re(n,o);this.data.set(i,{type:"file",content:a,mode:s?.mode??420,mtime:s?.mtime??new Date})}async readFile(e,n){let r=await this.readFileBuffer(e),s=q(n);return Ce(r,s)}async readFileBuffer(e){let n=this.resolvePathWithSymlinks(e),r=this.data.get(n);if(!r)throw new Error(`ENOENT: no such file or directory, open '${e}'`);if(r.type!=="file")throw new Error(`EISDIR: illegal operation on a directory, read '${e}'`);return r.content instanceof Uint8Array?r.content:Ze.encode(r.content)}async writeFile(e,n,r){this.writeFileSync(e,n,r)}async appendFile(e,n,r){let s=this.normalizePath(e),i=this.data.get(s);if(i&&i.type==="directory")throw new Error(`EISDIR: illegal operation on a directory, write '${e}'`);let o=q(r),a=re(n,o);if(i?.type==="file"){let c=i.content instanceof Uint8Array?i.content:Ze.encode(i.content),l=new Uint8Array(c.length+a.length);l.set(c),l.set(a,c.length),this.data.set(s,{type:"file",content:l,mode:i.mode,mtime:new Date})}else this.writeFileSync(e,n,r)}async exists(e){try{let n=this.resolvePathWithSymlinks(e);return this.data.has(n)}catch{return!1}}async stat(e){let n=this.resolvePathWithSymlinks(e),r=this.data.get(n);if(!r)throw new Error(`ENOENT: no such file or directory, stat '${e}'`);let s=0;return r.type==="file"&&r.content&&(r.content instanceof Uint8Array?s=r.content.length:s=Ze.encode(r.content).length),{isFile:r.type==="file",isDirectory:r.type==="directory",isSymbolicLink:!1,mode:r.mode,size:s,mtime:r.mtime||new Date}}async lstat(e){let n=this.resolveIntermediateSymlinks(e),r=this.data.get(n);if(!r)throw new Error(`ENOENT: no such file or directory, lstat '${e}'`);if(r.type==="symlink")return{isFile:!1,isDirectory:!1,isSymbolicLink:!0,mode:r.mode,size:r.target.length,mtime:r.mtime||new Date};let s=0;return r.type==="file"&&r.content&&(r.content instanceof Uint8Array?s=r.content.length:s=Ze.encode(r.content).length),{isFile:r.type==="file",isDirectory:r.type==="directory",isSymbolicLink:!1,mode:r.mode,size:s,mtime:r.mtime||new Date}}resolveSymlink(e,n){if(n.startsWith("/"))return this.normalizePath(n);let r=this.dirname(e);return this.normalizePath(r==="/"?`/${n}`:`${r}/${n}`)}resolveIntermediateSymlinks(e){let n=this.normalizePath(e);if(n==="/")return"/";let r=n.slice(1).split("/");if(r.length<=1)return n;let s="",i=new Set;for(let o=0;o<r.length-1;o++){let a=r[o];s=`${s}/${a}`;let c=this.data.get(s),l=0,u=40;for(;c&&c.type==="symlink"&&l<u;){if(i.has(s))throw new Error(`ELOOP: too many levels of symbolic links, lstat '${e}'`);i.add(s),s=this.resolveSymlink(s,c.target),c=this.data.get(s),l++}if(l>=u)throw new Error(`ELOOP: too many levels of symbolic links, lstat '${e}'`)}return`${s}/${r[r.length-1]}`}resolvePathWithSymlinks(e){let n=this.normalizePath(e);if(n==="/")return"/";let r=n.slice(1).split("/"),s="",i=new Set;for(let o of r){s=`${s}/${o}`;let a=this.data.get(s),c=0,l=40;for(;a&&a.type==="symlink"&&c<l;){if(i.has(s))throw new Error(`ELOOP: too many levels of symbolic links, open '${e}'`);i.add(s),s=this.resolveSymlink(s,a.target),a=this.data.get(s),c++}if(c>=l)throw new Error(`ELOOP: too many levels of symbolic links, open '${e}'`)}return s}async mkdir(e,n){this.mkdirSync(e,n)}mkdirSync(e,n){let r=this.normalizePath(e);if(this.data.has(r)){if(this.data.get(r)?.type==="file")throw new Error(`EEXIST: file already exists, mkdir '${e}'`);if(!n?.recursive)throw new Error(`EEXIST: directory already exists, mkdir '${e}'`);return}let s=this.dirname(r);if(s!=="/"&&!this.data.has(s))if(n?.recursive)this.mkdirSync(s,{recursive:!0});else throw new Error(`ENOENT: no such file or directory, mkdir '${e}'`);this.data.set(r,{type:"directory",mode:493,mtime:new Date})}async readdir(e){return(await this.readdirWithFileTypes(e)).map(r=>r.name)}async readdirWithFileTypes(e){let n=this.normalizePath(e),r=this.data.get(n);if(!r)throw new Error(`ENOENT: no such file or directory, scandir '${e}'`);let s=new Set;for(;r&&r.type==="symlink";){if(s.has(n))throw new Error(`ELOOP: too many levels of symbolic links, scandir '${e}'`);s.add(n),n=this.resolveSymlink(n,r.target),r=this.data.get(n)}if(!r)throw new Error(`ENOENT: no such file or directory, scandir '${e}'`);if(r.type!=="directory")throw new Error(`ENOTDIR: not a directory, scandir '${e}'`);let i=n==="/"?"/":`${n}/`,o=new Map;for(let[a,c]of this.data.entries())if(a!==n&&a.startsWith(i)){let l=a.slice(i.length),u=l.split("/")[0];u&&!l.includes("/",u.length)&&!o.has(u)&&o.set(u,{name:u,isFile:c.type==="file",isDirectory:c.type==="directory",isSymbolicLink:c.type==="symlink"})}return Array.from(o.values()).sort((a,c)=>a.name<c.name?-1:a.name>c.name?1:0)}async rm(e,n){let r=this.normalizePath(e),s=this.data.get(r);if(!s){if(n?.force)return;throw new Error(`ENOENT: no such file or directory, rm '${e}'`)}if(s.type==="directory"){let i=await this.readdir(r);if(i.length>0){if(!n?.recursive)throw new Error(`ENOTEMPTY: directory not empty, rm '${e}'`);for(let o of i){let a=r==="/"?`/${o}`:`${r}/${o}`;await this.rm(a,n)}}}this.data.delete(r)}async cp(e,n,r){let s=this.normalizePath(e),i=this.normalizePath(n),o=this.data.get(s);if(!o)throw new Error(`ENOENT: no such file or directory, cp '${e}'`);if(o.type==="file")this.ensureParentDirs(i),this.data.set(i,{...o});else if(o.type==="directory"){if(!r?.recursive)throw new Error(`EISDIR: is a directory, cp '${e}'`);await this.mkdir(i,{recursive:!0});let a=await this.readdir(s);for(let c of a){let l=s==="/"?`/${c}`:`${s}/${c}`,u=i==="/"?`/${c}`:`${i}/${c}`;await this.cp(l,u,r)}}}async mv(e,n){await this.cp(e,n,{recursive:!0}),await this.rm(e,{recursive:!0})}getAllPaths(){return Array.from(this.data.keys())}resolvePath(e,n){if(n.startsWith("/"))return this.normalizePath(n);let r=e==="/"?`/${n}`:`${e}/${n}`;return this.normalizePath(r)}async chmod(e,n){let r=this.normalizePath(e),s=this.data.get(r);if(!s)throw new Error(`ENOENT: no such file or directory, chmod '${e}'`);s.mode=n}async symlink(e,n){let r=this.normalizePath(n);if(this.data.has(r))throw new Error(`EEXIST: file already exists, symlink '${n}'`);this.ensureParentDirs(r),this.data.set(r,{type:"symlink",target:e,mode:511,mtime:new Date})}async link(e,n){let r=this.normalizePath(e),s=this.normalizePath(n),i=this.data.get(r);if(!i)throw new Error(`ENOENT: no such file or directory, link '${e}'`);if(i.type!=="file")throw new Error(`EPERM: operation not permitted, link '${e}'`);if(this.data.has(s))throw new Error(`EEXIST: file already exists, link '${n}'`);this.ensureParentDirs(s),this.data.set(s,{type:"file",content:i.content,mode:i.mode,mtime:i.mtime})}async readlink(e){let n=this.normalizePath(e),r=this.data.get(n);if(!r)throw new Error(`ENOENT: no such file or directory, readlink '${e}'`);if(r.type!=="symlink")throw new Error(`EINVAL: invalid argument, readlink '${e}'`);return r.target}};var Pr="5.1.0(1)-release",vr="Linux version 5.15.0-generic (just-bash) #1 SMP PREEMPT";function We(){return{pid:process.pid,ppid:process.ppid,uid:process.getuid?.()??1e3,gid:process.getgid?.()??1e3}}function $r(){let{pid:t,ppid:e,uid:n,gid:r}=We();return`Name: bash
|
|
1
|
+
import{a as U,b as Y,c as G,d as te,e as J,f as R,g as W,h as Ee,i as B,j as fe,k as qe}from"./chunks/chunk-CG2HXOFG.js";import"./chunks/chunk-NUFRM6SI.js";import{a as le}from"./chunks/chunk-44UOCSGV.js";import"./chunks/chunk-DXB73IDG.js";var ge=[{name:"echo",load:async()=>(await import("./chunks/echo-VUHWYV6L.js")).echoCommand},{name:"cat",load:async()=>(await import("./chunks/cat-MV4K6AUA.js")).catCommand},{name:"printf",load:async()=>(await import("./chunks/printf-VG2POOXB.js")).printfCommand},{name:"ls",load:async()=>(await import("./chunks/ls-5W3NU5OJ.js")).lsCommand},{name:"mkdir",load:async()=>(await import("./chunks/mkdir-7UKY4B3B.js")).mkdirCommand},{name:"touch",load:async()=>(await import("./chunks/touch-MVQSKQKT.js")).touchCommand},{name:"rm",load:async()=>(await import("./chunks/rm-I2SRVF7H.js")).rmCommand},{name:"cp",load:async()=>(await import("./chunks/cp-PBJT3GBF.js")).cpCommand},{name:"mv",load:async()=>(await import("./chunks/mv-FXHEKRTB.js")).mvCommand},{name:"ln",load:async()=>(await import("./chunks/ln-Y7YB677N.js")).lnCommand},{name:"chmod",load:async()=>(await import("./chunks/chmod-FBHLEIY6.js")).chmodCommand},{name:"pwd",load:async()=>(await import("./chunks/pwd-AC4P3JKI.js")).pwdCommand},{name:"readlink",load:async()=>(await import("./chunks/readlink-EM4O3U4P.js")).readlinkCommand},{name:"head",load:async()=>(await import("./chunks/head-FZ6IQHYW.js")).headCommand},{name:"tail",load:async()=>(await import("./chunks/tail-PD4RZR6J.js")).tailCommand},{name:"wc",load:async()=>(await import("./chunks/wc-DFQKWSIZ.js")).wcCommand},{name:"stat",load:async()=>(await import("./chunks/stat-IVQBBOKN.js")).statCommand},{name:"grep",load:async()=>(await import("./chunks/grep-TKGBN6VV.js")).grepCommand},{name:"fgrep",load:async()=>(await import("./chunks/grep-TKGBN6VV.js")).fgrepCommand},{name:"egrep",load:async()=>(await import("./chunks/grep-TKGBN6VV.js")).egrepCommand},{name:"rg",load:async()=>(await import("./chunks/rg-QWPJPSNC.js")).rgCommand},{name:"sed",load:async()=>(await import("./chunks/sed-ZKODWZ6F.js")).sedCommand},{name:"awk",load:async()=>(await import("./chunks/awk2-46RTIZKB.js")).awkCommand2},{name:"sort",load:async()=>(await import("./chunks/sort-EJUT5LXD.js")).sortCommand},{name:"uniq",load:async()=>(await import("./chunks/uniq-47QVBRNC.js")).uniqCommand},{name:"comm",load:async()=>(await import("./chunks/comm-AXQM7FFF.js")).commCommand},{name:"cut",load:async()=>(await import("./chunks/cut-NVKWEAZF.js")).cutCommand},{name:"paste",load:async()=>(await import("./chunks/paste-QTGVEPH5.js")).pasteCommand},{name:"tr",load:async()=>(await import("./chunks/tr-EDGW5FG6.js")).trCommand},{name:"rev",load:async()=>(await import("./chunks/rev-FKUV5GH5.js")).rev},{name:"nl",load:async()=>(await import("./chunks/nl-KWQGFZH5.js")).nl},{name:"fold",load:async()=>(await import("./chunks/fold-6CFXIPYZ.js")).fold},{name:"expand",load:async()=>(await import("./chunks/expand-VSTNOVF5.js")).expand},{name:"unexpand",load:async()=>(await import("./chunks/unexpand-I7A2VXFD.js")).unexpand},{name:"strings",load:async()=>(await import("./chunks/strings-LRU5XCFP.js")).strings},{name:"split",load:async()=>(await import("./chunks/split-YBTFW7MT.js")).split},{name:"column",load:async()=>(await import("./chunks/column-XPDNNO5Y.js")).column},{name:"join",load:async()=>(await import("./chunks/join-X3QYPZUA.js")).join},{name:"tee",load:async()=>(await import("./chunks/tee-2QU4NRSJ.js")).teeCommand},{name:"find",load:async()=>(await import("./chunks/find-ACOAWALE.js")).findCommand},{name:"basename",load:async()=>(await import("./chunks/basename-CFA5ZIGT.js")).basenameCommand},{name:"dirname",load:async()=>(await import("./chunks/dirname-YPJLCQYA.js")).dirnameCommand},{name:"tree",load:async()=>(await import("./chunks/tree-MEM64BW3.js")).treeCommand},{name:"du",load:async()=>(await import("./chunks/du-NQXEC3EF.js")).duCommand},{name:"env",load:async()=>(await import("./chunks/env-EG5SQSAQ.js")).envCommand},{name:"printenv",load:async()=>(await import("./chunks/env-EG5SQSAQ.js")).printenvCommand},{name:"alias",load:async()=>(await import("./chunks/alias-4UGRF4DM.js")).aliasCommand},{name:"unalias",load:async()=>(await import("./chunks/alias-4UGRF4DM.js")).unaliasCommand},{name:"history",load:async()=>(await import("./chunks/history-MQDK2OPD.js")).historyCommand},{name:"xargs",load:async()=>(await import("./chunks/xargs-4FRA6OJ7.js")).xargsCommand},{name:"true",load:async()=>(await import("./chunks/true-CNJ54NE6.js")).trueCommand},{name:"false",load:async()=>(await import("./chunks/true-CNJ54NE6.js")).falseCommand},{name:"clear",load:async()=>(await import("./chunks/clear-VT2LJIDX.js")).clearCommand},{name:"bash",load:async()=>(await import("./chunks/bash-ZILV3VHA.js")).bashCommand},{name:"sh",load:async()=>(await import("./chunks/bash-ZILV3VHA.js")).shCommand},{name:"jq",load:async()=>(await import("./chunks/jq-3YU5HRKE.js")).jqCommand},{name:"base64",load:async()=>(await import("./chunks/base64-3BME25ON.js")).base64Command},{name:"diff",load:async()=>(await import("./chunks/diff-ZLJYSBRK.js")).diffCommand},{name:"date",load:async()=>(await import("./chunks/date-PN3CMG7K.js")).dateCommand},{name:"sleep",load:async()=>(await import("./chunks/sleep-AK4QE4WR.js")).sleepCommand},{name:"timeout",load:async()=>(await import("./chunks/timeout-X3X3N6IE.js")).timeoutCommand},{name:"seq",load:async()=>(await import("./chunks/seq-5VRIVQYP.js")).seqCommand},{name:"expr",load:async()=>(await import("./chunks/expr-DG4E7SIS.js")).exprCommand},{name:"md5sum",load:async()=>(await import("./chunks/md5sum-KLHZSRUA.js")).md5sumCommand},{name:"sha1sum",load:async()=>(await import("./chunks/sha1sum-WKWTIZGQ.js")).sha1sumCommand},{name:"sha256sum",load:async()=>(await import("./chunks/sha256sum-IUVNMBTA.js")).sha256sumCommand},{name:"file",load:async()=>(await import("./chunks/file-XPA6O6H2.js")).fileCommand},{name:"html-to-markdown",load:async()=>(await import("./chunks/html-to-markdown-ZK6GQVSL.js")).htmlToMarkdownCommand},{name:"help",load:async()=>(await import("./chunks/help-75YOGKM4.js")).helpCommand},{name:"which",load:async()=>(await import("./chunks/which-M5MQ6QXQ.js")).whichCommand},{name:"tac",load:async()=>(await import("./chunks/tac-2X4JLF4W.js")).tac},{name:"hostname",load:async()=>(await import("./chunks/hostname-NWR32CGF.js")).hostname},{name:"od",load:async()=>(await import("./chunks/od-ECWXNUB4.js")).od},{name:"gzip",load:async()=>(await import("./chunks/gzip-L3NDJG3F.js")).gzipCommand},{name:"gunzip",load:async()=>(await import("./chunks/gzip-L3NDJG3F.js")).gunzipCommand},{name:"zcat",load:async()=>(await import("./chunks/gzip-L3NDJG3F.js")).zcatCommand}];(typeof __BROWSER__>"u"||!__BROWSER__)&&(ge.push({name:"tar",load:async()=>(await import("./chunks/tar-QWBXMF7K.js")).tarCommand}),ge.push({name:"yq",load:async()=>(await import("./chunks/yq-KANM4MD2.js")).yqCommand}),ge.push({name:"xan",load:async()=>(await import("./chunks/xan-2R2APJJ4.js")).xanCommand}),ge.push({name:"sqlite3",load:async()=>(await import("./chunks/sqlite3-5QVZOGER.js")).sqlite3Command}));var Ar=[{name:"curl",load:async()=>(await import("./chunks/curl-TVZH24MD.js")).curlCommand}],gr=new Map;function Sr(t){return{name:t.name,async execute(e,s){let r=gr.get(t.name);return r||(r=await t.load(),gr.set(t.name,r)),r.execute(e,s)}}}function Hs(){return ge.map(t=>t.name)}function js(){return Ar.map(t=>t.name)}function xr(t){return(t?ge.filter(s=>t.includes(s.name)):ge).map(Sr)}function br(){return Ar.map(Sr)}function Cr(t){return"load"in t&&typeof t.load=="function"}function qs(t,e){return{name:t,execute:e}}function Nr(t){let e=null;return{name:t.name,async execute(s,r){return e||(e=await t.load()),e.execute(s,r)}}}var Zs=new TextEncoder,Qs=new TextDecoder;function re(t,e){if(t instanceof Uint8Array)return t;if(e==="base64")return Uint8Array.from(atob(t),s=>s.charCodeAt(0));if(e==="hex"){let s=new Uint8Array(t.length/2);for(let r=0;r<t.length;r+=2)s[r/2]=parseInt(t.slice(r,r+2),16);return s}return e==="binary"||e==="latin1"?Uint8Array.from(t,s=>s.charCodeAt(0)):Zs.encode(t)}function Ce(t,e){return e==="base64"?btoa(String.fromCharCode(...t)):e==="hex"?Array.from(t).map(s=>s.toString(16).padStart(2,"0")).join(""):e==="binary"||e==="latin1"?String.fromCharCode(...t):Qs.decode(t)}function q(t){if(t!=null)return typeof t=="string"?t:t.encoding??void 0}var Ze=new TextEncoder;function Ks(t){return typeof t=="object"&&t!==null&&!(t instanceof Uint8Array)&&"content"in t}var se=class{data=new Map;constructor(e){if(this.data.set("/",{type:"directory",mode:493,mtime:new Date}),e)for(let[s,r]of Object.entries(e))Ks(r)?this.writeFileSync(s,r.content,void 0,{mode:r.mode,mtime:r.mtime}):this.writeFileSync(s,r)}normalizePath(e){if(!e||e==="/")return"/";let s=e.endsWith("/")&&e!=="/"?e.slice(0,-1):e;s.startsWith("/")||(s=`/${s}`);let r=s.split("/").filter(o=>o&&o!=="."),n=[];for(let o of r)o===".."?n.pop():n.push(o);return`/${n.join("/")}`||"/"}dirname(e){let s=this.normalizePath(e);if(s==="/")return"/";let r=s.lastIndexOf("/");return r===0?"/":s.slice(0,r)}ensureParentDirs(e){let s=this.dirname(e);s!=="/"&&(this.data.has(s)||(this.ensureParentDirs(s),this.data.set(s,{type:"directory",mode:493,mtime:new Date})))}writeFileSync(e,s,r,n){let o=this.normalizePath(e);this.ensureParentDirs(o);let i=q(r),a=re(s,i);this.data.set(o,{type:"file",content:a,mode:n?.mode??420,mtime:n?.mtime??new Date})}async readFile(e,s){let r=await this.readFileBuffer(e),n=q(s);return Ce(r,n)}async readFileBuffer(e){let s=this.resolvePathWithSymlinks(e),r=this.data.get(s);if(!r)throw new Error(`ENOENT: no such file or directory, open '${e}'`);if(r.type!=="file")throw new Error(`EISDIR: illegal operation on a directory, read '${e}'`);return r.content instanceof Uint8Array?r.content:Ze.encode(r.content)}async writeFile(e,s,r){this.writeFileSync(e,s,r)}async appendFile(e,s,r){let n=this.normalizePath(e),o=this.data.get(n);if(o&&o.type==="directory")throw new Error(`EISDIR: illegal operation on a directory, write '${e}'`);let i=q(r),a=re(s,i);if(o?.type==="file"){let c=o.content instanceof Uint8Array?o.content:Ze.encode(o.content),l=new Uint8Array(c.length+a.length);l.set(c),l.set(a,c.length),this.data.set(n,{type:"file",content:l,mode:o.mode,mtime:new Date})}else this.writeFileSync(e,s,r)}async exists(e){try{let s=this.resolvePathWithSymlinks(e);return this.data.has(s)}catch{return!1}}async stat(e){let s=this.resolvePathWithSymlinks(e),r=this.data.get(s);if(!r)throw new Error(`ENOENT: no such file or directory, stat '${e}'`);let n=0;return r.type==="file"&&r.content&&(r.content instanceof Uint8Array?n=r.content.length:n=Ze.encode(r.content).length),{isFile:r.type==="file",isDirectory:r.type==="directory",isSymbolicLink:!1,mode:r.mode,size:n,mtime:r.mtime||new Date}}async lstat(e){let s=this.resolveIntermediateSymlinks(e),r=this.data.get(s);if(!r)throw new Error(`ENOENT: no such file or directory, lstat '${e}'`);if(r.type==="symlink")return{isFile:!1,isDirectory:!1,isSymbolicLink:!0,mode:r.mode,size:r.target.length,mtime:r.mtime||new Date};let n=0;return r.type==="file"&&r.content&&(r.content instanceof Uint8Array?n=r.content.length:n=Ze.encode(r.content).length),{isFile:r.type==="file",isDirectory:r.type==="directory",isSymbolicLink:!1,mode:r.mode,size:n,mtime:r.mtime||new Date}}resolveSymlink(e,s){if(s.startsWith("/"))return this.normalizePath(s);let r=this.dirname(e);return this.normalizePath(r==="/"?`/${s}`:`${r}/${s}`)}resolveIntermediateSymlinks(e){let s=this.normalizePath(e);if(s==="/")return"/";let r=s.slice(1).split("/");if(r.length<=1)return s;let n="",o=new Set;for(let i=0;i<r.length-1;i++){let a=r[i];n=`${n}/${a}`;let c=this.data.get(n),l=0,f=40;for(;c&&c.type==="symlink"&&l<f;){if(o.has(n))throw new Error(`ELOOP: too many levels of symbolic links, lstat '${e}'`);o.add(n),n=this.resolveSymlink(n,c.target),c=this.data.get(n),l++}if(l>=f)throw new Error(`ELOOP: too many levels of symbolic links, lstat '${e}'`)}return`${n}/${r[r.length-1]}`}resolvePathWithSymlinks(e){let s=this.normalizePath(e);if(s==="/")return"/";let r=s.slice(1).split("/"),n="",o=new Set;for(let i of r){n=`${n}/${i}`;let a=this.data.get(n),c=0,l=40;for(;a&&a.type==="symlink"&&c<l;){if(o.has(n))throw new Error(`ELOOP: too many levels of symbolic links, open '${e}'`);o.add(n),n=this.resolveSymlink(n,a.target),a=this.data.get(n),c++}if(c>=l)throw new Error(`ELOOP: too many levels of symbolic links, open '${e}'`)}return n}async mkdir(e,s){this.mkdirSync(e,s)}mkdirSync(e,s){let r=this.normalizePath(e);if(this.data.has(r)){if(this.data.get(r)?.type==="file")throw new Error(`EEXIST: file already exists, mkdir '${e}'`);if(!s?.recursive)throw new Error(`EEXIST: directory already exists, mkdir '${e}'`);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 '${e}'`);this.data.set(r,{type:"directory",mode:493,mtime:new Date})}async readdir(e){return(await this.readdirWithFileTypes(e)).map(r=>r.name)}async readdirWithFileTypes(e){let s=this.normalizePath(e),r=this.data.get(s);if(!r)throw new Error(`ENOENT: no such file or directory, scandir '${e}'`);let n=new Set;for(;r&&r.type==="symlink";){if(n.has(s))throw new Error(`ELOOP: too many levels of symbolic links, scandir '${e}'`);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 '${e}'`);if(r.type!=="directory")throw new Error(`ENOTDIR: not a directory, scandir '${e}'`);let o=s==="/"?"/":`${s}/`,i=new Map;for(let[a,c]of this.data.entries())if(a!==s&&a.startsWith(o)){let l=a.slice(o.length),f=l.split("/")[0];f&&!l.includes("/",f.length)&&!i.has(f)&&i.set(f,{name:f,isFile:c.type==="file",isDirectory:c.type==="directory",isSymbolicLink:c.type==="symlink"})}return Array.from(i.values()).sort((a,c)=>a.name<c.name?-1:a.name>c.name?1:0)}async rm(e,s){let r=this.normalizePath(e),n=this.data.get(r);if(!n){if(s?.force)return;throw new Error(`ENOENT: no such file or directory, rm '${e}'`)}if(n.type==="directory"){let o=await this.readdir(r);if(o.length>0){if(!s?.recursive)throw new Error(`ENOTEMPTY: directory not empty, rm '${e}'`);for(let i of o){let a=r==="/"?`/${i}`:`${r}/${i}`;await this.rm(a,s)}}}this.data.delete(r)}async cp(e,s,r){let n=this.normalizePath(e),o=this.normalizePath(s),i=this.data.get(n);if(!i)throw new Error(`ENOENT: no such file or directory, cp '${e}'`);if(i.type==="file")this.ensureParentDirs(o),this.data.set(o,{...i});else if(i.type==="directory"){if(!r?.recursive)throw new Error(`EISDIR: is a directory, cp '${e}'`);await this.mkdir(o,{recursive:!0});let a=await this.readdir(n);for(let c of a){let l=n==="/"?`/${c}`:`${n}/${c}`,f=o==="/"?`/${c}`:`${o}/${c}`;await this.cp(l,f,r)}}}async mv(e,s){await this.cp(e,s,{recursive:!0}),await this.rm(e,{recursive:!0})}getAllPaths(){return Array.from(this.data.keys())}resolvePath(e,s){if(s.startsWith("/"))return this.normalizePath(s);let r=e==="/"?`/${s}`:`${e}/${s}`;return this.normalizePath(r)}async chmod(e,s){let r=this.normalizePath(e),n=this.data.get(r);if(!n)throw new Error(`ENOENT: no such file or directory, chmod '${e}'`);n.mode=s}async symlink(e,s){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:e,mode:511,mtime:new Date})}async link(e,s){let r=this.normalizePath(e),n=this.normalizePath(s),o=this.data.get(r);if(!o)throw new Error(`ENOENT: no such file or directory, link '${e}'`);if(o.type!=="file")throw new Error(`EPERM: operation not permitted, link '${e}'`);if(this.data.has(n))throw new Error(`EEXIST: file already exists, link '${s}'`);this.ensureParentDirs(n),this.data.set(n,{type:"file",content:o.content,mode:o.mode,mtime:o.mtime})}async readlink(e){let s=this.normalizePath(e),r=this.data.get(s);if(!r)throw new Error(`ENOENT: no such file or directory, readlink '${e}'`);if(r.type!=="symlink")throw new Error(`EINVAL: invalid argument, readlink '${e}'`);return r.target}};var Pr="5.1.0(1)-release",vr="Linux version 5.15.0-generic (just-bash) #1 SMP PREEMPT";function We(){return{pid:process.pid,ppid:process.ppid,uid:process.getuid?.()??1e3,gid:process.getgid?.()??1e3}}function $r(){let{pid:t,ppid:e,uid:s,gid:r}=We();return`Name: bash
|
|
2
2
|
State: R (running)
|
|
3
3
|
Pid: ${t}
|
|
4
4
|
PPid: ${e}
|
|
5
|
-
Uid: ${
|
|
5
|
+
Uid: ${s} ${s} ${s} ${s}
|
|
6
6
|
Gid: ${r} ${r} ${r} ${r}
|
|
7
|
-
`}function
|
|
7
|
+
`}function Xs(t){let e=t;return typeof e.mkdirSync=="function"&&typeof e.writeFileSync=="function"}function Ys(t,e){t.mkdirSync("/bin",{recursive:!0}),t.mkdirSync("/usr/bin",{recursive:!0}),e&&(t.mkdirSync("/home/user",{recursive:!0}),t.mkdirSync("/tmp",{recursive:!0}))}function Js(t){t.mkdirSync("/dev",{recursive:!0}),t.writeFileSync("/dev/null",""),t.writeFileSync("/dev/zero",new Uint8Array(0)),t.writeFileSync("/dev/stdin",""),t.writeFileSync("/dev/stdout",""),t.writeFileSync("/dev/stderr","")}function en(t){t.mkdirSync("/proc/self/fd",{recursive:!0}),t.writeFileSync("/proc/version",`${vr}
|
|
8
8
|
`),t.writeFileSync("/proc/self/exe","/bin/bash"),t.writeFileSync("/proc/self/cmdline","bash\0"),t.writeFileSync("/proc/self/comm",`bash
|
|
9
|
-
`),t.writeFileSync("/proc/self/status",$r()),t.writeFileSync("/proc/self/fd/0","/dev/stdin"),t.writeFileSync("/proc/self/fd/1","/dev/stdout"),t.writeFileSync("/proc/self/fd/2","/dev/stderr")}function kr(t,e){
|
|
10
|
-
`){e+=2;continue}if(/\s/.test(t[e])){e++;continue}break}return e}var A={script(t){return{type:"Script",statements:t}},statement(t,e=[],
|
|
11
|
-
`)r+=2,
|
|
12
|
-
`)return this.pos=
|
|
13
|
-
`,start:
|
|
14
|
-
`?this.readWord(
|
|
15
|
-
`;)
|
|
16
|
-
`||p===";"||p==="&"||p==="|"||p==="("||p===")"||p==="<"||p===">"||p==="'"||p==='"'||p==="\\"||p==="$"||p==="`"||p==="{"||p==="}"||p==="~"||p==="*"||p==="?"||p==="[")break;
|
|
17
|
-
`||p===";"||p==="&"||p==="|"||p==="("||p===")"||p==="<"||p===">"){let w=
|
|
18
|
-
`||p===";"||p==="&"||p==="|"||p==="("||p===")"||p==="<"||p===">"))break;if(p==="$"&&
|
|
19
|
-
`){
|
|
20
|
-
`){w==="$"||w==="`"?
|
|
21
|
-
`;)
|
|
22
|
-
`&&(l++,c=0,D=""),
|
|
23
|
-
`&&(l++,c=0),
|
|
24
|
-
`&&(l++,c=0),
|
|
25
|
-
`&&(l++,c=0),
|
|
26
|
-
`?(l++,c=1):c++}if(this.pos=
|
|
9
|
+
`),t.writeFileSync("/proc/self/status",$r()),t.writeFileSync("/proc/self/fd/0","/dev/stdin"),t.writeFileSync("/proc/self/fd/1","/dev/stdout"),t.writeFileSync("/proc/self/fd/2","/dev/stderr")}function kr(t,e){Xs(t)&&(Ys(t,e),Js(t),en(t))}var tn=["tar","yq","xan","sqlite3"];function Ir(t){return tn.includes(t)}function T(t,e){return{type:"ArithmeticExpression",expression:ne(t,e,0).expr}}function ne(t,e,s){return rn(t,e,s)}function rn(t,e,s){let{expr:r,pos:n}=Ke(t,e,s);for(n=O(e,n);e[n]===",";){n++;let{expr:o,pos:i}=Ke(t,e,n);r={type:"ArithBinary",operator:",",left:r,right:o},n=O(e,i)}return{expr:r,pos:n}}function Ke(t,e,s){let{expr:r,pos:n}=sn(t,e,s);if(n=O(e,n),e[n]==="?"){n++;let{expr:o,pos:i}=ne(t,e,n);if(n=O(e,i),e[n]===":"){n++;let{expr:a,pos:c}=ne(t,e,n);return{expr:{type:"ArithTernary",condition:r,consequent:o,alternate:a},pos:c}}}return{expr:r,pos:n}}function sn(t,e,s){let{expr:r,pos:n}=Rr(t,e,s);for(;n=O(e,n),e.slice(n,n+2)==="||";){n+=2;let{expr:o,pos:i}=Rr(t,e,n);r={type:"ArithBinary",operator:"||",left:r,right:o},n=i}return{expr:r,pos:n}}function Rr(t,e,s){let{expr:r,pos:n}=Dr(t,e,s);for(;n=O(e,n),e.slice(n,n+2)==="&&";){n+=2;let{expr:o,pos:i}=Dr(t,e,n);r={type:"ArithBinary",operator:"&&",left:r,right:o},n=i}return{expr:r,pos:n}}function Dr(t,e,s){let{expr:r,pos:n}=Or(t,e,s);for(;n=O(e,n),e[n]==="|"&&e[n+1]!=="|";){n++;let{expr:o,pos:i}=Or(t,e,n);r={type:"ArithBinary",operator:"|",left:r,right:o},n=i}return{expr:r,pos:n}}function Or(t,e,s){let{expr:r,pos:n}=_r(t,e,s);for(;n=O(e,n),e[n]==="^";){n++;let{expr:o,pos:i}=_r(t,e,n);r={type:"ArithBinary",operator:"^",left:r,right:o},n=i}return{expr:r,pos:n}}function _r(t,e,s){let{expr:r,pos:n}=Lr(t,e,s);for(;n=O(e,n),e[n]==="&"&&e[n+1]!=="&";){n++;let{expr:o,pos:i}=Lr(t,e,n);r={type:"ArithBinary",operator:"&",left:r,right:o},n=i}return{expr:r,pos:n}}function Lr(t,e,s){let{expr:r,pos:n}=Tr(t,e,s);for(;n=O(e,n),e.slice(n,n+2)==="=="||e.slice(n,n+2)==="!=";){let o=e.slice(n,n+2);n+=2;let{expr:i,pos:a}=Tr(t,e,n);r={type:"ArithBinary",operator:o,left:r,right:i},n=a}return{expr:r,pos:n}}function Tr(t,e,s){let{expr:r,pos:n}=Nt(t,e,s);for(;;)if(n=O(e,n),e.slice(n,n+2)==="<="||e.slice(n,n+2)===">="){let o=e.slice(n,n+2);n+=2;let{expr:i,pos:a}=Nt(t,e,n);r={type:"ArithBinary",operator:o,left:r,right:i},n=a}else if(e[n]==="<"||e[n]===">"){let o=e[n];n++;let{expr:i,pos:a}=Nt(t,e,n);r={type:"ArithBinary",operator:o,left:r,right:i},n=a}else break;return{expr:r,pos:n}}function Nt(t,e,s){let{expr:r,pos:n}=Fr(t,e,s);for(;n=O(e,n),e.slice(n,n+2)==="<<"||e.slice(n,n+2)===">>";){let o=e.slice(n,n+2);n+=2;let{expr:i,pos:a}=Fr(t,e,n);r={type:"ArithBinary",operator:o,left:r,right:i},n=a}return{expr:r,pos:n}}function Fr(t,e,s){let{expr:r,pos:n}=Wr(t,e,s);for(;n=O(e,n),(e[n]==="+"||e[n]==="-")&&e[n+1]!==e[n];){let o=e[n];n++;let{expr:i,pos:a}=Wr(t,e,n);r={type:"ArithBinary",operator:o,left:r,right:i},n=a}return{expr:r,pos:n}}function Wr(t,e,s){let{expr:r,pos:n}=Qe(t,e,s);for(;;)if(n=O(e,n),e[n]==="*"&&e[n+1]!=="*"){n++;let{expr:o,pos:i}=Qe(t,e,n);r={type:"ArithBinary",operator:"*",left:r,right:o},n=i}else if(e[n]==="/"||e[n]==="%"){let o=e[n];n++;let{expr:i,pos:a}=Qe(t,e,n);r={type:"ArithBinary",operator:o,left:r,right:i},n=a}else break;return{expr:r,pos:n}}function Qe(t,e,s){let{expr:r,pos:n}=Pt(t,e,s),o=O(e,n);if(e.slice(o,o+2)==="**"){o+=2;let{expr:i,pos:a}=Qe(t,e,o);return{expr:{type:"ArithBinary",operator:"**",left:r,right:i},pos:a}}return{expr:r,pos:n}}function Pt(t,e,s){let r=O(e,s);if(e.slice(r,r+2)==="++"||e.slice(r,r+2)==="--"){let n=e.slice(r,r+2);r+=2;let{expr:o,pos:i}=Pt(t,e,r);return{expr:{type:"ArithUnary",operator:n,operand:o,prefix:!0},pos:i}}if(e[r]==="+"||e[r]==="-"||e[r]==="!"||e[r]==="~"){let n=e[r];r++;let{expr:o,pos:i}=Pt(t,e,r);return{expr:{type:"ArithUnary",operator:n,operand:o,prefix:!0},pos:i}}return on(t,e,r)}function nn(t,e){let s=t[e];return s==="$"||s==="`"}function on(t,e,s){let{expr:r,pos:n}=Mr(t,e,s),o=[r];for(;nn(e,n);){let{expr:i,pos:a}=Mr(t,e,n);o.push(i),n=a}if(o.length>1&&(r={type:"ArithConcat",parts:o}),n=O(e,n),e.slice(n,n+2)==="++"||e.slice(n,n+2)==="--"){let i=e.slice(n,n+2);return n+=2,{expr:{type:"ArithUnary",operator:i,operand:r,prefix:!1},pos:n}}return{expr:r,pos:n}}function Mr(t,e,s){let r=O(e,s);if(e.slice(r,r+3)==="$(("){r+=3;let n=1,o=r;for(;r<e.length-1&&n>0;)e[r]==="("&&e[r+1]==="("?(n++,r+=2):e[r]===")"&&e[r+1]===")"?(n--,n>0&&(r+=2)):r++;let i=e.slice(o,r),{expr:a}=ne(t,i,0);return r+=2,{expr:{type:"ArithNested",expression:a},pos:r}}if(e.slice(r,r+2)==="$("&&e[r+2]!=="("){r+=2;let n=1,o=r;for(;r<e.length&&n>0;)e[r]==="("?n++:e[r]===")"&&n--,n>0&&r++;let i=e.slice(o,r);return r++,{expr:{type:"ArithCommandSubst",command:i},pos:r}}if(e[r]==="`"){r++;let n=r;for(;r<e.length&&e[r]!=="`";)r++;let o=e.slice(n,r);return e[r]==="`"&&r++,{expr:{type:"ArithCommandSubst",command:o},pos:r}}if(e[r]==="("){r++;let{expr:n,pos:o}=ne(t,e,r);return r=O(e,o),e[r]===")"&&r++,{expr:{type:"ArithGroup",expression:n},pos:r}}if(/[0-9]/.test(e[r])){let n="",o=!1;for(;r<e.length;){let a=e[r];if(o)if(/[0-9a-zA-Z@_]/.test(a))n+=a,r++;else break;else if(a==="#")o=!0,n+=a,r++;else if(/[0-9a-fA-FxX]/.test(a))n+=a,r++;else break}if(e[r]==="."&&/[0-9]/.test(e[r+1]))throw new W(`${n}.${e[r+1]}...: syntax error: invalid arithmetic operator`);if(e[r]==="["){let a=e.slice(r).trim();return{expr:{type:"ArithNumberSubscript",number:n,errorToken:a},pos:e.length}}return{expr:{type:"ArithNumber",value:Ne(n)},pos:r}}if(e[r]==="$"&&e[r+1]==="{"){let n=r+2,o=1,i=n;for(;i<e.length&&o>0;)e[i]==="{"?o++:e[i]==="}"&&o--,o>0&&i++;let a=e.slice(n,i),c=i+1;if(e[c]==="#"){let l=c+1;for(;l<e.length&&/[0-9a-zA-Z@_]/.test(e[l]);)l++;let f=e.slice(c+1,l);return{expr:{type:"ArithDynamicBase",baseExpr:a,value:f},pos:l}}if(/[0-9]/.test(e[c])||e[c]==="x"||e[c]==="X"){let l=c;if(e[c]==="x"||e[c]==="X")for(l++;l<e.length&&/[0-9a-fA-F]/.test(e[l]);)l++;else for(;l<e.length&&/[0-9]/.test(e[l]);)l++;let f=e.slice(c,l);return{expr:{type:"ArithDynamicNumber",prefix:a,suffix:f},pos:l}}return r=c,{expr:{type:"ArithBracedExpansion",content:a},pos:r}}if(e[r]==="$"&&r+1<e.length&&/[0-9]/.test(e[r+1])){r++;let n="";for(;r<e.length&&/[0-9]/.test(e[r]);)n+=e[r],r++;return{expr:{type:"ArithVariable",name:n},pos:r}}if(e[r]==="$"&&r+1<e.length&&/[a-zA-Z_]/.test(e[r+1])&&r++,/[a-zA-Z_]/.test(e[r])){let n="";for(;r<e.length&&/[a-zA-Z0-9_]/.test(e[r]);)n+=e[r],r++;if(e[r]==="["){r++;let i;if(e[r]==="'"||e[r]==='"'){let l=e[r];for(r++,i="";r<e.length&&e[r]!==l;)i+=e[r],r++;e[r]===l&&r++,r=O(e,r),e[r]==="]"&&r++}let a;if(i===void 0){let{expr:l,pos:f}=ne(t,e,r);a=l,r=f,e[r]==="]"&&r++}if(r=O(e,r),e[r]==="["&&a)return{expr:{type:"ArithDoubleSubscript",array:n,index:a},pos:r};let c=["=","+=","-=","*=","/=","%=","<<=",">>=","&=","|=","^="];for(let l of c)if(e.slice(r,r+l.length)===l&&e.slice(r,r+l.length+1)!=="=="){r+=l.length;let{expr:f,pos:h}=Ke(t,e,r);return{expr:{type:"ArithAssignment",operator:l,variable:n,subscript:a,stringKey:i,value:f},pos:h}}return{expr:{type:"ArithArrayElement",array:n,index:a,stringKey:i},pos:r}}r=O(e,r);let o=["=","+=","-=","*=","/=","%=","<<=",">>=","&=","|=","^="];for(let i of o)if(e.slice(r,r+i.length)===i&&e.slice(r,r+i.length+1)!=="=="){r+=i.length;let{expr:a,pos:c}=Ke(t,e,r);return{expr:{type:"ArithAssignment",operator:i,variable:n,value:a},pos:c}}return{expr:{type:"ArithVariable",name:n},pos:r}}return{expr:{type:"ArithNumber",value:0},pos:r}}function Ne(t){if(t.includes("#")){let[e,s]=t.split("#"),r=Number.parseInt(e,10);if(r<2||r>64)return Number.NaN;if(r<=36)return Number.parseInt(s,r);let n=0;for(let o of s){let i;if(o>="0"&&o<="9")i=o.charCodeAt(0)-48;else if(o>="a"&&o<="z")i=o.charCodeAt(0)-97+10;else if(o>="A"&&o<="Z")i=o.charCodeAt(0)-65+36;else if(o==="@")i=62;else if(o==="_")i=63;else return Number.NaN;if(i>=r)return Number.NaN;n=n*r+i}return n}return t.startsWith("0x")||t.startsWith("0X")?Number.parseInt(t.slice(2),16):t.startsWith("0")&&t.length>1&&/^[0-9]+$/.test(t)?/[89]/.test(t)?Number.NaN:Number.parseInt(t,8):Number.parseInt(t,10)}function O(t,e){for(;e<t.length;){if(t[e]==="\\"&&t[e+1]===`
|
|
10
|
+
`){e+=2;continue}if(/\s/.test(t[e])){e++;continue}break}return e}var A={script(t){return{type:"Script",statements:t}},statement(t,e=[],s=!1){return{type:"Statement",pipelines:t,operators:e,background:s}},pipeline(t,e=!1){return{type:"Pipeline",commands:t,negated:e}},simpleCommand(t,e=[],s=[],r=[]){return{type:"SimpleCommand",name:t,args:e,assignments:s,redirections:r}},word(t){return{type:"Word",parts:t}},literal(t){return{type:"Literal",value:t}},singleQuoted(t){return{type:"SingleQuoted",value:t}},doubleQuoted(t){return{type:"DoubleQuoted",parts:t}},escaped(t){return{type:"Escaped",value:t}},parameterExpansion(t,e=null){return{type:"ParameterExpansion",parameter:t,operation:e}},commandSubstitution(t,e=!1){return{type:"CommandSubstitution",body:t,legacy:e}},arithmeticExpansion(t){return{type:"ArithmeticExpansion",expression:t}},assignment(t,e,s=!1,r=null){return{type:"Assignment",name:t,value:e,append:s,array:r}},redirection(t,e,s=null){return{type:"Redirection",fd:s,operator:t,target:e}},hereDoc(t,e,s=!1,r=!1){return{type:"HereDoc",delimiter:t,content:e,stripTabs:s,quoted:r}},ifNode(t,e=null,s=[]){return{type:"If",clauses:t,elseBody:e,redirections:s}},forNode(t,e,s,r=[]){return{type:"For",variable:t,words:e,body:s,redirections:r}},whileNode(t,e,s=[]){return{type:"While",condition:t,body:e,redirections:s}},untilNode(t,e,s=[]){return{type:"Until",condition:t,body:e,redirections:s}},caseNode(t,e,s=[]){return{type:"Case",word:t,items:e,redirections:s}},caseItem(t,e,s=";;"){return{type:"CaseItem",patterns:t,body:e,terminator:s}},subshell(t,e=[]){return{type:"Subshell",body:t,redirections:e}},group(t,e=[]){return{type:"Group",body:t,redirections:e}},functionDef(t,e,s=[]){return{type:"FunctionDef",name:t,body:e,redirections:s}},conditionalCommand(t,e=[]){return{type:"ConditionalCommand",expression:t,redirections:e}},arithmeticCommand(t,e=[]){return{type:"ArithmeticCommand",expression:t,redirections:e}}};var u;(function(t){t.EOF="EOF",t.NEWLINE="NEWLINE",t.SEMICOLON="SEMICOLON",t.AMP="AMP",t.PIPE="PIPE",t.PIPE_AMP="PIPE_AMP",t.AND_AND="AND_AND",t.OR_OR="OR_OR",t.BANG="BANG",t.LESS="LESS",t.GREAT="GREAT",t.DLESS="DLESS",t.DGREAT="DGREAT",t.LESSAND="LESSAND",t.GREATAND="GREATAND",t.LESSGREAT="LESSGREAT",t.DLESSDASH="DLESSDASH",t.CLOBBER="CLOBBER",t.TLESS="TLESS",t.AND_GREAT="AND_GREAT",t.AND_DGREAT="AND_DGREAT",t.LPAREN="LPAREN",t.RPAREN="RPAREN",t.LBRACE="LBRACE",t.RBRACE="RBRACE",t.DSEMI="DSEMI",t.SEMI_AND="SEMI_AND",t.SEMI_SEMI_AND="SEMI_SEMI_AND",t.DBRACK_START="DBRACK_START",t.DBRACK_END="DBRACK_END",t.DPAREN_START="DPAREN_START",t.DPAREN_END="DPAREN_END",t.IF="IF",t.THEN="THEN",t.ELSE="ELSE",t.ELIF="ELIF",t.FI="FI",t.FOR="FOR",t.WHILE="WHILE",t.UNTIL="UNTIL",t.DO="DO",t.DONE="DONE",t.CASE="CASE",t.ESAC="ESAC",t.IN="IN",t.FUNCTION="FUNCTION",t.SELECT="SELECT",t.TIME="TIME",t.COPROC="COPROC",t.WORD="WORD",t.NAME="NAME",t.NUMBER="NUMBER",t.ASSIGNMENT_WORD="ASSIGNMENT_WORD",t.COMMENT="COMMENT",t.HEREDOC_CONTENT="HEREDOC_CONTENT"})(u||(u={}));var Xe={if:u.IF,then:u.THEN,else:u.ELSE,elif:u.ELIF,fi:u.FI,for:u.FOR,while:u.WHILE,until:u.UNTIL,do:u.DO,done:u.DONE,case:u.CASE,esac:u.ESAC,in:u.IN,function:u.FUNCTION,select:u.SELECT,time:u.TIME,coproc:u.COPROC};function Br(t){let e=t.match(/^[a-zA-Z_][a-zA-Z0-9_]*/);if(!e)return!1;let s=t.slice(e[0].length);if(s===""||s==="+")return!0;if(s[0]==="["){let r=0,n=0;for(;n<s.length;n++)if(s[n]==="[")r++;else if(s[n]==="]"&&(r--,r===0))break;if(r!==0||n>=s.length)return!1;let o=s.slice(n+1);return o===""||o==="+"}return!1}var an=[[";",";","&",u.SEMI_SEMI_AND],["<","<","<",u.TLESS],["&",">",">",u.AND_DGREAT]],cn=[["[","[",u.DBRACK_START],["]","]",u.DBRACK_END],["(","(",u.DPAREN_START],[")",")",u.DPAREN_END],["&","&",u.AND_AND],["|","|",u.OR_OR],[";",";",u.DSEMI],[";","&",u.SEMI_AND],["|","&",u.PIPE_AMP],[">",">",u.DGREAT],["<","&",u.LESSAND],[">","&",u.GREATAND],["<",">",u.LESSGREAT],[">","|",u.CLOBBER],["&",">",u.AND_GREAT]],ln={"|":u.PIPE,"&":u.AMP,";":u.SEMICOLON,"(":u.LPAREN,")":u.RPAREN,"<":u.LESS,">":u.GREAT};function fn(t){return/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t)}var Ye=class{input;pos=0;line=1;column=1;tokens=[];pendingHeredocs=[];constructor(e){this.input=e}tokenize(){let s=this.input.length,r=this.tokens,n=this.pendingHeredocs;for(;this.pos<s&&(this.skipWhitespace(),!(this.pos>=s));){if(n.length>0&&r.length>0&&r[r.length-1].type===u.NEWLINE){this.readHeredocContent();continue}let o=this.nextToken();o&&r.push(o)}return r.push({type:u.EOF,value:"",start:this.pos,end:this.pos,line:this.line,column:this.column}),r}skipWhitespace(){let e=this.input,s=e.length,r=this.pos,n=this.column,o=this.line;for(;r<s;){let i=e[r];if(i===" "||i===" ")r++,n++;else if(i==="\\"&&e[r+1]===`
|
|
11
|
+
`)r+=2,o++,n=1;else break}this.pos=r,this.column=n,this.line=o}nextToken(){let e=this.input,s=this.pos,r=this.line,n=this.column,o=e[s],i=e[s+1],a=e[s+2];if(o==="#")return this.readComment(s,r,n);if(o===`
|
|
12
|
+
`)return this.pos=s+1,this.line++,this.column=1,{type:u.NEWLINE,value:`
|
|
13
|
+
`,start:s,end:s+1,line:r,column:n};if(o==="<"&&i==="<"&&a==="-")return this.pos=s+3,this.column=n+3,this.registerHeredocFromLookahead(!0),this.makeToken(u.DLESSDASH,"<<-",s,r,n);for(let[l,f,h,d]of an)if(o===l&&i===f&&a===h)return this.pos=s+3,this.column=n+3,this.makeToken(d,l+f+h,s,r,n);if(o==="<"&&i==="<")return this.pos=s+2,this.column=n+2,this.registerHeredocFromLookahead(!1),this.makeToken(u.DLESS,"<<",s,r,n);for(let[l,f,h]of cn)if(o===l&&i===f)return this.pos=s+2,this.column=n+2,this.makeToken(h,l+f,s,r,n);let c=ln[o];return c?(this.pos=s+1,this.column=n+1,this.makeToken(c,o,s,r,n)):o==="{"?i==="}"?(this.pos=s+2,this.column=n+2,{type:u.WORD,value:"{}",start:s,end:s+2,line:r,column:n,quoted:!1,singleQuoted:!1}):this.scanBraceExpansion(s)!==null?this.readWordWithBraceExpansion(s,r,n):this.scanLiteralBraceWord(s)!==null?this.readWordWithBraceExpansion(s,r,n):i!==void 0&&i!==" "&&i!==" "&&i!==`
|
|
14
|
+
`?this.readWord(s,r,n):(this.pos=s+1,this.column=n+1,this.makeToken(u.LBRACE,"{",s,r,n)):o==="}"?this.isWordCharFollowing(s+1)?this.readWord(s,r,n):(this.pos=s+1,this.column=n+1,this.makeToken(u.RBRACE,"}",s,r,n)):o==="!"?i==="="?(this.pos=s+2,this.column=n+2,this.makeToken(u.WORD,"!=",s,r,n)):(this.pos=s+1,this.column=n+1,this.makeToken(u.BANG,"!",s,r,n)):this.readWord(s,r,n)}makeToken(e,s,r,n,o){return{type:e,value:s,start:r,end:this.pos,line:n,column:o}}readComment(e,s,r){let n=this.input,o=n.length,i=this.pos;for(;i<o&&n[i]!==`
|
|
15
|
+
`;)i++;let a=n.slice(e,i);return this.pos=i,this.column=r+(i-e),{type:u.COMMENT,value:a,start:e,end:i,line:s,column:r}}readWord(e,s,r){let n=this.input,o=n.length,i=this.pos,a=i;for(;i<o;){let p=n[i];if(p===" "||p===" "||p===`
|
|
16
|
+
`||p===";"||p==="&"||p==="|"||p==="("||p===")"||p==="<"||p===">"||p==="'"||p==='"'||p==="\\"||p==="$"||p==="`"||p==="{"||p==="}"||p==="~"||p==="*"||p==="?"||p==="[")break;i++}if(i>a){let p=n[i];if(i>=o||p===" "||p===" "||p===`
|
|
17
|
+
`||p===";"||p==="&"||p==="|"||p==="("||p===")"||p==="<"||p===">"){let w=n.slice(a,i);if(this.pos=i,this.column=r+(i-a),Xe[w])return{type:Xe[w],value:w,start:e,end:i,line:s,column:r};let g=w.indexOf("=");return g>0&&Br(w.slice(0,g))?{type:u.ASSIGNMENT_WORD,value:w,start:e,end:i,line:s,column:r}:/^[0-9]+$/.test(w)?{type:u.NUMBER,value:w,start:e,end:i,line:s,column:r}:/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(w)?{type:u.NAME,value:w,start:e,end:i,line:s,column:r,quoted:!1,singleQuoted:!1}:{type:u.WORD,value:w,start:e,end:i,line:s,column:r,quoted:!1,singleQuoted:!1}}}i=this.pos;let c=this.column,l=this.line,f="",h=!1,d=!1,m=!1,y=!1,E=n[i]==='"'||n[i]==="'";for(;i<o;){let p=n[i];if(!m&&!y&&(p===" "||p===" "||p===`
|
|
18
|
+
`||p===";"||p==="&"||p==="|"||p==="("||p===")"||p==="<"||p===">"))break;if(p==="$"&&i+1<o&&n[i+1]==="'"&&!m&&!y){for(f+="$'",i+=2,c+=2;i<o&&n[i]!=="'";)n[i]==="\\"&&i+1<o?(f+=n[i]+n[i+1],i+=2,c+=2):(f+=n[i],i++,c++);i<o&&(f+="'",i++,c++);continue}if(p==="$"&&i+1<o&&n[i+1]==='"'&&!m&&!y){i++,c++,y=!0,h=!0,f===""&&(E=!0),i++,c++;continue}if(p==="'"&&!y){m?(m=!1,E||(f+=p)):(m=!0,E?(d=!0,h=!0):f+=p),i++,c++;continue}if(p==='"'&&!m){y?(y=!1,E||(f+=p)):(y=!0,E?h=!0:f+=p),i++,c++;continue}if(p==="\\"&&!m&&i+1<o){let w=n[i+1];if(w===`
|
|
19
|
+
`){i+=2,l++,c=1;continue}if(y){if(w==='"'||w==="\\"||w==="$"||w==="`"||w===`
|
|
20
|
+
`){w==="$"||w==="`"?f+=p+w:f+=w,i+=2,c+=2;continue}}else{w==='"'||w==="'"?f+=p+w:f+=w,i+=2,c+=2;continue}}if(p==="$"&&i+1<o&&n[i+1]==="("){f+=p,i++,c++,f+=n[i],i++,c++;let w=1,g=!1,b=!1,C=0,I=!1,D="",we=n[i]==="(";for(;w>0&&i<o;){let L=n[i];if(f+=L,g)L==="'"&&(g=!1);else if(b)L==="\\"&&i+1<o?(f+=n[i+1],i++,c++):L==='"'&&(b=!1);else if(L==="'")g=!0,D="";else if(L==='"')b=!0,D="";else if(L==="\\"&&i+1<o)f+=n[i+1],i++,c++,D="";else if(L==="#"&&!we&&(D===""||/\s/.test(n[i-1]||""))){for(;i+1<o&&n[i+1]!==`
|
|
21
|
+
`;)i++,c++,f+=n[i];D=""}else/[a-zA-Z_]/.test(L)?D+=L:(D==="case"?(C++,I=!1):D==="in"&&C>0?I=!0:D==="esac"&&C>0&&(C--,I=!1),D="",L==="("?i>0&&n[i-1]==="$"?w++:I||w++:L===")"?I?I=!1:w--:L===";"&&C>0&&i+1<o&&n[i+1]===";"&&(I=!0));L===`
|
|
22
|
+
`&&(l++,c=0,D=""),i++,c++}continue}if(p==="$"&&i+1<o&&n[i+1]==="["){f+=p,i++,c++,f+=n[i],i++,c++;let w=1;for(;w>0&&i<o;){let g=n[i];f+=g,g==="["?w++:g==="]"?w--:g===`
|
|
23
|
+
`&&(l++,c=0),i++,c++}continue}if(p==="$"&&i+1<o&&n[i+1]==="{"){f+=p,i++,c++,f+=n[i],i++,c++;let w=1;for(;w>0&&i<o;){let g=n[i];f+=g,g==="{"?w++:g==="}"?w--:g===`
|
|
24
|
+
`&&(l++,c=0),i++,c++}continue}if(p==="$"&&i+1<o){let w=n[i+1];if(w==="#"||w==="?"||w==="$"||w==="!"||w==="@"||w==="*"||w==="-"||w>="0"&&w<="9"){f+=p+w,i+=2,c+=2;continue}}if(p==="`"){for(f+=p,i++,c++;i<o&&n[i]!=="`";){let w=n[i];f+=w,w==="\\"&&i+1<o&&(f+=n[i+1],i++,c++),w===`
|
|
25
|
+
`&&(l++,c=0),i++,c++}i<o&&(f+=n[i],i++,c++);continue}f+=p,i++,p===`
|
|
26
|
+
`?(l++,c=1):c++}if(this.pos=i,this.column=c,this.line=l,f==="")return{type:u.WORD,value:"",start:e,end:i,line:s,column:r,quoted:h,singleQuoted:d};if(!h&&Xe[f])return{type:Xe[f],value:f,start:e,end:i,line:s,column:r};if(!E){let p=f.indexOf("=");if(p>0&&Br(f.slice(0,p)))return{type:u.ASSIGNMENT_WORD,value:f,start:e,end:i,line:s,column:r,quoted:h,singleQuoted:d}}return/^[0-9]+$/.test(f)?{type:u.NUMBER,value:f,start:e,end:i,line:s,column:r}:fn(f)?{type:u.NAME,value:f,start:e,end:i,line:s,column:r,quoted:h,singleQuoted:d}:{type:u.WORD,value:f,start:e,end:i,line:s,column:r,quoted:h,singleQuoted:d}}readHeredocContent(){for(;this.pendingHeredocs.length>0;){let e=this.pendingHeredocs.shift();if(!e)break;let s=this.pos,r=this.line,n=this.column,o="";for(;this.pos<this.input.length;){let i=this.pos,a="";for(;this.pos<this.input.length&&this.input[this.pos]!==`
|
|
27
27
|
`;)a+=this.input[this.pos],this.pos++,this.column++;if((e.stripTabs?a.replace(/^\t+/,""):a)===e.delimiter){this.pos<this.input.length&&this.input[this.pos]===`
|
|
28
|
-
`&&(this.pos++,this.line++,this.column=1);break}
|
|
29
|
-
`&&(
|
|
30
|
-
`,this.pos++,this.line++,this.column=1)}this.tokens.push({type:
|
|
31
|
-
`||
|
|
32
|
-
`||l===";"||l==="&"||l==="|"||l==="("||l===")"||l==="<"||l===">")break;if(l==="{"){if(this.scanBraceExpansion(
|
|
33
|
-
`||c===";"||c==="&"||c==="|")return null;
|
|
34
|
-
`||
|
|
35
|
-
`,s+=2;break;case"t":r+=" ",s+=2;break;case"r":r+="\r",s+=2;break;case"\\":r+="\\",s+=2;break;case"'":r+="'",s+=2;break;case'"':r+='"',s+=2;break;case"a":r+="\x07",s+=2;break;case"b":r+="\b",s+=2;break;case"e":case"E":r+="\x1B",s+=2;break;case"f":r+="\f",s+=2;break;case"v":r+="\v",s+=2;break;case"x":{let a=e.slice(s+2,s+4),c=parseInt(a,16);Number.isNaN(c)?(r+="\\x",s+=2):(r+=String.fromCharCode(c),s+=4);break}case"u":{let a=e.slice(s+2,s+6),c=parseInt(a,16);Number.isNaN(c)?(r+="\\u",s+=2):(r+=String.fromCharCode(c),s+=6);break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":{let a="",c=s+1;for(;c<e.length&&c<s+4&&/[0-7]/.test(e[c]);)a+=e[c],c++;let l=parseInt(a,8);r+=String.fromCharCode(l),s=c;break}default:r+=i,s++}else r+=i,s++}return s<e.length&&e[s]==="'"&&s++,{part:A.literal(r),endIndex:s}}function It(t,e){let n=e.trim();return n===""?{type:"ArithmeticExpression",expression:{type:"ArithNumber",value:0}}:T(t,n)}function Hr(t){let e=[],n="",r=0;for(let s=0;s<t.length;s++){let i=t[s];i==="{"?(r++,n+=i):i==="}"?(r--,n+=i):i===","&&r===0?(e.push(n),n=""):n+=i}return e.push(n),e}function Kr(t,e,n,r){let s=kt(t,e,n,"{","}");if(s===-1)return null;let i=e.slice(n+1,s),o=i.match(/^(-?\d+)\.\.(-?\d+)(?:\.\.(-?\d+))?$/);if(o)return{part:{type:"BraceExpansion",items:[{type:"Range",start:Number.parseInt(o[1],10),end:Number.parseInt(o[2],10),step:o[3]?Number.parseInt(o[3],10):void 0,startStr:o[1],endStr:o[2]}]},endIndex:s+1};let a=i.match(/^([a-zA-Z])\.\.([a-zA-Z])(?:\.\.(-?\d+))?$/);return a?{part:{type:"BraceExpansion",items:[{type:"Range",start:a[1],end:a[2],step:a[3]?Number.parseInt(a[3],10):void 0}]},endIndex:s+1}:i.includes(",")&&r?{part:{type:"BraceExpansion",items:Hr(i).map(u=>({type:"Word",word:A.word(r(t,u,!1,!1,!1))}))},endIndex:s+1}:i.includes(",")?{part:{type:"BraceExpansion",items:Hr(i).map(u=>({type:"Word",word:A.word([A.literal(u)])}))},endIndex:s+1}:null}function Xr(t,e){let n="";for(let r of e.parts)switch(r.type){case"Literal":case"SingleQuoted":case"Escaped":n+=r.value;break;case"DoubleQuoted":n+='"';for(let s of r.parts)s.type==="Literal"||s.type==="Escaped"?n+=s.value:s.type==="ParameterExpansion"&&(n+=`\${${s.parameter}}`);n+='"';break;case"ParameterExpansion":n+=`\${${r.parameter}}`;break;case"Glob":n+=r.pattern;break;default:n+=r.type}return n}function Yr(t,e){return{[f.LESS]:"<",[f.GREAT]:">",[f.DGREAT]:">>",[f.LESSAND]:"<&",[f.GREATAND]:">&",[f.LESSGREAT]:"<>",[f.CLOBBER]:">|",[f.TLESS]:"<<<",[f.AND_GREAT]:"&>",[f.AND_DGREAT]:"&>>",[f.DLESS]:"<",[f.DLESSDASH]:"<"}[e]||">"}function Je(t){let e=t.current(),n=e.type;if(n===f.NUMBER){let r=t.peek(1);return e.end!==r.start?!1:Vr.has(r.type)}return Gr.has(n)}function et(t){let e=null;t.check(f.NUMBER)&&(e=Number.parseInt(t.advance().value,10));let n=t.advance(),r=Yr(t,n.type);if(n.type===f.DLESS||n.type===f.DLESSDASH)return hs(t,r,e,n.type===f.DLESSDASH);t.isWord()||t.error("Expected redirection target");let s=t.parseWord();return A.redirection(r,s,e)}function hs(t,e,n,r){t.isWord()||t.error("Expected here-document delimiter");let s=t.advance(),i=s.value,o=s.quoted||!1;(i.startsWith("'")&&i.endsWith("'")||i.startsWith('"')&&i.endsWith('"'))&&(i=i.slice(1,-1));let a=A.redirection(r?"<<-":"<<",A.hereDoc(i,A.word([]),r,o),n);return t.addPendingHeredoc(a,i,r,o),a}function en(t){let e=t.current().line,n=[],r=null,s=[],i=[];for(;t.check(f.ASSIGNMENT_WORD);)t.checkIterationLimit(),n.push(ds(t));for(;Je(t);)t.checkIterationLimit(),i.push(et(t));for(t.isWord()&&(r=t.parseWord());(!t.isStatementEnd()||t.check(f.RBRACE))&&!t.check(f.PIPE,f.PIPE_AMP);)if(t.checkIterationLimit(),Je(t))i.push(et(t));else if(t.check(f.RBRACE)){let a=t.advance();s.push(t.parseWordFromString(a.value,!1,!1))}else if(t.isWord())s.push(t.parseWord());else if(t.check(f.ASSIGNMENT_WORD)){let a=t.advance(),c=a.value,l=c.endsWith("="),u=c.endsWith("=(");if((l||u)&&(u||t.check(f.LPAREN))){let h=u?c.slice(0,-2):c.slice(0,-1);u||t.expect(f.LPAREN);let d=Rt(t);t.expect(f.RPAREN);let m=d.map(E=>Xr(t,E)),y=`${h}=(${m.join(" ")})`;s.push(t.parseWordFromString(y,!1,!1))}else s.push(t.parseWordFromString(c,a.quoted,a.singleQuoted))}else if(t.check(f.LPAREN))t.error("syntax error near unexpected token `('");else break;let o=A.simpleCommand(r,s,n,i);return o.line=e,o}function ds(t){let e=t.expect(f.ASSIGNMENT_WORD),n=e.value,r=n.match(/^[a-zA-Z_][a-zA-Z0-9_]*/);r||t.error(`Invalid assignment: ${n}`);let s=r[0],i,o=s.length;if(n[o]==="["){let h=0,d=o+1;for(;o<n.length;o++)if(n[o]==="[")h++;else if(n[o]==="]"&&(h--,h===0))break;h!==0&&t.error(`Invalid assignment: ${n}`),i=n.slice(d,o),o++}let a=n[o]==="+";a&&o++,n[o]!=="="&&t.error(`Invalid assignment: ${n}`),o++;let c=n.slice(o);if(c==="("){let h=Rt(t);t.expect(f.RPAREN);let d=i!==void 0?`${s}[${i}]`:s;return A.assignment(d,null,a,h)}if(c===""&&t.check(f.LPAREN)){let h=t.current();if(e.end===h.start){t.advance();let d=Rt(t);t.expect(f.RPAREN);let m=i!==void 0?`${s}[${i}]`:s;return A.assignment(m,null,a,d)}}let l=c?t.parseWordFromString(c,e.quoted,e.singleQuoted,!0):null,u=i!==void 0?`${s}[${i}]`:s;return A.assignment(u,l,a,null)}function Rt(t){let e=[];for(t.skipNewlines();!t.check(f.RPAREN,f.EOF);)t.checkIterationLimit(),t.isWord()?e.push(t.parseWord()):t.advance(),t.skipNewlines();return e}function Dt(t){t.expect(f.IF);let e=[],n=t.parseCompoundList();t.expect(f.THEN);let r=t.parseCompoundList();if(r.length===0){let o=t.check(f.FI)?"fi":t.check(f.ELSE)?"else":t.check(f.ELIF)?"elif":"fi";t.error(`syntax error near unexpected token \`${o}'`)}for(e.push({condition:n,body:r});t.check(f.ELIF);){t.advance();let o=t.parseCompoundList();t.expect(f.THEN);let a=t.parseCompoundList();if(a.length===0){let c=t.check(f.FI)?"fi":t.check(f.ELSE)?"else":t.check(f.ELIF)?"elif":"fi";t.error(`syntax error near unexpected token \`${c}'`)}e.push({condition:o,body:a})}let s=null;t.check(f.ELSE)&&(t.advance(),s=t.parseCompoundList(),s.length===0&&t.error("syntax error near unexpected token `fi'")),t.expect(f.FI);let i=t.parseOptionalRedirections();return A.ifNode(e,s,i)}function Ot(t){if(t.expect(f.FOR),t.check(f.DPAREN_START))return ps(t);t.isWord()||t.error("Expected variable name in for loop");let n=t.advance().value,r=null;if(t.skipNewlines(),t.check(f.IN))for(t.advance(),r=[];!t.check(f.SEMICOLON,f.NEWLINE,f.DO,f.EOF)&&t.isWord();)r.push(t.parseWord());t.check(f.SEMICOLON)&&t.advance(),t.skipNewlines(),t.expect(f.DO);let s=t.parseCompoundList();t.expect(f.DONE);let i=t.parseOptionalRedirections();return A.forNode(n,r,s,i)}function ps(t){t.expect(f.DPAREN_START);let e=null,n=null,r=null,s=["","",""],i=0,o=0;for(;!t.check(f.DPAREN_END,f.EOF);){let l=t.advance();if(l.type===f.SEMICOLON&&o===0){if(i++,i>2)break}else l.value==="("&&o++,l.value===")"&&o--,s[i]+=l.value}t.expect(f.DPAREN_END),s[0].trim()&&(e=T(t,s[0].trim())),s[1].trim()&&(n=T(t,s[1].trim())),s[2].trim()&&(r=T(t,s[2].trim())),t.skipNewlines(),t.check(f.SEMICOLON)&&t.advance(),t.skipNewlines(),t.expect(f.DO);let a=t.parseCompoundList();t.expect(f.DONE);let c=t.parseOptionalRedirections();return{type:"CStyleFor",init:e,condition:n,update:r,body:a,redirections:c}}function _t(t){t.expect(f.WHILE);let e=t.parseCompoundList();t.expect(f.DO);let n=t.parseCompoundList();n.length===0&&t.error("syntax error near unexpected token `done'"),t.expect(f.DONE);let r=t.parseOptionalRedirections();return A.whileNode(e,n,r)}function Lt(t){t.expect(f.UNTIL);let e=t.parseCompoundList();t.expect(f.DO);let n=t.parseCompoundList();n.length===0&&t.error("syntax error near unexpected token `done'"),t.expect(f.DONE);let r=t.parseOptionalRedirections();return A.untilNode(e,n,r)}function Tt(t){t.expect(f.CASE),t.isWord()||t.error("Expected word after 'case'");let e=t.parseWord();t.skipNewlines(),t.expect(f.IN),t.skipNewlines();let n=[];for(;!t.check(f.ESAC,f.EOF);){t.checkIterationLimit();let s=t.getPos(),i=ys(t);if(i&&n.push(i),t.skipNewlines(),t.getPos()===s&&!i)break}t.expect(f.ESAC);let r=t.parseOptionalRedirections();return A.caseNode(e,n,r)}function ys(t){t.check(f.LPAREN)&&t.advance();let e=[];for(;t.isWord()&&(e.push(t.parseWord()),t.check(f.PIPE));)t.advance();if(e.length===0)return null;t.expect(f.RPAREN),t.skipNewlines();let n=[];for(;!t.check(f.DSEMI,f.SEMI_AND,f.SEMI_SEMI_AND,f.ESAC,f.EOF);){t.checkIterationLimit(),t.isWord()&&t.peek(1).type===f.RPAREN&&t.error("syntax error near unexpected token `)'"),t.check(f.LPAREN)&&t.peek(1).type===f.WORD&&t.error(`syntax error near unexpected token \`${t.peek(1).value}'`);let s=t.getPos(),i=t.parseStatement();if(i&&n.push(i),t.skipSeparators(!1),t.getPos()===s&&!i)break}let r=";;";return t.check(f.DSEMI)?(t.advance(),r=";;"):t.check(f.SEMI_AND)?(t.advance(),r=";&"):t.check(f.SEMI_SEMI_AND)&&(t.advance(),r=";;&"),A.caseItem(e,n,r)}function Ft(t){t.peek(1).type,f.LPAREN,t.expect(f.LPAREN),t.check(f.LPAREN)&&t.advance();let e=t.parseCompoundList();t.expect(f.RPAREN);let n=t.parseOptionalRedirections();return A.subshell(e,n)}function Wt(t){t.expect(f.LBRACE);let e=t.parseCompoundList();t.expect(f.RBRACE);let n=t.parseOptionalRedirections();return A.group(e,n)}var Es=["-a","-b","-c","-d","-e","-f","-g","-h","-k","-p","-r","-s","-t","-u","-w","-x","-G","-L","-N","-O","-S","-z","-n","-o","-v","-R"],gs=["==","!=","=~","<",">","-eq","-ne","-lt","-le","-gt","-ge","-nt","-ot","-ef"];function zt(t){return t.skipNewlines(),As(t)}function As(t){let e=tn(t);for(t.skipNewlines();t.check(f.OR_OR);){t.advance(),t.skipNewlines();let n=tn(t);e={type:"CondOr",left:e,right:n},t.skipNewlines()}return e}function tn(t){let e=Mt(t);for(t.skipNewlines();t.check(f.AND_AND);){t.advance(),t.skipNewlines();let n=Mt(t);e={type:"CondAnd",left:e,right:n},t.skipNewlines()}return e}function Mt(t){return t.skipNewlines(),t.check(f.BANG)?(t.advance(),t.skipNewlines(),{type:"CondNot",operand:Mt(t)}):Ss(t)}function Ss(t){if(t.check(f.LPAREN)){t.advance();let e=zt(t);return t.expect(f.RPAREN),{type:"CondGroup",expression:e}}if(t.isWord()){let e=t.current(),n=e.value;if(Es.includes(n)&&!e.quoted&&(t.advance(),t.check(f.DBRACK_END)&&t.error(`Expected operand after ${n}`),t.isWord())){let s=t.parseWord();return{type:"CondUnary",operator:n,operand:s}}let r=t.parseWord();if(t.isWord()&&gs.includes(t.current().value)){let s=t.advance().value,i=t.parseWord();return{type:"CondBinary",operator:s,left:r,right:i}}if(t.check(f.LESS)){t.advance();let s=t.parseWord();return{type:"CondBinary",operator:"<",left:r,right:s}}if(t.check(f.GREAT)){t.advance();let s=t.parseWord();return{type:"CondBinary",operator:">",left:r,right:s}}if(t.isWord()&&t.current().value==="="){t.advance();let s=t.parseWord();return{type:"CondBinary",operator:"==",left:r,right:s}}return{type:"CondWord",word:r}}t.error("Expected conditional expression")}function bs(t,e,n){let r=n+1,s=e[r];if("@*#?$!-0123456789".includes(s))return{part:A.parameterExpansion(s),endIndex:r+1};let i="";for(;r<e.length&&/[a-zA-Z0-9_]/.test(e[r]);)i+=e[r],r++;return{part:A.parameterExpansion(i),endIndex:r}}function Cs(t,e,n,r=!1){let s=n+2,i=!1;e[s]==="!"&&(i=!0,s++);let o=!1;e[s]==="#"&&!/[}:#%/^,]/.test(e[s+1]||"}")&&(o=!0,s++);let a="",c=e[s];if(/[@*#?$!-]/.test(c)&&!/[a-zA-Z0-9_]/.test(e[s+1]||""))a=c,s++;else for(;s<e.length&&/[a-zA-Z0-9_]/.test(e[s]);)a+=e[s],s++;if(e[s]==="["){let u=kt(t,e,s,"[","]");a+=e.slice(s,u+1),s=u+1}a===""&&!i&&!o&&e[s]!=="}"&&t.error(`\${${e[s]}}: bad substitution`);let l=null;if(i){let u=a.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(u)l={type:"ArrayKeys",array:u[1],star:u[2]==="*"},a="";else if(e[s]==="*"||e[s]==="@"){let h=e[s];s++,l={type:"VarNamePrefix",prefix:a,star:h==="*"},a=""}else l={type:"Indirection"}}else if(o)if(e[s]===":")for(l={type:"LengthSliceError"};s<e.length&&e[s]!=="}";)s++;else e[s]!=="}"&&/[-+=?]/.test(e[s])?t.error(`\${#${a}${e.slice(s,e.indexOf("}",s))}}: bad substitution`):l={type:"Length"};if(!l&&s<e.length&&e[s]!=="}"){let u=Ns(t,e,s,a,r);l=u.operation,s=u.endIndex}if(s<e.length&&e[s]!=="}"){let u=e[s];if(!/[:\-+=?#%/^,@[]/.test(u)){let h=s;for(;h<e.length&&e[h]!=="}";)h++;let d=e.slice(n,h+1);t.error(`\${${d.slice(2,-1)}}: bad substitution`)}}for(;s<e.length&&e[s]!=="}";)s++;return{part:A.parameterExpansion(a,l),endIndex:s+1}}function Ns(t,e,n,r,s=!1){let i=n,o=e[i],a=e[i+1]||"";if(o===":"){let c=a;if("-=?+".includes(c)){i+=2;let w=Ae(t,e,i),g=e.slice(i,w),b=fe(t,g,!1,!1,!0,!1,s),C=A.word(b.length>0?b:[A.literal("")]);if(c==="-")return{operation:{type:"DefaultValue",word:C,checkEmpty:!0},endIndex:w};if(c==="=")return{operation:{type:"AssignDefault",word:C,checkEmpty:!0},endIndex:w};if(c==="?")return{operation:{type:"ErrorIfUnset",word:C,checkEmpty:!0},endIndex:w};if(c==="+")return{operation:{type:"UseAlternative",word:C,checkEmpty:!0},endIndex:w}}i++;let l=Ae(t,e,i),u=e.slice(i,l),h=-1,d=0,m=0;for(let p=0;p<u.length;p++){let w=u[p];if(w==="("||w==="[")d++;else if(w===")"||w==="]")d--;else if(w==="?"&&d===0)m++;else if(w===":"&&d===0)if(m>0)m--;else{h=p;break}}let y=h>=0?u.slice(0,h):u,E=h>=0?u.slice(h+1):null;return{operation:{type:"Substring",offset:It(t,y),length:E?It(t,E):null},endIndex:l}}if("-=?+".includes(o)){i++;let c=Ae(t,e,i),l=e.slice(i,c),u=fe(t,l,!1,!1,!0,!1,s),h=A.word(u.length>0?u:[A.literal("")]);if(o==="-")return{operation:{type:"DefaultValue",word:h,checkEmpty:!1},endIndex:c};if(o==="=")return{operation:{type:"AssignDefault",word:h,checkEmpty:!1},endIndex:c};if(o==="?")return{operation:{type:"ErrorIfUnset",word:l?h:null,checkEmpty:!1},endIndex:c};if(o==="+")return{operation:{type:"UseAlternative",word:h,checkEmpty:!1},endIndex:c}}if(o==="#"||o==="%"){let c=a===o,l=o==="#"?"prefix":"suffix";i+=c?2:1;let u=Ae(t,e,i),h=e.slice(i,u),d=fe(t,h,!1,!1,!1);return{operation:{type:"PatternRemoval",pattern:A.word(d.length>0?d:[A.literal("")]),side:l,greedy:c},endIndex:u}}if(o==="/"){let c=a==="/";i+=c?2:1;let l=null;e[i]==="#"?(l="start",i++):e[i]==="%"&&(l="end",i++);let u=qr(t,e,i),h=e.slice(i,u),d=fe(t,h,!1,!1,!1),m=A.word(d.length>0?d:[A.literal("")]),y=null,E=u;if(e[u]==="/"){let p=u+1,w=Ae(t,e,p),g=e.slice(p,w),b=fe(t,g,!1,!1,!1);y=A.word(b.length>0?b:[A.literal("")]),E=w}return{operation:{type:"PatternReplacement",pattern:m,replacement:y,all:c,anchor:l},endIndex:E}}if(o==="^"||o===","){let c=a===o,l=o==="^"?"upper":"lower";i+=c?2:1;let u=Ae(t,e,i),h=e.slice(i,u),d=h?A.word([A.literal(h)]):null;return{operation:{type:"CaseModification",direction:l,all:c,pattern:d},endIndex:u}}return o==="@"&&/[QPaAEK]/.test(a)?{operation:{type:"Transform",operator:a},endIndex:i+2}:{operation:null,endIndex:i}}function Bt(t,e,n,r=!1){let s=n+1;if(s>=e.length)return{part:A.literal("$"),endIndex:s};let i=e[s];if(i==="("&&e[s+1]==="(")return t.parseArithmeticExpansion(e,n);if(i==="["){let o=1,a=s+1;for(;a<e.length&&o>0;)e[a]==="["?o++:e[a]==="]"&&o--,o>0&&a++;if(o===0){let c=e.slice(s+1,a),l=T(t,c);return{part:A.arithmeticExpansion(l),endIndex:a+1}}}return i==="("?t.parseCommandSubstitution(e,n):i==="{"?Cs(t,e,n,r):/[a-zA-Z_0-9@*#?$!-]/.test(i)?bs(t,e,n):{part:A.literal("$"),endIndex:s}}function Ps(t,e){let n=[],r=0,s="",i=()=>{s&&(n.push(A.literal(s)),s="")};for(;r<e.length;){let o=e[r];if(o==="\\"&&r+1<e.length){let a=e[r+1];if(a==="$"||a==="`"){s+=a,r+=2;continue}s+=o,r++;continue}if(o==="$"){i();let{part:a,endIndex:c}=Bt(t,e,r,!0);a&&n.push(a),r=c;continue}if(o==="`"){i();let{part:a,endIndex:c}=t.parseBacktickSubstitution(e,r,!0);n.push(a),r=c;continue}s+=o,r++}return i(),n}function vs(t,e,n){let r=[],s=n,i="",o=()=>{i&&(r.push(A.literal(i)),i="")};for(;s<e.length&&e[s]!=='"';){let a=e[s];if(a==="\\"&&s+1<e.length){let c=e[s+1];if('"\\$`\n'.includes(c)){i+=c,s+=2;continue}i+=a,s++;continue}if(a==="$"){o();let{part:c,endIndex:l}=Bt(t,e,s,!0);c&&r.push(c),s=l;continue}if(a==="`"){o();let{part:c,endIndex:l}=t.parseBacktickSubstitution(e,s,!0);r.push(c),s=l;continue}i+=a,s++}return o(),{part:A.doubleQuoted(r),endIndex:s}}function fe(t,e,n=!1,r=!1,s=!1,i=!1,o=!1){if(r)return[A.singleQuoted(e)];if(n){let h=Ps(t,e);return[A.doubleQuoted(h)]}let a=[],c=0,l="",u=()=>{l&&(a.push(A.literal(l)),l="")};for(;c<e.length;){let h=e[c];if(h==="\\"&&c+1<e.length){let d=e[c+1];(i?d==="$"||d==="`"||d==="\\"||d===`
|
|
28
|
+
`&&(this.pos++,this.line++,this.column=1);break}o+=a,this.pos<this.input.length&&this.input[this.pos]===`
|
|
29
|
+
`&&(o+=`
|
|
30
|
+
`,this.pos++,this.line++,this.column=1)}this.tokens.push({type:u.HEREDOC_CONTENT,value:o,start:s,end:this.pos,line:r,column:n})}}addPendingHeredoc(e,s,r){this.pendingHeredocs.push({delimiter:e,stripTabs:s,quoted:r})}registerHeredocFromLookahead(e){let s=this.pos,r=this.column;for(;this.pos<this.input.length&&(this.input[this.pos]===" "||this.input[this.pos]===" ");)this.pos++,this.column++;let n="",o=!1,i=this.input[this.pos];if(i==="'"||i==='"'){o=!0;let a=i;for(this.pos++,this.column++;this.pos<this.input.length&&this.input[this.pos]!==a;)n+=this.input[this.pos],this.pos++,this.column++}else for(;this.pos<this.input.length&&!/[\s;<>&|()]/.test(this.input[this.pos]);)n+=this.input[this.pos],this.pos++,this.column++;this.pos=s,this.column=r,n&&this.pendingHeredocs.push({delimiter:n,stripTabs:e,quoted:o})}isWordCharFollowing(e){if(e>=this.input.length)return!1;let s=this.input[e];return!(s===" "||s===" "||s===`
|
|
31
|
+
`||s===";"||s==="&"||s==="|"||s==="("||s===")"||s==="<"||s===">")}readWordWithBraceExpansion(e,s,r){let n=this.input,o=n.length,i=e,a=r;for(;i<o;){let l=n[i];if(l===" "||l===" "||l===`
|
|
32
|
+
`||l===";"||l==="&"||l==="|"||l==="("||l===")"||l==="<"||l===">")break;if(l==="{"){if(this.scanBraceExpansion(i)!==null){let h=1;for(i++,a++;i<o&&h>0;)n[i]==="{"?h++:n[i]==="}"&&h--,i++,a++;continue}i++,a++;continue}if(l==="}"){i++,a++;continue}if(l==="$"&&i+1<o&&n[i+1]==="("){i++,a++,i++,a++;let f=1;for(;f>0&&i<o;)n[i]==="("?f++:n[i]===")"&&f--,i++,a++;continue}if(l==="$"&&i+1<o&&n[i+1]==="{"){i++,a++,i++,a++;let f=1;for(;f>0&&i<o;)n[i]==="{"?f++:n[i]==="}"&&f--,i++,a++;continue}if(l==="`"){for(i++,a++;i<o&&n[i]!=="`";)n[i]==="\\"&&i+1<o?(i+=2,a+=2):(i++,a++);i<o&&(i++,a++);continue}i++,a++}let c=n.slice(e,i);return this.pos=i,this.column=a,{type:u.WORD,value:c,start:e,end:i,line:s,column:r,quoted:!1,singleQuoted:!1}}scanBraceExpansion(e){let s=this.input,r=s.length,n=e+1,o=1,i=!1,a=!1;for(;n<r&&o>0;){let c=s[n];if(c==="{")o++,n++;else if(c==="}")o--,n++;else if(c===","&&o===1)i=!0,n++;else if(c==="."&&n+1<r&&s[n+1]===".")a=!0,n+=2;else{if(c===" "||c===" "||c===`
|
|
33
|
+
`||c===";"||c==="&"||c==="|")return null;n++}}return o===0&&(i||a)?s.slice(e,n):null}scanLiteralBraceWord(e){let s=this.input,r=s.length,n=e+1,o=1;for(;n<r&&o>0;){let i=s[n];if(i==="{")o++,n++;else if(i==="}"){if(o--,o===0)return s.slice(e,n+1);n++}else{if(i===" "||i===" "||i===`
|
|
34
|
+
`||i===";"||i==="&"||i==="|")return null;n++}}return null}};var vt=1e6,$t=1e5,Ur=1e6,Gr=new Set([u.LESS,u.GREAT,u.DLESS,u.DGREAT,u.LESSAND,u.GREATAND,u.LESSGREAT,u.DLESSDASH,u.CLOBBER,u.TLESS,u.AND_GREAT,u.AND_DGREAT]),Vr=new Set([u.LESS,u.GREAT,u.DLESS,u.DGREAT,u.LESSAND,u.GREATAND,u.LESSGREAT,u.DLESSDASH,u.CLOBBER,u.TLESS]),ie=class extends Error{line;column;token;constructor(e,s,r,n=void 0){super(`Parse error at ${s}:${r}: ${e}`),this.line=s,this.column=r,this.token=n,this.name="ParseException"}};function jr(t,e,s){let r=s+1;for(;r<e.length&&/[a-zA-Z0-9_-]/.test(e[r]);)r++;return r}function kt(t,e,s,r,n){let o=1,i=s+1;for(;i<e.length&&o>0;)e[i]===r?o++:e[i]===n&&o--,o>0&&i++;return o===0?i:-1}function Ae(t,e,s){let r=s,n=1;for(;r<e.length&&n>0;){let o=e[r];if(o==="\\"&&r+1<e.length){r+=2;continue}if(o==="'"){let i=e.indexOf("'",r+1);if(i!==-1){r=i+1;continue}}if(o==='"'){for(r++;r<e.length&&e[r]!=='"';)e[r]==="\\"&&r+1<e.length?r+=2:r++;r<e.length&&r++;continue}o==="{"?n++:o==="}"&&n--,n>0&&r++}return r}function qr(t,e,s){let r=s,n=!1;for(;r<e.length;){let o=e[r];if(o==="/"&&n||o==="}")break;if(o==="'"){let i=e.indexOf("'",r+1);if(i!==-1){r=i+1,n=!0;continue}}if(o==='"'){for(r++;r<e.length&&e[r]!=='"';)e[r]==="\\"&&r+1<e.length?r+=2:r++;r<e.length&&r++,n=!0;continue}o==="\\"?(r+=2,n=!0):(r++,n=!0)}return r}function Zr(t,e,s){let r=s,n="";for(;r<e.length;){let o=e[r];if(o==="*"||o==="?")n+=o,r++;else if(o==="["){let i=un(e,r);i===-1?(n+=o,r++):(n+=e.slice(r,i+1),r=i+1)}else break}return{pattern:n,endIndex:r}}function un(t,e){let s=e+1;for(s<t.length&&t[s]==="^"&&s++,s<t.length&&t[s]==="]"&&s++;s<t.length;){let r=t[s];if(r==="\\"&&s+1<t.length){s+=2;continue}if(r==="]")return s;if(r==='"'||r==="$"||r==="`")return-1;if(r==="'"){let n=t.indexOf("'",s+1);if(n!==-1){s=n+1;continue}}if(r==="["&&s+1<t.length&&t[s+1]===":"){let n=t.indexOf(":]",s+2);if(n!==-1){s=n+2;continue}}if(r==="["&&s+1<t.length&&(t[s+1]==="."||t[s+1]==="=")){let o=`${t[s+1]}]`,i=t.indexOf(o,s+2);if(i!==-1){s=i+2;continue}}s++}return-1}function Qr(t,e,s){let r="",n=s;for(;n<e.length&&e[n]!=="'";){let o=e[n];if(o==="\\"&&n+1<e.length)switch(e[n+1]){case"n":r+=`
|
|
35
|
+
`,n+=2;break;case"t":r+=" ",n+=2;break;case"r":r+="\r",n+=2;break;case"\\":r+="\\",n+=2;break;case"'":r+="'",n+=2;break;case'"':r+='"',n+=2;break;case"a":r+="\x07",n+=2;break;case"b":r+="\b",n+=2;break;case"e":case"E":r+="\x1B",n+=2;break;case"f":r+="\f",n+=2;break;case"v":r+="\v",n+=2;break;case"x":{let a=e.slice(n+2,n+4),c=parseInt(a,16);Number.isNaN(c)?(r+="\\x",n+=2):(r+=String.fromCharCode(c),n+=4);break}case"u":{let a=e.slice(n+2,n+6),c=parseInt(a,16);Number.isNaN(c)?(r+="\\u",n+=2):(r+=String.fromCharCode(c),n+=6);break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":{let a="",c=n+1;for(;c<e.length&&c<n+4&&/[0-7]/.test(e[c]);)a+=e[c],c++;let l=parseInt(a,8);r+=String.fromCharCode(l),n=c;break}default:r+=o,n++}else r+=o,n++}return n<e.length&&e[n]==="'"&&n++,{part:A.literal(r),endIndex:n}}function It(t,e){let s=e.trim();return s===""?{type:"ArithmeticExpression",expression:{type:"ArithNumber",value:0}}:T(t,s)}function Hr(t){let e=[],s="",r=0;for(let n=0;n<t.length;n++){let o=t[n];o==="{"?(r++,s+=o):o==="}"?(r--,s+=o):o===","&&r===0?(e.push(s),s=""):s+=o}return e.push(s),e}function Kr(t,e,s,r){let n=kt(t,e,s,"{","}");if(n===-1)return null;let o=e.slice(s+1,n),i=o.match(/^(-?\d+)\.\.(-?\d+)(?:\.\.(-?\d+))?$/);if(i)return{part:{type:"BraceExpansion",items:[{type:"Range",start:Number.parseInt(i[1],10),end:Number.parseInt(i[2],10),step:i[3]?Number.parseInt(i[3],10):void 0,startStr:i[1],endStr:i[2]}]},endIndex:n+1};let a=o.match(/^([a-zA-Z])\.\.([a-zA-Z])(?:\.\.(-?\d+))?$/);return a?{part:{type:"BraceExpansion",items:[{type:"Range",start:a[1],end:a[2],step:a[3]?Number.parseInt(a[3],10):void 0}]},endIndex:n+1}:o.includes(",")&&r?{part:{type:"BraceExpansion",items:Hr(o).map(f=>({type:"Word",word:A.word(r(t,f,!1,!1,!1))}))},endIndex:n+1}:o.includes(",")?{part:{type:"BraceExpansion",items:Hr(o).map(f=>({type:"Word",word:A.word([A.literal(f)])}))},endIndex:n+1}:null}function Xr(t,e){let s="";for(let r of e.parts)switch(r.type){case"Literal":case"SingleQuoted":case"Escaped":s+=r.value;break;case"DoubleQuoted":s+='"';for(let n of r.parts)n.type==="Literal"||n.type==="Escaped"?s+=n.value:n.type==="ParameterExpansion"&&(s+=`\${${n.parameter}}`);s+='"';break;case"ParameterExpansion":s+=`\${${r.parameter}}`;break;case"Glob":s+=r.pattern;break;default:s+=r.type}return s}function Yr(t,e){return{[u.LESS]:"<",[u.GREAT]:">",[u.DGREAT]:">>",[u.LESSAND]:"<&",[u.GREATAND]:">&",[u.LESSGREAT]:"<>",[u.CLOBBER]:">|",[u.TLESS]:"<<<",[u.AND_GREAT]:"&>",[u.AND_DGREAT]:"&>>",[u.DLESS]:"<",[u.DLESSDASH]:"<"}[e]||">"}function Je(t){let e=t.current(),s=e.type;if(s===u.NUMBER){let r=t.peek(1);return e.end!==r.start?!1:Vr.has(r.type)}return Gr.has(s)}function et(t){let e=null;t.check(u.NUMBER)&&(e=Number.parseInt(t.advance().value,10));let s=t.advance(),r=Yr(t,s.type);if(s.type===u.DLESS||s.type===u.DLESSDASH)return hn(t,r,e,s.type===u.DLESSDASH);t.isWord()||t.error("Expected redirection target");let n=t.parseWord();return A.redirection(r,n,e)}function hn(t,e,s,r){t.isWord()||t.error("Expected here-document delimiter");let n=t.advance(),o=n.value,i=n.quoted||!1;(o.startsWith("'")&&o.endsWith("'")||o.startsWith('"')&&o.endsWith('"'))&&(o=o.slice(1,-1));let a=A.redirection(r?"<<-":"<<",A.hereDoc(o,A.word([]),r,i),s);return t.addPendingHeredoc(a,o,r,i),a}function es(t){let e=t.current().line,s=[],r=null,n=[],o=[];for(;t.check(u.ASSIGNMENT_WORD);)t.checkIterationLimit(),s.push(dn(t));for(;Je(t);)t.checkIterationLimit(),o.push(et(t));for(t.isWord()&&(r=t.parseWord());(!t.isStatementEnd()||t.check(u.RBRACE))&&!t.check(u.PIPE,u.PIPE_AMP);)if(t.checkIterationLimit(),Je(t))o.push(et(t));else if(t.check(u.RBRACE)){let a=t.advance();n.push(t.parseWordFromString(a.value,!1,!1))}else if(t.isWord())n.push(t.parseWord());else if(t.check(u.ASSIGNMENT_WORD)){let a=t.advance(),c=a.value,l=c.endsWith("="),f=c.endsWith("=(");if((l||f)&&(f||t.check(u.LPAREN))){let h=f?c.slice(0,-2):c.slice(0,-1);f||t.expect(u.LPAREN);let d=Rt(t);t.expect(u.RPAREN);let m=d.map(E=>Xr(t,E)),y=`${h}=(${m.join(" ")})`;n.push(t.parseWordFromString(y,!1,!1))}else n.push(t.parseWordFromString(c,a.quoted,a.singleQuoted))}else if(t.check(u.LPAREN))t.error("syntax error near unexpected token `('");else break;let i=A.simpleCommand(r,n,s,o);return i.line=e,i}function dn(t){let e=t.expect(u.ASSIGNMENT_WORD),s=e.value,r=s.match(/^[a-zA-Z_][a-zA-Z0-9_]*/);r||t.error(`Invalid assignment: ${s}`);let n=r[0],o,i=n.length;if(s[i]==="["){let h=0,d=i+1;for(;i<s.length;i++)if(s[i]==="[")h++;else if(s[i]==="]"&&(h--,h===0))break;h!==0&&t.error(`Invalid assignment: ${s}`),o=s.slice(d,i),i++}let a=s[i]==="+";a&&i++,s[i]!=="="&&t.error(`Invalid assignment: ${s}`),i++;let c=s.slice(i);if(c==="("){let h=Rt(t);t.expect(u.RPAREN);let d=o!==void 0?`${n}[${o}]`:n;return A.assignment(d,null,a,h)}if(c===""&&t.check(u.LPAREN)){let h=t.current();if(e.end===h.start){t.advance();let d=Rt(t);t.expect(u.RPAREN);let m=o!==void 0?`${n}[${o}]`:n;return A.assignment(m,null,a,d)}}let l=c?t.parseWordFromString(c,e.quoted,e.singleQuoted,!0):null,f=o!==void 0?`${n}[${o}]`:n;return A.assignment(f,l,a,null)}function Rt(t){let e=[];for(t.skipNewlines();!t.check(u.RPAREN,u.EOF);)t.checkIterationLimit(),t.isWord()?e.push(t.parseWord()):t.advance(),t.skipNewlines();return e}function Dt(t){t.expect(u.IF);let e=[],s=t.parseCompoundList();t.expect(u.THEN);let r=t.parseCompoundList();if(r.length===0){let i=t.check(u.FI)?"fi":t.check(u.ELSE)?"else":t.check(u.ELIF)?"elif":"fi";t.error(`syntax error near unexpected token \`${i}'`)}for(e.push({condition:s,body:r});t.check(u.ELIF);){t.advance();let i=t.parseCompoundList();t.expect(u.THEN);let a=t.parseCompoundList();if(a.length===0){let c=t.check(u.FI)?"fi":t.check(u.ELSE)?"else":t.check(u.ELIF)?"elif":"fi";t.error(`syntax error near unexpected token \`${c}'`)}e.push({condition:i,body:a})}let n=null;t.check(u.ELSE)&&(t.advance(),n=t.parseCompoundList(),n.length===0&&t.error("syntax error near unexpected token `fi'")),t.expect(u.FI);let o=t.parseOptionalRedirections();return A.ifNode(e,n,o)}function Ot(t){if(t.expect(u.FOR),t.check(u.DPAREN_START))return pn(t);t.isWord()||t.error("Expected variable name in for loop");let s=t.advance().value,r=null;if(t.skipNewlines(),t.check(u.IN))for(t.advance(),r=[];!t.check(u.SEMICOLON,u.NEWLINE,u.DO,u.EOF)&&t.isWord();)r.push(t.parseWord());t.check(u.SEMICOLON)&&t.advance(),t.skipNewlines(),t.expect(u.DO);let n=t.parseCompoundList();t.expect(u.DONE);let o=t.parseOptionalRedirections();return A.forNode(s,r,n,o)}function pn(t){t.expect(u.DPAREN_START);let e=null,s=null,r=null,n=["","",""],o=0,i=0;for(;!t.check(u.DPAREN_END,u.EOF);){let l=t.advance();if(l.type===u.SEMICOLON&&i===0){if(o++,o>2)break}else l.value==="("&&i++,l.value===")"&&i--,n[o]+=l.value}t.expect(u.DPAREN_END),n[0].trim()&&(e=T(t,n[0].trim())),n[1].trim()&&(s=T(t,n[1].trim())),n[2].trim()&&(r=T(t,n[2].trim())),t.skipNewlines(),t.check(u.SEMICOLON)&&t.advance(),t.skipNewlines(),t.expect(u.DO);let a=t.parseCompoundList();t.expect(u.DONE);let c=t.parseOptionalRedirections();return{type:"CStyleFor",init:e,condition:s,update:r,body:a,redirections:c}}function _t(t){t.expect(u.WHILE);let e=t.parseCompoundList();t.expect(u.DO);let s=t.parseCompoundList();s.length===0&&t.error("syntax error near unexpected token `done'"),t.expect(u.DONE);let r=t.parseOptionalRedirections();return A.whileNode(e,s,r)}function Lt(t){t.expect(u.UNTIL);let e=t.parseCompoundList();t.expect(u.DO);let s=t.parseCompoundList();s.length===0&&t.error("syntax error near unexpected token `done'"),t.expect(u.DONE);let r=t.parseOptionalRedirections();return A.untilNode(e,s,r)}function Tt(t){t.expect(u.CASE),t.isWord()||t.error("Expected word after 'case'");let e=t.parseWord();t.skipNewlines(),t.expect(u.IN),t.skipNewlines();let s=[];for(;!t.check(u.ESAC,u.EOF);){t.checkIterationLimit();let n=t.getPos(),o=yn(t);if(o&&s.push(o),t.skipNewlines(),t.getPos()===n&&!o)break}t.expect(u.ESAC);let r=t.parseOptionalRedirections();return A.caseNode(e,s,r)}function yn(t){t.check(u.LPAREN)&&t.advance();let e=[];for(;t.isWord()&&(e.push(t.parseWord()),t.check(u.PIPE));)t.advance();if(e.length===0)return null;t.expect(u.RPAREN),t.skipNewlines();let s=[];for(;!t.check(u.DSEMI,u.SEMI_AND,u.SEMI_SEMI_AND,u.ESAC,u.EOF);){t.checkIterationLimit(),t.isWord()&&t.peek(1).type===u.RPAREN&&t.error("syntax error near unexpected token `)'"),t.check(u.LPAREN)&&t.peek(1).type===u.WORD&&t.error(`syntax error near unexpected token \`${t.peek(1).value}'`);let n=t.getPos(),o=t.parseStatement();if(o&&s.push(o),t.skipSeparators(!1),t.getPos()===n&&!o)break}let r=";;";return t.check(u.DSEMI)?(t.advance(),r=";;"):t.check(u.SEMI_AND)?(t.advance(),r=";&"):t.check(u.SEMI_SEMI_AND)&&(t.advance(),r=";;&"),A.caseItem(e,s,r)}function Ft(t){t.peek(1).type,u.LPAREN,t.expect(u.LPAREN),t.check(u.LPAREN)&&t.advance();let e=t.parseCompoundList();t.expect(u.RPAREN);let s=t.parseOptionalRedirections();return A.subshell(e,s)}function Wt(t){t.expect(u.LBRACE);let e=t.parseCompoundList();t.expect(u.RBRACE);let s=t.parseOptionalRedirections();return A.group(e,s)}var En=["-a","-b","-c","-d","-e","-f","-g","-h","-k","-p","-r","-s","-t","-u","-w","-x","-G","-L","-N","-O","-S","-z","-n","-o","-v","-R"],gn=["==","!=","=~","<",">","-eq","-ne","-lt","-le","-gt","-ge","-nt","-ot","-ef"];function zt(t){return t.skipNewlines(),An(t)}function An(t){let e=ts(t);for(t.skipNewlines();t.check(u.OR_OR);){t.advance(),t.skipNewlines();let s=ts(t);e={type:"CondOr",left:e,right:s},t.skipNewlines()}return e}function ts(t){let e=Mt(t);for(t.skipNewlines();t.check(u.AND_AND);){t.advance(),t.skipNewlines();let s=Mt(t);e={type:"CondAnd",left:e,right:s},t.skipNewlines()}return e}function Mt(t){return t.skipNewlines(),t.check(u.BANG)?(t.advance(),t.skipNewlines(),{type:"CondNot",operand:Mt(t)}):Sn(t)}function Sn(t){if(t.check(u.LPAREN)){t.advance();let e=zt(t);return t.expect(u.RPAREN),{type:"CondGroup",expression:e}}if(t.isWord()){let e=t.current(),s=e.value;if(En.includes(s)&&!e.quoted&&(t.advance(),t.check(u.DBRACK_END)&&t.error(`Expected operand after ${s}`),t.isWord())){let n=t.parseWord();return{type:"CondUnary",operator:s,operand:n}}let r=t.parseWord();if(t.isWord()&&gn.includes(t.current().value)){let n=t.advance().value,o=t.parseWord();return{type:"CondBinary",operator:n,left:r,right:o}}if(t.check(u.LESS)){t.advance();let n=t.parseWord();return{type:"CondBinary",operator:"<",left:r,right:n}}if(t.check(u.GREAT)){t.advance();let n=t.parseWord();return{type:"CondBinary",operator:">",left:r,right:n}}if(t.isWord()&&t.current().value==="="){t.advance();let n=t.parseWord();return{type:"CondBinary",operator:"==",left:r,right:n}}return{type:"CondWord",word:r}}t.error("Expected conditional expression")}function bn(t,e,s){let r=s+1,n=e[r];if("@*#?$!-0123456789".includes(n))return{part:A.parameterExpansion(n),endIndex:r+1};let o="";for(;r<e.length&&/[a-zA-Z0-9_]/.test(e[r]);)o+=e[r],r++;return{part:A.parameterExpansion(o),endIndex:r}}function Cn(t,e,s,r=!1){let n=s+2,o=!1;e[n]==="!"&&(o=!0,n++);let i=!1;e[n]==="#"&&!/[}:#%/^,]/.test(e[n+1]||"}")&&(i=!0,n++);let a="",c=e[n];if(/[@*#?$!-]/.test(c)&&!/[a-zA-Z0-9_]/.test(e[n+1]||""))a=c,n++;else for(;n<e.length&&/[a-zA-Z0-9_]/.test(e[n]);)a+=e[n],n++;if(e[n]==="["){let f=kt(t,e,n,"[","]");a+=e.slice(n,f+1),n=f+1}a===""&&!o&&!i&&e[n]!=="}"&&t.error(`\${${e[n]}}: bad substitution`);let l=null;if(o){let f=a.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(f)l={type:"ArrayKeys",array:f[1],star:f[2]==="*"},a="";else if(e[n]==="*"||e[n]==="@"){let h=e[n];n++,l={type:"VarNamePrefix",prefix:a,star:h==="*"},a=""}else l={type:"Indirection"}}else if(i)if(e[n]===":")for(l={type:"LengthSliceError"};n<e.length&&e[n]!=="}";)n++;else e[n]!=="}"&&/[-+=?]/.test(e[n])?t.error(`\${#${a}${e.slice(n,e.indexOf("}",n))}}: bad substitution`):l={type:"Length"};if(!l&&n<e.length&&e[n]!=="}"){let f=Nn(t,e,n,a,r);l=f.operation,n=f.endIndex}if(n<e.length&&e[n]!=="}"){let f=e[n];if(!/[:\-+=?#%/^,@[]/.test(f)){let h=n;for(;h<e.length&&e[h]!=="}";)h++;let d=e.slice(s,h+1);t.error(`\${${d.slice(2,-1)}}: bad substitution`)}}for(;n<e.length&&e[n]!=="}";)n++;return{part:A.parameterExpansion(a,l),endIndex:n+1}}function Nn(t,e,s,r,n=!1){let o=s,i=e[o],a=e[o+1]||"";if(i===":"){let c=a;if("-=?+".includes(c)){o+=2;let w=Ae(t,e,o),g=e.slice(o,w),b=ue(t,g,!1,!1,!0,!1,n),C=A.word(b.length>0?b:[A.literal("")]);if(c==="-")return{operation:{type:"DefaultValue",word:C,checkEmpty:!0},endIndex:w};if(c==="=")return{operation:{type:"AssignDefault",word:C,checkEmpty:!0},endIndex:w};if(c==="?")return{operation:{type:"ErrorIfUnset",word:C,checkEmpty:!0},endIndex:w};if(c==="+")return{operation:{type:"UseAlternative",word:C,checkEmpty:!0},endIndex:w}}o++;let l=Ae(t,e,o),f=e.slice(o,l),h=-1,d=0,m=0;for(let p=0;p<f.length;p++){let w=f[p];if(w==="("||w==="[")d++;else if(w===")"||w==="]")d--;else if(w==="?"&&d===0)m++;else if(w===":"&&d===0)if(m>0)m--;else{h=p;break}}let y=h>=0?f.slice(0,h):f,E=h>=0?f.slice(h+1):null;return{operation:{type:"Substring",offset:It(t,y),length:E?It(t,E):null},endIndex:l}}if("-=?+".includes(i)){o++;let c=Ae(t,e,o),l=e.slice(o,c),f=ue(t,l,!1,!1,!0,!1,n),h=A.word(f.length>0?f:[A.literal("")]);if(i==="-")return{operation:{type:"DefaultValue",word:h,checkEmpty:!1},endIndex:c};if(i==="=")return{operation:{type:"AssignDefault",word:h,checkEmpty:!1},endIndex:c};if(i==="?")return{operation:{type:"ErrorIfUnset",word:l?h:null,checkEmpty:!1},endIndex:c};if(i==="+")return{operation:{type:"UseAlternative",word:h,checkEmpty:!1},endIndex:c}}if(i==="#"||i==="%"){let c=a===i,l=i==="#"?"prefix":"suffix";o+=c?2:1;let f=Ae(t,e,o),h=e.slice(o,f),d=ue(t,h,!1,!1,!1);return{operation:{type:"PatternRemoval",pattern:A.word(d.length>0?d:[A.literal("")]),side:l,greedy:c},endIndex:f}}if(i==="/"){let c=a==="/";o+=c?2:1;let l=null;e[o]==="#"?(l="start",o++):e[o]==="%"&&(l="end",o++);let f=qr(t,e,o),h=e.slice(o,f),d=ue(t,h,!1,!1,!1),m=A.word(d.length>0?d:[A.literal("")]),y=null,E=f;if(e[f]==="/"){let p=f+1,w=Ae(t,e,p),g=e.slice(p,w),b=ue(t,g,!1,!1,!1);y=A.word(b.length>0?b:[A.literal("")]),E=w}return{operation:{type:"PatternReplacement",pattern:m,replacement:y,all:c,anchor:l},endIndex:E}}if(i==="^"||i===","){let c=a===i,l=i==="^"?"upper":"lower";o+=c?2:1;let f=Ae(t,e,o),h=e.slice(o,f),d=h?A.word([A.literal(h)]):null;return{operation:{type:"CaseModification",direction:l,all:c,pattern:d},endIndex:f}}return i==="@"&&/[QPaAEK]/.test(a)?{operation:{type:"Transform",operator:a},endIndex:o+2}:{operation:null,endIndex:o}}function Bt(t,e,s,r=!1){let n=s+1;if(n>=e.length)return{part:A.literal("$"),endIndex:n};let o=e[n];if(o==="("&&e[n+1]==="(")return t.parseArithmeticExpansion(e,s);if(o==="["){let i=1,a=n+1;for(;a<e.length&&i>0;)e[a]==="["?i++:e[a]==="]"&&i--,i>0&&a++;if(i===0){let c=e.slice(n+1,a),l=T(t,c);return{part:A.arithmeticExpansion(l),endIndex:a+1}}}return o==="("?t.parseCommandSubstitution(e,s):o==="{"?Cn(t,e,s,r):/[a-zA-Z_0-9@*#?$!-]/.test(o)?bn(t,e,s):{part:A.literal("$"),endIndex:n}}function Pn(t,e){let s=[],r=0,n="",o=()=>{n&&(s.push(A.literal(n)),n="")};for(;r<e.length;){let i=e[r];if(i==="\\"&&r+1<e.length){let a=e[r+1];if(a==="$"||a==="`"){n+=a,r+=2;continue}n+=i,r++;continue}if(i==="$"){o();let{part:a,endIndex:c}=Bt(t,e,r,!0);a&&s.push(a),r=c;continue}if(i==="`"){o();let{part:a,endIndex:c}=t.parseBacktickSubstitution(e,r,!0);s.push(a),r=c;continue}n+=i,r++}return o(),s}function vn(t,e,s){let r=[],n=s,o="",i=()=>{o&&(r.push(A.literal(o)),o="")};for(;n<e.length&&e[n]!=='"';){let a=e[n];if(a==="\\"&&n+1<e.length){let c=e[n+1];if('"\\$`\n'.includes(c)){o+=c,n+=2;continue}o+=a,n++;continue}if(a==="$"){i();let{part:c,endIndex:l}=Bt(t,e,n,!0);c&&r.push(c),n=l;continue}if(a==="`"){i();let{part:c,endIndex:l}=t.parseBacktickSubstitution(e,n,!0);r.push(c),n=l;continue}o+=a,n++}return i(),{part:A.doubleQuoted(r),endIndex:n}}function ue(t,e,s=!1,r=!1,n=!1,o=!1,i=!1){if(r)return[A.singleQuoted(e)];if(s){let h=Pn(t,e);return[A.doubleQuoted(h)]}let a=[],c=0,l="",f=()=>{l&&(a.push(A.literal(l)),l="")};for(;c<e.length;){let h=e[c];if(h==="\\"&&c+1<e.length){let d=e[c+1];(o?d==="$"||d==="`"||d==="\\"||d===`
|
|
36
36
|
`:d==="$"||d==="`"||d==="\\"||d==='"'||d===`
|
|
37
|
-
`)?l+=d:l+=`\\${d}`,c+=2;continue}if(h==="'"&&!o
|
|
37
|
+
`)?l+=d:l+=`\\${d}`,c+=2;continue}if(h==="'"&&!i&&!o){f();let d=e.indexOf("'",c+1);if(d===-1){l+=e.slice(c);break}a.push(A.singleQuoted(e.slice(c+1,d))),c=d+1;continue}if(h==='"'&&!o){f();let{part:d,endIndex:m}=vn(t,e,c+1);a.push(d),c=m+1;continue}if(h==="$"&&e[c+1]==="'"){f();let{part:d,endIndex:m}=Qr(t,e,c+2);a.push(d),c=m;continue}if(h==="$"){f();let{part:d,endIndex:m}=Bt(t,e,c);d&&a.push(d),c=m;continue}if(h==="`"){f();let{part:d,endIndex:m}=t.parseBacktickSubstitution(e,c);a.push(d),c=m;continue}if(h==="~"){let d=c>0?e[c-1]:"";if(c===0||d==="="||n&&d===":"){let y=jr(t,e,c),E=e[y];if(E===void 0||E==="/"||E===":"){f();let p=e.slice(c+1,y)||null;a.push({type:"TildeExpansion",user:p}),c=y;continue}}}if(h==="*"||h==="?"||h==="["){f();let{pattern:d,endIndex:m}=Zr(t,e,c);a.push({type:"Glob",pattern:d}),c=m;continue}if(h==="{"&&!n){let d=Kr(t,e,c,ue);if(d){f(),a.push(d.part),c=d.endIndex;continue}}l+=h,c++}return f(),a}var z=class t{tokens=[];pos=0;pendingHeredocs=[];parseIterations=0;checkIterationLimit(){if(this.parseIterations++,this.parseIterations>Ur)throw new ie("Maximum parse iterations exceeded (possible infinite loop)",this.current().line,this.current().column)}parse(e){if(e.length>vt)throw new ie(`Input too large: ${e.length} bytes exceeds limit of ${vt}`,1,1);let s=new Ye(e);if(this.tokens=s.tokenize(),this.tokens.length>$t)throw new ie(`Too many tokens: ${this.tokens.length} exceeds limit of ${$t}`,1,1);return this.pos=0,this.pendingHeredocs=[],this.parseIterations=0,this.parseScript()}parseTokens(e){return this.tokens=e,this.pos=0,this.pendingHeredocs=[],this.parseScript()}current(){return this.tokens[this.pos]||this.tokens[this.tokens.length-1]}peek(e=0){return this.tokens[this.pos+e]||this.tokens[this.tokens.length-1]}advance(){let e=this.current();return this.pos<this.tokens.length-1&&this.pos++,e}getPos(){return this.pos}check(e,s,r,n,...o){let i=this.tokens[this.pos]?.type;return i===e||s!==void 0&&i===s||r!==void 0&&i===r||n!==void 0&&i===n?!0:o.length>0?o.includes(i):!1}expect(e,s){if(this.check(e))return this.advance();let r=this.current();throw new ie(s||`Expected ${e}, got ${r.type}`,r.line,r.column,r)}error(e){let s=this.current();throw new ie(e,s.line,s.column,s)}skipNewlines(){for(;this.check(u.NEWLINE,u.COMMENT);)this.check(u.NEWLINE)?(this.advance(),this.processHeredocs()):this.advance()}skipSeparators(e=!0){for(;;){if(this.check(u.NEWLINE)){this.advance(),this.processHeredocs();continue}if(this.check(u.SEMICOLON,u.COMMENT)){this.advance();continue}if(e&&this.check(u.DSEMI,u.SEMI_AND,u.SEMI_SEMI_AND)){this.advance();continue}break}}addPendingHeredoc(e,s,r,n){this.pendingHeredocs.push({redirect:e,delimiter:s,stripTabs:r,quoted:n})}processHeredocs(){for(let e of this.pendingHeredocs)if(this.check(u.HEREDOC_CONTENT)){let s=this.advance(),r;e.quoted?r=A.word([A.literal(s.value)]):r=this.parseWordFromString(s.value,!1,!1,!1,!0),e.redirect.target=A.hereDoc(e.delimiter,r,e.stripTabs,e.quoted)}this.pendingHeredocs=[]}isStatementEnd(){return this.check(u.EOF,u.NEWLINE,u.SEMICOLON,u.AMP,u.AND_AND,u.OR_OR,u.RPAREN,u.RBRACE,u.DSEMI,u.SEMI_AND,u.SEMI_SEMI_AND)}isCommandStart(){let e=this.current().type;return e===u.WORD||e===u.NAME||e===u.NUMBER||e===u.ASSIGNMENT_WORD||e===u.IF||e===u.FOR||e===u.WHILE||e===u.UNTIL||e===u.CASE||e===u.LPAREN||e===u.LBRACE||e===u.DPAREN_START||e===u.DBRACK_START||e===u.FUNCTION||e===u.BANG||e===u.IN||e===u.LESS||e===u.GREAT||e===u.DLESS||e===u.DGREAT||e===u.LESSAND||e===u.GREATAND||e===u.LESSGREAT||e===u.DLESSDASH||e===u.CLOBBER||e===u.TLESS||e===u.AND_GREAT||e===u.AND_DGREAT}parseScript(){let e=[],r=0;for(this.skipNewlines();!this.check(u.EOF);){r++,r>1e4&&this.error("Parser stuck: too many iterations (>10000)"),this.checkUnexpectedToken();let n=this.pos,o=this.parseStatement();o&&e.push(o),this.skipSeparators(!1),this.check(u.DSEMI,u.SEMI_AND,u.SEMI_SEMI_AND)&&this.error(`syntax error near unexpected token \`${this.current().value}'`),this.pos===n&&!this.check(u.EOF)&&this.advance()}return A.script(e)}checkUnexpectedToken(){let e=this.current().type,s=this.current().value;(e===u.DO||e===u.DONE||e===u.THEN||e===u.ELSE||e===u.ELIF||e===u.FI||e===u.ESAC)&&this.error(`syntax error near unexpected token \`${s}'`),(e===u.RBRACE||e===u.RPAREN)&&this.error(`syntax error near unexpected token \`${s}'`),(e===u.DSEMI||e===u.SEMI_AND||e===u.SEMI_SEMI_AND)&&this.error(`syntax error near unexpected token \`${s}'`),e===u.SEMICOLON&&this.error(`syntax error near unexpected token \`${s}'`)}parseStatement(){if(this.skipNewlines(),!this.isCommandStart())return null;let e=[],s=[],r=!1,n=this.parsePipeline();for(e.push(n);this.check(u.AND_AND,u.OR_OR);){let o=this.advance();s.push(o.type===u.AND_AND?"&&":"||"),this.skipNewlines();let i=this.parsePipeline();e.push(i)}return this.check(u.AMP)&&(this.advance(),r=!0),A.statement(e,s,r)}parsePipeline(){let e=0;for(;this.check(u.BANG);)this.advance(),e++;let s=e%2===1,r=[],n=this.parseCommand();for(r.push(n);this.check(u.PIPE,u.PIPE_AMP);){let o=this.advance();this.skipNewlines();let i=this.parseCommand();o.type===u.PIPE_AMP&&i.type==="SimpleCommand"&&i.redirections.unshift(A.redirection(">&",A.word([A.literal("1")]),2)),r.push(i)}return A.pipeline(r,s)}parseCommand(){return this.check(u.IF)?Dt(this):this.check(u.FOR)?Ot(this):this.check(u.WHILE)?_t(this):this.check(u.UNTIL)?Lt(this):this.check(u.CASE)?Tt(this):this.check(u.LPAREN)?Ft(this):this.check(u.LBRACE)?Wt(this):this.check(u.DPAREN_START)?this.parseArithmeticCommand():this.check(u.DBRACK_START)?this.parseConditionalCommand():this.check(u.FUNCTION)?this.parseFunctionDef():this.check(u.NAME,u.WORD)&&this.peek(1).type===u.LPAREN&&this.peek(2).type===u.RPAREN?this.parseFunctionDef():es(this)}isWord(){let e=this.current().type;return e===u.WORD||e===u.NAME||e===u.NUMBER||e===u.IF||e===u.FOR||e===u.WHILE||e===u.UNTIL||e===u.CASE||e===u.FUNCTION||e===u.ELSE||e===u.ELIF||e===u.FI||e===u.THEN||e===u.DO||e===u.DONE||e===u.ESAC||e===u.IN||e===u.SELECT||e===u.TIME||e===u.COPROC||e===u.BANG}parseWord(){let e=this.advance();return this.parseWordFromString(e.value,e.quoted,e.singleQuoted)}parseWordFromString(e,s=!1,r=!1,n=!1,o=!1){let i=ue(this,e,s,r,n,o);return A.word(i)}parseCommandSubstitution(e,s){let r=s+2,n=1,o=r,i=!1,a=!1,c=0,l=!1,f="";for(;o<e.length&&n>0;){let y=e[o];i?y==="'"&&(i=!1):a?y==="\\"&&o+1<e.length?o++:y==='"'&&(a=!1):y==="'"?(i=!0,f=""):y==='"'?(a=!0,f=""):y==="\\"&&o+1<e.length?(o++,f=""):/[a-zA-Z_]/.test(y)?f+=y:(f==="case"?(c++,l=!1):f==="in"&&c>0?l=!0:f==="esac"&&c>0&&(c--,l=!1),f="",y==="("?o>0&&e[o-1]==="$"?n++:l||n++:y===")"?l?l=!1:n--:y===";"&&c>0&&o+1<e.length&&e[o+1]===";"&&(l=!0)),n>0&&o++}n>0&&this.error("unexpected EOF while looking for matching `)'");let h=e.slice(r,o),m=new t().parse(h);return{part:A.commandSubstitution(m,!1),endIndex:o+1}}parseBacktickSubstitution(e,s,r=!1){let o=s+1,i="";for(;o<e.length&&e[o]!=="`";)if(e[o]==="\\"){let l=e[o+1];l==="$"||l==="`"||l==="\\"||l===`
|
|
38
38
|
`||r&&l==='"'?(l!==`
|
|
39
|
-
`&&(o+=l),i+=2):(o+=e[i],i++)}else o+=e[i],i++;i>=e.length&&this.error("unexpected EOF while looking for matching ``'");let c=new t().parse(o);return{part:A.commandSubstitution(c,!0),endIndex:i+1}}parseArithmeticExpansion(e,n){let r=n+3,s=1,i=0,o=r;for(;o<e.length-1&&s>0;)e[o]==="$"&&e[o+1]==="("?e[o+2]==="("?(s++,o+=3):(i++,o+=2):e[o]==="("&&e[o+1]==="("?(s++,o+=2):e[o]===")"&&e[o+1]===")"?i>0?(i--,o++):(s--,s>0&&(o+=2)):e[o]==="("?(i++,o++):(e[o]===")"&&i>0&&i--,o++);let a=e.slice(r,o),c=this.parseArithmeticExpression(a);return{part:A.arithmeticExpansion(c),endIndex:o+2}}parseArithmeticCommand(){this.expect(f.DPAREN_START);let e="",n=1,r=0,s=!1,i=!1;for(;n>0&&!this.check(f.EOF);){if(s){if(s=!1,r>0){r--,e+=")";continue}if(this.check(f.RPAREN)){n--,i=!0,this.advance();continue}if(this.check(f.DPAREN_END)){n--,i=!0;continue}e+=")";continue}this.check(f.DPAREN_START)?(n++,e+="((",this.advance()):this.check(f.DPAREN_END)?r>=2?(r-=2,e+="))",this.advance()):r===1?(r--,e+=")",s=!0,this.advance()):(n--,i=!0,n>0&&(e+="))"),this.advance()):this.check(f.LPAREN)?(r++,e+="(",this.advance()):this.check(f.RPAREN)?(r>0&&r--,e+=")",this.advance()):(e+=this.current().value,this.advance())}i||this.expect(f.DPAREN_END);let o=this.parseArithmeticExpression(e.trim()),a=this.parseOptionalRedirections();return A.arithmeticCommand(o,a)}parseConditionalCommand(){this.expect(f.DBRACK_START);let e=zt(this);this.expect(f.DBRACK_END);let n=this.parseOptionalRedirections();return A.conditionalCommand(e,n)}parseFunctionDef(){let e;this.check(f.FUNCTION)?(this.advance(),e=this.expect(f.NAME,"Expected function name").value,this.check(f.LPAREN)&&(this.advance(),this.expect(f.RPAREN))):(e=this.advance().value,this.expect(f.LPAREN),this.expect(f.RPAREN)),this.skipNewlines();let n=this.parseCompoundCommandBody(),r=this.parseOptionalRedirections();return A.functionDef(e,n,r)}parseCompoundCommandBody(){if(this.check(f.LBRACE))return Wt(this);if(this.check(f.LPAREN))return Ft(this);if(this.check(f.IF))return Dt(this);if(this.check(f.FOR))return Ot(this);if(this.check(f.WHILE))return _t(this);if(this.check(f.UNTIL))return Lt(this);if(this.check(f.CASE))return Tt(this);this.error("Expected compound command for function body")}parseCompoundList(){let e=[];for(this.skipNewlines();!this.check(f.EOF,f.FI,f.ELSE,f.ELIF,f.THEN,f.DO,f.DONE,f.ESAC,f.RPAREN,f.RBRACE,f.DSEMI,f.SEMI_AND,f.SEMI_SEMI_AND)&&this.isCommandStart();){this.checkIterationLimit();let n=this.pos,r=this.parseStatement();if(r&&e.push(r),this.skipSeparators(),this.pos===n&&!r)break}return e}parseOptionalRedirections(){let e=[];for(;Je(this);){this.checkIterationLimit();let n=this.pos;if(e.push(et(this)),this.pos===n)break}return e}parseArithmeticExpression(e){return T(this,e)}};function he(t){return new z().parse(t)}var ve=class{fs;cwd;constructor(e,n){this.fs=e,this.cwd=n}isGlobPattern(e){return e.includes("*")||e.includes("?")||/\[.*\]/.test(e)}async expandArgs(e,n){let r=e.map((o,a)=>(n?.[a]??!1)||!this.isGlobPattern(o)?null:this.expand(o)),s=await Promise.all(r.map(o=>o||Promise.resolve(null))),i=[];for(let o=0;o<e.length;o++){let a=s[o];a===null?i.push(e[o]):a.length>0?i.push(...a):i.push(e[o])}return i}async expand(e){return e.includes("**")?this.expandRecursive(e):this.expandSimple(e)}async expandSimple(e){let n=[],r=e.lastIndexOf("/"),s,i;r===-1?(s=this.cwd,i=e):(s=e.slice(0,r)||"/",i=e.slice(r+1));let o=this.fs.resolvePath(this.cwd,s);try{let a=await this.fs.readdir(o);for(let c of a)if(this.matchPattern(c,i)){let l=r===-1?c:`${s}/${c}`;n.push(l)}}catch{}return n.sort()}async expandRecursive(e){let n=[],r=e.indexOf("**"),s=e.slice(0,r).replace(/\/$/,"")||".",o=e.slice(r+2).replace(/^\//,"");return await this.walkDirectory(s,o,n),n.sort()}async walkDirectory(e,n,r){let s=this.fs.resolvePath(this.cwd,e);try{if(this.fs.readdirWithFileTypes){let i=await this.fs.readdirWithFileTypes(s),o=[],a=[];for(let c of i){let l=e==="."?c.name:`${e}/${c.name}`;c.isDirectory?a.push(l):n&&this.matchPattern(c.name,n)&&o.push(l)}r.push(...o);for(let c=0;c<a.length;c+=100){let l=a.slice(c,c+100);await Promise.all(l.map(u=>this.walkDirectory(u,n,r)))}}else{let i=await this.fs.readdir(s),o=[];for(let c=0;c<i.length;c+=100){let l=i.slice(c,c+100),u=await Promise.all(l.map(async h=>{let d=e==="."?h:`${e}/${h}`,m=this.fs.resolvePath(this.cwd,d);try{let y=await this.fs.stat(m);return{name:h,path:d,isDirectory:y.isDirectory}}catch{return null}}));o.push(...u.filter(h=>h!==null))}for(let c of o)!c.isDirectory&&n&&this.matchPattern(c.name,n)&&r.push(c.path);let a=o.filter(c=>c.isDirectory);for(let c=0;c<a.length;c+=100){let l=a.slice(c,c+100);await Promise.all(l.map(u=>this.walkDirectory(u.path,n,r)))}}}catch{}}matchPattern(e,n){return this.patternToRegex(n).test(e)}patternToRegex(e){let n="^";for(let r=0;r<e.length;r++){let s=e[r];if(s==="*")n+=".*";else if(s==="?")n+=".";else if(s==="["){let i=r+1,o="[";for(i<e.length&&(e[i]==="^"||e[i]==="!")&&(o+="^",i++),i<e.length&&e[i]==="]"&&(o+="\\]",i++);i<e.length&&e[i]!=="]";){if(e[i]==="["&&i+1<e.length&&e[i+1]===":"){let a=e.indexOf(":]",i+2);if(a!==-1){let c=e.slice(i+2,a),l=this.posixClassToRegex(c);o+=l,i=a+2;continue}}if(e[i]==="\\"&&i+1<e.length){o+=`\\${e[i+1]}`,i+=2;continue}e[i]==="-"?o+="\\-":o+=e[i],i++}o+="]",n+=o,r=i}else if(s==="\\"&&r+1<e.length){let i=e[r+1];/[.+^${}()|\\*?[\]]/.test(i)?n+=`\\${i}`:n+=i,r++}else/[.+^${}()|]/.test(s)?n+=`\\${s}`:n+=s}return n+="$",new RegExp(n)}posixClassToRegex(e){return{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"}[e]||""}};function Z(t){switch(t.type){case"ArithCommandSubst":return!0;case"ArithNested":return Z(t.expression);case"ArithBinary":return Z(t.left)||Z(t.right);case"ArithUnary":return Z(t.operand);case"ArithTernary":return Z(t.condition)||Z(t.consequent)||Z(t.alternate);case"ArithAssignment":return Z(t.value);case"ArithGroup":return Z(t.expression);case"ArithArrayElement":return t.index?Z(t.index):!1;case"ArithConcat":return t.parts.some(Z);default:return!1}}function Ut(t){let e=t.operation;return e?!!("word"in e&&e.word&&oe(e.word)||e.type==="PatternReplacement"&&(e.pattern&&oe(e.pattern)||e.replacement&&oe(e.replacement))||e.type==="PatternRemoval"&&e.pattern&&oe(e.pattern)):!1}function tt(t){switch(t.type){case"CommandSubstitution":return!0;case"ArithmeticExpansion":return Z(t.expression.expression);case"DoubleQuoted":return t.parts.some(tt);case"BraceExpansion":return t.items.some(e=>e.type==="Word"&&oe(e.word));case"ParameterExpansion":return Ut(t);default:return!1}}function oe(t){return t.parts.some(tt)}function Gt(t){if(!t.operation)return!1;let e=t.operation,n;if((e.type==="DefaultValue"||e.type==="AssignDefault"||e.type==="UseAlternative"||e.type==="ErrorIfUnset")&&(n=e.word?.parts),!n)return!1;for(let r of n)if(r.type==="DoubleQuoted"||r.type==="SingleQuoted")return!0;return!1}function rn(t){let e=!1,n=!1,r=!1,s=!1,i=!1;for(let o of t){if((o.type==="SingleQuoted"||o.type==="DoubleQuoted")&&(e=!0,o.type==="DoubleQuoted"))for(let a of o.parts)a.type==="ParameterExpansion"&&a.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[[@*]\]$/)&&!a.operation&&(s=!0);o.type==="CommandSubstitution"&&(n=!0),o.type==="ParameterExpansion"&&(i=!0,(o.parameter==="@"||o.parameter==="*")&&(r=!0),Gt(o)&&(e=!0))}return{hasQuoted:e,hasCommandSub:n,hasArrayVar:r,hasArrayAtExpansion:s,hasParamExpansion:i}}function ks(t,e,n,r,s){let i=n??1;i===0&&(i=1);let o=Math.abs(i),a=[],c=0;r?.match(/^-?0\d/)&&(c=Math.max(c,r.replace(/^-/,"").length)),s?.match(/^-?0\d/)&&(c=Math.max(c,s.replace(/^-/,"").length));let l=u=>{if(c>0){let h=u<0,d=String(Math.abs(u)).padStart(c,"0");return h?`-${d}`:d}return String(u)};if(t<=e)for(let u=t,h=0;u<=e&&h<1e4;u+=o,h++)a.push(l(u));else for(let u=t,h=0;u>=e&&h<1e4;u-=o,h++)a.push(l(u));return a}function Is(t,e,n){let r=n??1;r===0&&(r=1);let s=t.charCodeAt(0),i=e.charCodeAt(0),o=Math.abs(r),a=t>="A"&&t<="Z",c=t>="a"&&t<="z",l=e>="A"&&e<="Z",u=e>="a"&&e<="z";if(a&&u||c&&l)return null;let h=[];if(s<=i)for(let d=s,m=0;d<=i&&m<1e4;d+=o,m++)h.push(String.fromCharCode(d));else for(let d=s,m=0;d>=i&&m<1e4;d-=o,m++)h.push(String.fromCharCode(d));return h}function Me(t,e,n,r,s){let i=n!==void 0?`..${n}`:"";return typeof t=="number"&&typeof e=="number"?{expanded:ks(t,e,n,r,s),literal:`{${t}..${e}${i}}`}:typeof t=="string"&&typeof e=="string"?{expanded:Is(t,e,n),literal:`{${t}..${e}${i}}`}:{expanded:null,literal:`{${t}..${e}${i}}`}}function V(t,e){let n="",r=0;for(;r<t.length;){let s=t[r];if(s==="\\")if(r+1<t.length){let i=t[r+1];/[\\^$.|+(){}[\]*?]/.test(i)?n+=`\\${i}`:n+=i,r+=2}else n+="\\\\",r++;else if(s==="*")n+=e?".*":".*?",r++;else if(s==="?")n+=".",r++;else if(s==="["){let i=Rs(t,r);if(i===-1)n+="\\[",r++;else{let o=t.slice(r+1,i);n+=Ds(o),r=i+1}}else/[\^$.|+(){}]/.test(s)?(n+=`\\${s}`,r++):(n+=s,r++)}return n}function Rs(t,e){let n=e+1;for(n<t.length&&t[n]==="^"&&n++,n<t.length&&t[n]==="]"&&n++;n<t.length;){if(t[n]==="\\"&&n+1<t.length){n+=2;continue}if(t[n]==="]")return n;if(t[n]==="'"){let r=t.indexOf("'",n+1);if(r!==-1){n=r+1;continue}}if(t[n]==="["&&n+1<t.length&&t[n+1]===":"){let r=t.indexOf(":]",n+2);if(r!==-1){n=r+2;continue}}n++}return-1}function Ds(t){let e="[",n=0;for((t[0]==="^"||t[0]==="!")&&(e+="^",n++);n<t.length;){if(t[n]==="'"){let s=t.indexOf("'",n+1);if(s!==-1){let i=t.slice(n+1,s);for(let o of i)o==="\\"?e+="\\\\":o==="]"?e+="\\]":o==="^"&&e==="["?e+="\\^":e+=o;n=s+1;continue}}if(t[n]==="["&&n+1<t.length&&t[n+1]===":"){let s=t.indexOf(":]",n+2);if(s!==-1){let i=t.slice(n+2,s);e+=_s(i),n=s+2;continue}}let r=t[n];r==="\\"?n+1<t.length?(e+=`\\${t[n+1]}`,n+=2):(e+="\\\\",n++):r==="-"&&n>0&&n<t.length-1?(e+="-",n++):r==="^"&&n===0?(e+="^",n++):(r==="]"&&n===0?e+="\\]":e+=r,n++)}return e+="]",e}var Os={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"};function _s(t){return Os[t]??""}function ze(t,e){let n=`${e}_`,r=[];for(let s of Object.keys(t.state.env))if(s.startsWith(n)){let i=s.slice(n.length),o=Number.parseInt(i,10);!Number.isNaN(o)&&String(o)===i&&r.push(o)}return r.sort((s,i)=>s-i)}function Be(t,e){let n=`${e}_`;for(let r of Object.keys(t.state.env))r.startsWith(n)&&delete t.state.env[r]}function Vt(t,e){let n=`${e}_`,r=[];for(let s of Object.keys(t.state.env))if(s.startsWith(n)&&!s.includes("__")){let i=s.slice(n.length);r.push(i)}return r.sort()}function nn(t){return t.startsWith("'")&&t.endsWith("'")||t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1):t}function rt(t){return t.IFS??`
|
|
40
|
-
`}function
|
|
41
|
-
`?"\\n":e).join("")}function
|
|
42
|
-
`,"";let m=Math.max(...h.map(([E])=>typeof E=="number"?E:0))+1+l;return m<0?(t.state.expansionStderr=(t.state.expansionStderr||"")+`bash: ${
|
|
43
|
-
`,""):t.state.env[`${
|
|
44
|
-
`:e+="\\n";break;case"\r":e+="\\r";break;case" ":e+="\\t";break;default:{let r=
|
|
45
|
-
`)}return
|
|
46
|
-
`;case"r":return"\r";case"t":return" ";case"v":return"\v";case"'":return"'";case'"':return'"';case"?":return"?";default:return h}});case"K":return"";default:return
|
|
47
|
-
`)}return
|
|
48
|
-
`,0;let l=Math.max(...a.map(([
|
|
49
|
-
`,0;
|
|
50
|
-
`);
|
|
51
|
-
`)}catch{return x(`bash: cd: ${
|
|
52
|
-
`)}}let
|
|
53
|
-
`:"")}function Kt(t,e){if(t.state.loopDepth===0){if(t.state.parentHasLoopContext)throw new
|
|
54
|
-
`);
|
|
55
|
-
`):null}function
|
|
56
|
-
`}}return j(c)}if(a.length===0&&!
|
|
57
|
-
`}return j(c)}for(let c of a){let l=c.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\((.*)\)$/s);if(l){let
|
|
58
|
-
`)&&!r&&!
|
|
59
|
-
`)}return j(a)}}else if(
|
|
39
|
+
`&&(i+=l),o+=2):(i+=e[o],o++)}else i+=e[o],o++;o>=e.length&&this.error("unexpected EOF while looking for matching ``'");let c=new t().parse(i);return{part:A.commandSubstitution(c,!0),endIndex:o+1}}parseArithmeticExpansion(e,s){let r=s+3,n=1,o=0,i=r;for(;i<e.length-1&&n>0;)e[i]==="$"&&e[i+1]==="("?e[i+2]==="("?(n++,i+=3):(o++,i+=2):e[i]==="("&&e[i+1]==="("?(n++,i+=2):e[i]===")"&&e[i+1]===")"?o>0?(o--,i++):(n--,n>0&&(i+=2)):e[i]==="("?(o++,i++):(e[i]===")"&&o>0&&o--,i++);let a=e.slice(r,i),c=this.parseArithmeticExpression(a);return{part:A.arithmeticExpansion(c),endIndex:i+2}}parseArithmeticCommand(){this.expect(u.DPAREN_START);let e="",s=1,r=0,n=!1,o=!1;for(;s>0&&!this.check(u.EOF);){if(n){if(n=!1,r>0){r--,e+=")";continue}if(this.check(u.RPAREN)){s--,o=!0,this.advance();continue}if(this.check(u.DPAREN_END)){s--,o=!0;continue}e+=")";continue}this.check(u.DPAREN_START)?(s++,e+="((",this.advance()):this.check(u.DPAREN_END)?r>=2?(r-=2,e+="))",this.advance()):r===1?(r--,e+=")",n=!0,this.advance()):(s--,o=!0,s>0&&(e+="))"),this.advance()):this.check(u.LPAREN)?(r++,e+="(",this.advance()):this.check(u.RPAREN)?(r>0&&r--,e+=")",this.advance()):(e+=this.current().value,this.advance())}o||this.expect(u.DPAREN_END);let i=this.parseArithmeticExpression(e.trim()),a=this.parseOptionalRedirections();return A.arithmeticCommand(i,a)}parseConditionalCommand(){this.expect(u.DBRACK_START);let e=zt(this);this.expect(u.DBRACK_END);let s=this.parseOptionalRedirections();return A.conditionalCommand(e,s)}parseFunctionDef(){let e;this.check(u.FUNCTION)?(this.advance(),e=this.expect(u.NAME,"Expected function name").value,this.check(u.LPAREN)&&(this.advance(),this.expect(u.RPAREN))):(e=this.advance().value,this.expect(u.LPAREN),this.expect(u.RPAREN)),this.skipNewlines();let s=this.parseCompoundCommandBody(),r=this.parseOptionalRedirections();return A.functionDef(e,s,r)}parseCompoundCommandBody(){if(this.check(u.LBRACE))return Wt(this);if(this.check(u.LPAREN))return Ft(this);if(this.check(u.IF))return Dt(this);if(this.check(u.FOR))return Ot(this);if(this.check(u.WHILE))return _t(this);if(this.check(u.UNTIL))return Lt(this);if(this.check(u.CASE))return Tt(this);this.error("Expected compound command for function body")}parseCompoundList(){let e=[];for(this.skipNewlines();!this.check(u.EOF,u.FI,u.ELSE,u.ELIF,u.THEN,u.DO,u.DONE,u.ESAC,u.RPAREN,u.RBRACE,u.DSEMI,u.SEMI_AND,u.SEMI_SEMI_AND)&&this.isCommandStart();){this.checkIterationLimit();let s=this.pos,r=this.parseStatement();if(r&&e.push(r),this.skipSeparators(),this.pos===s&&!r)break}return e}parseOptionalRedirections(){let e=[];for(;Je(this);){this.checkIterationLimit();let s=this.pos;if(e.push(et(this)),this.pos===s)break}return e}parseArithmeticExpression(e){return T(this,e)}};function he(t){return new z().parse(t)}var ve=class{fs;cwd;constructor(e,s){this.fs=e,this.cwd=s}isGlobPattern(e){return e.includes("*")||e.includes("?")||/\[.*\]/.test(e)}async expandArgs(e,s){let r=e.map((i,a)=>(s?.[a]??!1)||!this.isGlobPattern(i)?null:this.expand(i)),n=await Promise.all(r.map(i=>i||Promise.resolve(null))),o=[];for(let i=0;i<e.length;i++){let a=n[i];a===null?o.push(e[i]):a.length>0?o.push(...a):o.push(e[i])}return o}async expand(e){return e.includes("**")?this.expandRecursive(e):this.expandSimple(e)}hasGlobChars(e){return e.includes("*")||e.includes("?")||/\[.*\]/.test(e)}async expandSimple(e){let s=e.startsWith("/"),r=e.split("/").filter(l=>l!==""),n=-1;for(let l=0;l<r.length;l++)if(this.hasGlobChars(r[l])){n=l;break}if(n===-1)return[e];let o,i;if(n===0)s?(o="/",i="/"):(o=this.cwd,i="");else{let l=r.slice(0,n);s?(o=`/${l.join("/")}`,i=`/${l.join("/")}`):(o=this.fs.resolvePath(this.cwd,l.join("/")),i=l.join("/"))}let a=r.slice(n);return(await this.expandSegments(o,i,a)).sort()}async expandSegments(e,s,r){if(r.length===0)return[s];let[n,...o]=r,i=[];try{if(this.fs.readdirWithFileTypes){let a=await this.fs.readdirWithFileTypes(e),c=[];for(let f of a)if(!(f.name.startsWith(".")&&!n.startsWith("."))&&this.matchPattern(f.name,n)){let h=e==="/"?`/${f.name}`:`${e}/${f.name}`,d;s===""?d=f.name:s==="/"?d=`/${f.name}`:d=`${s}/${f.name}`,o.length===0?c.push(Promise.resolve([d])):f.isDirectory&&c.push(this.expandSegments(h,d,o))}let l=await Promise.all(c);for(let f of l)i.push(...f)}else{let a=await this.fs.readdir(e),c=[];for(let f of a)if(!(f.startsWith(".")&&!n.startsWith("."))&&this.matchPattern(f,n)){let h=e==="/"?`/${f}`:`${e}/${f}`,d;s===""?d=f:s==="/"?d=`/${f}`:d=`${s}/${f}`,o.length===0?c.push(Promise.resolve([d])):c.push((async()=>{try{if((await this.fs.stat(h)).isDirectory)return this.expandSegments(h,d,o)}catch{}return[]})())}let l=await Promise.all(c);for(let f of l)i.push(...f)}}catch{}return i}async expandRecursive(e){let s=[],r=e.indexOf("**"),n=e.slice(0,r).replace(/\/$/,"")||".",i=e.slice(r+2).replace(/^\//,"");return await this.walkDirectory(n,i,s),s.sort()}async walkDirectory(e,s,r){let n=this.fs.resolvePath(this.cwd,e);try{if(this.fs.readdirWithFileTypes){let o=await this.fs.readdirWithFileTypes(n),i=[],a=[];for(let c of o){let l=e==="."?c.name:`${e}/${c.name}`;c.isDirectory?a.push(l):s&&this.matchPattern(c.name,s)&&i.push(l)}r.push(...i);for(let c=0;c<a.length;c+=100){let l=a.slice(c,c+100);await Promise.all(l.map(f=>this.walkDirectory(f,s,r)))}}else{let o=await this.fs.readdir(n),i=[];for(let c=0;c<o.length;c+=100){let l=o.slice(c,c+100),f=await Promise.all(l.map(async h=>{let d=e==="."?h:`${e}/${h}`,m=this.fs.resolvePath(this.cwd,d);try{let y=await this.fs.stat(m);return{name:h,path:d,isDirectory:y.isDirectory}}catch{return null}}));i.push(...f.filter(h=>h!==null))}for(let c of i)!c.isDirectory&&s&&this.matchPattern(c.name,s)&&r.push(c.path);let a=i.filter(c=>c.isDirectory);for(let c=0;c<a.length;c+=100){let l=a.slice(c,c+100);await Promise.all(l.map(f=>this.walkDirectory(f.path,s,r)))}}}catch{}}matchPattern(e,s){return this.patternToRegex(s).test(e)}patternToRegex(e){let s="^";for(let r=0;r<e.length;r++){let n=e[r];if(n==="*")s+=".*";else if(n==="?")s+=".";else if(n==="["){let o=r+1,i="[";for(o<e.length&&(e[o]==="^"||e[o]==="!")&&(i+="^",o++),o<e.length&&e[o]==="]"&&(i+="\\]",o++);o<e.length&&e[o]!=="]";){if(e[o]==="["&&o+1<e.length&&e[o+1]===":"){let a=e.indexOf(":]",o+2);if(a!==-1){let c=e.slice(o+2,a),l=this.posixClassToRegex(c);i+=l,o=a+2;continue}}if(e[o]==="\\"&&o+1<e.length){i+=`\\${e[o+1]}`,o+=2;continue}e[o]==="-"?i+="\\-":i+=e[o],o++}i+="]",s+=i,r=o}else if(n==="\\"&&r+1<e.length){let o=e[r+1];/[.+^${}()|\\*?[\]]/.test(o)?s+=`\\${o}`:s+=o,r++}else/[.+^${}()|]/.test(n)?s+=`\\${n}`:s+=n}return s+="$",new RegExp(s)}posixClassToRegex(e){return{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"}[e]||""}};function Z(t){switch(t.type){case"ArithCommandSubst":return!0;case"ArithNested":return Z(t.expression);case"ArithBinary":return Z(t.left)||Z(t.right);case"ArithUnary":return Z(t.operand);case"ArithTernary":return Z(t.condition)||Z(t.consequent)||Z(t.alternate);case"ArithAssignment":return Z(t.value);case"ArithGroup":return Z(t.expression);case"ArithArrayElement":return t.index?Z(t.index):!1;case"ArithConcat":return t.parts.some(Z);default:return!1}}function Ut(t){let e=t.operation;return e?!!("word"in e&&e.word&&oe(e.word)||e.type==="PatternReplacement"&&(e.pattern&&oe(e.pattern)||e.replacement&&oe(e.replacement))||e.type==="PatternRemoval"&&e.pattern&&oe(e.pattern)):!1}function tt(t){switch(t.type){case"CommandSubstitution":return!0;case"ArithmeticExpansion":return Z(t.expression.expression);case"DoubleQuoted":return t.parts.some(tt);case"BraceExpansion":return t.items.some(e=>e.type==="Word"&&oe(e.word));case"ParameterExpansion":return Ut(t);default:return!1}}function oe(t){return t.parts.some(tt)}function Gt(t){if(!t.operation)return!1;let e=t.operation,s;if((e.type==="DefaultValue"||e.type==="AssignDefault"||e.type==="UseAlternative"||e.type==="ErrorIfUnset")&&(s=e.word?.parts),!s)return!1;for(let r of s)if(r.type==="DoubleQuoted"||r.type==="SingleQuoted")return!0;return!1}function rs(t){let e=!1,s=!1,r=!1,n=!1,o=!1;for(let i of t){if((i.type==="SingleQuoted"||i.type==="DoubleQuoted")&&(e=!0,i.type==="DoubleQuoted"))for(let a of i.parts)a.type==="ParameterExpansion"&&a.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[[@*]\]$/)&&!a.operation&&(n=!0);i.type==="CommandSubstitution"&&(s=!0),i.type==="ParameterExpansion"&&(o=!0,(i.parameter==="@"||i.parameter==="*")&&(r=!0),Gt(i)&&(e=!0))}return{hasQuoted:e,hasCommandSub:s,hasArrayVar:r,hasArrayAtExpansion:n,hasParamExpansion:o}}function kn(t,e,s,r,n){let o=s??1;o===0&&(o=1);let i=Math.abs(o),a=[],c=0;r?.match(/^-?0\d/)&&(c=Math.max(c,r.replace(/^-/,"").length)),n?.match(/^-?0\d/)&&(c=Math.max(c,n.replace(/^-/,"").length));let l=f=>{if(c>0){let h=f<0,d=String(Math.abs(f)).padStart(c,"0");return h?`-${d}`:d}return String(f)};if(t<=e)for(let f=t,h=0;f<=e&&h<1e4;f+=i,h++)a.push(l(f));else for(let f=t,h=0;f>=e&&h<1e4;f-=i,h++)a.push(l(f));return a}function In(t,e,s){let r=s??1;r===0&&(r=1);let n=t.charCodeAt(0),o=e.charCodeAt(0),i=Math.abs(r),a=t>="A"&&t<="Z",c=t>="a"&&t<="z",l=e>="A"&&e<="Z",f=e>="a"&&e<="z";if(a&&f||c&&l)return null;let h=[];if(n<=o)for(let d=n,m=0;d<=o&&m<1e4;d+=i,m++)h.push(String.fromCharCode(d));else for(let d=n,m=0;d>=o&&m<1e4;d-=i,m++)h.push(String.fromCharCode(d));return h}function Me(t,e,s,r,n){let o=s!==void 0?`..${s}`:"";return typeof t=="number"&&typeof e=="number"?{expanded:kn(t,e,s,r,n),literal:`{${t}..${e}${o}}`}:typeof t=="string"&&typeof e=="string"?{expanded:In(t,e,s),literal:`{${t}..${e}${o}}`}:{expanded:null,literal:`{${t}..${e}${o}}`}}function V(t,e){let s="",r=0;for(;r<t.length;){let n=t[r];if(n==="\\")if(r+1<t.length){let o=t[r+1];/[\\^$.|+(){}[\]*?]/.test(o)?s+=`\\${o}`:s+=o,r+=2}else s+="\\\\",r++;else if(n==="*")s+=e?".*":".*?",r++;else if(n==="?")s+=".",r++;else if(n==="["){let o=Rn(t,r);if(o===-1)s+="\\[",r++;else{let i=t.slice(r+1,o);s+=Dn(i),r=o+1}}else/[\^$.|+(){}]/.test(n)?(s+=`\\${n}`,r++):(s+=n,r++)}return s}function Rn(t,e){let s=e+1;for(s<t.length&&t[s]==="^"&&s++,s<t.length&&t[s]==="]"&&s++;s<t.length;){if(t[s]==="\\"&&s+1<t.length){s+=2;continue}if(t[s]==="]")return s;if(t[s]==="'"){let r=t.indexOf("'",s+1);if(r!==-1){s=r+1;continue}}if(t[s]==="["&&s+1<t.length&&t[s+1]===":"){let r=t.indexOf(":]",s+2);if(r!==-1){s=r+2;continue}}s++}return-1}function Dn(t){let e="[",s=0;for((t[0]==="^"||t[0]==="!")&&(e+="^",s++);s<t.length;){if(t[s]==="'"){let n=t.indexOf("'",s+1);if(n!==-1){let o=t.slice(s+1,n);for(let i of o)i==="\\"?e+="\\\\":i==="]"?e+="\\]":i==="^"&&e==="["?e+="\\^":e+=i;s=n+1;continue}}if(t[s]==="["&&s+1<t.length&&t[s+1]===":"){let n=t.indexOf(":]",s+2);if(n!==-1){let o=t.slice(s+2,n);e+=_n(o),s=n+2;continue}}let r=t[s];r==="\\"?s+1<t.length?(e+=`\\${t[s+1]}`,s+=2):(e+="\\\\",s++):r==="-"&&s>0&&s<t.length-1?(e+="-",s++):r==="^"&&s===0?(e+="^",s++):(r==="]"&&s===0?e+="\\]":e+=r,s++)}return e+="]",e}var On={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"};function _n(t){return On[t]??""}function ze(t,e){let s=`${e}_`,r=[];for(let n of Object.keys(t.state.env))if(n.startsWith(s)){let o=n.slice(s.length),i=Number.parseInt(o,10);!Number.isNaN(i)&&String(i)===o&&r.push(i)}return r.sort((n,o)=>n-o)}function Be(t,e){let s=`${e}_`;for(let r of Object.keys(t.state.env))r.startsWith(s)&&delete t.state.env[r]}function Vt(t,e){let s=`${e}_`,r=[];for(let n of Object.keys(t.state.env))if(n.startsWith(s)&&!n.includes("__")){let o=n.slice(s.length);r.push(o)}return r.sort()}function ss(t){return t.startsWith("'")&&t.endsWith("'")||t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1):t}function rt(t){return t.IFS??`
|
|
40
|
+
`}function ns(t){return t.IFS===""}function Ue(t){return t.split("").map(e=>/[\\^$.*+?()[\]{}|-]/.test(e)?`\\${e}`:e===" "?"\\t":e===`
|
|
41
|
+
`?"\\n":e).join("")}function Ln(t,e){let s=Ue(t);return new RegExp(`[${s}]+`,e)}function Tn(t){let e=Ue(t);return new RegExp(`^[${e}]+`)}function Fn(t){let e=Ue(t);return new RegExp(`[${e}]+$`)}function $e(t){let e=t.IFS;return e===void 0?" ":e[0]||""}function is(t,e){if(e==="")return{words:[t],wordStarts:[0]};let s=[],r=[],n=Ln(e,"g"),o=0,i=t.match(Tn(e));i&&(o=i[0].length),n.lastIndex=o;let a=n.exec(t);for(;a!==null;)a.index>o&&(r.push(o),s.push(t.substring(o,a.index))),o=n.lastIndex,a=n.exec(t);return o<t.length&&(r.push(o),s.push(t.substring(o))),{words:s,wordStarts:r}}function os(t,e){return e===""?t:t.replace(Fn(e),"")}function F(t,e){return t.state.associativeArrays?.has(e)?Vt(t,e).map(o=>[o,t.state.env[`${e}_${o}`]]):ze(t,e).map(n=>[n,t.state.env[`${e}_${n}`]])}function as(t,e){return t.state.associativeArrays?.has(e)?Vt(t,e).length>0:ze(t,e).length>0}function Q(t,e,s=!0,r=!1){switch(e){case"?":return String(t.state.lastExitCode);case"$":return String(process.pid);case"#":return t.state.env["#"]||"0";case"@":return t.state.env["@"]||"";case"_":return t.state.lastArg;case"-":{let i="";return t.state.options.errexit&&(i+="e"),t.state.options.nounset&&(i+="u"),t.state.options.verbose&&(i+="v"),t.state.options.xtrace&&(i+="x"),t.state.options.pipefail&&(i+="p"),i}case"*":{let i=Number.parseInt(t.state.env["#"]||"0",10);if(i===0)return"";let a=[];for(let c=1;c<=i;c++)a.push(t.state.env[String(c)]||"");return a.join($e(t.state.env))}case"0":return t.state.env[0]||"bash";case"PWD":return t.state.env.PWD!==void 0?t.state.env.PWD:"";case"OLDPWD":return t.state.env.OLDPWD!==void 0?t.state.env.OLDPWD:"";case"PPID":{let{ppid:i}=We();return String(i)}case"UID":{let{uid:i}=We();return String(i)}case"EUID":return String(process.geteuid?.()??We().uid);case"RANDOM":return String(Math.floor(Math.random()*32768));case"SECONDS":return String(Math.floor((Date.now()-t.state.startTime)/1e3));case"BASH_VERSION":return Pr;case"!":return String(t.state.lastBackgroundPid);case"LINENO":return String(t.state.currentLine)}if(/^[a-zA-Z_][a-zA-Z0-9_]*\[\]$/.test(e))throw new Ee(`\${${e}}`);let n=e.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(n){let i=n[1],a=n[2];if(a==="@"||a==="*"){let h=F(t,i);if(h.length>0)return h.map(([,m])=>m).join(" ");let d=t.state.env[i];return d!==void 0?d:""}if(t.state.associativeArrays?.has(i)){let h=ss(a),d=t.state.env[`${i}_${h}`];if(d===void 0&&s&&t.state.options.nounset)throw new J(`${i}[${a}]`);return d||""}let l;if(/^-?\d+$/.test(a))l=Number.parseInt(a,10);else try{let h=new z,d=T(h,a);l=P(t,d.expression)}catch{let h=t.state.env[a];l=h?Number.parseInt(h,10):0,Number.isNaN(l)&&(l=0)}if(l<0){let h=F(t,i);if(h.length===0)return t.state.expansionStderr=(t.state.expansionStderr||"")+`bash: ${i}: bad array subscript
|
|
42
|
+
`,"";let m=Math.max(...h.map(([E])=>typeof E=="number"?E:0))+1+l;return m<0?(t.state.expansionStderr=(t.state.expansionStderr||"")+`bash: ${i}: bad array subscript
|
|
43
|
+
`,""):t.state.env[`${i}_${m}`]||""}let f=t.state.env[`${i}_${l}`];if(f===void 0&&s&&t.state.options.nounset)throw new J(`${i}[${l}]`);return f||""}if(/^[1-9][0-9]*$/.test(e)){let i=t.state.env[e];if(i===void 0&&s&&t.state.options.nounset)throw new J(e);return i||""}let o=t.state.env[e];if(o===void 0&&s&&t.state.options.nounset)throw new J(e);return o||""}async function cs(t,e,s,r,n){let o=[];for(let f of e){let h=f.type==="ParameterExpansion"||f.type==="CommandSubstitution"||f.type==="ArithmeticExpansion";if(f.type==="ParameterExpansion"&&Gt(f)){let d=await n(t,f);o.push({value:d,splittable:!1})}else{let d=await n(t,f);o.push({value:d,splittable:h})}}if(!o.some(f=>f.splittable&&new RegExp(`[${r}]`).test(f.value))){let f=o.map(h=>h.value).join("");return f?[f]:[]}let a=new RegExp(`[${r}]+`),c=[],l="";for(let f=0;f<o.length;f++){let h=o[f];if(!h.splittable)l+=h.value;else{let d=h.value.split(a);for(let m=0;m<d.length;m++)m===0?l+=d[m]:(l!==""&&c.push(l),l=d[m])}}return l!==""&&c.push(l),c}function H(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ls(t){switch(t.type){case"Literal":return t.value;case"SingleQuoted":return t.value;case"Escaped":return t.value;default:return null}}function fs(t){switch(t.type){case"SingleQuoted":case"Escaped":case"DoubleQuoted":return!0;case"Literal":return t.value==="";default:return!1}}function Ht(t){if(t==="")return"''";if(!/['\\\n\r\t\x00-\x1f\x7f]/.test(t))return`'${t}'`;let e="$'";for(let s of t)switch(s){case"'":e+="\\'";break;case"\\":e+="\\\\";break;case`
|
|
44
|
+
`:e+="\\n";break;case"\r":e+="\\r";break;case" ":e+="\\t";break;default:{let r=s.charCodeAt(0);r<32||r===127?e+=`\\x${r.toString(16).padStart(2,"0")}`:e+=s}}return`${e}'`}function Se(t,e,s=!1){return e.map(r=>ae(t,r,s)).join("")}async function xe(t,e,s=!1){let r=[];for(let n of e)r.push(await K(t,n));return r.join("")}function Wn(t){return fs(t)}function us(t){if(t.parts.length===0)return!0;for(let e of t.parts)if(!Wn(e))return!1;return!0}function hs(t){return t.replace(/([*?[\]\\])/g,"\\$1")}function ds(t,e,s=!1){let r=ls(e);if(r!==null)return r;switch(e.type){case"ParameterExpansion":return Es(t,e,s);case"TildeExpansion":return s?e.user===null?"~":`~${e.user}`:e.user===null?t.state.env.HOME||"/home/user":e.user==="root"?"/root":`~${e.user}`;case"Glob":return e.pattern;default:return null}}function ae(t,e,s=!1){let r=ds(t,e,s);if(r!==null)return r;switch(e.type){case"DoubleQuoted":{let n=[];for(let o of e.parts)n.push(ae(t,o,!0));return n.join("")}case"ArithmeticExpansion":return String(P(t,e.expression.expression));case"BraceExpansion":{let n=[];for(let o of e.items)if(o.type==="Range"){let i=Me(o.start,o.end,o.step,o.startStr,o.endStr);if(i.expanded)n.push(...i.expanded);else return i.literal}else n.push(st(t,o.word));return n.join(" ")}default:return""}}function st(t,e){let s=e.parts,r=s.length;if(r===1)return ae(t,s[0]);let n=[];for(let o=0;o<r;o++)n.push(ae(t,s[o]));return n.join("")}async function k(t,e){return oe(e)?ws(t,e):st(t,e)}function nt(t){for(let e of t)if(e.type==="BraceExpansion"||e.type==="DoubleQuoted"&&nt(e.parts))return!0;return!1}function Mn(t){for(let e of t){if(e.type==="BraceExpansion"){for(let s of e.items)if(s.type==="Word"&&oe(s.word))return!0}if(tt(e))return!0}return!1}var ms=1e4,ke=1e5;function ps(t,e,s={count:0}){if(s.count>ke)return[[]];let r=[[]];for(let n of e)if(n.type==="BraceExpansion"){let o=[],i=!1,a="";for(let f of n.items)if(f.type==="Range"){let h=Me(f.start,f.end,f.step,f.startStr,f.endStr);if(h.expanded)for(let d of h.expanded)s.count++,o.push(d);else{i=!0,a=h.literal;break}}else{let h=ps(t,f.word.parts,s);for(let d of h)s.count++,o.push(d.join(""))}if(i){for(let f of r)s.count++,f.push(a);continue}if(r.length*o.length>ms||s.count>ke)return r;let l=[];for(let f of r)for(let h of o){if(s.count++,s.count>ke)return l.length>0?l:r;l.push([...f,h])}r=l}else{let o=ae(t,n);for(let i of r)s.count++,i.push(o)}return r}function zn(t,e){let s=e.parts;return nt(s)?ps(t,s).map(n=>n.join("")):[st(t,e)]}async function ys(t,e,s={count:0}){if(s.count>ke)return[[]];let r=[[]];for(let n of e)if(n.type==="BraceExpansion"){let o=[],i=!1,a="";for(let f of n.items)if(f.type==="Range"){let h=Me(f.start,f.end,f.step,f.startStr,f.endStr);if(h.expanded)for(let d of h.expanded)s.count++,o.push(d);else{i=!0,a=h.literal;break}}else{let h=await ys(t,f.word.parts,s);for(let d of h)s.count++,o.push(d.join(""))}if(i){for(let f of r)s.count++,f.push(a);continue}if(r.length*o.length>ms||s.count>ke)return r;let l=[];for(let f of r)for(let h of o){if(s.count++,s.count>ke)return l.length>0?l:r;l.push([...f,h])}r=l}else{let o=await K(t,n);for(let i of r)s.count++,i.push(o)}return r}async function Bn(t,e){let s=e.parts;return nt(s)?(await ys(t,s)).map(n=>n.join("")):[await k(t,e)]}async function Ge(t,e){let s=e.parts,{hasQuoted:r,hasCommandSub:n,hasArrayVar:o,hasArrayAtExpansion:i,hasParamExpansion:a}=rs(s),l=nt(s)?Mn(s)?await Bn(t,e):zn(t,e):null;if(l&&l.length>1){let d=[];for(let m of l)if(!r&&/[*?[]/.test(m)){let E=await new ve(t.fs,t.state.cwd).expand(m);E.length>0?d.push(...E):d.push(m)}else d.push(m);return{values:d,quoted:!1}}if(i&&s.length===1&&s[0].type==="DoubleQuoted"){let d=s[0];if(d.parts.length===1&&d.parts[0].type==="ParameterExpansion"){let y=d.parts[0].parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[[@]\]$/);if(y){let E=y[1],p=F(t,E);if(p.length>0)return{values:p.map(([,g])=>g),quoted:!0};let w=t.state.env[E];return w!==void 0?{values:[w],quoted:!0}:{values:[],quoted:!0}}}}if(s.length===1&&s[0].type==="DoubleQuoted"){let d=s[0],m=-1,y=!1;for(let E=0;E<d.parts.length;E++){let p=d.parts[E];if(p.type==="ParameterExpansion"&&(p.parameter==="@"||p.parameter==="*")){m=E,y=p.parameter==="*";break}}if(m!==-1){let E=d.parts[m];E.type==="ParameterExpansion"&&E.operation&&(m=-1)}if(m!==-1){let E=Number.parseInt(t.state.env["#"]||"0",10),p="";for(let C=0;C<m;C++)p+=await K(t,d.parts[C]);let w="";for(let C=m+1;C<d.parts.length;C++)w+=await K(t,d.parts[C]);if(E===0){if(y)return{values:[p+w],quoted:!0};let C=p+w;return{values:C?[C]:[],quoted:!0}}let g=[];for(let C=1;C<=E;C++)g.push(t.state.env[String(C)]||"");if(y){let C=$e(t.state.env);return{values:[p+g.join(C)+w],quoted:!0}}return g.length===1?{values:[p+g[0]+w],quoted:!0}:{values:[p+g[0],...g.slice(1,-1),g[g.length-1]+w],quoted:!0}}}if((n||o||a)&&!ns(t.state.env)){let d=rt(t.state.env),m=Ue(d),y=await cs(t,s,d,m,K),E=[],p=new ve(t.fs,t.state.cwd);for(let w of y)if(/[*?[]/.test(w)){let g=await p.expand(w);g.length>0?E.push(...g):E.push(w)}else E.push(w);return{values:E,quoted:!1}}let h=oe(e)?await ws(t,e):st(t,e);if(!r&&/[*?[]/.test(h)){let m=await new ve(t.fs,t.state.cwd).expand(h);if(m.length>0)return{values:m,quoted:!1}}return h===""&&!r?{values:[],quoted:!1}:{values:[h],quoted:r}}async function ws(t,e){let s=e.parts,r=s.length;if(r===1)return K(t,s[0]);let n=[];for(let o=0;o<r;o++)n.push(await K(t,s[o]));return n.join("")}async function K(t,e){if(e.type==="ParameterExpansion"&&Ut(e))return Un(t,e);let s=ds(t,e);if(s!==null)return s;switch(e.type){case"DoubleQuoted":{let r=[];for(let n of e.parts)r.push(await K(t,n));return r.join("")}case"CommandSubstitution":try{let r=await t.executeScript(e.body);return t.state.lastExitCode=r.exitCode,t.state.env["?"]=String(r.exitCode),r.stdout.replace(/\n+$/,"")}catch(r){if(r instanceof B)throw r;if(r instanceof R)return t.state.lastExitCode=r.exitCode,t.state.env["?"]=String(r.exitCode),r.stdout.replace(/\n+$/,"");throw r}case"ArithmeticExpansion":return String(await v(t,e.expression.expression));case"BraceExpansion":{let r=[];for(let n of e.items)if(n.type==="Range"){let o=Me(n.start,n.end,n.step,n.startStr,n.endStr);if(o.expanded)r.push(...o.expanded);else return o.literal}else r.push(await k(t,n.word));return r.join(" ")}default:return""}}function Es(t,e,s=!1){let{parameter:r,operation:n}=e,o=n&&(n.type==="DefaultValue"||n.type==="AssignDefault"||n.type==="UseAlternative"||n.type==="ErrorIfUnset"),i=Q(t,r,!o);if(!n)return i;let a=!(r in t.state.env),c=i==="";switch(n.type){case"DefaultValue":return(a||n.checkEmpty&&c)&&n.word?Se(t,n.word.parts,s):i;case"AssignDefault":{if((a||n.checkEmpty&&c)&&n.word){let f=Se(t,n.word.parts,s),h=r.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(h){let[,d,m]=h,y;if(/^\d+$/.test(m))y=Number.parseInt(m,10);else{try{let p=new z,w=T(p,m);y=P(t,w.expression)}catch{let p=t.state.env[m];y=p?Number.parseInt(p,10):0}Number.isNaN(y)&&(y=0)}t.state.env[`${d}_${y}`]=f;let E=Number.parseInt(t.state.env[`${d}__length`]||"0",10);y>=E&&(t.state.env[`${d}__length`]=String(y+1))}else t.state.env[r]=f;return f}return i}case"ErrorIfUnset":{if(a||n.checkEmpty&&c){let f=n.word?Se(t,n.word.parts,s):`${r}: parameter null or not set`;throw new R(1,"",`bash: ${f}
|
|
45
|
+
`)}return i}case"UseAlternative":return!(a||n.checkEmpty&&c)&&n.word?Se(t,n.word.parts,s):"";case"Length":{let l=r.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[[@*]\]$/);if(l){let f=F(t,l[1]);return String(f.length)}if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(r)&&as(t,r)){let f=t.state.env[`${r}_0`]||"";return String(f.length)}return String(i.length)}case"LengthSliceError":throw new Ee(r);case"Substring":{let l=n.offset?P(t,n.offset.expression):0,f=n.length?P(t,n.length.expression):void 0;if(r==="@"||r==="*"){let y=(t.state.env["@"]||"").split(" ").filter(g=>g),E=t.state.env[0]||"bash",p=l===0?[E,...y]:y,w=l===0?0:l-1;if(w<0||w>=p.length)return"";if(f!==void 0){let g=f<0?p.length+f:w+f;return p.slice(w,Math.max(w,g)).join(" ")}return p.slice(w).join(" ")}let h=r.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[[@*]\]$/);if(h){let E=F(t,h[1]).map(([,w])=>w),p=l;if(p<0&&(p=E.length+p,p<0))return"";if(f!==void 0){if(f<0){let w=E.length+f;return E.slice(p,Math.max(p,w)).join(" ")}return E.slice(p,p+f).join(" ")}return E.slice(p).join(" ")}let d=[...i],m=l;if(m<0&&(m=Math.max(0,d.length+m)),f!==void 0){if(f<0){let y=d.length+f;return d.slice(m,Math.max(m,y)).join("")}return d.slice(m,m+f).join("")}return d.slice(m).join("")}case"PatternRemoval":{let l="";if(n.pattern)for(let h of n.pattern.parts)if(h.type==="Glob")l+=V(h.pattern,n.greedy);else if(h.type==="Literal")l+=V(h.value,n.greedy);else if(h.type==="SingleQuoted"||h.type==="Escaped")l+=H(h.value);else if(h.type==="DoubleQuoted"){let d=Se(t,h.parts);l+=H(d)}else if(h.type==="ParameterExpansion"){let d=ae(t,h);l+=V(d,n.greedy)}else{let d=ae(t,h);l+=H(d)}if(n.side==="prefix")return i.replace(new RegExp(`^${l}`),"");let f=new RegExp(`${l}$`);if(n.greedy)return i.replace(f,"");for(let h=i.length;h>=0;h--){let d=i.slice(h);if(f.test(d))return i.slice(0,h)}return i}case"PatternReplacement":{let l="";if(n.pattern)for(let d of n.pattern.parts)if(d.type==="Glob")l+=V(d.pattern,!0);else if(d.type==="Literal")l+=V(d.value,!0);else if(d.type==="SingleQuoted"||d.type==="Escaped")l+=H(d.value);else if(d.type==="DoubleQuoted"){let m=Se(t,d.parts);l+=H(m)}else if(d.type==="ParameterExpansion"){let m=ae(t,d);l+=V(m,!0)}else{let m=ae(t,d);l+=H(m)}let f=n.replacement?Se(t,n.replacement.parts):"";if(l==="")return i;n.anchor==="start"?l=`^${l}`:n.anchor==="end"&&(l=`${l}$`);let h=n.all?"g":"";try{let d=new RegExp(l,h);if(n.all){let m="",y=0,E=d.exec(i);for(;E!==null&&!(E[0].length===0&&E.index===i.length);)m+=i.slice(y,E.index)+f,y=E.index+E[0].length,E[0].length===0&&y++,E=d.exec(i);return m+=i.slice(y),m}return i.replace(d,f)}catch{return i}}case"CaseModification":return n.direction==="upper"?n.all?i.toUpperCase():i.charAt(0).toUpperCase()+i.slice(1):n.all?i.toLowerCase():i.charAt(0).toLowerCase()+i.slice(1);case"Transform":{let l=r.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[[@*]\]$/);if(l&&n.operator==="Q")return F(t,l[1]).map(([,d])=>Ht(d)).join(" ");switch(n.operator){case"Q":return Ht(i);case"P":return i;case"a":return"";case"A":return`${r}=${Ht(i)}`;case"E":return i.replace(/\\([\\abefnrtv'"?])/g,(f,h)=>{switch(h){case"\\":return"\\";case"a":return"\x07";case"b":return"\b";case"e":return"\x1B";case"f":return"\f";case"n":return`
|
|
46
|
+
`;case"r":return"\r";case"t":return" ";case"v":return"\v";case"'":return"'";case'"':return'"';case"?":return"?";default:return h}});case"K":return"";default:return i}}case"Indirection":return Q(t,i);case"ArrayKeys":{let f=F(t,n.array).map(([h])=>String(h));return n.star?f.join($e(t.state.env)):f.join(" ")}case"VarNamePrefix":{let l=Object.keys(t.state.env).filter(f=>f.startsWith(n.prefix)&&!f.includes("__")).sort();return n.star?l.join($e(t.state.env)):l.join(" ")}default:return i}}async function Un(t,e,s=!1){let{parameter:r,operation:n}=e,o=n&&(n.type==="DefaultValue"||n.type==="AssignDefault"||n.type==="UseAlternative"||n.type==="ErrorIfUnset"),i=Q(t,r,!o);if(!n)return i;let a=!(r in t.state.env),c=i==="";switch(n.type){case"DefaultValue":return(a||n.checkEmpty&&c)&&n.word?xe(t,n.word.parts,s):i;case"AssignDefault":{if((a||n.checkEmpty&&c)&&n.word){let f=await xe(t,n.word.parts,s),h=r.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(h){let[,d,m]=h,y;if(/^\d+$/.test(m))y=Number.parseInt(m,10);else{try{let p=new z,w=T(p,m);y=await v(t,w.expression)}catch{let p=t.state.env[m];y=p?Number.parseInt(p,10):0}Number.isNaN(y)&&(y=0)}t.state.env[`${d}_${y}`]=f;let E=Number.parseInt(t.state.env[`${d}__length`]||"0",10);y>=E&&(t.state.env[`${d}__length`]=String(y+1))}else t.state.env[r]=f;return f}return i}case"ErrorIfUnset":{if(a||n.checkEmpty&&c){let f=n.word?await xe(t,n.word.parts,s):`${r}: parameter null or not set`;throw new R(1,"",`bash: ${f}
|
|
47
|
+
`)}return i}case"UseAlternative":return!(a||n.checkEmpty&&c)&&n.word?xe(t,n.word.parts,s):"";case"PatternRemoval":{let l="";if(n.pattern)for(let h of n.pattern.parts)if(h.type==="Glob")l+=V(h.pattern,n.greedy);else if(h.type==="Literal")l+=V(h.value,n.greedy);else if(h.type==="SingleQuoted"||h.type==="Escaped")l+=H(h.value);else if(h.type==="DoubleQuoted"){let d=await xe(t,h.parts);l+=H(d)}else if(h.type==="ParameterExpansion"){let d=await K(t,h);l+=V(d,n.greedy)}else{let d=await K(t,h);l+=H(d)}if(n.side==="prefix")return i.replace(new RegExp(`^${l}`),"");let f=new RegExp(`${l}$`);if(n.greedy)return i.replace(f,"");for(let h=i.length;h>=0;h--){let d=i.slice(h);if(f.test(d))return i.slice(0,h)}return i}case"PatternReplacement":{let l="";if(n.pattern)for(let d of n.pattern.parts)if(d.type==="Glob")l+=V(d.pattern,!0);else if(d.type==="Literal")l+=V(d.value,!0);else if(d.type==="SingleQuoted"||d.type==="Escaped")l+=H(d.value);else if(d.type==="DoubleQuoted"){let m=await xe(t,d.parts);l+=H(m)}else if(d.type==="ParameterExpansion"){let m=await K(t,d);l+=V(m,!0)}else{let m=await K(t,d);l+=H(m)}let f=n.replacement?await xe(t,n.replacement.parts):"";if(l==="")return i;n.anchor==="start"?l=`^${l}`:n.anchor==="end"&&(l=`${l}$`);let h=n.all?"g":"";try{let d=new RegExp(l,h);if(n.all){let m="",y=0,E=d.exec(i);for(;E!==null&&!(E[0].length===0&&E.index===i.length);)m+=i.slice(y,E.index)+f,y=E.index+E[0].length,E[0].length===0&&y++,E=d.exec(i);return m+=i.slice(y),m}return i.replace(d,f)}catch{return i}}default:return Es(t,e,s)}}function jt(t,e,s){switch(s){case"+":return t+e;case"-":return t-e;case"*":return t*e;case"/":return e!==0?Math.trunc(t/e):0;case"%":return e!==0?t%e:0;case"**":if(e<0)throw new W("exponent less than 0");return t**e;case"<<":return t<<e;case">>":return t>>e;case"<":return t<e?1:0;case"<=":return t<=e?1:0;case">":return t>e?1:0;case">=":return t>=e?1:0;case"==":return t===e?1:0;case"!=":return t!==e?1:0;case"&":return t&e;case"|":return t|e;case"^":return t^e;case",":return e;default:return 0}}function gs(t,e,s){switch(s){case"=":return e;case"+=":return t+e;case"-=":return t-e;case"*=":return t*e;case"/=":return e!==0?Math.trunc(t/e):0;case"%=":return e!==0?t%e:0;case"<<=":return t<<e;case">>=":return t>>e;case"&=":return t&e;case"|=":return t|e;case"^=":return t^e;default:return e}}function qt(t,e){switch(e){case"-":return-t;case"+":return+t;case"!":return t===0?1:0;case"~":return~t;default:return t}}function Gn(t,e){let s=t.state.env[e];if(s!==void 0)return s;let r=t.state.env[`${e}_0`];return r!==void 0?r:Q(t,e)}function Ie(t){if(!t)return 0;let e=Number.parseInt(t,10);if(!Number.isNaN(e)&&/^-?\d+$/.test(t.trim()))return e;let s=t.trim();if(!s)return 0;try{let r=new z,{expr:n,pos:o}=ne(r,s,0);if(o<s.length){let i=s.slice(o).trim().split(/\s+/)[0];throw new W(`${s}: syntax error in expression (error token is "${i}")`)}return n.type==="ArithNumber"?n.value:e||0}catch(r){if(r instanceof W)throw r;let n=s.split(/\s+/).slice(1)[0]||s;throw new W(`${s}: syntax error in expression (error token is "${n}")`)}}function it(t,e,s=new Set){if(s.has(e))return 0;s.add(e);let r=Gn(t,e);if(!r)return 0;let n=Number.parseInt(r,10);if(!Number.isNaN(n)&&/^-?\d+$/.test(r.trim()))return n;let o=r.trim();if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(o))return it(t,o,s);try{let i=new z,{expr:a}=ne(i,o,0);return X(t,a,s)}catch{return 0}}function X(t,e,s){switch(e.type){case"ArithNumber":if(Number.isNaN(e.value))throw new W("value too great for base");return e.value;case"ArithVariable":return it(t,e.name,s);case"ArithBinary":{if(e.operator==="||")return X(t,e.left,s)||X(t,e.right,s)?1:0;if(e.operator==="&&")return X(t,e.left,s)&&X(t,e.right,s)?1:0;let r=X(t,e.left,s),n=X(t,e.right,s);return jt(r,n,e.operator)}case"ArithUnary":{let r=X(t,e.operand,s);return qt(r,e.operator)}case"ArithTernary":return X(t,e.condition,s)?X(t,e.consequent,s):X(t,e.alternate,s);case"ArithGroup":return X(t,e.expression,s);default:return P(t,e)}}function de(t,e){if(e.startsWith("#")){let h=e.slice(1),d=t.state.env[h]||"";return String(d.length)}if(e.startsWith("!")){let h=e.slice(1),d=t.state.env[h]||"";return t.state.env[d]||""}let s=[":-",":=",":?",":+","-","=","?","+"],r=-1,n="";for(let h of s){let d=e.indexOf(h);d>0&&(r===-1||d<r)&&(r=d,n=h)}if(r===-1)return Q(t,e);let o=e.slice(0,r),i=e.slice(r+n.length),a=t.state.env[o],c=a===void 0,l=a==="",f=n.startsWith(":");switch(n){case":-":case"-":return c||f&&l?i:a||"";case":=":case"=":return c||f&&l?(t.state.env[o]=i,i):a||"";case":+":case"+":return!(c||f&&l)?i:"";case":?":case"?":{if(c||f&&l)throw new Error(i||`${o}: parameter null or not set`);return a||""}default:return a||""}}function P(t,e){switch(e.type){case"ArithNumber":if(Number.isNaN(e.value))throw new W("value too great for base");return e.value;case"ArithVariable":return it(t,e.name);case"ArithNested":return P(t,e.expression);case"ArithCommandSubst":return 0;case"ArithBracedExpansion":{let s=de(t,e.content);return Number.parseInt(s,10)||0}case"ArithDynamicBase":{let s=de(t,e.baseExpr),r=Number.parseInt(s,10);if(r<2||r>64)return 0;let n=`${r}#${e.value}`;return Ne(n)}case"ArithDynamicNumber":{let r=de(t,e.prefix)+e.suffix;return Ne(r)}case"ArithArrayElement":{let s=t.state.associativeArrays?.has(e.array),r;if(e.stringKey!==void 0)r=`${e.array}_${e.stringKey}`;else if(s&&e.index?.type==="ArithVariable")r=`${e.array}_${e.index.name}`;else if(e.index){let o=P(t,e.index);if(o<0){let a=F(t,e.array);if(a.length===0)return t.state.expansionStderr=(t.state.expansionStderr||"")+`bash: ${e.array}: bad array subscript
|
|
48
|
+
`,0;let l=Math.max(...a.map(([f])=>typeof f=="number"?f:0))+1+o;if(l<0)return t.state.expansionStderr=(t.state.expansionStderr||"")+`bash: ${e.array}: bad array subscript
|
|
49
|
+
`,0;o=l}r=`${e.array}_${o}`;let i=t.state.env[r];if(i!==void 0)return Ie(i);if(o===0){let a=t.state.env[e.array];if(a!==void 0)return Ie(a)}if(t.state.options.nounset&&!Object.keys(t.state.env).some(c=>c===e.array||c.startsWith(`${e.array}_`)))throw new J(`${e.array}[${o}]`);return 0}else return 0;let n=t.state.env[r];return n!==void 0?Ie(n):0}case"ArithDoubleSubscript":throw new W("double subscript","","");case"ArithNumberSubscript":throw new W(`${e.number}${e.errorToken}: syntax error: invalid arithmetic operator (error token is "${e.errorToken}")`);case"ArithBinary":{if(e.operator==="||")return P(t,e.left)||P(t,e.right)?1:0;if(e.operator==="&&")return P(t,e.left)&&P(t,e.right)?1:0;let s=P(t,e.left),r=P(t,e.right);return jt(s,r,e.operator)}case"ArithUnary":{let s=P(t,e.operand);if(e.operator==="++"||e.operator==="--"){if(e.operand.type==="ArithVariable"){let r=e.operand.name,n=Number.parseInt(Q(t,r),10)||0,o=e.operator==="++"?n+1:n-1;return t.state.env[r]=String(o),e.prefix?o:n}if(e.operand.type==="ArithArrayElement"){let r=e.operand.array,n=t.state.associativeArrays?.has(r),o;if(e.operand.stringKey!==void 0)o=`${r}_${e.operand.stringKey}`;else if(n&&e.operand.index?.type==="ArithVariable")o=`${r}_${e.operand.index.name}`;else if(e.operand.index){let c=P(t,e.operand.index);o=`${r}_${c}`}else return s;let i=Number.parseInt(t.state.env[o]||"0",10)||0,a=e.operator==="++"?i+1:i-1;return t.state.env[o]=String(a),e.prefix?a:i}return s}return qt(s,e.operator)}case"ArithTernary":return P(t,e.condition)?P(t,e.consequent):P(t,e.alternate);case"ArithAssignment":{let s=e.variable,r=s;if(e.stringKey!==void 0)r=`${s}_${e.stringKey}`;else if(e.subscript){let a=t.state.associativeArrays?.has(s);if(a&&e.subscript.type==="ArithVariable")r=`${s}_${e.subscript.name}`;else if(a){let c=P(t,e.subscript);r=`${s}_${c}`}else{let c=P(t,e.subscript);if(c<0){let l=F(t,s);l.length>0&&(c=Math.max(...l.map(([h])=>typeof h=="number"?h:0))+1+c)}r=`${s}_${c}`}}let n=Number.parseInt(t.state.env[r]||"0",10)||0,o=P(t,e.value),i=gs(n,o,e.operator);return t.state.env[r]=String(i),i}case"ArithGroup":return P(t,e.expression);case"ArithConcat":{let s="";for(let r of e.parts)s+=As(t,r);return Number.parseInt(s,10)||0}default:return 0}}function As(t,e){switch(e.type){case"ArithNumber":return String(e.value);case"ArithVariable":return Q(t,e.name);case"ArithBracedExpansion":return de(t,e.content);case"ArithCommandSubst":return"0";case"ArithConcat":{let s="";for(let r of e.parts)s+=As(t,r);return s}default:return String(P(t,e))}}async function v(t,e){switch(e.type){case"ArithNumber":if(Number.isNaN(e.value))throw new W("value too great for base");return e.value;case"ArithVariable":return it(t,e.name);case"ArithNested":return v(t,e.expression);case"ArithCommandSubst":{if(t.execFn){let r=(await t.execFn(e.command)).stdout.trim();return Number.parseInt(r,10)||0}return 0}case"ArithBracedExpansion":{let s=de(t,e.content);return Number.parseInt(s,10)||0}case"ArithDynamicBase":{let s=de(t,e.baseExpr),r=Number.parseInt(s,10);if(r<2||r>64)return 0;let n=`${r}#${e.value}`;return Ne(n)}case"ArithDynamicNumber":{let r=de(t,e.prefix)+e.suffix;return Ne(r)}case"ArithArrayElement":{let s=t.state.associativeArrays?.has(e.array),r;if(e.stringKey!==void 0)r=`${e.array}_${e.stringKey}`;else if(s&&e.index?.type==="ArithVariable")r=`${e.array}_${e.index.name}`;else if(e.index){let o=await v(t,e.index);r=`${e.array}_${o}`;let i=t.state.env[r];if(i!==void 0)return Ie(i);if(o===0){let a=t.state.env[e.array];if(a!==void 0)return Ie(a)}if(t.state.options.nounset&&!Object.keys(t.state.env).some(c=>c===e.array||c.startsWith(`${e.array}_`)))throw new J(`${e.array}[${o}]`);return 0}else return 0;let n=t.state.env[r];return n!==void 0?Ie(n):0}case"ArithDoubleSubscript":throw new W("double subscript","","");case"ArithNumberSubscript":throw new W(`${e.number}${e.errorToken}: syntax error: invalid arithmetic operator (error token is "${e.errorToken}")`);case"ArithBinary":{if(e.operator==="||")return await v(t,e.left)||await v(t,e.right)?1:0;if(e.operator==="&&")return await v(t,e.left)&&await v(t,e.right)?1:0;let s=await v(t,e.left),r=await v(t,e.right);return jt(s,r,e.operator)}case"ArithUnary":{let s=await v(t,e.operand);if(e.operator==="++"||e.operator==="--"){if(e.operand.type==="ArithVariable"){let r=e.operand.name,n=Number.parseInt(Q(t,r),10)||0,o=e.operator==="++"?n+1:n-1;return t.state.env[r]=String(o),e.prefix?o:n}if(e.operand.type==="ArithArrayElement"){let r=e.operand.array,n=t.state.associativeArrays?.has(r),o;if(e.operand.stringKey!==void 0)o=`${r}_${e.operand.stringKey}`;else if(n&&e.operand.index?.type==="ArithVariable")o=`${r}_${e.operand.index.name}`;else if(e.operand.index){let c=await v(t,e.operand.index);o=`${r}_${c}`}else return s;let i=Number.parseInt(t.state.env[o]||"0",10)||0,a=e.operator==="++"?i+1:i-1;return t.state.env[o]=String(a),e.prefix?a:i}return s}return qt(s,e.operator)}case"ArithTernary":return await v(t,e.condition)?await v(t,e.consequent):await v(t,e.alternate);case"ArithAssignment":{let s=e.variable,r=s;if(e.stringKey!==void 0)r=`${s}_${e.stringKey}`;else if(e.subscript){let a=t.state.associativeArrays?.has(s);if(a&&e.subscript.type==="ArithVariable")r=`${s}_${e.subscript.name}`;else if(a){let c=await v(t,e.subscript);r=`${s}_${c}`}else{let c=await v(t,e.subscript);if(c<0){let l=F(t,s);l.length>0&&(c=Math.max(...l.map(([h])=>typeof h=="number"?h:0))+1+c)}r=`${s}_${c}`}}let n=Number.parseInt(t.state.env[r]||"0",10)||0,o=await v(t,e.value),i=gs(n,o,e.operator);return t.state.env[r]=String(i),i}case"ArithGroup":return await v(t,e.expression);case"ArithConcat":{let s="";for(let r of e.parts)s+=await Ss(t,r);return Number.parseInt(s,10)||0}default:return 0}}async function Ss(t,e){switch(e.type){case"ArithNumber":return String(e.value);case"ArithVariable":return Q(t,e.name);case"ArithBracedExpansion":return de(t,e.content);case"ArithCommandSubst":return t.execFn?(await t.execFn(e.command)).stdout.trim():"0";case"ArithConcat":{let s="";for(let r of e.parts)s+=await Ss(t,r);return s}default:return String(await v(t,e))}}var N=Object.freeze({stdout:"",stderr:"",exitCode:0});function j(t=""){return{stdout:t,stderr:"",exitCode:0}}function x(t,e=1){return{stdout:"",stderr:t,exitCode:e}}function S(t,e,s){return{stdout:t,stderr:e,exitCode:s}}function _(t){return{stdout:"",stderr:"",exitCode:t?0:1}}function ce(t,e,s="",r=""){throw new B(t,e,s,r)}function Zt(t,e){if(t.state.loopDepth===0){if(t.state.parentHasLoopContext)throw new fe;return N}let s=1;if(e.length>0){let r=Number.parseInt(e[0],10);if(Number.isNaN(r)||r<1)throw new R(128,"",`bash: break: ${e[0]}: numeric argument required
|
|
50
|
+
`);s=r}throw new U(s)}async function Qt(t,e){let s,r=!1,n=!1,o=0;for(;o<e.length;)if(e[o]==="--"){o++;break}else if(e[o]==="-L")n=!1,o++;else if(e[o]==="-P")n=!0,o++;else if(e[o].startsWith("-")&&e[o]!=="-")o++;else break;let i=e.slice(o);if(i.length===0||i[0]==="~"?s=t.state.env.HOME||"/":i[0]==="-"?(s=t.state.previousDir,r=!0):s=i[0],!s.startsWith("/")&&!s.startsWith("./")&&!s.startsWith("../")&&s!=="."&&s!==".."){let h=t.state.env.CDPATH;if(h){let d=h.split(":").filter(m=>m);for(let m of d){let y=m.startsWith("/")?`${m}/${s}`:`${t.state.cwd}/${m}/${s}`;try{if((await t.fs.stat(y)).isDirectory){s=y,r=!0;break}}catch{}}}}let c=(s.startsWith("/")?s:`${t.state.cwd}/${s}`).split("/").filter(h=>h&&h!=="."),l="";for(let h of c)if(h==="..")l=l.split("/").slice(0,-1).join("/")||"/";else{l=l?`${l}/${h}`:`/${h}`;try{if(!(await t.fs.stat(l)).isDirectory)return x(`bash: cd: ${s}: Not a directory
|
|
51
|
+
`)}catch{return x(`bash: cd: ${s}: No such file or directory
|
|
52
|
+
`)}}let f=l||"/";return t.state.previousDir=t.state.cwd,t.state.cwd=f,t.state.env.PWD=t.state.cwd,t.state.env.OLDPWD=t.state.previousDir,j(r?`${f}
|
|
53
|
+
`:"")}function Kt(t,e){if(t.state.loopDepth===0){if(t.state.parentHasLoopContext)throw new fe;return N}if(e.length>1)throw new U(1);let s=1;if(e.length>0){let r=Number.parseInt(e[0],10);if(Number.isNaN(r)||r<1)return x(`bash: continue: ${e[0]}: numeric argument required
|
|
54
|
+
`);s=r}throw new Y(s)}function be(t,e){t.state.readonlyVars=t.state.readonlyVars||new Set,t.state.readonlyVars.add(e)}function Vn(t,e){return t.state.readonlyVars?.has(e)??!1}function me(t,e,s="bash"){return Vn(t,e)?x(`${s}: ${e}: readonly variable
|
|
55
|
+
`):null}function xs(t){let e=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\((.*)\)$/s);if(e)return{name:e[1],isArray:!0,arrayElements:Xt(e[2])};if(t.includes("=")){let s=t.indexOf("=");return{name:t.slice(0,s),isArray:!1,value:t.slice(s+1)}}return{name:t,isArray:!1}}function bs(t,e,s={}){let{name:r,isArray:n,arrayElements:o,value:i}=e,{makeReadonly:a=!1,checkReadonly:c=!0}=s;if(c){let l=me(t,r);if(l)return l}if(n&&o){for(let l=0;l<o.length;l++)t.state.env[`${r}_${l}`]=o[l];t.state.env[`${r}__length`]=String(o.length)}else i!==void 0&&(t.state.env[r]=i);return a&&be(t,r),null}function Yt(t,e){let s=!1,r=!1,n=!1,o=!1,i=!1,a=[];for(let c=0;c<e.length;c++){let l=e[c];if(l==="-a")s=!0;else if(l==="-A")r=!0;else if(l==="-r")n=!0;else if(l==="-x")o=!0;else if(l==="-p")i=!0;else if(l==="--"){a.push(...e.slice(c+1));break}else if(l.startsWith("-"))for(let f of l.slice(1))f==="a"?s=!0:f==="A"?r=!0:f==="r"?n=!0:f==="x"?o=!0:f==="p"&&(i=!0);else a.push(l)}if(i&&a.length>0){let c="";for(let l of a){let f=t.state.env[l];if(f!==void 0){let h=f.replace(/\\/g,"\\\\").replace(/"/g,'\\"');c+=`declare -- ${l}="${h}"
|
|
56
|
+
`}}return j(c)}if(a.length===0&&!i){let c="",l=Object.entries(t.state.env).filter(([f])=>!f.startsWith("BASH_")).sort(([f],[h])=>f.localeCompare(h));for(let[f,h]of l){let d=h.replace(/'/g,"'\\''");c+=`declare -- ${f}='${d}'
|
|
57
|
+
`}return j(c)}for(let c of a){let l=c.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\((.*)\)$/s);if(l){let f=l[1],h=l[2];if(r&&(t.state.associativeArrays??=new Set,t.state.associativeArrays.add(f)),r&&h.includes("[")){let d=Hn(h);for(let[m,y]of d)t.state.env[`${f}_${m}`]=y}else{let d=Xt(h);for(let m=0;m<d.length;m++)t.state.env[`${f}_${m}`]=d[m];t.state.env[`${f}__length`]=String(d.length)}n&&be(t,f);continue}if(c.includes("=")){let f=c.indexOf("="),h=c.slice(0,f),d=c.slice(f+1),m=me(t,h);if(m)return m;t.state.env[h]=d,n&&be(t,h)}else{let f=c;r&&(t.state.associativeArrays??=new Set,t.state.associativeArrays.add(f));let h=Object.keys(t.state.env).some(d=>d.startsWith(`${f}_`)&&!d.startsWith(`${f}__length`));!(f in t.state.env)&&!h&&(s||r?t.state.env[`${f}__length`]="0":t.state.env[f]=""),n&&be(t,f)}}return N}function Xt(t){let e=[],s="",r=!1,n=!1,o=!1;for(let i of t){if(o){s+=i,o=!1;continue}if(i==="\\"){o=!0;continue}if(i==="'"&&!n){r=!r;continue}if(i==='"'&&!r){n=!n;continue}if((i===" "||i===" "||i===`
|
|
58
|
+
`)&&!r&&!n){s&&(e.push(s),s="");continue}s+=i}return s&&e.push(s),e}function Hn(t){let e=[],s=0;for(;s<t.length;){for(;s<t.length&&/\s/.test(t[s]);)s++;if(s>=t.length)break;if(t[s]!=="["){s++;continue}s++;let r="";if(t[s]==="'"||t[s]==='"'){let o=t[s];for(s++;s<t.length&&t[s]!==o;)r+=t[s],s++;t[s]===o&&s++}else for(;s<t.length&&t[s]!=="]"&&t[s]!=="=";)r+=t[s],s++;for(;s<t.length&&t[s]!=="]";)s++;if(t[s]==="]"&&s++,t[s]!=="=")continue;s++;let n="";if(t[s]==="'"||t[s]==='"'){let o=t[s];for(s++;s<t.length&&t[s]!==o;)t[s]==="\\"&&s+1<t.length&&s++,n+=t[s],s++;t[s]===o&&s++}else for(;s<t.length&&!/\s/.test(t[s]);)n+=t[s],s++;e.push([r,n])}return e}function Jt(t,e){let s=!1,r=!1,n=[];for(let o=0;o<e.length;o++){let i=e[o];if(i==="-a")s=!0;else if(i==="-A")r=!0;else if(i==="-p"){if(e.length===1){let a="";for(let c of t.state.readonlyVars||[]){let l=t.state.env[c];l!==void 0&&(a+=`declare -r ${c}="${l}"
|
|
59
|
+
`)}return j(a)}}else if(i==="--"){n.push(...e.slice(o+1));break}else i.startsWith("-")||n.push(i)}for(let o of n){let i=xs(o);if(i.value===void 0&&!i.isArray){be(t,i.name);continue}let a=bs(t,i,{makeReadonly:!0});if(a)return a}return N}async function er(t,e){let s=e;if(s.length>0){let n=s[0];if(n==="--")s=s.slice(1);else if(n.startsWith("-")&&n!=="-"&&n.length>1)return x(`bash: eval: ${n}: invalid option
|
|
60
60
|
eval: usage: eval [arg ...]
|
|
61
|
-
`,2)}if(
|
|
62
|
-
`);throw
|
|
63
|
-
`,
|
|
64
|
-
`}return j(
|
|
65
|
-
`,
|
|
66
|
-
`);let
|
|
67
|
-
`)}return S("","",r===0?1:0)}function
|
|
68
|
-
`);let
|
|
69
|
-
`,
|
|
70
|
-
`,
|
|
71
|
-
`,l+=2):E==="-n"&&l+1<e.length?(
|
|
72
|
-
`,
|
|
61
|
+
`,2)}if(s.length===0)return N;let r=s.join(" ");if(r.trim()==="")return N;try{let n=he(r);return t.executeScript(n)}catch(n){if(n instanceof U||n instanceof Y||n instanceof G||n instanceof R)throw n;if(n.name==="ParseException")return x(`bash: eval: ${n.message}
|
|
62
|
+
`);throw n}}function tr(t,e){let s,r="";if(e.length===0)s=t.state.lastExitCode;else{let n=e[0],o=Number.parseInt(n,10);n===""||Number.isNaN(o)||!/^-?\d+$/.test(n)?(r=`bash: exit: ${n}: numeric argument required
|
|
63
|
+
`,s=2):s=(o%256+256)%256}throw new R(s,"",r)}function rr(t,e){let s=!1,r=[];for(let i of e)i==="-n"?s=!0:i==="-p"||i==="--"||r.push(i);if(r.length===0&&!s){let i="",a=Object.entries(t.state.env).filter(([c])=>!c.startsWith("BASH_ALIAS_")).sort(([c],[l])=>c.localeCompare(l));for(let[c,l]of a){let f=l.replace(/'/g,"'\\''");i+=`declare -x ${c}='${f}'
|
|
64
|
+
`}return j(i)}if(s){for(let i of r){let a=i.split("=")[0];delete t.state.env[a]}return N}let n="",o=0;for(let i of r){let a,c;if(i.includes("=")){let l=i.indexOf("=");a=i.slice(0,l),c=i.slice(l+1)}else a=i;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(a)){n+=`bash: export: \`${i}': not a valid identifier
|
|
65
|
+
`,o=1;continue}c!==void 0?t.state.env[a]=c:a in t.state.env||(t.state.env[a]="")}return S("",n,o)}function jn(t){let e=[],s="",r=0;for(let n of t){for(let o of n)o==="("?r++:o===")"&&r--;s?s+=` ${n}`:s=n,r===0&&(e.push(s),s="")}return s&&e.push(s),e}async function sr(t,e){if(e.length===0)return x(`bash: let: expression expected
|
|
66
|
+
`);let s=jn(e),r=0;for(let n of s)try{let i=he(`(( ${n} ))`).statements[0];if(i&&i.pipelines.length>0&&i.pipelines[0].commands.length>0){let a=i.pipelines[0].commands[0];a.type==="ArithmeticCommand"&&(r=await v(t,a.expression.expression))}}catch(o){return x(`bash: let: ${n}: ${o.message}
|
|
67
|
+
`)}return S("","",r===0?1:0)}function qn(t,e){let s=t.state.env.HOME||"/home/user";return e.split(":").map(o=>o==="~"?s:o==="~root"?"/root":o.startsWith("~/")?s+o.slice(1):o.startsWith("~root/")?`/root${o.slice(5)}`:o).join(":")}function nr(t,e){if(t.state.localScopes.length===0)return x(`bash: local: can only be used in a function
|
|
68
|
+
`);let s=t.state.localScopes[t.state.localScopes.length-1],r="",n=0;for(let o of e){let i,a;if(o.includes("=")){let c=o.indexOf("=");i=o.slice(0,c),a=qn(t,o.slice(c+1))}else i=o;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(i)){r+=`bash: local: \`${o}': not a valid identifier
|
|
69
|
+
`,n=1;continue}s.has(i)||s.set(i,t.state.env[i]),a!==void 0&&(t.state.env[i]=a)}return S("",r,n)}function ir(t,e,s){let r=`
|
|
70
|
+
`,n=0,o=0,i=0,a=!1,c="MAPFILE",l=0;for(;l<e.length;){let E=e[l];E==="-d"&&l+1<e.length?(r=e[l+1]||`
|
|
71
|
+
`,l+=2):E==="-n"&&l+1<e.length?(n=Number.parseInt(e[l+1],10)||0,l+=2):E==="-O"&&l+1<e.length?(o=Number.parseInt(e[l+1],10)||0,l+=2):E==="-s"&&l+1<e.length?(i=Number.parseInt(e[l+1],10)||0,l+=2):E==="-t"?(a=!0,l++):E==="-u"||E==="-C"||E==="-c"?l+=2:(E.startsWith("-")||(c=E),l++)}let f=s;!f&&t.state.groupStdin!==void 0&&(f=t.state.groupStdin);let h=[],d=f,m=0,y=0;for(;d.length>0;){let E=d.indexOf(r);if(E===-1){d.length>0&&(y<i?y++:(n===0||m<n)&&(h.push(d),m++));break}let p=d.substring(0,E);if(a||(p+=r),d=d.substring(E+r.length),y<i){y++;continue}if(n>0&&m>=n)break;h.push(p),m++}Be(t,c);for(let E=0;E<h.length;E++)t.state.env[`${c}_${o+E}`]=h[E];return h.length>0&&(t.state.env[`${c}__length`]=String(o+h.length)),t.state.groupStdin!==void 0&&!s&&(t.state.groupStdin=""),S("","",0)}function or(t,e,s){let r=!1,n=`
|
|
72
|
+
`,o="",i=-1,a=null,c=[],l=0,f=!1;for(;l<e.length;){let g=e[l];g==="-r"?r=!0:g==="-d"&&l+1<e.length?(n=e[l+1],l++):g==="-p"&&l+1<e.length?(o=e[l+1],l++):g==="-n"&&l+1<e.length?(i=Number.parseInt(e[l+1],10),(Number.isNaN(i)||i<0)&&(f=!0,i=0),l++):g==="-a"&&l+1<e.length?(a=e[l+1],l++):g==="-t"?l+1<e.length&&!e[l+1].startsWith("-")&&l++:g==="-s"||g.startsWith("-")||c.push(g),l++}if(f)return S("","",1);c.length===0&&a===null&&c.push("REPLY");let h=s;!h&&t.state.groupStdin!==void 0&&(h=t.state.groupStdin);let d="",m=0,y=!0;if(i>=0){for(let g=0;g<h.length&&g<i;g++){let b=h[g];if(b===n){m=g+1;break}d+=b,m=g+1}t.state.groupStdin!==void 0&&!s&&(t.state.groupStdin=h.substring(m))}else{let g=h;for(m=0;;){let b=g.indexOf(n);if(b!==-1){let C=g.substring(0,b);if(m+=b+n.length,g=g.substring(b+n.length),!r&&C.endsWith("\\")){d+=C.slice(0,-1);continue}d+=C,y=!0;break}else if(g.length>0){d+=g,m+=g.length,y=!1,g="";break}else{if(d.length===0){for(let C of c)t.state.env[C]="";return a&&Be(t,a),S("","",1)}y=!1;break}}t.state.groupStdin!==void 0&&!s&&(t.state.groupStdin=h.substring(m))}if(n===`
|
|
73
73
|
`&&d.endsWith(`
|
|
74
|
-
`)&&(d=d.slice(0,-1)),r||(d=d.replace(/\\(.)/g,"$1")),c.length===1&&c[0]==="REPLY")return t.state.env.REPLY=d,S("","",y?0:1);let E=rt(t.state.env),{words:p,wordStarts:w}=
|
|
75
|
-
`,2);
|
|
74
|
+
`)&&(d=d.slice(0,-1)),r||(d=d.replace(/\\(.)/g,"$1")),c.length===1&&c[0]==="REPLY")return t.state.env.REPLY=d,S("","",y?0:1);let E=rt(t.state.env),{words:p,wordStarts:w}=is(d,E);if(a){Be(t,a);for(let g=0;g<p.length;g++)t.state.env[`${a}_${g}`]=p[g];return S("","",y?0:1)}for(let g=0;g<c.length;g++){let b=c[g];if(g<c.length-1)t.state.env[b]=p[g]??"";else if(g<w.length){let C=os(d.substring(w[g]),E);t.state.env[b]=C}else t.state.env[b]=""}return S("","",y?0:1)}function ar(t,e){if(t.state.callDepth===0&&t.state.sourceDepth===0)return x("bash: return: can only `return' from a function or sourced script\n");let s=t.state.lastExitCode;if(e.length>0){let r=e[0],n=Number.parseInt(r,10);if(r===""||Number.isNaN(n)||!/^-?\d+$/.test(r))return x(`bash: return: ${r}: numeric argument required
|
|
75
|
+
`,2);s=(n%256+256)%256}throw new G(s)}function Zn(t){return/^[a-zA-Z0-9_/.:-]*$/.test(t)?t:`'${t.replace(/'/g,"'\\''")}'`}var ot=`set: usage: set [-eux] [+eux] [-o option] [+o option]
|
|
76
76
|
Options:
|
|
77
77
|
-e Exit immediately if a command exits with non-zero status
|
|
78
78
|
+e Disable -e
|
|
@@ -88,65 +88,65 @@ Options:
|
|
|
88
88
|
+o pipefail Disable pipefail
|
|
89
89
|
-o xtrace Same as -x
|
|
90
90
|
+o xtrace Disable xtrace
|
|
91
|
-
`,
|
|
91
|
+
`,Cs={e:"errexit",u:"nounset",x:"xtrace",v:"verbose",f:null,h:null,C:null,n:null,a:null,b:null,m:null,B:null,H:null,P:null,T:null,E:null,p:null},Ns={errexit:"errexit",pipefail:"pipefail",nounset:"nounset",xtrace:"xtrace",verbose:"verbose",noclobber:null,noglob:null,noexec:null,allexport:null,notify:null,monitor:null,braceexpand:null,histexpand:null,physical:null,functrace:null,errtrace:null,privileged:null,hashall:null,posix:null,vi:null,emacs:null,ignoreeof:null,"interactive-comments":null,keyword:null,onecmd:null},Ps=["errexit","nounset","pipefail","verbose","xtrace"],vs=["allexport","braceexpand","emacs","errtrace","functrace","hashall","histexpand","history","ignoreeof","interactive-comments","keyword","monitor","noclobber","noexec","noglob","nolog","notify","onecmd","physical","posix","privileged","vi"];function $s(t,e,s){e!==null&&(t.state.options[e]=s)}function Qn(t,e){return e+1<t.length&&!t[e+1].startsWith("-")&&!t[e+1].startsWith("+")}function lr(t,e){if(e.includes("--help"))return j(ot);if(e.length===0){let r=Object.entries(t.state.env).filter(([n])=>/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(n)).sort(([n],[o])=>n.localeCompare(o)).map(([n,o])=>`${n}=${Zn(o)}`).join(`
|
|
92
92
|
`);return j(r?`${r}
|
|
93
|
-
`:"")}let
|
|
94
|
-
${ot}`)
|
|
93
|
+
`:"")}let s=0;for(;s<e.length;){let r=e[s];if((r==="-o"||r==="+o")&&Qn(e,s)){let n=e[s+1];if(!(n in Ns))return x(`bash: set: ${n}: invalid option name
|
|
94
|
+
${ot}`);$s(t,Ns[n],r==="-o"),s+=2;continue}if(r==="-o"){let n=Ps.map(a=>`${a.padEnd(16)}${t.state.options[a]?"on":"off"}`),o=vs.map(a=>`${a.padEnd(16)}off`),i=[...n,...o].sort();return j(`${i.join(`
|
|
95
95
|
`)}
|
|
96
|
-
`)}if(r==="+o"){let
|
|
96
|
+
`)}if(r==="+o"){let n=Ps.map(a=>`set ${t.state.options[a]?"-o":"+o"} ${a}`),o=vs.map(a=>`set +o ${a}`),i=[...n,...o].sort();return j(`${i.join(`
|
|
97
97
|
`)}
|
|
98
|
-
`)}if(r.length>1&&(r[0]==="-"||r[0]==="+")&&r[1]!=="-"){let
|
|
99
|
-
${ot}`)
|
|
100
|
-
${ot}`):(cr(t,e.slice(
|
|
101
|
-
`);
|
|
102
|
-
`);if(
|
|
103
|
-
`,2);let r=
|
|
104
|
-
`);let
|
|
105
|
-
`);throw c}}function hr(t,e){let
|
|
106
|
-
`,
|
|
107
|
-
`,
|
|
108
|
-
`,2):at(r)?_(await ct(t,r,
|
|
109
|
-
`,2):S("","",1)}if(e.length===3){let r=e[0],
|
|
110
|
-
`,2):_(
|
|
111
|
-
`,exitCode:1}}async function At(t,e,
|
|
112
|
-
`,exitCode:1}}return{stdout:
|
|
113
|
-
`);let
|
|
98
|
+
`)}if(r.length>1&&(r[0]==="-"||r[0]==="+")&&r[1]!=="-"){let n=r[0]==="-";for(let o=1;o<r.length;o++){let i=r[o];if(!(i in Cs))return x(`bash: set: ${r[0]}${i}: invalid option
|
|
99
|
+
${ot}`);$s(t,Cs[i],n)}s++;continue}if(r==="--")return cr(t,e.slice(s+1)),N;if(r==="-"){if(t.state.options.xtrace=!1,t.state.options.verbose=!1,s+1<e.length)return cr(t,e.slice(s+1)),N;s++;continue}if(r==="+"){s++;continue}return r.startsWith("-")||r.startsWith("+")?x(`bash: set: ${r}: invalid option
|
|
100
|
+
${ot}`):(cr(t,e.slice(s)),N)}return N}function cr(t,e){let s=1;for(;t.state.env[String(s)]!==void 0;)delete t.state.env[String(s)],s++;for(let r=0;r<e.length;r++)t.state.env[String(r+1)]=e[r];t.state.env["#"]=String(e.length),t.state.env["@"]=e.join(" "),t.state.env["*"]=e.join(" ")}function fr(t,e){let s=1;if(e.length>0){let i=Number.parseInt(e[0],10);if(Number.isNaN(i)||i<0)return x(`bash: shift: ${e[0]}: numeric argument required
|
|
101
|
+
`);s=i}let r=Number.parseInt(t.state.env["#"]||"0",10);if(s>r)return x(`bash: shift: shift count out of range
|
|
102
|
+
`);if(s===0)return N;let n=[];for(let i=1;i<=r;i++)n.push(t.state.env[String(i)]||"");let o=n.slice(s);for(let i=1;i<=r;i++)delete t.state.env[String(i)];for(let i=0;i<o.length;i++)t.state.env[String(i+1)]=o[i];return t.state.env["#"]=String(o.length),t.state.env["@"]=o.join(" "),N}async function ur(t,e){let s=e;if(s.length>0&&s[0]==="--"&&(s=s.slice(1)),s.length===0)return S("",`bash: source: filename argument required
|
|
103
|
+
`,2);let r=s[0],n=null,o=null;if(r.includes("/")){let c=t.fs.resolvePath(t.state.cwd,r);try{o=await t.fs.readFile(c),n=c}catch{}}else{let l=(t.state.env.PATH||"").split(":").filter(f=>f);for(let f of l){let h=t.fs.resolvePath(t.state.cwd,`${f}/${r}`);try{if((await t.fs.stat(h)).isDirectory)continue;o=await t.fs.readFile(h),n=h;break}catch{}}if(o===null){let f=t.fs.resolvePath(t.state.cwd,r);try{o=await t.fs.readFile(f),n=f}catch{}}}if(o===null)return x(`bash: ${r}: No such file or directory
|
|
104
|
+
`);let i={};if(s.length>1){for(let l=1;l<=9;l++)i[String(l)]=t.state.env[String(l)];i["#"]=t.state.env["#"],i["@"]=t.state.env["@"];let c=s.slice(1);t.state.env["#"]=String(c.length),t.state.env["@"]=c.join(" ");for(let l=0;l<c.length&&l<9;l++)t.state.env[String(l+1)]=c[l];for(let l=c.length+1;l<=9;l++)delete t.state.env[String(l)]}let a=()=>{if(t.state.sourceDepth--,s.length>1)for(let[c,l]of Object.entries(i))l===void 0?delete t.state.env[c]:t.state.env[c]=l};t.state.sourceDepth++;try{let c=he(o),l=await t.executeScript(c);return a(),l}catch(c){if(a(),c instanceof R)throw c;if(c instanceof G)return S(c.stdout,c.stderr,c.exitCode);if(c.name==="ParseException")return x(`bash: ${r}: ${c.message}
|
|
105
|
+
`);throw c}}function hr(t,e){let s="variable",r="",n=0;for(let o of e){if(o==="-v"){s="variable";continue}if(o==="-f"){s="function";continue}if(s==="function"){t.state.functions.delete(o);continue}let i=o.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(i){let a=i[1],c=i[2];if(c==="@"||c==="*"){let f=F(t,a);for(let[h]of f)delete t.state.env[`${a}_${h}`];delete t.state.env[a];continue}let l;if(/^-?\d+$/.test(c))l=Number.parseInt(c,10);else{let f=t.state.env[c];l=f?Number.parseInt(f,10):0,Number.isNaN(l)&&(l=0)}if(l<0){let f=F(t,a),h=f.length;if(h===0){r+=`bash: unset: [${l}]: bad array subscript
|
|
106
|
+
`,n=1;continue}let d=h+l;if(d<0){r+=`bash: unset: [${l}]: bad array subscript
|
|
107
|
+
`,n=1;continue}let m=f[d][0];delete t.state.env[`${a}_${m}`];continue}delete t.state.env[`${a}_${l}`];continue}delete t.state.env[o],t.state.functions.delete(o)}return S("",r,n)}function dr(t,e){return t.fs.resolvePath(t.state.cwd,e)}var Kn=["-e","-a","-f","-d","-r","-w","-x","-s","-L","-h","-k","-g","-u","-G","-O","-b","-c","-p","-S","-t","-N"];function at(t){return Kn.includes(t)}async function ct(t,e,s){let r=dr(t,s);switch(e){case"-e":case"-a":return t.fs.exists(r);case"-f":return await t.fs.exists(r)?(await t.fs.stat(r)).isFile:!1;case"-d":return await t.fs.exists(r)?(await t.fs.stat(r)).isDirectory:!1;case"-r":case"-w":case"-x":return t.fs.exists(r);case"-s":return await t.fs.exists(r)?(await t.fs.stat(r)).size>0:!1;case"-L":case"-h":try{return(await t.fs.lstat(r)).isSymbolicLink}catch{return!1}case"-k":return await t.fs.exists(r)?((await t.fs.stat(r)).mode&512)!==0:!1;case"-g":return await t.fs.exists(r)?((await t.fs.stat(r)).mode&1024)!==0:!1;case"-u":return await t.fs.exists(r)?((await t.fs.stat(r)).mode&2048)!==0:!1;case"-G":case"-O":return t.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(o=>r===o||r.endsWith(o));case"-p":return!1;case"-S":return!1;case"-t":return!1;case"-N":return t.fs.exists(r);default:return!1}}var Xn=["-nt","-ot","-ef"];function lt(t){return Xn.includes(t)}async function ft(t,e,s,r){let n=dr(t,s),o=dr(t,r);switch(e){case"-nt":try{let i=await t.fs.stat(n),a=await t.fs.stat(o);return i.mtime>a.mtime}catch{return!1}case"-ot":try{let i=await t.fs.stat(n),a=await t.fs.stat(o);return i.mtime<a.mtime}catch{return!1}case"-ef":try{if(!await t.fs.exists(n)||!await t.fs.exists(o))return!1;let i=t.fs.resolvePath(t.state.cwd,n),a=t.fs.resolvePath(t.state.cwd,o);return i===a}catch{return!1}default:return!1}}var Yn=new Set(["-eq","-ne","-lt","-le","-gt","-ge"]);function ut(t){return Yn.has(t)}function ht(t,e,s){switch(t){case"-eq":return e===s;case"-ne":return e!==s;case"-lt":return e<s;case"-le":return e<=s;case"-gt":return e>s;case"-ge":return e>=s}}function dt(t){return t==="="||t==="=="||t==="!="}function mt(t,e,s,r=!1){let n=r?pt(e,s):e===s;return t==="!="?!n:n}var Jn=new Set(["-z","-n"]);function yt(t){return Jn.has(t)}function wt(t,e){switch(t){case"-z":return e==="";case"-n":return e!==""}}function Et(t,e){let s=e.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(s){let r=s[1],n=s[2];n=n.replace(/\$([a-zA-Z_][a-zA-Z0-9_]*)/g,(i,a)=>t.state.env[a]||"");let o;if(/^-?\d+$/.test(n))o=Number.parseInt(n,10);else try{let i=Function(`"use strict"; return (${n})`)();o=typeof i=="number"?Math.floor(i):0}catch{let i=t.state.env[n];o=i?Number.parseInt(i,10):0}if(o<0){let i=ze(t,r);if(i.length===0||(o=Math.max(...i)+1+o,o<0))return!1}return`${r}_${o}`in t.state.env}return e in t.state.env}async function pe(t,e){switch(e.type){case"CondBinary":{let s=await k(t,e.left),r=await k(t,e.right),n=e.right.parts.length>0&&e.right.parts.every(o=>o.type==="SingleQuoted"||o.type==="DoubleQuoted"||o.type==="Escaped");if(dt(e.operator))return mt(e.operator,s,r,!n);if(ut(e.operator))return ht(e.operator,Is(t,s),Is(t,r));if(lt(e.operator))return ft(t,e.operator,s,r);switch(e.operator){case"=~":try{let o=new RegExp(r),i=s.match(o);if(i){t.state.env.BASH_REMATCH=i[0];for(let a=1;a<i.length;a++)t.state.env[`BASH_REMATCH_${a}`]=i[a]||""}return i!==null}catch{throw new Error("syntax error in regular expression")}case"<":return s<r;case">":return s>r;default:return!1}}case"CondUnary":{let s=await k(t,e.operand);return at(e.operator)?ct(t,e.operator,s):yt(e.operator)?wt(e.operator,s):e.operator==="-v"?Et(t,s):e.operator==="-o"?pr(t,s):!1}case"CondNot":return!await pe(t,e.operand);case"CondAnd":return await pe(t,e.left)?await pe(t,e.right):!1;case"CondOr":return await pe(t,e.left)?!0:await pe(t,e.right);case"CondGroup":return await pe(t,e.expression);case"CondWord":return await k(t,e.word)!=="";default:return!1}}async function Re(t,e){if(e.length===0)return S("","",1);if(e.length===1)return _(!!e[0]);if(e.length===2){let r=e[0],n=e[1];return r==="("?x(`test: '(' without matching ')'
|
|
108
|
+
`,2):at(r)?_(await ct(t,r,n)):yt(r)?_(wt(r,n)):r==="!"?_(!n):r==="-v"?_(Et(t,n)):r==="-o"?_(pr(t,n)):r==="="||r==="=="||r==="!="||r==="<"||r===">"||r==="-eq"||r==="-ne"||r==="-lt"||r==="-le"||r==="-gt"||r==="-ge"||r==="-nt"||r==="-ot"||r==="-ef"?x(`test: ${r}: unary operator expected
|
|
109
|
+
`,2):S("","",1)}if(e.length===3){let r=e[0],n=e[1],o=e[2];if(dt(n))return _(mt(n,r,o));if(ut(n)){let i=gt(r),a=gt(o);return!i.valid||!a.valid?S("","",2):_(ht(n,i.value,a.value))}if(lt(n))return _(await ft(t,n,r,o));switch(n){case"-a":return _(r!==""&&o!=="");case"-o":return _(r!==""||o!=="");case">":return _(r>o);case"<":return _(r<o)}if(r==="!"){let i=await Re(t,[n,o]);return S("",i.stderr,i.exitCode===0?1:i.exitCode===1?0:i.exitCode)}if(r==="("&&o===")")return _(n!=="")}if(e.length===4){if(e[0]==="!"){let r=await Re(t,e.slice(1));return S("",r.stderr,r.exitCode===0?1:r.exitCode===1?0:r.exitCode)}if(e[0]==="("&&e[3]===")")return Re(t,[e[1],e[2]])}let s=await Ds(t,e,0);return s.pos<e.length?x(`test: too many arguments
|
|
110
|
+
`,2):_(s.value)}async function Ds(t,e,s){return ei(t,e,s)}async function ei(t,e,s){let{value:r,pos:n}=await ks(t,e,s);for(;e[n]==="-o";){let o=await ks(t,e,n+1);r=r||o.value,n=o.pos}return{value:r,pos:n}}async function ks(t,e,s){let{value:r,pos:n}=await mr(t,e,s);for(;e[n]==="-a";){let o=await mr(t,e,n+1);r=r&&o.value,n=o.pos}return{value:r,pos:n}}async function mr(t,e,s){if(e[s]==="!"){let{value:r,pos:n}=await mr(t,e,s+1);return{value:!r,pos:n}}return ti(t,e,s)}async function ti(t,e,s){let r=e[s];if(r==="("){let{value:o,pos:i}=await Ds(t,e,s+1);return{value:o,pos:e[i]===")"?i+1:i}}if(at(r)){let o=e[s+1]??"";return{value:await ct(t,r,o),pos:s+2}}if(yt(r)){let o=e[s+1]??"";return{value:wt(r,o),pos:s+2}}if(r==="-v"){let o=e[s+1]??"";return{value:Et(t,o),pos:s+2}}if(r==="-o"){let o=e[s+1]??"";return{value:pr(t,o),pos:s+2}}let n=e[s+1];if(dt(n)){let o=r,i=e[s+2]??"";return{value:mt(n,o,i),pos:s+3}}if(ut(n)){let o=gt(r),i=gt(e[s+2]??"0");return!o.valid||!i.valid?{value:!1,pos:s+3}:{value:ht(n,o.value,i.value),pos:s+3}}if(lt(n)){let o=r,i=e[s+2]??"";return{value:await ft(t,n,o,i),pos:s+3}}return{value:r!==void 0&&r!=="",pos:s+1}}function pt(t,e){let s="^";for(let r=0;r<e.length;r++){let n=e[r];if(n==="\\")if(r+1<e.length){let o=e[r+1];/[\\^$.|+(){}[\]*?]/.test(o)?s+=`\\${o}`:s+=o,r++}else s+="\\\\";else if(n==="*")s+=".*";else if(n==="?")s+=".";else if(n==="["){let o=e.indexOf("]",r+1);o!==-1?(s+=e.slice(r,o+1),r=o):s+="\\["}else/[\\^$.|+(){}]/.test(n)?s+=`\\${n}`:s+=n}return s+="$",new RegExp(s).test(t)}function pr(t,e){let r={errexit:()=>t.state.options.errexit===!0,nounset:()=>t.state.options.nounset===!0,pipefail:()=>t.state.options.pipefail===!0,xtrace:()=>t.state.options.xtrace===!0,e:()=>t.state.options.errexit===!0,u:()=>t.state.options.nounset===!0,x:()=>t.state.options.xtrace===!0}[e];return r?r():!1}function Is(t,e){if(e=e.trim(),e==="")return 0;if(/^[+-]?(\d+#[a-zA-Z0-9@_]+|0[xX][0-9a-fA-F]+|0[0-7]+|\d+)$/.test(e))return Rs(e);try{let s=new z,r=T(s,e);return P(t,r.expression)}catch{return Rs(e)}}function ri(t,e){let s=0;for(let r of t){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>=e)return Number.NaN;s=s*e+n}return s}function Rs(t){if(t=t.trim(),t==="")return 0;let e=!1;t.startsWith("-")?(e=!0,t=t.slice(1)):t.startsWith("+")&&(t=t.slice(1));let s,r=t.match(/^(\d+)#([a-zA-Z0-9@_]+)$/);if(r){let n=Number.parseInt(r[1],10);n>=2&&n<=64?s=ri(r[2],n):s=0}else/^0[xX][0-9a-fA-F]+$/.test(t)?s=Number.parseInt(t,16):/^0[0-7]+$/.test(t)?s=Number.parseInt(t,8):s=Number.parseInt(t,10);return Number.isNaN(s)&&(s=0),e?-s:s}function gt(t){if(t=t.trim(),t==="")return{value:0,valid:!0};let e=!1;if(t.startsWith("-")?(e=!0,t=t.slice(1)):t.startsWith("+")&&(t=t.slice(1)),!/^\d+$/.test(t))return{value:0,valid:!1};let s=Number.parseInt(t,10);return Number.isNaN(s)?{value:0,valid:!1}:{value:e?-s:s,valid:!0}}async function yr(t,e){let s=t.state.inCondition;t.state.inCondition=!0;let r="",n="",o=0;try{for(let i of e){let a=await t.executeStatement(i);r+=a.stdout,n+=a.stderr,o=a.exitCode}}finally{t.state.inCondition=s}return{stdout:r,stderr:n,exitCode:o}}function Ve(t,e,s,r){if(t instanceof U)return e+=t.stdout,s+=t.stderr,t.levels>1&&r>1?(t.levels--,t.stdout=e,t.stderr=s,{action:"rethrow",stdout:e,stderr:s,error:t}):{action:"break",stdout:e,stderr:s};if(t instanceof Y)return e+=t.stdout,s+=t.stderr,t.levels>1&&r>1?(t.levels--,t.stdout=e,t.stderr=s,{action:"rethrow",stdout:e,stderr:s,error:t}):{action:"continue",stdout:e,stderr:s};if(t instanceof G||t instanceof te||t instanceof R||t instanceof B)return t.prependOutput(e,s),{action:"rethrow",stdout:e,stderr:s,error:t};let n=le(t);return{action:"error",stdout:e,stderr:`${s}${n}
|
|
111
|
+
`,exitCode:1}}async function At(t,e,s="",r=""){let n=s,o=r,i=0;try{for(let a of e){let c=await t.executeStatement(a);n+=c.stdout,o+=c.stderr,i=c.exitCode}}catch(a){if(qe(a)||a instanceof te||a instanceof R||a instanceof B||a instanceof fe)throw a.prependOutput(n,o),a;return{stdout:n,stderr:`${o}${le(a)}
|
|
112
|
+
`,exitCode:1}}return{stdout:n,stderr:o,exitCode:i}}async function Os(t,e){let s="",r="";for(let n of e.clauses){let o=await yr(t,n.condition);if(s+=o.stdout,r+=o.stderr,o.exitCode===0)return At(t,n.body,s,r)}return e.elseBody?At(t,e.elseBody,s,r):S(s,r,0)}async function _s(t,e){let s="",r="",n=0,o=0;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e.variable))return x(`bash: \`${e.variable}': not a valid identifier
|
|
113
|
+
`);let i=[];if(e.words===null)i=(t.state.env["@"]||"").split(" ").filter(Boolean);else if(e.words.length===0)i=[];else for(let a of e.words){let c=await Ge(t,a);i.push(...c.values)}t.state.loopDepth++;try{for(let a of i){o++,o>t.limits.maxLoopIterations&&ce(`for loop: too many iterations (${t.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",s,r),t.state.env[e.variable]=a;try{for(let c of e.body){let l=await t.executeStatement(c);s+=l.stdout,r+=l.stderr,n=l.exitCode}}catch(c){let l=Ve(c,s,r,t.state.loopDepth);if(s=l.stdout,r=l.stderr,l.action==="break")break;if(l.action==="continue")continue;if(l.action==="error")return S(s,r,l.exitCode??1);throw l.error}}}finally{t.state.loopDepth--}return S(s,r,n)}async function Ls(t,e){let s="",r="",n=0,o=0;e.init&&await v(t,e.init.expression),t.state.loopDepth++;try{for(;o++,o>t.limits.maxLoopIterations&&ce(`for loop: too many iterations (${t.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",s,r),!(e.condition&&await v(t,e.condition.expression)===0);){try{for(let i of e.body){let a=await t.executeStatement(i);s+=a.stdout,r+=a.stderr,n=a.exitCode}}catch(i){let a=Ve(i,s,r,t.state.loopDepth);if(s=a.stdout,r=a.stderr,a.action==="break")break;if(a.action==="continue"){e.update&&await v(t,e.update.expression);continue}if(a.action==="error")return S(s,r,a.exitCode??1);throw a.error}e.update&&await v(t,e.update.expression)}}finally{t.state.loopDepth--}return S(s,r,n)}async function Ts(t,e,s=""){let r="",n="",o=0,i=0,a=s;for(let l of e.redirections)if((l.operator==="<<"||l.operator==="<<-")&&l.target.type==="HereDoc"){let f=l.target,h=await k(t,f.content);f.stripTabs&&(h=h.split(`
|
|
114
114
|
`).map(d=>d.replace(/^\t+/,"")).join(`
|
|
115
115
|
`)),a=h}else if(l.operator==="<<<"&&l.target.type==="Word")a=`${await k(t,l.target)}
|
|
116
|
-
`;else if(l.operator==="<"&&l.target.type==="Word")try{let
|
|
117
|
-
`)}let c=t.state.groupStdin;a&&(t.state.groupStdin=a),t.state.loopDepth++;try{for(;;){
|
|
118
|
-
`,
|
|
119
|
-
`,
|
|
120
|
-
`,
|
|
121
|
-
`,
|
|
122
|
-
`,
|
|
123
|
-
`,
|
|
124
|
-
`,1);let E=me(this.ctx,l);if(E)return E;let p=[];for(let g of c.array){let b=await Ge(this.ctx,g);p.push(...b.values)}let w=0;if(c.append){let g=F(this.ctx,l);g.length>0&&(w=Math.max(...g.map(([C])=>typeof C=="number"?C:0))+1)}else{let g=`${l}_`;for(let b of Object.keys(this.ctx.state.env))b.startsWith(g)&&!b.includes("__")&&delete this.ctx.state.env[b]}for(let g=0;g<p.length;g++)this.ctx.state.env[`${l}_${w+g}`]=p[g];c.append||(this.ctx.state.env[`${l}__length`]=String(p.length));continue}let
|
|
116
|
+
`;else if(l.operator==="<"&&l.target.type==="Word")try{let f=await k(t,l.target),h=t.fs.resolvePath(t.state.cwd,f);a=await t.fs.readFile(h)}catch{let f=await k(t,l.target);return x(`bash: ${f}: No such file or directory
|
|
117
|
+
`)}let c=t.state.groupStdin;a&&(t.state.groupStdin=a),t.state.loopDepth++;try{for(;;){i++,i>t.limits.maxLoopIterations&&ce(`while loop: too many iterations (${t.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",r,n);let l=0,f=!1,h=!1,d=t.state.inCondition;t.state.inCondition=!0;try{for(let m of e.condition){let y=await t.executeStatement(m);r+=y.stdout,n+=y.stderr,l=y.exitCode}}catch(m){if(m instanceof U){if(r+=m.stdout,n+=m.stderr,m.levels>1&&t.state.loopDepth>1)throw m.levels--,m.stdout=r,m.stderr=n,t.state.inCondition=d,m;f=!0}else if(m instanceof Y){if(r+=m.stdout,n+=m.stderr,m.levels>1&&t.state.loopDepth>1)throw m.levels--,m.stdout=r,m.stderr=n,t.state.inCondition=d,m;h=!0}else throw t.state.inCondition=d,m}finally{t.state.inCondition=d}if(f)break;if(!h){if(l!==0)break;try{for(let m of e.body){let y=await t.executeStatement(m);r+=y.stdout,n+=y.stderr,o=y.exitCode}}catch(m){let y=Ve(m,r,n,t.state.loopDepth);if(r=y.stdout,n=y.stderr,y.action==="break")break;if(y.action==="continue")continue;if(y.action==="error")return S(r,n,y.exitCode??1);throw y.error}}}}finally{t.state.loopDepth--,t.state.groupStdin=c}return S(r,n,o)}async function Fs(t,e){let s="",r="",n=0,o=0;t.state.loopDepth++;try{for(;;){o++,o>t.limits.maxLoopIterations&&ce(`until loop: too many iterations (${t.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",s,r);let i=await yr(t,e.condition);if(s+=i.stdout,r+=i.stderr,i.exitCode===0)break;try{for(let a of e.body){let c=await t.executeStatement(a);s+=c.stdout,r+=c.stderr,n=c.exitCode}}catch(a){let c=Ve(a,s,r,t.state.loopDepth);if(s=c.stdout,r=c.stderr,c.action==="break")break;if(c.action==="continue")continue;if(c.action==="error")return S(s,r,c.exitCode??1);throw c.error}}}finally{t.state.loopDepth--}return S(s,r,n)}async function Ws(t,e){let s="",r="",n=0,o=await k(t,e.word),i=!1;for(let a=0;a<e.items.length;a++){let c=e.items[a],l=i;if(!i)for(let f of c.patterns){let h=await k(t,f);if(us(f)&&(h=hs(h)),pt(o,h)){l=!0;break}}if(l){let f=await At(t,c.body,s,r);if(s=f.stdout,r=f.stderr,n=f.exitCode,c.terminator===";;")break;c.terminator===";&"?i=!0:i=!1}else i=!1}return S(s,r,n)}function Ms(t,e){return t.state.functions.set(e.name,e),N}async function zs(t,e,s){t.state.callDepth++,t.state.callDepth>t.limits.maxCallDepth&&(t.state.callDepth--,ce(`${e.name}: maximum recursion depth (${t.limits.maxCallDepth}) exceeded, increase executionLimits.maxCallDepth`,"recursion")),t.state.localScopes.push(new Map);let r={};for(let o=0;o<s.length;o++)r[String(o+1)]=t.state.env[String(o+1)],t.state.env[String(o+1)]=s[o];r["@"]=t.state.env["@"],r["#"]=t.state.env["#"],t.state.env["@"]=s.join(" "),t.state.env["#"]=String(s.length);let n=()=>{let o=t.state.localScopes.pop();if(o)for(let[i,a]of o)a===void 0?delete t.state.env[i]:t.state.env[i]=a;for(let[i,a]of Object.entries(r))a===void 0?delete t.state.env[i]:t.state.env[i]=a;t.state.callDepth--};try{let o=await t.executeCommand(e.body,"");return n(),o}catch(o){if(n(),o instanceof G)return S(o.stdout,o.stderr,o.exitCode);throw o}}async function Bs(t,e,s){let{stdout:r,stderr:n,exitCode:o}=e;for(let i of s){if(i.target.type==="HereDoc")continue;let a=await k(t,i.target);switch(i.operator){case">":{let c=i.fd??1;if(c===1){let l=t.fs.resolvePath(t.state.cwd,a);try{if((await t.fs.stat(l)).isDirectory){n+=`bash: ${a}: Is a directory
|
|
118
|
+
`,o=1,r="";break}}catch{}await t.fs.writeFile(l,r,"binary"),r=""}else if(c===2)if(a==="/dev/null")n="";else{let l=t.fs.resolvePath(t.state.cwd,a);try{if((await t.fs.stat(l)).isDirectory){n+=`bash: ${a}: Is a directory
|
|
119
|
+
`,o=1;break}}catch{}await t.fs.writeFile(l,n,"binary"),n=""}break}case">>":{let c=i.fd??1;if(c===1){let l=t.fs.resolvePath(t.state.cwd,a);try{if((await t.fs.stat(l)).isDirectory){n+=`bash: ${a}: Is a directory
|
|
120
|
+
`,o=1,r="";break}}catch{}await t.fs.appendFile(l,r,"binary"),r=""}else if(c===2){let l=t.fs.resolvePath(t.state.cwd,a);try{if((await t.fs.stat(l)).isDirectory){n+=`bash: ${a}: Is a directory
|
|
121
|
+
`,o=1;break}}catch{}await t.fs.appendFile(l,n,"binary"),n=""}break}case">&":{let c=i.fd??1;a==="2"||a==="&2"?c===1&&(n+=r,r=""):(a==="1"||a==="&1")&&(r+=n,n="");break}case"&>":{let c=t.fs.resolvePath(t.state.cwd,a);try{if((await t.fs.stat(c)).isDirectory){n=`bash: ${a}: Is a directory
|
|
122
|
+
`,o=1,r="";break}}catch{}await t.fs.writeFile(c,r+n,"binary"),r="",n="";break}case"&>>":{let c=t.fs.resolvePath(t.state.cwd,a);try{if((await t.fs.stat(c)).isDirectory){n=`bash: ${a}: Is a directory
|
|
123
|
+
`,o=1,r="";break}}catch{}await t.fs.appendFile(c,r+n,"binary"),r="",n="";break}}}return S(r,n,o)}var He=class{ctx;constructor(e,s){this.ctx={state:s,fs:e.fs,commands:e.commands,limits:e.limits,execFn:e.exec,executeScript:this.executeScript.bind(this),executeStatement:this.executeStatement.bind(this),executeCommand:this.executeCommand.bind(this),fetch:e.fetch,sleep:e.sleep,trace:e.trace}}async executeScript(e){let s="",r="",n=0;for(let o of e.statements)try{let i=await this.executeStatement(o);s+=i.stdout,r+=i.stderr,n=i.exitCode,this.ctx.state.lastExitCode=n,this.ctx.state.env["?"]=String(n)}catch(i){if(i instanceof R)throw i.prependOutput(s,r),i;if(i instanceof B)throw i;if(i instanceof te)return s+=i.stdout,r+=i.stderr,n=i.exitCode,this.ctx.state.lastExitCode=n,this.ctx.state.env["?"]=String(n),{stdout:s,stderr:r,exitCode:n,env:{...this.ctx.state.env}};if(i instanceof J)return s+=i.stdout,r+=i.stderr,n=1,this.ctx.state.lastExitCode=n,this.ctx.state.env["?"]=String(n),{stdout:s,stderr:r,exitCode:n,env:{...this.ctx.state.env}};if(i instanceof Ee)return s+=i.stdout,r+=i.stderr,n=1,this.ctx.state.lastExitCode=n,this.ctx.state.env["?"]=String(n),{stdout:s,stderr:r,exitCode:n,env:{...this.ctx.state.env}};if(i instanceof U||i instanceof Y){if(this.ctx.state.loopDepth>0)throw i.prependOutput(s,r),i;s+=i.stdout,r+=i.stderr;continue}throw i instanceof G&&i.prependOutput(s,r),i}return{stdout:s,stderr:r,exitCode:n,env:{...this.ctx.state.env}}}async executeStatement(e){this.ctx.state.commandCount++,this.ctx.state.commandCount>this.ctx.limits.maxCommandCount&&ce(`too many commands executed (>${this.ctx.limits.maxCommandCount}), increase executionLimits.maxCommandCount`,"commands");let s="",r="",n=0,o=-1,i=!1;for(let a=0;a<e.pipelines.length;a++){let c=e.pipelines[a],l=a>0?e.operators[a-1]:null;if(l==="&&"&&n!==0||l==="||"&&n===0)continue;let f=await this.executePipeline(c);s+=f.stdout,r+=f.stderr,n=f.exitCode,o=a,i=c.negated,this.ctx.state.lastExitCode=n,this.ctx.state.env["?"]=String(n)}if(this.ctx.state.options.errexit&&n!==0&&o===e.pipelines.length-1&&!i&&!this.ctx.state.inCondition)throw new te(n,s,r);return S(s,r,n)}async executePipeline(e){let s="",r=N,n=0,o=[];for(let i=0;i<e.commands.length;i++){let a=e.commands[i],c=i===e.commands.length-1,l;try{l=await this.executeCommand(a,s)}catch(f){if(f instanceof Ee)l={stdout:f.stdout,stderr:f.stderr,exitCode:1};else if(f instanceof R&&e.commands.length>1)l={stdout:f.stdout,stderr:f.stderr,exitCode:f.exitCode};else throw f}o.push(l.exitCode),l.exitCode!==0&&(n=l.exitCode),c?r=l:(s=l.stdout,r={stdout:"",stderr:l.stderr,exitCode:l.exitCode})}for(let i of Object.keys(this.ctx.state.env))i.startsWith("PIPESTATUS_")&&delete this.ctx.state.env[i];for(let i=0;i<o.length;i++)this.ctx.state.env[`PIPESTATUS_${i}`]=String(o[i]);return this.ctx.state.env.PIPESTATUS__length=String(o.length),this.ctx.state.options.pipefail&&n!==0&&(r={...r,exitCode:n}),e.negated&&(r={...r,exitCode:r.exitCode===0?1:0}),r}async executeCommand(e,s){switch(e.type){case"SimpleCommand":return this.executeSimpleCommand(e,s);case"If":return Os(this.ctx,e);case"For":return _s(this.ctx,e);case"CStyleFor":return Ls(this.ctx,e);case"While":return Ts(this.ctx,e,s);case"Until":return Fs(this.ctx,e);case"Case":return Ws(this.ctx,e);case"Subshell":return this.executeSubshell(e,s);case"Group":return this.executeGroup(e,s);case"FunctionDef":return Ms(this.ctx,e);case"ArithmeticCommand":return this.executeArithmeticCommand(e);case"ConditionalCommand":return this.executeConditionalCommand(e);default:return N}}async executeSimpleCommand(e,s){try{return await this.executeSimpleCommandInner(e,s)}catch(r){if(r instanceof W)return x(r.stderr);throw r}}async executeSimpleCommandInner(e,s){e.line!==void 0&&(this.ctx.state.currentLine=e.line),this.ctx.state.expansionStderr="";let r={};for(let c of e.assignments){let l=c.name;if(c.array){if(/\[.+\]$/.test(l))return S("",`bash: ${l}: cannot assign list to array member
|
|
124
|
+
`,1);let E=me(this.ctx,l);if(E)return E;let p=[];for(let g of c.array){let b=await Ge(this.ctx,g);p.push(...b.values)}let w=0;if(c.append){let g=F(this.ctx,l);g.length>0&&(w=Math.max(...g.map(([C])=>typeof C=="number"?C:0))+1)}else{let g=`${l}_`;for(let b of Object.keys(this.ctx.state.env))b.startsWith(g)&&!b.includes("__")&&delete this.ctx.state.env[b]}for(let g=0;g<p.length;g++)this.ctx.state.env[`${l}_${w+g}`]=p[g];c.append||(this.ctx.state.env[`${l}__length`]=String(p.length));continue}let f=c.value?await k(this.ctx,c.value):"";if(l.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[\]$/))return S("",`bash: ${l}: bad array subscript
|
|
125
125
|
`,1);let d=l.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(d){let E=d[1],p=d[2],w=me(this.ctx,E);if(w)return w;let g=this.ctx.state.associativeArrays?.has(E),b;if(g){let I;if(p.startsWith("'")&&p.endsWith("'"))I=p.slice(1,-1);else if(p.startsWith('"')&&p.endsWith('"')){let D=p.slice(1,-1),L=new z().parseWordFromString(D,!0,!1);I=await k(this.ctx,L)}else if(p.includes("$")){let we=new z().parseWordFromString(p,!1,!1);I=await k(this.ctx,we)}else I=p;b=`${E}_${I}`}else{let I;if(/^-?\d+$/.test(p))I=Number.parseInt(p,10);else{try{let D=new z,we=T(D,p);I=P(this.ctx,we.expression)}catch{let D=this.ctx.state.env[p];I=D?Number.parseInt(D,10):0}Number.isNaN(I)&&(I=0)}if(I<0){let D=F(this.ctx,E);if(D.length===0)return S("",`bash: ${E}[${p}]: bad array subscript
|
|
126
126
|
`,1);if(I=Math.max(...D.map(([L])=>typeof L=="number"?L:0))+1+I,I<0)return S("",`bash: ${E}[${p}]: bad array subscript
|
|
127
|
-
`,1)}b=`${E}_${I}`}let C=c.append?(this.ctx.state.env[b]||"")+
|
|
127
|
+
`,1)}b=`${E}_${I}`}let C=c.append?(this.ctx.state.env[b]||"")+f:f;e.name?(r[b]=this.ctx.state.env[b],this.ctx.state.env[b]=C):this.ctx.state.env[b]=C;continue}let m=me(this.ctx,l);if(m)return m;let y=c.append?(this.ctx.state.env[l]||"")+f:f;e.name?(r[l]=this.ctx.state.env[l],this.ctx.state.env[l]=y):this.ctx.state.env[l]=y}if(!e.name)return S("","",this.ctx.state.lastExitCode);for(let c of e.redirections){if((c.operator==="<<"||c.operator==="<<-")&&c.target.type==="HereDoc"){let l=c.target,f=await k(this.ctx,l.content);l.stripTabs&&(f=f.split(`
|
|
128
128
|
`).map(h=>h.replace(/^\t+/,"")).join(`
|
|
129
|
-
`)),
|
|
130
|
-
`;continue}if(c.operator==="<"&&c.target.type==="Word")try{let l=await k(this.ctx,c.target),
|
|
131
|
-
`)}}let
|
|
132
|
-
`,127)}let a=await this.runCommand(
|
|
129
|
+
`)),s=f;continue}if(c.operator==="<<<"&&c.target.type==="Word"){s=`${await k(this.ctx,c.target)}
|
|
130
|
+
`;continue}if(c.operator==="<"&&c.target.type==="Word")try{let l=await k(this.ctx,c.target),f=this.ctx.fs.resolvePath(this.ctx.state.cwd,l);s=await this.ctx.fs.readFile(f)}catch{let l=await k(this.ctx,c.target);for(let[f,h]of Object.entries(r))h===void 0?delete this.ctx.state.env[f]:this.ctx.state.env[f]=h;return x(`bash: ${l}: No such file or directory
|
|
131
|
+
`)}}let n=await k(this.ctx,e.name),o=[],i=[];for(let c of e.args){let l=await Ge(this.ctx,c);for(let f of l.values)o.push(f),i.push(l.quoted)}if(!n){if(e.name.parts.every(l=>l.type==="CommandSubstitution"||l.type==="ParameterExpansion"||l.type==="ArithmeticExpansion")){if(o.length>0){let l=o.shift();return i.shift(),await this.runCommand(l,o,i,s)}return S("","",this.ctx.state.lastExitCode)}return x(`bash: : command not found
|
|
132
|
+
`,127)}let a=await this.runCommand(n,o,i,s);a=await Bs(this.ctx,a,e.redirections),this.ctx.state.lastArg=o.length>0?o[o.length-1]:n;for(let[c,l]of Object.entries(r))l===void 0?delete this.ctx.state.env[c]:this.ctx.state.env[c]=l;return this.ctx.state.expansionStderr&&(a={...a,stderr:this.ctx.state.expansionStderr+a.stderr},this.ctx.state.expansionStderr=""),a}async runCommand(e,s,r,n,o=!1){if(e==="cd")return await Qt(this.ctx,s);if(e==="export")return rr(this.ctx,s);if(e==="unset")return hr(this.ctx,s);if(e==="exit")return tr(this.ctx,s);if(e==="local")return nr(this.ctx,s);if(e==="set")return lr(this.ctx,s);if(e==="break")return Zt(this.ctx,s);if(e==="continue")return Kt(this.ctx,s);if(e==="return")return ar(this.ctx,s);if(e==="eval")return er(this.ctx,s);if(e==="shift")return fr(this.ctx,s);if(e==="source"||e===".")return ur(this.ctx,s);if(e==="read")return or(this.ctx,s,n);if(e==="mapfile"||e==="readarray")return ir(this.ctx,s,n);if(e==="declare"||e==="typeset")return Yt(this.ctx,s);if(e==="readonly")return Jt(this.ctx,s);if(!o){let f=this.ctx.state.functions.get(e);if(f)return zs(this.ctx,f,s)}if(e===":"||e==="true")return N;if(e==="false")return _(!1);if(e==="let")return sr(this.ctx,s);if(e==="command"){if(s.length===0)return N;let f=s;for(;f.length>0&&f[0].startsWith("-");)f=f.slice(1);if(f.length===0)return N;let[h,...d]=f;return this.runCommand(h,d,[],n,!0)}if(e==="builtin"){if(s.length===0)return N;let[f,...h]=s;return this.runCommand(f,h,[],n)}if(e==="shopt")return N;if(e==="exec"){if(s.length===0)return N;let[f,...h]=s;return this.runCommand(f,h,[],n)}if(e==="wait")return N;if(e==="type")return this.handleType(s);if(e==="[["){let f=s.lastIndexOf("]]");if(f!==-1){let h=s.slice(0,f);return Re(this.ctx,h)}return x("bash: [[: missing `]]'\n",2)}if(e==="["||e==="test"){let f=s;if(e==="["){if(s[s.length-1]!=="]")return x("[: missing `]'\n",2);f=s.slice(0,-1)}return Re(this.ctx,f)}let i=await this.resolveCommand(e);if(!i)return Ir(e)?x(`bash: ${e}: command not available in browser environments. Exclude '${e}' from your commands or use the Node.js bundle.
|
|
133
133
|
`,127):x(`bash: ${e}: command not found
|
|
134
|
-
`,127);let{cmd:a,path:c}=
|
|
135
|
-
`)}}async resolveCommand(e){if(e.includes("/")){let
|
|
136
|
-
`:r.has(a)?
|
|
137
|
-
`:this.ctx.state.functions.has(a)?
|
|
138
|
-
`:this.ctx.commands.has(a)?
|
|
139
|
-
`:(
|
|
140
|
-
`,
|
|
141
|
-
`,1)}return this.ctx.state.env=r,this.ctx.state.cwd=
|
|
142
|
-
`,1)}return this.ctx.state.groupStdin=
|
|
143
|
-
`)}}async executeConditionalCommand(e){try{let
|
|
144
|
-
`,2)}}};var ye={maxCallDepth:100,maxCommandCount:1e4,maxLoopIterations:1e4,maxAwkIterations:1e4,maxSedIterations:1e4,maxJqIterations:1e4,maxSqliteTimeoutMs:5e3};function
|
|
145
|
-
`,OSTYPE:"linux-gnu",MACHTYPE:"x86_64-pc-linux-gnu",HOSTTYPE:"x86_64",PWD:r,OLDPWD:r,...e.env};if(this.limits=
|
|
134
|
+
`,127);let{cmd:a,path:c}=i,l={fs:this.ctx.fs,cwd:this.ctx.state.cwd,env:this.ctx.state.env,stdin:n,limits:this.ctx.limits,exec:this.ctx.execFn,fetch:this.ctx.fetch,getRegisteredCommands:()=>Array.from(this.ctx.commands.keys()),sleep:this.ctx.sleep,trace:this.ctx.trace};try{return await a.execute(s,l)}catch(f){return x(`${e}: ${le(f)}
|
|
135
|
+
`)}}async resolveCommand(e){if(e.includes("/")){let o=this.ctx.fs.resolvePath(this.ctx.state.cwd,e);if(!await this.ctx.fs.exists(o))return null;let i=o.split("/").pop()||e,a=this.ctx.commands.get(i);return a?{cmd:a,path:o}:null}let r=(this.ctx.state.env.PATH||"/bin:/usr/bin").split(":");for(let o of r){if(!o)continue;let i=`${o}/${e}`;if(await this.ctx.fs.exists(i)){let a=this.ctx.commands.get(e);if(a)return{cmd:a,path:i}}}if(!await this.ctx.fs.exists("/bin")){let o=this.ctx.commands.get(e);if(o)return{cmd:o,path:`/bin/${e}`}}return null}async findCommandInPath(e){let s=[],n=(this.ctx.state.env.PATH||"/bin:/usr/bin").split(":");for(let o of n){if(!o)continue;let i=`${o}/${e}`;await this.ctx.fs.exists(i)&&s.push(i)}return s}handleType(e){let s=new Set(["if","then","else","elif","fi","case","esac","for","select","while","until","do","done","in","function","{","}","time","[[","]]","!"]),r=new Set(["cd","export","unset","exit","local","set","break","continue","return","eval","shift","source",".","read","declare","typeset","readonly",":","true","false","let","command","builtin","shopt","exec","wait","type","[","test"]),n="",o="",i=0;for(let a of e)s.has(a)?n+=`${a} is a shell keyword
|
|
136
|
+
`:r.has(a)?n+=`${a} is a shell builtin
|
|
137
|
+
`:this.ctx.state.functions.has(a)?n+=`${a} is a function
|
|
138
|
+
`:this.ctx.commands.has(a)?n+=`${a} is /bin/${a}
|
|
139
|
+
`:(o+=`bash: type: ${a}: not found
|
|
140
|
+
`,i=1);return S(n,o,i)}async executeSubshell(e,s=""){let r={...this.ctx.state.env},n=this.ctx.state.cwd,o=this.ctx.state.loopDepth,i=this.ctx.state.parentHasLoopContext;this.ctx.state.parentHasLoopContext=o>0,this.ctx.state.loopDepth=0;let a=this.ctx.state.groupStdin;s&&(this.ctx.state.groupStdin=s);let c="",l="",f=0;try{for(let h of e.body){let d=await this.executeStatement(h);c+=d.stdout,l+=d.stderr,f=d.exitCode}}catch(h){if(this.ctx.state.env=r,this.ctx.state.cwd=n,this.ctx.state.loopDepth=o,this.ctx.state.parentHasLoopContext=i,this.ctx.state.groupStdin=a,h instanceof B)throw h;if(h instanceof fe)return c+=h.stdout,l+=h.stderr,S(c,l,0);if(h instanceof U||h instanceof Y)return c+=h.stdout,l+=h.stderr,S(c,l,0);if(h instanceof R)return c+=h.stdout,l+=h.stderr,S(c,l,h.exitCode);if(h instanceof G)return c+=h.stdout,l+=h.stderr,S(c,l,h.exitCode);if(h instanceof te)throw h.stdout=c+h.stdout,h.stderr=l+h.stderr,h;return S(c,`${l}${le(h)}
|
|
141
|
+
`,1)}return this.ctx.state.env=r,this.ctx.state.cwd=n,this.ctx.state.loopDepth=o,this.ctx.state.parentHasLoopContext=i,this.ctx.state.groupStdin=a,S(c,l,f)}async executeGroup(e,s=""){let r="",n="",o=0,i=this.ctx.state.groupStdin;s&&(this.ctx.state.groupStdin=s);try{for(let a of e.body){let c=await this.executeStatement(a);r+=c.stdout,n+=c.stderr,o=c.exitCode}}catch(a){if(this.ctx.state.groupStdin=i,a instanceof B)throw a;if(qe(a)||a instanceof te||a instanceof R)throw a.prependOutput(r,n),a;return S(r,`${n}${le(a)}
|
|
142
|
+
`,1)}return this.ctx.state.groupStdin=i,S(r,n,o)}async executeArithmeticCommand(e){try{let s=await v(this.ctx,e.expression.expression);return _(s!==0)}catch(s){return x(`bash: arithmetic expression: ${s.message}
|
|
143
|
+
`)}}async executeConditionalCommand(e){try{let s=await pe(this.ctx,e.expression);return _(s)}catch(s){return x(`bash: conditional expression: ${s.message}
|
|
144
|
+
`,2)}}};var ye={maxCallDepth:100,maxCommandCount:1e4,maxLoopIterations:1e4,maxAwkIterations:1e4,maxSedIterations:1e4,maxJqIterations:1e4,maxSqliteTimeoutMs:5e3};function Us(t){return t?{maxCallDepth:t.maxCallDepth??ye.maxCallDepth,maxCommandCount:t.maxCommandCount??ye.maxCommandCount,maxLoopIterations:t.maxLoopIterations??ye.maxLoopIterations,maxAwkIterations:t.maxAwkIterations??ye.maxAwkIterations,maxSedIterations:t.maxSedIterations??ye.maxSedIterations,maxJqIterations:t.maxJqIterations??ye.maxJqIterations,maxSqliteTimeoutMs:t.maxSqliteTimeoutMs??ye.maxSqliteTimeoutMs}:{...ye}}function Gs(t){try{let e=new URL(t);return{origin:e.origin,pathname:e.pathname,href:e.href}}catch{return null}}function si(t){let e=Gs(t);return e?{origin:e.origin,pathPrefix:e.pathname}:null}function ni(t,e){let s=Gs(t);if(!s)return!1;let r=si(e);return!r||s.origin!==r.origin?!1:r.pathPrefix==="/"||r.pathPrefix===""?!0:s.pathname.startsWith(r.pathPrefix)}function wr(t,e){return!e||e.length===0?!1:e.some(s=>ni(t,s))}var De=class extends Error{constructor(e){super(`Network access denied: URL not in allow-list: ${e}`),this.name="NetworkAccessDeniedError"}},Oe=class extends Error{constructor(e){super(`Too many redirects (max: ${e})`),this.name="TooManyRedirectsError"}},_e=class extends Error{constructor(e){super(`Redirect target not in allow-list: ${e}`),this.name="RedirectNotAllowedError"}},St=class extends Error{constructor(e,s){super(`HTTP method '${e}' not allowed. Allowed methods: ${s.join(", ")}`),this.name="MethodNotAllowedError"}};var ii=20,oi=3e4,ai=["GET","HEAD"],ci=new Set(["GET","HEAD","OPTIONS"]),li=new Set([301,302,303,307,308]);function Er(t){let e=t.maxRedirects??ii,s=t.timeoutMs??oi,r=t.dangerouslyAllowFullInternetAccess?["GET","HEAD","POST","PUT","DELETE","PATCH","OPTIONS"]:t.allowedMethods??ai;function n(a){if(!t.dangerouslyAllowFullInternetAccess&&!wr(a,t.allowedUrlPrefixes??[]))throw new De(a)}function o(a){if(t.dangerouslyAllowFullInternetAccess)return;let c=a.toUpperCase();if(!r.includes(c))throw new St(c,r)}async function i(a,c={}){let l=c.method?.toUpperCase()??"GET";n(a),o(l);let f=a,h=0,d=c.followRedirects??!0,m=c.timeoutMs!==void 0?Math.min(c.timeoutMs,s):s;for(;;){let y=new AbortController,E=setTimeout(()=>y.abort(),m);try{let p={method:l,headers:c.headers,signal:y.signal,redirect:"manual"};c.body&&!ci.has(l)&&(p.body=c.body);let w=await fetch(f,p);if(li.has(w.status)&&d){let g=w.headers.get("location");if(!g)return await Vs(w,f);let b=new URL(g,f).href;if(!t.dangerouslyAllowFullInternetAccess&&!wr(b,t.allowedUrlPrefixes??[]))throw new _e(b);if(h++,h>e)throw new Oe(e);f=b;continue}return await Vs(w,f)}finally{clearTimeout(E)}}}return i}async function Vs(t,e){let s={};return t.headers.forEach((r,n)=>{s[n.toLowerCase()]=r}),{status:t.status,statusText:t.statusText,headers:s,body:await t.text(),url:e}}var je=class{fs;commands=new Map;useDefaultLayout=!1;limits;secureFetch;sleepFn;traceFn;logger;state;constructor(e={}){let s=e.fs??new se(e.files);this.fs=s,this.useDefaultLayout=!e.cwd&&!e.files;let r=e.cwd||(this.useDefaultLayout?"/home/user":"/"),n={HOME:this.useDefaultLayout?"/home/user":"/",PATH:"/bin:/usr/bin",IFS:`
|
|
145
|
+
`,OSTYPE:"linux-gnu",MACHTYPE:"x86_64-pc-linux-gnu",HOSTTYPE:"x86_64",PWD:r,OLDPWD:r,...e.env};if(this.limits=Us({...e.executionLimits,...e.maxCallDepth!==void 0&&{maxCallDepth:e.maxCallDepth},...e.maxCommandCount!==void 0&&{maxCommandCount:e.maxCommandCount},...e.maxLoopIterations!==void 0&&{maxLoopIterations:e.maxLoopIterations}}),e.network&&(this.secureFetch=Er(e.network)),this.sleepFn=e.sleep,this.traceFn=e.trace,this.logger=e.logger,this.state={env:n,cwd:r,previousDir:"/home/user",functions:new Map,localScopes:[],callDepth:0,sourceDepth:0,commandCount:0,lastExitCode:0,lastArg:"",startTime:Date.now(),lastBackgroundPid:0,currentLine:1,options:{errexit:!1,pipefail:!1,nounset:!1,xtrace:!1,verbose:!1},inCondition:!1,loopDepth:0},kr(s,this.useDefaultLayout),r!=="/"&&s instanceof se)try{s.mkdirSync(r,{recursive:!0})}catch{}for(let o of xr(e.commands))this.registerCommand(o);if(e.network)for(let o of br())this.registerCommand(o);if(e.customCommands)for(let o of e.customCommands)Cr(o)?this.registerCommand(Nr(o)):this.registerCommand(o)}registerCommand(e){this.commands.set(e.name,e);let s=this.fs;if(typeof s.writeFileSync=="function")try{s.writeFileSync(`/bin/${e.name}`,`#!/bin/bash
|
|
146
146
|
# Built-in command: ${e.name}
|
|
147
|
-
`)}catch{}}logResult(e){return this.logger&&(e.stdout&&this.logger.debug("stdout",{output:e.stdout}),e.stderr&&this.logger.info("stderr",{output:e.stderr}),this.logger.info("exit",{exitCode:e.exitCode})),e}async exec(e,
|
|
148
|
-
`,exitCode:1,env:{...this.state.env,...
|
|
147
|
+
`)}catch{}}logResult(e){return this.logger&&(e.stdout&&this.logger.debug("stdout",{output:e.stdout}),e.stderr&&this.logger.info("stderr",{output:e.stderr}),this.logger.info("exit",{exitCode:e.exitCode})),e}async exec(e,s){if(this.state.callDepth===0&&(this.state.commandCount=0),this.state.commandCount++,this.state.commandCount>this.limits.maxCommandCount)return{stdout:"",stderr:`bash: maximum command count (${this.limits.maxCommandCount}) exceeded (possible infinite loop). Increase with executionLimits.maxCommandCount option.
|
|
148
|
+
`,exitCode:1,env:{...this.state.env,...s?.env}};if(!e.trim())return{stdout:"",stderr:"",exitCode:0,env:{...this.state.env,...s?.env}};this.logger?.info("exec",{command:e});let r=s?.cwd??this.state.cwd,n={...this.state,env:{...this.state.env,...s?.env,...s?.cwd?{PWD:s.cwd}:{}},cwd:r,functions:new Map(this.state.functions),localScopes:[...this.state.localScopes],options:{...this.state.options}},o=e;s?.rawScript||(o=e.split(`
|
|
149
149
|
`).map(a=>a.trimStart()).join(`
|
|
150
|
-
`));try{let
|
|
151
|
-
`,exitCode:2,env:{...this.state.env,...
|
|
152
|
-
`,exitCode:1,env:{...this.state.env,...n?.env}});throw o}}async readFile(e){return this.fs.readFile(this.fs.resolvePath(this.state.cwd,e))}async writeFile(e,n){return this.fs.writeFile(this.fs.resolvePath(this.state.cwd,e),n)}getCwd(){return this.state.cwd}getEnv(){return{...this.state.env}}};var xt=class{baseFs;mounts=new Map;constructor(e){if(this.baseFs=e?.base??new ne,e?.mounts)for(let{mountPoint:n,filesystem:r}of e.mounts)this.mount(n,r)}mount(e,n){this.validateMountPath(e);let r=this.normalizePath(e);this.validateMount(r),this.mounts.set(r,{mountPoint:r,filesystem:n})}unmount(e){let n=this.normalizePath(e);if(!this.mounts.has(n))throw new Error(`No filesystem mounted at '${e}'`);this.mounts.delete(n)}getMounts(){return Array.from(this.mounts.values()).map(e=>({mountPoint:e.mountPoint,filesystem:e.filesystem}))}isMountPoint(e){let n=this.normalizePath(e);return this.mounts.has(n)}validateMountPath(e){let n=e.split("/");for(let r of n)if(r==="."||r==="..")throw new Error(`Invalid mount point '${e}': contains '.' or '..' segments`)}validateMount(e){if(e==="/")throw new Error("Cannot mount at root '/'");for(let n of this.mounts.keys())if(n!==e){if(e.startsWith(`${n}/`))throw new Error(`Cannot mount at '${e}': inside existing mount '${n}'`);if(n.startsWith(`${e}/`))throw new Error(`Cannot mount at '${e}': would contain existing mount '${n}'`)}}normalizePath(e){if(!e||e==="/")return"/";let n=e.endsWith("/")&&e!=="/"?e.slice(0,-1):e;n.startsWith("/")||(n=`/${n}`);let r=n.split("/").filter(i=>i&&i!=="."),s=[];for(let i of r)i===".."?s.pop():s.push(i);return`/${s.join("/")}`}routePath(e){let n=this.normalizePath(e),r=null,s=0;for(let i of this.mounts.values()){let o=i.mountPoint;if(n===o)return{fs:i.filesystem,relativePath:"/"};n.startsWith(`${o}/`)&&o.length>s&&(r=i,s=o.length)}if(r){let i=n.slice(s);return{fs:r.filesystem,relativePath:i||"/"}}return{fs:this.baseFs,relativePath:n}}getChildMountPoints(e){let n=this.normalizePath(e),r=n==="/"?"/":`${n}/`,s=[];for(let i of this.mounts.keys())if(i.startsWith(r)){let a=i.slice(r.length).split("/")[0];a&&!s.includes(a)&&s.push(a)}return s}async readFile(e,n){let{fs:r,relativePath:s}=this.routePath(e);return r.readFile(s,n)}async readFileBuffer(e){let{fs:n,relativePath:r}=this.routePath(e);return n.readFileBuffer(r)}async writeFile(e,n,r){let{fs:s,relativePath:i}=this.routePath(e);return s.writeFile(i,n,r)}async appendFile(e,n,r){let{fs:s,relativePath:i}=this.routePath(e);return s.appendFile(i,n,r)}async exists(e){let n=this.normalizePath(e);if(this.mounts.has(n)||this.getChildMountPoints(n).length>0)return!0;let{fs:s,relativePath:i}=this.routePath(e);return s.exists(i)}async stat(e){let n=this.normalizePath(e),r=this.mounts.get(n);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(n).length>0)try{return await this.baseFs.stat(n)}catch{return{isFile:!1,isDirectory:!0,isSymbolicLink:!1,mode:493,size:0,mtime:new Date}}let{fs:i,relativePath:o}=this.routePath(e);return i.stat(o)}async lstat(e){let n=this.normalizePath(e),r=this.mounts.get(n);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(n).length>0)try{return await this.baseFs.lstat(n)}catch{return{isFile:!1,isDirectory:!0,isSymbolicLink:!1,mode:493,size:0,mtime:new Date}}let{fs:i,relativePath:o}=this.routePath(e);return i.lstat(o)}async mkdir(e,n){let r=this.normalizePath(e);if(this.mounts.has(r)){if(n?.recursive)return;throw new Error(`EEXIST: directory already exists, mkdir '${e}'`)}if(this.getChildMountPoints(r).length>0&&n?.recursive)return;let{fs:i,relativePath:o}=this.routePath(e);return i.mkdir(o,n)}async readdir(e){let n=this.normalizePath(e),r=new Set,s=null,{fs:i,relativePath:o}=this.routePath(e);try{let c=await i.readdir(o);for(let l of c)r.add(l)}catch(c){let l=c.code,u=c.message||"";if(l!=="ENOENT"&&!u.includes("ENOENT"))throw c;s=c}let a=this.getChildMountPoints(n);for(let c of a)r.add(c);if(r.size===0&&s&&!this.mounts.has(n))throw s;return Array.from(r).sort()}async rm(e,n){let r=this.normalizePath(e);if(this.mounts.has(r))throw new Error(`EBUSY: mount point, cannot remove '${e}'`);if(this.getChildMountPoints(r).length>0)throw new Error(`EBUSY: contains mount points, cannot remove '${e}'`);let{fs:i,relativePath:o}=this.routePath(e);return i.rm(o,n)}async cp(e,n,r){let s=this.routePath(e),i=this.routePath(n);return s.fs===i.fs?s.fs.cp(s.relativePath,i.relativePath,r):this.crossMountCopy(e,n,r)}async mv(e,n){let r=this.normalizePath(e);if(this.mounts.has(r))throw new Error(`EBUSY: mount point, cannot move '${e}'`);let s=this.routePath(e),i=this.routePath(n);if(s.fs===i.fs)return s.fs.mv(s.relativePath,i.relativePath);await this.cp(e,n,{recursive:!0}),await this.rm(e,{recursive:!0})}resolvePath(e,n){if(n.startsWith("/"))return this.normalizePath(n);let r=e==="/"?`/${n}`:`${e}/${n}`;return this.normalizePath(r)}getAllPaths(){let e=new Set;for(let n of this.baseFs.getAllPaths())e.add(n);for(let n of this.mounts.keys()){let r=n.split("/").filter(Boolean),s="";for(let o of r)s=`${s}/${o}`,e.add(s);let i=this.mounts.get(n);if(i)for(let o of i.filesystem.getAllPaths())o==="/"?e.add(n):e.add(`${n}${o}`)}return Array.from(e).sort()}async chmod(e,n){let r=this.normalizePath(e),s=this.mounts.get(r);if(s)return s.filesystem.chmod("/",n);let{fs:i,relativePath:o}=this.routePath(e);return i.chmod(o,n)}async symlink(e,n){let{fs:r,relativePath:s}=this.routePath(n);return r.symlink(e,s)}async link(e,n){let r=this.routePath(e),s=this.routePath(n);if(r.fs!==s.fs)throw new Error(`EXDEV: cross-device link not permitted, link '${e}' -> '${n}'`);return r.fs.link(r.relativePath,s.relativePath)}async readlink(e){let{fs:n,relativePath:r}=this.routePath(e);return n.readlink(r)}async crossMountCopy(e,n,r){let s=await this.lstat(e);if(s.isFile){let i=await this.readFileBuffer(e);await this.writeFile(n,i),await this.chmod(n,s.mode)}else if(s.isDirectory){if(!r?.recursive)throw new Error(`cp: ${e} is a directory (not copied)`);await this.mkdir(n,{recursive:!0});let i=await this.readdir(e);for(let o of i){let a=e==="/"?`/${o}`:`${e}/${o}`,c=n==="/"?`/${o}`:`${n}/${o}`;await this.crossMountCopy(a,c,r)}}else if(s.isSymbolicLink){let i=await this.readlink(e);await this.symlink(i,n)}}};import*as M from"node:fs";import*as Le from"node:path";var ui="/home/user/project",Te=class{root;mountPoint;readOnly;memory=new Map;deleted=new Set;constructor(e){this.root=Le.resolve(e.root);let n=e.mountPoint??ui;if(this.mountPoint=n==="/"?"/":n.replace(/\/+$/,""),!this.mountPoint.startsWith("/"))throw new Error(`Mount point must be an absolute path: ${n}`);if(this.readOnly=e.readOnly??!1,!M.existsSync(this.root))throw new Error(`OverlayFs root does not exist: ${this.root}`);if(!M.statSync(this.root).isDirectory())throw new Error(`OverlayFs root is not a directory: ${this.root}`);this.createMountPointDirs()}assertWritable(e){if(this.readOnly)throw new Error(`EROFS: read-only file system, ${e}`)}createMountPointDirs(){let e=this.mountPoint.split("/").filter(Boolean),n="";for(let r of e)n+=`/${r}`,this.memory.has(n)||this.memory.set(n,{type:"directory",mode:493,mtime:new Date});this.memory.has("/")||this.memory.set("/",{type:"directory",mode:493,mtime:new Date})}getMountPoint(){return this.mountPoint}mkdirSync(e,n){let s=this.normalizePath(e).split("/").filter(Boolean),i="";for(let o of s)i+=`/${o}`,this.memory.has(i)||this.memory.set(i,{type:"directory",mode:493,mtime:new Date})}writeFileSync(e,n){let r=this.normalizePath(e),s=this.getDirname(r);s!=="/"&&this.mkdirSync(s);let i=n instanceof Uint8Array?n:new TextEncoder().encode(n);this.memory.set(r,{type:"file",content:i,mode:420,mtime:new Date})}getDirname(e){let n=e.lastIndexOf("/");return n===0?"/":e.slice(0,n)}normalizePath(e){if(!e||e==="/")return"/";let n=e.endsWith("/")&&e!=="/"?e.slice(0,-1):e;n.startsWith("/")||(n=`/${n}`);let r=n.split("/").filter(i=>i&&i!=="."),s=[];for(let i of r)i===".."?s.pop():s.push(i);return`/${s.join("/")}`||"/"}getRelativeToMount(e){return this.mountPoint==="/"?e:e===this.mountPoint?"/":e.startsWith(`${this.mountPoint}/`)?e.slice(this.mountPoint.length):null}toRealPath(e){let n=this.normalizePath(e),r=this.getRelativeToMount(n);if(r===null)return null;let s=Le.join(this.root,r),i=Le.resolve(s);return!i.startsWith(this.root)&&i!==this.root.replace(/\/$/,"")?null:i}dirname(e){let n=this.normalizePath(e);if(n==="/")return"/";let r=n.lastIndexOf("/");return r===0?"/":n.slice(0,r)}ensureParentDirs(e){let n=this.dirname(e);n!=="/"&&(this.memory.has(n)||(this.ensureParentDirs(n),this.memory.set(n,{type:"directory",mode:493,mtime:new Date})),this.deleted.delete(n))}async existsInOverlay(e){let n=this.normalizePath(e);if(this.deleted.has(n))return!1;if(this.memory.has(n))return!0;let r=this.toRealPath(n);if(!r)return!1;try{return await M.promises.access(r),!0}catch{return!1}}async readFile(e,n){let r=await this.readFileBuffer(e),s=q(n);return Ce(r,s)}async readFileBuffer(e,n=new Set){let r=this.normalizePath(e);if(n.has(r))throw new Error(`ELOOP: too many levels of symbolic links, open '${e}'`);if(n.add(r),this.deleted.has(r))throw new Error(`ENOENT: no such file or directory, open '${e}'`);let s=this.memory.get(r);if(s){if(s.type==="symlink"){let o=this.resolveSymlink(r,s.target);return this.readFileBuffer(o,n)}if(s.type!=="file")throw new Error(`EISDIR: illegal operation on a directory, read '${e}'`);return s.content}let i=this.toRealPath(r);if(!i)throw new Error(`ENOENT: no such file or directory, open '${e}'`);try{let o=await M.promises.lstat(i);if(o.isSymbolicLink()){let c=await M.promises.readlink(i),l=this.resolveSymlink(r,c);return this.readFileBuffer(l,n)}if(o.isDirectory())throw new Error(`EISDIR: illegal operation on a directory, read '${e}'`);let a=await M.promises.readFile(i);return new Uint8Array(a)}catch(o){throw o.code==="ENOENT"?new Error(`ENOENT: no such file or directory, open '${e}'`):o}}async writeFile(e,n,r){this.assertWritable(`write '${e}'`);let s=this.normalizePath(e);this.ensureParentDirs(s);let i=q(r),o=re(n,i);this.memory.set(s,{type:"file",content:o,mode:420,mtime:new Date}),this.deleted.delete(s)}async appendFile(e,n,r){this.assertWritable(`append '${e}'`);let s=this.normalizePath(e),i=q(r),o=re(n,i),a;try{a=await this.readFileBuffer(s)}catch{a=new Uint8Array(0)}let c=new Uint8Array(a.length+o.length);c.set(a),c.set(o,a.length),this.ensureParentDirs(s),this.memory.set(s,{type:"file",content:c,mode:420,mtime:new Date}),this.deleted.delete(s)}async exists(e){return this.existsInOverlay(e)}async stat(e,n=new Set){let r=this.normalizePath(e);if(n.has(r))throw new Error(`ELOOP: too many levels of symbolic links, stat '${e}'`);if(n.add(r),this.deleted.has(r))throw new Error(`ENOENT: no such file or directory, stat '${e}'`);let s=this.memory.get(r);if(s){if(s.type==="symlink"){let a=this.resolveSymlink(r,s.target);return this.stat(a,n)}let o=0;return s.type==="file"&&(o=s.content.length),{isFile:s.type==="file",isDirectory:s.type==="directory",isSymbolicLink:!1,mode:s.mode,size:o,mtime:s.mtime}}let i=this.toRealPath(r);if(!i)throw new Error(`ENOENT: no such file or directory, stat '${e}'`);try{let o=await M.promises.stat(i);return{isFile:o.isFile(),isDirectory:o.isDirectory(),isSymbolicLink:!1,mode:o.mode,size:o.size,mtime:o.mtime}}catch(o){throw o.code==="ENOENT"?new Error(`ENOENT: no such file or directory, stat '${e}'`):o}}async lstat(e){let n=this.normalizePath(e);if(this.deleted.has(n))throw new Error(`ENOENT: no such file or directory, lstat '${e}'`);let r=this.memory.get(n);if(r){if(r.type==="symlink")return{isFile:!1,isDirectory:!1,isSymbolicLink:!0,mode:r.mode,size:r.target.length,mtime:r.mtime};let i=0;return r.type==="file"&&(i=r.content.length),{isFile:r.type==="file",isDirectory:r.type==="directory",isSymbolicLink:!1,mode:r.mode,size:i,mtime:r.mtime}}let s=this.toRealPath(n);if(!s)throw new Error(`ENOENT: no such file or directory, lstat '${e}'`);try{let i=await M.promises.lstat(s);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 '${e}'`):i}}resolveSymlink(e,n){if(n.startsWith("/"))return this.normalizePath(n);let r=this.dirname(e);return this.normalizePath(r==="/"?`/${n}`:`${r}/${n}`)}async mkdir(e,n){this.assertWritable(`mkdir '${e}'`);let r=this.normalizePath(e);if(await this.existsInOverlay(r)){if(!n?.recursive)throw new Error(`EEXIST: file already exists, mkdir '${e}'`);return}let i=this.dirname(r);if(i!=="/"&&!await this.existsInOverlay(i))if(n?.recursive)await this.mkdir(i,{recursive:!0});else throw new Error(`ENOENT: no such file or directory, mkdir '${e}'`);this.memory.set(r,{type:"directory",mode:493,mtime:new Date}),this.deleted.delete(r)}async readdirCore(e,n){if(this.deleted.has(n))throw new Error(`ENOENT: no such file or directory, scandir '${e}'`);let r=new Map,s=new Set,i=n==="/"?"/":`${n}/`;for(let a of this.deleted)if(a.startsWith(i)){let c=a.slice(i.length),l=c.split("/")[0];l&&!c.includes("/",l.length)&&s.add(l)}for(let[a,c]of this.memory)if(a!==n&&a.startsWith(i)){let l=a.slice(i.length),u=l.split("/")[0];u&&!s.has(u)&&!l.includes("/",1)&&r.set(u,{name:u,isFile:c.type==="file",isDirectory:c.type==="directory",isSymbolicLink:c.type==="symlink"})}let o=this.toRealPath(n);if(o)try{let a=await M.promises.readdir(o,{withFileTypes:!0});for(let c of a)!s.has(c.name)&&!r.has(c.name)&&r.set(c.name,{name:c.name,isFile:c.isFile(),isDirectory:c.isDirectory(),isSymbolicLink:c.isSymbolicLink()})}catch(a){if(a.code==="ENOENT"){if(!this.memory.has(n))throw new Error(`ENOENT: no such file or directory, scandir '${e}'`)}else if(a.code!=="ENOTDIR")throw a}return r}async resolveForReaddir(e,n=!1){let r=this.normalizePath(e),s=new Set,i=n,o=this.memory.get(r);for(;o&&o.type==="symlink";){if(s.has(r))throw new Error(`ELOOP: too many levels of symbolic links, scandir '${e}'`);s.add(r),i=!0,r=this.resolveSymlink(r,o.target),o=this.memory.get(r)}if(o)return{normalized:r,outsideOverlay:!1};if(this.getRelativeToMount(r)===null)return{normalized:r,outsideOverlay:!0};let c=this.toRealPath(r);if(!c)return{normalized:r,outsideOverlay:!0};try{if((await M.promises.lstat(c)).isSymbolicLink()){let u=await M.promises.readlink(c),h=this.resolveSymlink(r,u);return this.resolveForReaddir(h,!0)}return{normalized:r,outsideOverlay:!1}}catch{return i?{normalized:r,outsideOverlay:!0}:{normalized:r,outsideOverlay:!1}}}async readdir(e){let{normalized:n,outsideOverlay:r}=await this.resolveForReaddir(e);if(r)return[];let s=await this.readdirCore(e,n);return Array.from(s.keys()).sort((i,o)=>i<o?-1:i>o?1:0)}async readdirWithFileTypes(e){let{normalized:n,outsideOverlay:r}=await this.resolveForReaddir(e);if(r)return[];let s=await this.readdirCore(e,n);return Array.from(s.values()).sort((i,o)=>i.name<o.name?-1:i.name>o.name?1:0)}async rm(e,n){this.assertWritable(`rm '${e}'`);let r=this.normalizePath(e);if(!await this.existsInOverlay(r)){if(n?.force)return;throw new Error(`ENOENT: no such file or directory, rm '${e}'`)}try{if((await this.stat(r)).isDirectory){let o=await this.readdir(r);if(o.length>0){if(!n?.recursive)throw new Error(`ENOTEMPTY: directory not empty, rm '${e}'`);for(let a of o){let c=r==="/"?`/${a}`:`${r}/${a}`;await this.rm(c,n)}}}}catch{}this.deleted.add(r),this.memory.delete(r)}async cp(e,n,r){this.assertWritable(`cp '${n}'`);let s=this.normalizePath(e),i=this.normalizePath(n);if(!await this.existsInOverlay(s))throw new Error(`ENOENT: no such file or directory, cp '${e}'`);let a=await this.stat(s);if(a.isFile){let c=await this.readFileBuffer(s);await this.writeFile(i,c)}else if(a.isDirectory){if(!r?.recursive)throw new Error(`EISDIR: is a directory, cp '${e}'`);await this.mkdir(i,{recursive:!0});let c=await this.readdir(s);for(let l of c){let u=s==="/"?`/${l}`:`${s}/${l}`,h=i==="/"?`/${l}`:`${i}/${l}`;await this.cp(u,h,r)}}}async mv(e,n){this.assertWritable(`mv '${n}'`),await this.cp(e,n,{recursive:!0}),await this.rm(e,{recursive:!0})}resolvePath(e,n){if(n.startsWith("/"))return this.normalizePath(n);let r=e==="/"?`/${n}`:`${e}/${n}`;return this.normalizePath(r)}getAllPaths(){let e=new Set(this.memory.keys());for(let n of this.deleted)e.delete(n);return this.scanRealFs("/",e),Array.from(e)}scanRealFs(e,n){if(this.deleted.has(e))return;let r=this.toRealPath(e);if(r)try{let s=M.readdirSync(r);for(let i of s){let o=e==="/"?`/${i}`:`${e}/${i}`;if(this.deleted.has(o))continue;n.add(o);let a=Le.join(r,i);M.statSync(a).isDirectory()&&this.scanRealFs(o,n)}}catch{}}async chmod(e,n){this.assertWritable(`chmod '${e}'`);let r=this.normalizePath(e);if(!await this.existsInOverlay(r))throw new Error(`ENOENT: no such file or directory, chmod '${e}'`);let i=this.memory.get(r);if(i){i.mode=n;return}let o=await this.stat(r);if(o.isFile){let a=await this.readFileBuffer(r);this.memory.set(r,{type:"file",content:a,mode:n,mtime:new Date})}else o.isDirectory&&this.memory.set(r,{type:"directory",mode:n,mtime:new Date})}async symlink(e,n){this.assertWritable(`symlink '${n}'`);let r=this.normalizePath(n);if(await this.existsInOverlay(r))throw new Error(`EEXIST: file already exists, symlink '${n}'`);this.ensureParentDirs(r),this.memory.set(r,{type:"symlink",target:e,mode:511,mtime:new Date}),this.deleted.delete(r)}async link(e,n){this.assertWritable(`link '${n}'`);let r=this.normalizePath(e),s=this.normalizePath(n);if(!await this.existsInOverlay(r))throw new Error(`ENOENT: no such file or directory, link '${e}'`);let o=await this.stat(r);if(!o.isFile)throw new Error(`EPERM: operation not permitted, link '${e}'`);if(await this.existsInOverlay(s))throw new Error(`EEXIST: file already exists, link '${n}'`);let c=await this.readFileBuffer(r);this.ensureParentDirs(s),this.memory.set(s,{type:"file",content:c,mode:o.mode,mtime:new Date}),this.deleted.delete(s)}async readlink(e){let n=this.normalizePath(e);if(this.deleted.has(n))throw new Error(`ENOENT: no such file or directory, readlink '${e}'`);let r=this.memory.get(n);if(r){if(r.type!=="symlink")throw new Error(`EINVAL: invalid argument, readlink '${e}'`);return r.target}let s=this.toRealPath(n);if(!s)throw new Error(`ENOENT: no such file or directory, readlink '${e}'`);try{return await M.promises.readlink(s)}catch(i){throw i.code==="ENOENT"?new Error(`ENOENT: no such file or directory, readlink '${e}'`):i.code==="EINVAL"?new Error(`EINVAL: invalid argument, readlink '${e}'`):i}}};import*as $ from"node:fs";import*as ee from"node:path";var bt=class{root;constructor(e){if(this.root=ee.resolve(e.root),!$.existsSync(this.root))throw new Error(`ReadWriteFs root does not exist: ${this.root}`);if(!$.statSync(this.root).isDirectory())throw new Error(`ReadWriteFs root is not a directory: ${this.root}`)}toRealPath(e){let n=this.normalizePath(e),r=ee.join(this.root,n);return ee.resolve(r)}normalizePath(e){if(!e||e==="/")return"/";let n=e.endsWith("/")&&e!=="/"?e.slice(0,-1):e;n.startsWith("/")||(n=`/${n}`);let r=n.split("/").filter(i=>i&&i!=="."),s=[];for(let i of r)i===".."?s.pop():s.push(i);return`/${s.join("/")}`||"/"}async readFile(e,n){let r=await this.readFileBuffer(e),s=q(n);return Ce(r,s)}async readFileBuffer(e){let n=this.toRealPath(e);try{let r=await $.promises.readFile(n);return new Uint8Array(r)}catch(r){let s=r;throw s.code==="ENOENT"?new Error(`ENOENT: no such file or directory, open '${e}'`):s.code==="EISDIR"?new Error(`EISDIR: illegal operation on a directory, read '${e}'`):r}}async writeFile(e,n,r){let s=this.toRealPath(e),i=q(r),o=re(n,i),a=ee.dirname(s);await $.promises.mkdir(a,{recursive:!0}),await $.promises.writeFile(s,o)}async appendFile(e,n,r){let s=this.toRealPath(e),i=q(r),o=re(n,i),a=ee.dirname(s);await $.promises.mkdir(a,{recursive:!0}),await $.promises.appendFile(s,o)}async exists(e){let n=this.toRealPath(e);try{return await $.promises.access(n),!0}catch{return!1}}async stat(e){let n=this.toRealPath(e);try{let r=await $.promises.stat(n);return{isFile:r.isFile(),isDirectory:r.isDirectory(),isSymbolicLink:!1,mode:r.mode,size:r.size,mtime:r.mtime}}catch(r){throw r.code==="ENOENT"?new Error(`ENOENT: no such file or directory, stat '${e}'`):r}}async lstat(e){let n=this.toRealPath(e);try{let r=await $.promises.lstat(n);return{isFile:r.isFile(),isDirectory:r.isDirectory(),isSymbolicLink:r.isSymbolicLink(),mode:r.mode,size:r.size,mtime:r.mtime}}catch(r){throw r.code==="ENOENT"?new Error(`ENOENT: no such file or directory, lstat '${e}'`):r}}async mkdir(e,n){let r=this.toRealPath(e);try{await $.promises.mkdir(r,{recursive:n?.recursive})}catch(s){let i=s;throw i.code==="EEXIST"?new Error(`EEXIST: file already exists, mkdir '${e}'`):i.code==="ENOENT"?new Error(`ENOENT: no such file or directory, mkdir '${e}'`):s}}async readdir(e){return(await this.readdirWithFileTypes(e)).map(r=>r.name)}async readdirWithFileTypes(e){let n=this.toRealPath(e);try{return(await $.promises.readdir(n,{withFileTypes:!0})).map(s=>({name:s.name,isFile:s.isFile(),isDirectory:s.isDirectory(),isSymbolicLink:s.isSymbolicLink()})).sort((s,i)=>s.name<i.name?-1:s.name>i.name?1:0)}catch(r){let s=r;throw s.code==="ENOENT"?new Error(`ENOENT: no such file or directory, scandir '${e}'`):s.code==="ENOTDIR"?new Error(`ENOTDIR: not a directory, scandir '${e}'`):r}}async rm(e,n){let r=this.toRealPath(e);try{await $.promises.rm(r,{recursive:n?.recursive??!1,force:n?.force??!1})}catch(s){let i=s;throw i.code==="ENOENT"&&!n?.force?new Error(`ENOENT: no such file or directory, rm '${e}'`):i.code==="ENOTEMPTY"?new Error(`ENOTEMPTY: directory not empty, rm '${e}'`):s}}async cp(e,n,r){let s=this.toRealPath(e),i=this.toRealPath(n);try{await $.promises.cp(s,i,{recursive:r?.recursive??!1})}catch(o){let a=o;throw a.code==="ENOENT"?new Error(`ENOENT: no such file or directory, cp '${e}'`):a.code==="EISDIR"?new Error(`EISDIR: is a directory, cp '${e}'`):o}}async mv(e,n){let r=this.toRealPath(e),s=this.toRealPath(n),i=ee.dirname(s);await $.promises.mkdir(i,{recursive:!0});try{await $.promises.rename(r,s)}catch(o){let a=o;if(a.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, mv '${e}'`);if(a.code==="EXDEV"){await this.cp(e,n,{recursive:!0}),await this.rm(e,{recursive:!0});return}throw o}}resolvePath(e,n){if(n.startsWith("/"))return this.normalizePath(n);let r=e==="/"?`/${n}`:`${e}/${n}`;return this.normalizePath(r)}getAllPaths(){let e=[];return this.scanDir("/",e),e}scanDir(e,n){let r=this.toRealPath(e);try{let s=$.readdirSync(r);for(let i of s){let o=e==="/"?`/${i}`:`${e}/${i}`;n.push(o);let a=ee.join(r,i);$.statSync(a).isDirectory()&&this.scanDir(o,n)}}catch{}}async chmod(e,n){let r=this.toRealPath(e);try{await $.promises.chmod(r,n)}catch(s){throw s.code==="ENOENT"?new Error(`ENOENT: no such file or directory, chmod '${e}'`):s}}async symlink(e,n){let r=this.toRealPath(n);try{await $.promises.symlink(e,r)}catch(s){throw s.code==="EEXIST"?new Error(`EEXIST: file already exists, symlink '${n}'`):s}}async link(e,n){let r=this.toRealPath(e),s=this.toRealPath(n);try{await $.promises.link(r,s)}catch(i){let o=i;throw o.code==="ENOENT"?new Error(`ENOENT: no such file or directory, link '${e}'`):o.code==="EEXIST"?new Error(`EEXIST: file already exists, link '${n}'`):o.code==="EPERM"?new Error(`EPERM: operation not permitted, link '${e}'`):i}}async readlink(e){let n=this.toRealPath(e);try{return await $.promises.readlink(n)}catch(r){let s=r;throw s.code==="ENOENT"?new Error(`ENOENT: no such file or directory, readlink '${e}'`):s.code==="EINVAL"?new Error(`EINVAL: invalid argument, readlink '${e}'`):r}}};var Fe=class{cmdId;cwd;startedAt;exitCode;bashEnv;cmdLine;env;explicitCwd;resultPromise;constructor(e,n,r,s,i=!1){this.cmdId=crypto.randomUUID(),this.cwd=r,this.startedAt=new Date,this.bashEnv=e,this.cmdLine=n,this.env=s,this.explicitCwd=i,this.resultPromise=this.execute()}async execute(){let e=this.env||this.explicitCwd?{cwd:this.explicitCwd?this.cwd:void 0,env:this.env}:void 0,n=await this.bashEnv.exec(this.cmdLine,e);return this.exitCode=n.exitCode,n}async*logs(){let e=await this.resultPromise;e.stdout&&(yield{type:"stdout",data:e.stdout,timestamp:new Date}),e.stderr&&(yield{type:"stderr",data:e.stderr,timestamp:new Date})}async wait(){return await this.resultPromise,this}async output(){let e=await this.resultPromise;return e.stdout+e.stderr}async stdout(){return(await this.resultPromise).stdout}async stderr(){return(await this.resultPromise).stderr}async kill(){}};var Ct=class t{bashEnv;constructor(e){this.bashEnv=e}static async create(e){let n=e?.fs;if(e?.overlayRoot){if(e?.fs)throw new Error("Cannot specify both 'fs' and 'overlayRoot' options");n=new Te({root:e.overlayRoot})}let r=new je({env:e?.env,cwd:e?.cwd,fs:n,maxCallDepth:e?.maxCallDepth,maxCommandCount:e?.maxCommandCount,maxLoopIterations:e?.maxLoopIterations,network:e?.network});return new t(r)}async runCommand(e,n){let r=n?.cwd??this.bashEnv.getCwd(),s=n?.cwd!==void 0;return new Fe(this.bashEnv,e,r,n?.env,s)}async writeFiles(e){for(let[n,r]of Object.entries(e)){let s;typeof r=="string"?s=r:r.encoding==="base64"?s=Buffer.from(r.content,"base64").toString("utf-8"):s=r.content;let i=n.substring(0,n.lastIndexOf("/"))||"/";i!=="/"&&await this.bashEnv.exec(`mkdir -p ${i}`),await this.bashEnv.writeFile(n,s)}}async readFile(e,n){let r=await this.bashEnv.readFile(e);return n==="base64"?Buffer.from(r).toString("base64"):r}async mkDir(e,n){let r=n?.recursive?"-p":"";await this.bashEnv.exec(`mkdir ${r} ${e}`)}async stop(){}async extendTimeout(e){}get domain(){}get bashEnvInstance(){return this.bashEnv}};export{je as Bash,ne as InMemoryFs,xt as MountableFs,De as NetworkAccessDeniedError,Te as OverlayFs,bt as ReadWriteFs,_e as RedirectNotAllowedError,Ct as Sandbox,Fe as SandboxCommand,Oe as TooManyRedirectsError,Zn as defineCommand,jn as getCommandNames,qn as getNetworkCommandNames};
|
|
150
|
+
`));try{let i=he(o),a={fs:this.fs,commands:this.commands,limits:this.limits,exec:this.exec.bind(this),fetch:this.secureFetch,sleep:this.sleepFn,trace:this.traceFn},l=await new He(a,n).executeScript(i);return this.logResult(l)}catch(i){if(i instanceof R)return this.logResult({stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode,env:{...this.state.env,...s?.env}});if(i instanceof W)return this.logResult({stdout:i.stdout,stderr:i.stderr,exitCode:1,env:{...this.state.env,...s?.env}});if(i instanceof B)return this.logResult({stdout:i.stdout,stderr:i.stderr,exitCode:B.EXIT_CODE,env:{...this.state.env,...s?.env}});if(i.name==="ParseException")return this.logResult({stdout:"",stderr:`bash: syntax error: ${i.message}
|
|
151
|
+
`,exitCode:2,env:{...this.state.env,...s?.env}});if(i instanceof RangeError)return this.logResult({stdout:"",stderr:`bash: ${i.message}
|
|
152
|
+
`,exitCode:1,env:{...this.state.env,...s?.env}});throw i}}async readFile(e){return this.fs.readFile(this.fs.resolvePath(this.state.cwd,e))}async writeFile(e,s){return this.fs.writeFile(this.fs.resolvePath(this.state.cwd,e),s)}getCwd(){return this.state.cwd}getEnv(){return{...this.state.env}}};var xt=class{baseFs;mounts=new Map;constructor(e){if(this.baseFs=e?.base??new se,e?.mounts)for(let{mountPoint:s,filesystem:r}of e.mounts)this.mount(s,r)}mount(e,s){this.validateMountPath(e);let r=this.normalizePath(e);this.validateMount(r),this.mounts.set(r,{mountPoint:r,filesystem:s})}unmount(e){let s=this.normalizePath(e);if(!this.mounts.has(s))throw new Error(`No filesystem mounted at '${e}'`);this.mounts.delete(s)}getMounts(){return Array.from(this.mounts.values()).map(e=>({mountPoint:e.mountPoint,filesystem:e.filesystem}))}isMountPoint(e){let s=this.normalizePath(e);return this.mounts.has(s)}validateMountPath(e){let s=e.split("/");for(let r of s)if(r==="."||r==="..")throw new Error(`Invalid mount point '${e}': contains '.' or '..' segments`)}validateMount(e){if(e==="/")throw new Error("Cannot mount at root '/'");for(let s of this.mounts.keys())if(s!==e){if(e.startsWith(`${s}/`))throw new Error(`Cannot mount at '${e}': inside existing mount '${s}'`);if(s.startsWith(`${e}/`))throw new Error(`Cannot mount at '${e}': would contain existing mount '${s}'`)}}normalizePath(e){if(!e||e==="/")return"/";let s=e.endsWith("/")&&e!=="/"?e.slice(0,-1):e;s.startsWith("/")||(s=`/${s}`);let r=s.split("/").filter(o=>o&&o!=="."),n=[];for(let o of r)o===".."?n.pop():n.push(o);return`/${n.join("/")}`}routePath(e){let s=this.normalizePath(e),r=null,n=0;for(let o of this.mounts.values()){let i=o.mountPoint;if(s===i)return{fs:o.filesystem,relativePath:"/"};s.startsWith(`${i}/`)&&i.length>n&&(r=o,n=i.length)}if(r){let o=s.slice(n);return{fs:r.filesystem,relativePath:o||"/"}}return{fs:this.baseFs,relativePath:s}}getChildMountPoints(e){let s=this.normalizePath(e),r=s==="/"?"/":`${s}/`,n=[];for(let o of this.mounts.keys())if(o.startsWith(r)){let a=o.slice(r.length).split("/")[0];a&&!n.includes(a)&&n.push(a)}return n}async readFile(e,s){let{fs:r,relativePath:n}=this.routePath(e);return r.readFile(n,s)}async readFileBuffer(e){let{fs:s,relativePath:r}=this.routePath(e);return s.readFileBuffer(r)}async writeFile(e,s,r){let{fs:n,relativePath:o}=this.routePath(e);return n.writeFile(o,s,r)}async appendFile(e,s,r){let{fs:n,relativePath:o}=this.routePath(e);return n.appendFile(o,s,r)}async exists(e){let s=this.normalizePath(e);if(this.mounts.has(s)||this.getChildMountPoints(s).length>0)return!0;let{fs:n,relativePath:o}=this.routePath(e);return n.exists(o)}async stat(e){let s=this.normalizePath(e),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:o,relativePath:i}=this.routePath(e);return o.stat(i)}async lstat(e){let s=this.normalizePath(e),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:o,relativePath:i}=this.routePath(e);return o.lstat(i)}async mkdir(e,s){let r=this.normalizePath(e);if(this.mounts.has(r)){if(s?.recursive)return;throw new Error(`EEXIST: directory already exists, mkdir '${e}'`)}if(this.getChildMountPoints(r).length>0&&s?.recursive)return;let{fs:o,relativePath:i}=this.routePath(e);return o.mkdir(i,s)}async readdir(e){let s=this.normalizePath(e),r=new Set,n=null,{fs:o,relativePath:i}=this.routePath(e);try{let c=await o.readdir(i);for(let l of c)r.add(l)}catch(c){let l=c.code,f=c.message||"";if(l!=="ENOENT"&&!f.includes("ENOENT"))throw c;n=c}let a=this.getChildMountPoints(s);for(let c of a)r.add(c);if(r.size===0&&n&&!this.mounts.has(s))throw n;return Array.from(r).sort()}async rm(e,s){let r=this.normalizePath(e);if(this.mounts.has(r))throw new Error(`EBUSY: mount point, cannot remove '${e}'`);if(this.getChildMountPoints(r).length>0)throw new Error(`EBUSY: contains mount points, cannot remove '${e}'`);let{fs:o,relativePath:i}=this.routePath(e);return o.rm(i,s)}async cp(e,s,r){let n=this.routePath(e),o=this.routePath(s);return n.fs===o.fs?n.fs.cp(n.relativePath,o.relativePath,r):this.crossMountCopy(e,s,r)}async mv(e,s){let r=this.normalizePath(e);if(this.mounts.has(r))throw new Error(`EBUSY: mount point, cannot move '${e}'`);let n=this.routePath(e),o=this.routePath(s);if(n.fs===o.fs)return n.fs.mv(n.relativePath,o.relativePath);await this.cp(e,s,{recursive:!0}),await this.rm(e,{recursive:!0})}resolvePath(e,s){if(s.startsWith("/"))return this.normalizePath(s);let r=e==="/"?`/${s}`:`${e}/${s}`;return this.normalizePath(r)}getAllPaths(){let e=new Set;for(let s of this.baseFs.getAllPaths())e.add(s);for(let s of this.mounts.keys()){let r=s.split("/").filter(Boolean),n="";for(let i of r)n=`${n}/${i}`,e.add(n);let o=this.mounts.get(s);if(o)for(let i of o.filesystem.getAllPaths())i==="/"?e.add(s):e.add(`${s}${i}`)}return Array.from(e).sort()}async chmod(e,s){let r=this.normalizePath(e),n=this.mounts.get(r);if(n)return n.filesystem.chmod("/",s);let{fs:o,relativePath:i}=this.routePath(e);return o.chmod(i,s)}async symlink(e,s){let{fs:r,relativePath:n}=this.routePath(s);return r.symlink(e,n)}async link(e,s){let r=this.routePath(e),n=this.routePath(s);if(r.fs!==n.fs)throw new Error(`EXDEV: cross-device link not permitted, link '${e}' -> '${s}'`);return r.fs.link(r.relativePath,n.relativePath)}async readlink(e){let{fs:s,relativePath:r}=this.routePath(e);return s.readlink(r)}async crossMountCopy(e,s,r){let n=await this.lstat(e);if(n.isFile){let o=await this.readFileBuffer(e);await this.writeFile(s,o),await this.chmod(s,n.mode)}else if(n.isDirectory){if(!r?.recursive)throw new Error(`cp: ${e} is a directory (not copied)`);await this.mkdir(s,{recursive:!0});let o=await this.readdir(e);for(let i of o){let a=e==="/"?`/${i}`:`${e}/${i}`,c=s==="/"?`/${i}`:`${s}/${i}`;await this.crossMountCopy(a,c,r)}}else if(n.isSymbolicLink){let o=await this.readlink(e);await this.symlink(o,s)}}};import*as M from"node:fs";import*as Le from"node:path";var fi="/home/user/project",Te=class{root;mountPoint;readOnly;memory=new Map;deleted=new Set;constructor(e){this.root=Le.resolve(e.root);let s=e.mountPoint??fi;if(this.mountPoint=s==="/"?"/":s.replace(/\/+$/,""),!this.mountPoint.startsWith("/"))throw new Error(`Mount point must be an absolute path: ${s}`);if(this.readOnly=e.readOnly??!1,!M.existsSync(this.root))throw new Error(`OverlayFs root does not exist: ${this.root}`);if(!M.statSync(this.root).isDirectory())throw new Error(`OverlayFs root is not a directory: ${this.root}`);this.createMountPointDirs()}assertWritable(e){if(this.readOnly)throw new Error(`EROFS: read-only file system, ${e}`)}createMountPointDirs(){let e=this.mountPoint.split("/").filter(Boolean),s="";for(let r of e)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(e,s){let n=this.normalizePath(e).split("/").filter(Boolean),o="";for(let i of n)o+=`/${i}`,this.memory.has(o)||this.memory.set(o,{type:"directory",mode:493,mtime:new Date})}writeFileSync(e,s){let r=this.normalizePath(e),n=this.getDirname(r);n!=="/"&&this.mkdirSync(n);let o=s instanceof Uint8Array?s:new TextEncoder().encode(s);this.memory.set(r,{type:"file",content:o,mode:420,mtime:new Date})}getDirname(e){let s=e.lastIndexOf("/");return s===0?"/":e.slice(0,s)}normalizePath(e){if(!e||e==="/")return"/";let s=e.endsWith("/")&&e!=="/"?e.slice(0,-1):e;s.startsWith("/")||(s=`/${s}`);let r=s.split("/").filter(o=>o&&o!=="."),n=[];for(let o of r)o===".."?n.pop():n.push(o);return`/${n.join("/")}`||"/"}getRelativeToMount(e){return this.mountPoint==="/"?e:e===this.mountPoint?"/":e.startsWith(`${this.mountPoint}/`)?e.slice(this.mountPoint.length):null}toRealPath(e){let s=this.normalizePath(e),r=this.getRelativeToMount(s);if(r===null)return null;let n=Le.join(this.root,r),o=Le.resolve(n);return!o.startsWith(this.root)&&o!==this.root.replace(/\/$/,"")?null:o}dirname(e){let s=this.normalizePath(e);if(s==="/")return"/";let r=s.lastIndexOf("/");return r===0?"/":s.slice(0,r)}ensureParentDirs(e){let s=this.dirname(e);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(e){let s=this.normalizePath(e);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 M.promises.access(r),!0}catch{return!1}}async readFile(e,s){let r=await this.readFileBuffer(e),n=q(s);return Ce(r,n)}async readFileBuffer(e,s=new Set){let r=this.normalizePath(e);if(s.has(r))throw new Error(`ELOOP: too many levels of symbolic links, open '${e}'`);if(s.add(r),this.deleted.has(r))throw new Error(`ENOENT: no such file or directory, open '${e}'`);let n=this.memory.get(r);if(n){if(n.type==="symlink"){let i=this.resolveSymlink(r,n.target);return this.readFileBuffer(i,s)}if(n.type!=="file")throw new Error(`EISDIR: illegal operation on a directory, read '${e}'`);return n.content}let o=this.toRealPath(r);if(!o)throw new Error(`ENOENT: no such file or directory, open '${e}'`);try{let i=await M.promises.lstat(o);if(i.isSymbolicLink()){let c=await M.promises.readlink(o),l=this.resolveSymlink(r,c);return this.readFileBuffer(l,s)}if(i.isDirectory())throw new Error(`EISDIR: illegal operation on a directory, read '${e}'`);let a=await M.promises.readFile(o);return new Uint8Array(a)}catch(i){throw i.code==="ENOENT"?new Error(`ENOENT: no such file or directory, open '${e}'`):i}}async writeFile(e,s,r){this.assertWritable(`write '${e}'`);let n=this.normalizePath(e);this.ensureParentDirs(n);let o=q(r),i=re(s,o);this.memory.set(n,{type:"file",content:i,mode:420,mtime:new Date}),this.deleted.delete(n)}async appendFile(e,s,r){this.assertWritable(`append '${e}'`);let n=this.normalizePath(e),o=q(r),i=re(s,o),a;try{a=await this.readFileBuffer(n)}catch{a=new Uint8Array(0)}let c=new Uint8Array(a.length+i.length);c.set(a),c.set(i,a.length),this.ensureParentDirs(n),this.memory.set(n,{type:"file",content:c,mode:420,mtime:new Date}),this.deleted.delete(n)}async exists(e){return this.existsInOverlay(e)}async stat(e,s=new Set){let r=this.normalizePath(e);if(s.has(r))throw new Error(`ELOOP: too many levels of symbolic links, stat '${e}'`);if(s.add(r),this.deleted.has(r))throw new Error(`ENOENT: no such file or directory, stat '${e}'`);let n=this.memory.get(r);if(n){if(n.type==="symlink"){let a=this.resolveSymlink(r,n.target);return this.stat(a,s)}let i=0;return n.type==="file"&&(i=n.content.length),{isFile:n.type==="file",isDirectory:n.type==="directory",isSymbolicLink:!1,mode:n.mode,size:i,mtime:n.mtime}}let o=this.toRealPath(r);if(!o)throw new Error(`ENOENT: no such file or directory, stat '${e}'`);try{let i=await M.promises.stat(o);return{isFile:i.isFile(),isDirectory:i.isDirectory(),isSymbolicLink:!1,mode:i.mode,size:i.size,mtime:i.mtime}}catch(i){throw i.code==="ENOENT"?new Error(`ENOENT: no such file or directory, stat '${e}'`):i}}async lstat(e){let s=this.normalizePath(e);if(this.deleted.has(s))throw new Error(`ENOENT: no such file or directory, lstat '${e}'`);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 o=0;return r.type==="file"&&(o=r.content.length),{isFile:r.type==="file",isDirectory:r.type==="directory",isSymbolicLink:!1,mode:r.mode,size:o,mtime:r.mtime}}let n=this.toRealPath(s);if(!n)throw new Error(`ENOENT: no such file or directory, lstat '${e}'`);try{let o=await M.promises.lstat(n);return{isFile:o.isFile(),isDirectory:o.isDirectory(),isSymbolicLink:o.isSymbolicLink(),mode:o.mode,size:o.size,mtime:o.mtime}}catch(o){throw o.code==="ENOENT"?new Error(`ENOENT: no such file or directory, lstat '${e}'`):o}}resolveSymlink(e,s){if(s.startsWith("/"))return this.normalizePath(s);let r=this.dirname(e);return this.normalizePath(r==="/"?`/${s}`:`${r}/${s}`)}async mkdir(e,s){this.assertWritable(`mkdir '${e}'`);let r=this.normalizePath(e);if(await this.existsInOverlay(r)){if(!s?.recursive)throw new Error(`EEXIST: file already exists, mkdir '${e}'`);return}let o=this.dirname(r);if(o!=="/"&&!await this.existsInOverlay(o))if(s?.recursive)await this.mkdir(o,{recursive:!0});else throw new Error(`ENOENT: no such file or directory, mkdir '${e}'`);this.memory.set(r,{type:"directory",mode:493,mtime:new Date}),this.deleted.delete(r)}async readdirCore(e,s){if(this.deleted.has(s))throw new Error(`ENOENT: no such file or directory, scandir '${e}'`);let r=new Map,n=new Set,o=s==="/"?"/":`${s}/`;for(let a of this.deleted)if(a.startsWith(o)){let c=a.slice(o.length),l=c.split("/")[0];l&&!c.includes("/",l.length)&&n.add(l)}for(let[a,c]of this.memory)if(a!==s&&a.startsWith(o)){let l=a.slice(o.length),f=l.split("/")[0];f&&!n.has(f)&&!l.includes("/",1)&&r.set(f,{name:f,isFile:c.type==="file",isDirectory:c.type==="directory",isSymbolicLink:c.type==="symlink"})}let i=this.toRealPath(s);if(i)try{let a=await M.promises.readdir(i,{withFileTypes:!0});for(let c of a)!n.has(c.name)&&!r.has(c.name)&&r.set(c.name,{name:c.name,isFile:c.isFile(),isDirectory:c.isDirectory(),isSymbolicLink:c.isSymbolicLink()})}catch(a){if(a.code==="ENOENT"){if(!this.memory.has(s))throw new Error(`ENOENT: no such file or directory, scandir '${e}'`)}else if(a.code!=="ENOTDIR")throw a}return r}async resolveForReaddir(e,s=!1){let r=this.normalizePath(e),n=new Set,o=s,i=this.memory.get(r);for(;i&&i.type==="symlink";){if(n.has(r))throw new Error(`ELOOP: too many levels of symbolic links, scandir '${e}'`);n.add(r),o=!0,r=this.resolveSymlink(r,i.target),i=this.memory.get(r)}if(i)return{normalized:r,outsideOverlay:!1};if(this.getRelativeToMount(r)===null)return{normalized:r,outsideOverlay:!0};let c=this.toRealPath(r);if(!c)return{normalized:r,outsideOverlay:!0};try{if((await M.promises.lstat(c)).isSymbolicLink()){let f=await M.promises.readlink(c),h=this.resolveSymlink(r,f);return this.resolveForReaddir(h,!0)}return{normalized:r,outsideOverlay:!1}}catch{return o?{normalized:r,outsideOverlay:!0}:{normalized:r,outsideOverlay:!1}}}async readdir(e){let{normalized:s,outsideOverlay:r}=await this.resolveForReaddir(e);if(r)return[];let n=await this.readdirCore(e,s);return Array.from(n.keys()).sort((o,i)=>o<i?-1:o>i?1:0)}async readdirWithFileTypes(e){let{normalized:s,outsideOverlay:r}=await this.resolveForReaddir(e);if(r)return[];let n=await this.readdirCore(e,s);return Array.from(n.values()).sort((o,i)=>o.name<i.name?-1:o.name>i.name?1:0)}async rm(e,s){this.assertWritable(`rm '${e}'`);let r=this.normalizePath(e);if(!await this.existsInOverlay(r)){if(s?.force)return;throw new Error(`ENOENT: no such file or directory, rm '${e}'`)}try{if((await this.stat(r)).isDirectory){let i=await this.readdir(r);if(i.length>0){if(!s?.recursive)throw new Error(`ENOTEMPTY: directory not empty, rm '${e}'`);for(let a of i){let c=r==="/"?`/${a}`:`${r}/${a}`;await this.rm(c,s)}}}}catch{}this.deleted.add(r),this.memory.delete(r)}async cp(e,s,r){this.assertWritable(`cp '${s}'`);let n=this.normalizePath(e),o=this.normalizePath(s);if(!await this.existsInOverlay(n))throw new Error(`ENOENT: no such file or directory, cp '${e}'`);let a=await this.stat(n);if(a.isFile){let c=await this.readFileBuffer(n);await this.writeFile(o,c)}else if(a.isDirectory){if(!r?.recursive)throw new Error(`EISDIR: is a directory, cp '${e}'`);await this.mkdir(o,{recursive:!0});let c=await this.readdir(n);for(let l of c){let f=n==="/"?`/${l}`:`${n}/${l}`,h=o==="/"?`/${l}`:`${o}/${l}`;await this.cp(f,h,r)}}}async mv(e,s){this.assertWritable(`mv '${s}'`),await this.cp(e,s,{recursive:!0}),await this.rm(e,{recursive:!0})}resolvePath(e,s){if(s.startsWith("/"))return this.normalizePath(s);let r=e==="/"?`/${s}`:`${e}/${s}`;return this.normalizePath(r)}getAllPaths(){let e=new Set(this.memory.keys());for(let s of this.deleted)e.delete(s);return this.scanRealFs("/",e),Array.from(e)}scanRealFs(e,s){if(this.deleted.has(e))return;let r=this.toRealPath(e);if(r)try{let n=M.readdirSync(r);for(let o of n){let i=e==="/"?`/${o}`:`${e}/${o}`;if(this.deleted.has(i))continue;s.add(i);let a=Le.join(r,o);M.statSync(a).isDirectory()&&this.scanRealFs(i,s)}}catch{}}async chmod(e,s){this.assertWritable(`chmod '${e}'`);let r=this.normalizePath(e);if(!await this.existsInOverlay(r))throw new Error(`ENOENT: no such file or directory, chmod '${e}'`);let o=this.memory.get(r);if(o){o.mode=s;return}let i=await this.stat(r);if(i.isFile){let a=await this.readFileBuffer(r);this.memory.set(r,{type:"file",content:a,mode:s,mtime:new Date})}else i.isDirectory&&this.memory.set(r,{type:"directory",mode:s,mtime:new Date})}async symlink(e,s){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:e,mode:511,mtime:new Date}),this.deleted.delete(r)}async link(e,s){this.assertWritable(`link '${s}'`);let r=this.normalizePath(e),n=this.normalizePath(s);if(!await this.existsInOverlay(r))throw new Error(`ENOENT: no such file or directory, link '${e}'`);let i=await this.stat(r);if(!i.isFile)throw new Error(`EPERM: operation not permitted, link '${e}'`);if(await this.existsInOverlay(n))throw new Error(`EEXIST: file already exists, link '${s}'`);let c=await this.readFileBuffer(r);this.ensureParentDirs(n),this.memory.set(n,{type:"file",content:c,mode:i.mode,mtime:new Date}),this.deleted.delete(n)}async readlink(e){let s=this.normalizePath(e);if(this.deleted.has(s))throw new Error(`ENOENT: no such file or directory, readlink '${e}'`);let r=this.memory.get(s);if(r){if(r.type!=="symlink")throw new Error(`EINVAL: invalid argument, readlink '${e}'`);return r.target}let n=this.toRealPath(s);if(!n)throw new Error(`ENOENT: no such file or directory, readlink '${e}'`);try{return await M.promises.readlink(n)}catch(o){throw o.code==="ENOENT"?new Error(`ENOENT: no such file or directory, readlink '${e}'`):o.code==="EINVAL"?new Error(`EINVAL: invalid argument, readlink '${e}'`):o}}};import*as $ from"node:fs";import*as ee from"node:path";var bt=class{root;constructor(e){if(this.root=ee.resolve(e.root),!$.existsSync(this.root))throw new Error(`ReadWriteFs root does not exist: ${this.root}`);if(!$.statSync(this.root).isDirectory())throw new Error(`ReadWriteFs root is not a directory: ${this.root}`)}toRealPath(e){let s=this.normalizePath(e),r=ee.join(this.root,s);return ee.resolve(r)}normalizePath(e){if(!e||e==="/")return"/";let s=e.endsWith("/")&&e!=="/"?e.slice(0,-1):e;s.startsWith("/")||(s=`/${s}`);let r=s.split("/").filter(o=>o&&o!=="."),n=[];for(let o of r)o===".."?n.pop():n.push(o);return`/${n.join("/")}`||"/"}async readFile(e,s){let r=await this.readFileBuffer(e),n=q(s);return Ce(r,n)}async readFileBuffer(e){let s=this.toRealPath(e);try{let r=await $.promises.readFile(s);return new Uint8Array(r)}catch(r){let n=r;throw n.code==="ENOENT"?new Error(`ENOENT: no such file or directory, open '${e}'`):n.code==="EISDIR"?new Error(`EISDIR: illegal operation on a directory, read '${e}'`):r}}async writeFile(e,s,r){let n=this.toRealPath(e),o=q(r),i=re(s,o),a=ee.dirname(n);await $.promises.mkdir(a,{recursive:!0}),await $.promises.writeFile(n,i)}async appendFile(e,s,r){let n=this.toRealPath(e),o=q(r),i=re(s,o),a=ee.dirname(n);await $.promises.mkdir(a,{recursive:!0}),await $.promises.appendFile(n,i)}async exists(e){let s=this.toRealPath(e);try{return await $.promises.access(s),!0}catch{return!1}}async stat(e){let s=this.toRealPath(e);try{let r=await $.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 '${e}'`):r}}async lstat(e){let s=this.toRealPath(e);try{let r=await $.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 '${e}'`):r}}async mkdir(e,s){let r=this.toRealPath(e);try{await $.promises.mkdir(r,{recursive:s?.recursive})}catch(n){let o=n;throw o.code==="EEXIST"?new Error(`EEXIST: file already exists, mkdir '${e}'`):o.code==="ENOENT"?new Error(`ENOENT: no such file or directory, mkdir '${e}'`):n}}async readdir(e){return(await this.readdirWithFileTypes(e)).map(r=>r.name)}async readdirWithFileTypes(e){let s=this.toRealPath(e);try{return(await $.promises.readdir(s,{withFileTypes:!0})).map(n=>({name:n.name,isFile:n.isFile(),isDirectory:n.isDirectory(),isSymbolicLink:n.isSymbolicLink()})).sort((n,o)=>n.name<o.name?-1:n.name>o.name?1:0)}catch(r){let n=r;throw n.code==="ENOENT"?new Error(`ENOENT: no such file or directory, scandir '${e}'`):n.code==="ENOTDIR"?new Error(`ENOTDIR: not a directory, scandir '${e}'`):r}}async rm(e,s){let r=this.toRealPath(e);try{await $.promises.rm(r,{recursive:s?.recursive??!1,force:s?.force??!1})}catch(n){let o=n;throw o.code==="ENOENT"&&!s?.force?new Error(`ENOENT: no such file or directory, rm '${e}'`):o.code==="ENOTEMPTY"?new Error(`ENOTEMPTY: directory not empty, rm '${e}'`):n}}async cp(e,s,r){let n=this.toRealPath(e),o=this.toRealPath(s);try{await $.promises.cp(n,o,{recursive:r?.recursive??!1})}catch(i){let a=i;throw a.code==="ENOENT"?new Error(`ENOENT: no such file or directory, cp '${e}'`):a.code==="EISDIR"?new Error(`EISDIR: is a directory, cp '${e}'`):i}}async mv(e,s){let r=this.toRealPath(e),n=this.toRealPath(s),o=ee.dirname(n);await $.promises.mkdir(o,{recursive:!0});try{await $.promises.rename(r,n)}catch(i){let a=i;if(a.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, mv '${e}'`);if(a.code==="EXDEV"){await this.cp(e,s,{recursive:!0}),await this.rm(e,{recursive:!0});return}throw i}}resolvePath(e,s){if(s.startsWith("/"))return this.normalizePath(s);let r=e==="/"?`/${s}`:`${e}/${s}`;return this.normalizePath(r)}getAllPaths(){let e=[];return this.scanDir("/",e),e}scanDir(e,s){let r=this.toRealPath(e);try{let n=$.readdirSync(r);for(let o of n){let i=e==="/"?`/${o}`:`${e}/${o}`;s.push(i);let a=ee.join(r,o);$.statSync(a).isDirectory()&&this.scanDir(i,s)}}catch{}}async chmod(e,s){let r=this.toRealPath(e);try{await $.promises.chmod(r,s)}catch(n){throw n.code==="ENOENT"?new Error(`ENOENT: no such file or directory, chmod '${e}'`):n}}async symlink(e,s){let r=this.toRealPath(s);try{await $.promises.symlink(e,r)}catch(n){throw n.code==="EEXIST"?new Error(`EEXIST: file already exists, symlink '${s}'`):n}}async link(e,s){let r=this.toRealPath(e),n=this.toRealPath(s);try{await $.promises.link(r,n)}catch(o){let i=o;throw i.code==="ENOENT"?new Error(`ENOENT: no such file or directory, link '${e}'`):i.code==="EEXIST"?new Error(`EEXIST: file already exists, link '${s}'`):i.code==="EPERM"?new Error(`EPERM: operation not permitted, link '${e}'`):o}}async readlink(e){let s=this.toRealPath(e);try{return await $.promises.readlink(s)}catch(r){let n=r;throw n.code==="ENOENT"?new Error(`ENOENT: no such file or directory, readlink '${e}'`):n.code==="EINVAL"?new Error(`EINVAL: invalid argument, readlink '${e}'`):r}}};var Fe=class{cmdId;cwd;startedAt;exitCode;bashEnv;cmdLine;env;explicitCwd;resultPromise;constructor(e,s,r,n,o=!1){this.cmdId=crypto.randomUUID(),this.cwd=r,this.startedAt=new Date,this.bashEnv=e,this.cmdLine=s,this.env=n,this.explicitCwd=o,this.resultPromise=this.execute()}async execute(){let e=this.env||this.explicitCwd?{cwd:this.explicitCwd?this.cwd:void 0,env:this.env}:void 0,s=await this.bashEnv.exec(this.cmdLine,e);return this.exitCode=s.exitCode,s}async*logs(){let e=await this.resultPromise;e.stdout&&(yield{type:"stdout",data:e.stdout,timestamp:new Date}),e.stderr&&(yield{type:"stderr",data:e.stderr,timestamp:new Date})}async wait(){return await this.resultPromise,this}async output(){let e=await this.resultPromise;return e.stdout+e.stderr}async stdout(){return(await this.resultPromise).stdout}async stderr(){return(await this.resultPromise).stderr}async kill(){}};var Ct=class t{bashEnv;constructor(e){this.bashEnv=e}static async create(e){let s=e?.fs;if(e?.overlayRoot){if(e?.fs)throw new Error("Cannot specify both 'fs' and 'overlayRoot' options");s=new Te({root:e.overlayRoot})}let r=new je({env:e?.env,cwd:e?.cwd,fs:s,maxCallDepth:e?.maxCallDepth,maxCommandCount:e?.maxCommandCount,maxLoopIterations:e?.maxLoopIterations,network:e?.network});return new t(r)}async runCommand(e,s){let r=s?.cwd??this.bashEnv.getCwd(),n=s?.cwd!==void 0;return new Fe(this.bashEnv,e,r,s?.env,n)}async writeFiles(e){for(let[s,r]of Object.entries(e)){let n;typeof r=="string"?n=r:r.encoding==="base64"?n=Buffer.from(r.content,"base64").toString("utf-8"):n=r.content;let o=s.substring(0,s.lastIndexOf("/"))||"/";o!=="/"&&await this.bashEnv.exec(`mkdir -p ${o}`),await this.bashEnv.writeFile(s,n)}}async readFile(e,s){let r=await this.bashEnv.readFile(e);return s==="base64"?Buffer.from(r).toString("base64"):r}async mkDir(e,s){let r=s?.recursive?"-p":"";await this.bashEnv.exec(`mkdir ${r} ${e}`)}async stop(){}async extendTimeout(e){}get domain(){}get bashEnvInstance(){return this.bashEnv}};export{je as Bash,se as InMemoryFs,xt as MountableFs,De as NetworkAccessDeniedError,Te as OverlayFs,bt as ReadWriteFs,_e as RedirectNotAllowedError,Ct as Sandbox,Fe as SandboxCommand,Oe as TooManyRedirectsError,qs as defineCommand,Hs as getCommandNames,js as getNetworkCommandNames};
|