just-bash 2.4.4 → 2.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +42 -4
- package/dist/AGENTS.md +2 -2
- package/dist/bin/chunks/base64-O7TCK5TL.js +6 -0
- package/dist/bin/{shell/chunks/cat-ZEMMQGY5.js → chunks/cat-AJXZOSPN.js} +1 -1
- package/dist/bin/chunks/{chunk-45SNFRCY.js → chunk-5WFYIUU2.js} +2 -2
- package/dist/bin/chunks/chunk-CTLU5QUH.js +17 -0
- package/dist/bin/{shell/chunks/chunk-GX4MPCG6.js → chunks/chunk-Y5QKO4KO.js} +5 -5
- package/dist/bin/chunks/{cut-WWPJ2PYT.js → cut-IHF6BEOO.js} +1 -1
- package/dist/bin/chunks/grep-QCXXYC54.js +9 -0
- package/dist/bin/{shell/chunks/gzip-MNCJB6OR.js → chunks/gzip-YXK3WZQL.js} +22 -22
- package/dist/bin/{shell/chunks/jq-XH2PXRWE.js → chunks/jq-XXZPU5CA.js} +1 -1
- package/dist/bin/chunks/{md5sum-VGXAOUBA.js → md5sum-2VAAFCTS.js} +1 -1
- package/dist/bin/chunks/rg-GVIT6FTE.js +33 -0
- package/dist/bin/chunks/{sha1sum-BIUH233Z.js → sha1sum-67P4ME4N.js} +1 -1
- package/dist/bin/{shell/chunks/sha256sum-SUIK2MT2.js → chunks/sha256sum-MV3WQ4QF.js} +1 -1
- package/dist/bin/{shell/chunks/sort-C3F6LCNY.js → chunks/sort-KUHOCH5S.js} +1 -1
- package/dist/bin/chunks/tar-C27YYUAS.js +63 -0
- package/dist/bin/{shell/chunks/uniq-DKS7RIAE.js → chunks/uniq-IXHB2FVS.js} +1 -1
- package/dist/bin/chunks/{wc-4LMTC3QD.js → wc-QSBRKIF5.js} +1 -1
- package/dist/bin/chunks/{xan-WNN2ZOAX.js → xan-6K2NGTHM.js} +1 -1
- package/dist/bin/just-bash.js +78 -78
- package/dist/bin/shell/chunks/base64-O7TCK5TL.js +6 -0
- package/dist/bin/{chunks/cat-ZEMMQGY5.js → shell/chunks/cat-AJXZOSPN.js} +1 -1
- package/dist/bin/shell/chunks/{chunk-45SNFRCY.js → chunk-5WFYIUU2.js} +2 -2
- package/dist/bin/shell/chunks/chunk-CTLU5QUH.js +17 -0
- package/dist/bin/{chunks/chunk-GX4MPCG6.js → shell/chunks/chunk-Y5QKO4KO.js} +5 -5
- package/dist/bin/shell/chunks/{cut-WWPJ2PYT.js → cut-IHF6BEOO.js} +1 -1
- package/dist/bin/shell/chunks/grep-QCXXYC54.js +9 -0
- package/dist/bin/{chunks/gzip-MNCJB6OR.js → shell/chunks/gzip-YXK3WZQL.js} +22 -22
- package/dist/bin/{chunks/jq-XH2PXRWE.js → shell/chunks/jq-XXZPU5CA.js} +1 -1
- package/dist/bin/shell/chunks/{md5sum-VGXAOUBA.js → md5sum-2VAAFCTS.js} +1 -1
- package/dist/bin/shell/chunks/rg-GVIT6FTE.js +33 -0
- package/dist/bin/shell/chunks/{sha1sum-BIUH233Z.js → sha1sum-67P4ME4N.js} +1 -1
- package/dist/bin/{chunks/sha256sum-SUIK2MT2.js → shell/chunks/sha256sum-MV3WQ4QF.js} +1 -1
- package/dist/bin/{chunks/sort-C3F6LCNY.js → shell/chunks/sort-KUHOCH5S.js} +1 -1
- package/dist/bin/shell/chunks/tar-C27YYUAS.js +63 -0
- package/dist/bin/{chunks/uniq-DKS7RIAE.js → shell/chunks/uniq-IXHB2FVS.js} +1 -1
- package/dist/bin/shell/chunks/{wc-4LMTC3QD.js → wc-QSBRKIF5.js} +1 -1
- package/dist/bin/shell/chunks/{xan-WNN2ZOAX.js → xan-6K2NGTHM.js} +1 -1
- package/dist/bin/shell/shell.js +100 -100
- package/dist/bundle/browser.js +557 -517
- package/dist/bundle/chunks/base64-3BME25ON.js +5 -0
- package/dist/bundle/chunks/{cat-W5XITXDC.js → cat-MV4K6AUA.js} +1 -1
- package/dist/bundle/chunks/{chunk-4ACWXGKW.js → chunk-7L36YK2X.js} +2 -2
- package/dist/bundle/chunks/{chunk-46TSKXFW.js → chunk-GFLIVSUW.js} +5 -5
- package/dist/bundle/chunks/chunk-OHJS5H37.js +16 -0
- package/dist/bundle/chunks/{cut-KKAAQJVD.js → cut-NVKWEAZF.js} +1 -1
- package/dist/bundle/chunks/grep-TUWLGQC2.js +8 -0
- package/dist/bundle/chunks/{gzip-7QAS5P2Y.js → gzip-L3NDJG3F.js} +22 -22
- package/dist/bundle/chunks/{jq-AAWVUTC4.js → jq-3YU5HRKE.js} +1 -1
- package/dist/bundle/chunks/{md5sum-LJHKXLVT.js → md5sum-KLHZSRUA.js} +1 -1
- package/dist/bundle/chunks/rg-KTCMPGU6.js +32 -0
- package/dist/bundle/chunks/{sha1sum-NRUZZ4Q6.js → sha1sum-WKWTIZGQ.js} +1 -1
- package/dist/bundle/chunks/{sha256sum-5ZGJ4NJL.js → sha256sum-IUVNMBTA.js} +1 -1
- package/dist/bundle/chunks/{sort-JHO22QVO.js → sort-EJUT5LXD.js} +1 -1
- package/dist/bundle/chunks/tar-QWBXMF7K.js +62 -0
- package/dist/bundle/chunks/{uniq-SEKCFR7B.js → uniq-47QVBRNC.js} +1 -1
- package/dist/bundle/chunks/{wc-52FZ4QGS.js → wc-DFQKWSIZ.js} +1 -1
- package/dist/bundle/chunks/{xan-ZHXYF6B4.js → xan-2R2APJJ4.js} +1 -1
- package/dist/bundle/index.js +119 -119
- package/dist/commands/registry.d.ts +1 -1
- package/dist/commands/rg/file-types.d.ts +49 -0
- package/dist/commands/rg/gitignore.d.ts +98 -0
- package/dist/commands/rg/rg-options.d.ts +61 -0
- package/dist/commands/rg/rg-parser.d.ts +20 -0
- package/dist/commands/rg/rg-search.d.ts +15 -0
- package/dist/commands/rg/rg.d.ts +12 -0
- package/dist/commands/search-engine/index.d.ts +10 -0
- package/dist/commands/search-engine/matcher.d.ts +57 -0
- package/dist/commands/search-engine/regex.d.ts +27 -0
- package/dist/commands/tar/archive.d.ts +107 -0
- package/dist/commands/tar/tar.d.ts +8 -0
- package/dist/fs/in-memory-fs/in-memory-fs.d.ts +51 -0
- package/dist/fs/in-memory-fs/index.d.ts +1 -0
- package/dist/fs/init.d.ts +12 -0
- package/dist/fs/interface.d.ts +203 -0
- package/dist/fs/mountable-fs/index.d.ts +1 -0
- package/dist/fs/mountable-fs/mountable-fs.d.ts +108 -0
- package/dist/fs/overlay-fs/index.d.ts +1 -0
- package/dist/fs/overlay-fs/overlay-fs.d.ts +107 -0
- package/dist/fs/read-write-fs/index.d.ts +1 -0
- package/dist/fs/read-write-fs/read-write-fs.d.ts +47 -0
- package/dist/fs/utils.d.ts +17 -0
- package/dist/index.d.ts +1 -0
- package/package.json +12 -7
- package/dist/bin/chunks/base64-RJX7MYGG.js +0 -6
- package/dist/bin/chunks/grep-U2RCKOEG.js +0 -15
- package/dist/bin/shell/chunks/base64-RJX7MYGG.js +0 -6
- package/dist/bin/shell/chunks/grep-U2RCKOEG.js +0 -15
- package/dist/bundle/chunks/base64-F5R4G5EG.js +0 -5
- package/dist/bundle/chunks/grep-CTJRP2G3.js +0 -14
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 k,g as W,h as Ee,i as z,j as le,k as qe}from"./chunks/chunk-CG2HXOFG.js";import"./chunks/chunk-NUFRM6SI.js";import{a as ce}from"./chunks/chunk-44UOCSGV.js";import"./chunks/chunk-DXB73IDG.js";var be=[{name:"echo",load:async()=>(await import("./chunks/echo-VUHWYV6L.js")).echoCommand},{name:"cat",load:async()=>(await import("./chunks/cat-W5XITXDC.js")).catCommand},{name:"printf",load:async()=>(await import("./chunks/printf-VG2POOXB.js")).printfCommand},{name:"ls",load:async()=>(await import("./chunks/ls-5W3NU5OJ.js")).lsCommand},{name:"mkdir",load:async()=>(await import("./chunks/mkdir-7UKY4B3B.js")).mkdirCommand},{name:"touch",load:async()=>(await import("./chunks/touch-MVQSKQKT.js")).touchCommand},{name:"rm",load:async()=>(await import("./chunks/rm-I2SRVF7H.js")).rmCommand},{name:"cp",load:async()=>(await import("./chunks/cp-PBJT3GBF.js")).cpCommand},{name:"mv",load:async()=>(await import("./chunks/mv-FXHEKRTB.js")).mvCommand},{name:"ln",load:async()=>(await import("./chunks/ln-Y7YB677N.js")).lnCommand},{name:"chmod",load:async()=>(await import("./chunks/chmod-FBHLEIY6.js")).chmodCommand},{name:"pwd",load:async()=>(await import("./chunks/pwd-AC4P3JKI.js")).pwdCommand},{name:"readlink",load:async()=>(await import("./chunks/readlink-EM4O3U4P.js")).readlinkCommand},{name:"head",load:async()=>(await import("./chunks/head-FZ6IQHYW.js")).headCommand},{name:"tail",load:async()=>(await import("./chunks/tail-PD4RZR6J.js")).tailCommand},{name:"wc",load:async()=>(await import("./chunks/wc-52FZ4QGS.js")).wcCommand},{name:"stat",load:async()=>(await import("./chunks/stat-IVQBBOKN.js")).statCommand},{name:"grep",load:async()=>(await import("./chunks/grep-CTJRP2G3.js")).grepCommand},{name:"fgrep",load:async()=>(await import("./chunks/grep-CTJRP2G3.js")).fgrepCommand},{name:"egrep",load:async()=>(await import("./chunks/grep-CTJRP2G3.js")).egrepCommand},{name:"sed",load:async()=>(await import("./chunks/sed-ZKODWZ6F.js")).sedCommand},{name:"awk",load:async()=>(await import("./chunks/awk2-46RTIZKB.js")).awkCommand2},{name:"sort",load:async()=>(await import("./chunks/sort-JHO22QVO.js")).sortCommand},{name:"uniq",load:async()=>(await import("./chunks/uniq-SEKCFR7B.js")).uniqCommand},{name:"comm",load:async()=>(await import("./chunks/comm-AXQM7FFF.js")).commCommand},{name:"cut",load:async()=>(await import("./chunks/cut-KKAAQJVD.js")).cutCommand},{name:"paste",load:async()=>(await import("./chunks/paste-QTGVEPH5.js")).pasteCommand},{name:"tr",load:async()=>(await import("./chunks/tr-EDGW5FG6.js")).trCommand},{name:"rev",load:async()=>(await import("./chunks/rev-FKUV5GH5.js")).rev},{name:"nl",load:async()=>(await import("./chunks/nl-KWQGFZH5.js")).nl},{name:"fold",load:async()=>(await import("./chunks/fold-6CFXIPYZ.js")).fold},{name:"expand",load:async()=>(await import("./chunks/expand-VSTNOVF5.js")).expand},{name:"unexpand",load:async()=>(await import("./chunks/unexpand-I7A2VXFD.js")).unexpand},{name:"strings",load:async()=>(await import("./chunks/strings-LRU5XCFP.js")).strings},{name:"split",load:async()=>(await import("./chunks/split-YBTFW7MT.js")).split},{name:"column",load:async()=>(await import("./chunks/column-XPDNNO5Y.js")).column},{name:"join",load:async()=>(await import("./chunks/join-X3QYPZUA.js")).join},{name:"tee",load:async()=>(await import("./chunks/tee-2QU4NRSJ.js")).teeCommand},{name:"find",load:async()=>(await import("./chunks/find-ACOAWALE.js")).findCommand},{name:"basename",load:async()=>(await import("./chunks/basename-CFA5ZIGT.js")).basenameCommand},{name:"dirname",load:async()=>(await import("./chunks/dirname-YPJLCQYA.js")).dirnameCommand},{name:"tree",load:async()=>(await import("./chunks/tree-MEM64BW3.js")).treeCommand},{name:"du",load:async()=>(await import("./chunks/du-NQXEC3EF.js")).duCommand},{name:"env",load:async()=>(await import("./chunks/env-EG5SQSAQ.js")).envCommand},{name:"printenv",load:async()=>(await import("./chunks/env-EG5SQSAQ.js")).printenvCommand},{name:"alias",load:async()=>(await import("./chunks/alias-4UGRF4DM.js")).aliasCommand},{name:"unalias",load:async()=>(await import("./chunks/alias-4UGRF4DM.js")).unaliasCommand},{name:"history",load:async()=>(await import("./chunks/history-MQDK2OPD.js")).historyCommand},{name:"xargs",load:async()=>(await import("./chunks/xargs-4FRA6OJ7.js")).xargsCommand},{name:"true",load:async()=>(await import("./chunks/true-CNJ54NE6.js")).trueCommand},{name:"false",load:async()=>(await import("./chunks/true-CNJ54NE6.js")).falseCommand},{name:"clear",load:async()=>(await import("./chunks/clear-VT2LJIDX.js")).clearCommand},{name:"bash",load:async()=>(await import("./chunks/bash-ZILV3VHA.js")).bashCommand},{name:"sh",load:async()=>(await import("./chunks/bash-ZILV3VHA.js")).shCommand},{name:"jq",load:async()=>(await import("./chunks/jq-AAWVUTC4.js")).jqCommand},{name:"base64",load:async()=>(await import("./chunks/base64-F5R4G5EG.js")).base64Command},{name:"diff",load:async()=>(await import("./chunks/diff-ZLJYSBRK.js")).diffCommand},{name:"date",load:async()=>(await import("./chunks/date-PN3CMG7K.js")).dateCommand},{name:"sleep",load:async()=>(await import("./chunks/sleep-AK4QE4WR.js")).sleepCommand},{name:"timeout",load:async()=>(await import("./chunks/timeout-X3X3N6IE.js")).timeoutCommand},{name:"seq",load:async()=>(await import("./chunks/seq-5VRIVQYP.js")).seqCommand},{name:"expr",load:async()=>(await import("./chunks/expr-DG4E7SIS.js")).exprCommand},{name:"md5sum",load:async()=>(await import("./chunks/md5sum-LJHKXLVT.js")).md5sumCommand},{name:"sha1sum",load:async()=>(await import("./chunks/sha1sum-NRUZZ4Q6.js")).sha1sumCommand},{name:"sha256sum",load:async()=>(await import("./chunks/sha256sum-5ZGJ4NJL.js")).sha256sumCommand},{name:"file",load:async()=>(await import("./chunks/file-AWZ3TUFP.js")).fileCommand},{name:"html-to-markdown",load:async()=>(await import("./chunks/html-to-markdown-ZK6GQVSL.js")).htmlToMarkdownCommand},{name:"help",load:async()=>(await import("./chunks/help-75YOGKM4.js")).helpCommand},{name:"which",load:async()=>(await import("./chunks/which-M5MQ6QXQ.js")).whichCommand},{name:"tac",load:async()=>(await import("./chunks/tac-2X4JLF4W.js")).tac},{name:"hostname",load:async()=>(await import("./chunks/hostname-NWR32CGF.js")).hostname},{name:"od",load:async()=>(await import("./chunks/od-ECWXNUB4.js")).od},{name:"gzip",load:async()=>(await import("./chunks/gzip-7QAS5P2Y.js")).gzipCommand},{name:"gunzip",load:async()=>(await import("./chunks/gzip-7QAS5P2Y.js")).gunzipCommand},{name:"zcat",load:async()=>(await import("./chunks/gzip-7QAS5P2Y.js")).zcatCommand}];(typeof __BROWSER__>"u"||!__BROWSER__)&&(be.push({name:"yq",load:async()=>(await import("./chunks/yq-KANM4MD2.js")).yqCommand}),be.push({name:"xan",load:async()=>(await import("./chunks/xan-ZHXYF6B4.js")).xanCommand}),be.push({name:"sqlite3",load:async()=>(await import("./chunks/sqlite3-5QVZOGER.js")).sqlite3Command}));var gr=[{name:"curl",load:async()=>(await import("./chunks/curl-TVZH24MD.js")).curlCommand}],wr=new Map;function Ar(t){return{name:t.name,async execute(e,n){let r=wr.get(t.name);return r||(r=await t.load(),wr.set(t.name,r)),r.execute(e,n)}}}function Hn(){return be.map(t=>t.name)}function jn(){return gr.map(t=>t.name)}function xr(t){return(t?be.filter(n=>t.includes(n.name)):be).map(Ar)}function Sr(){return gr.map(Ar)}function br(t){return"load"in t&&typeof t.load=="function"}function qn(t,e){return{name:t,execute:e}}function Nr(t){let e=null;return{name:t.name,async execute(n,r){return e||(e=await t.load()),e.execute(n,r)}}}var Zn=new TextEncoder,Qn=new TextDecoder;function re(t,e){if(t instanceof Uint8Array)return t;switch(e){case"base64":return Uint8Array.from(atob(t),n=>n.charCodeAt(0));case"hex":{let n=new Uint8Array(t.length/2);for(let r=0;r<t.length;r+=2)n[r/2]=parseInt(t.slice(r,r+2),16);return n}case"binary":case"latin1":return Uint8Array.from(t,n=>n.charCodeAt(0));default:return Zn.encode(t)}}function Ne(t,e){switch(e){case"base64":return btoa(String.fromCharCode(...t));case"hex":return Array.from(t).map(n=>n.toString(16).padStart(2,"0")).join("");case"binary":case"latin1":return String.fromCharCode(...t);default:return Qn.decode(t)}}function q(t){if(t!=null)return typeof t=="string"?t:t.encoding??void 0}var Ze=new TextEncoder;function Kn(t){return typeof t=="object"&&t!==null&&!(t instanceof Uint8Array)&&"content"in t}var we=class{data=new Map;constructor(e){if(this.data.set("/",{type:"directory",mode:493,mtime:new Date}),e)for(let[n,r]of Object.entries(e))Kn(r)?this.writeFileSync(n,r.content,void 0,{mode:r.mode,mtime:r.mtime}):this.writeFileSync(n,r)}normalizePath(e){if(!e||e==="/")return"/";let n=e.endsWith("/")&&e!=="/"?e.slice(0,-1):e;n.startsWith("/")||(n=`/${n}`);let r=n.split("/").filter(o=>o&&o!=="."),s=[];for(let o of r)o===".."?s.pop():s.push(o);return`/${s.join("/")}`||"/"}dirname(e){let n=this.normalizePath(e);if(n==="/")return"/";let r=n.lastIndexOf("/");return r===0?"/":n.slice(0,r)}ensureParentDirs(e){let n=this.dirname(e);n!=="/"&&(this.data.has(n)||(this.ensureParentDirs(n),this.data.set(n,{type:"directory",mode:493,mtime:new Date})))}writeFileSync(e,n,r,s){let o=this.normalizePath(e);this.ensureParentDirs(o);let i=q(r),a=re(n,i);this.data.set(o,{type:"file",content:a,mode:s?.mode??420,mtime:s?.mtime??new Date})}async readFile(e,n){let r=await this.readFileBuffer(e),s=q(n);return Ne(r,s)}async readFileBuffer(e){let n=this.normalizePath(e),r=this.data.get(n),s=n;if(!r)throw new Error(`ENOENT: no such file or directory, open '${e}'`);let o=new Set;for(;r&&r.type==="symlink";){if(o.has(s))throw new Error(`ELOOP: too many levels of symbolic links, open '${e}'`);o.add(s),s=this.resolveSymlink(s,r.target),r=this.data.get(s)}if(!r)throw new Error(`ENOENT: no such file or directory, open '${e}'`);if(r.type!=="file")throw new Error(`EISDIR: illegal operation on a directory, read '${e}'`);return r.content instanceof Uint8Array?r.content:Ze.encode(r.content)}async writeFile(e,n,r){this.writeFileSync(e,n,r)}async appendFile(e,n,r){let s=this.normalizePath(e),o=this.data.get(s);if(o&&o.type==="directory")throw new Error(`EISDIR: illegal operation on a directory, write '${e}'`);let i=q(r),a=re(n,i);if(o?.type==="file"){let l=o.content instanceof Uint8Array?o.content:Ze.encode(o.content),c=new Uint8Array(l.length+a.length);c.set(l),c.set(a,l.length),this.data.set(s,{type:"file",content:c,mode:o.mode,mtime:new Date})}else this.writeFileSync(e,n,r)}async exists(e){return this.data.has(this.normalizePath(e))}async stat(e){let n=this.normalizePath(e),r=this.data.get(n);if(!r)throw new Error(`ENOENT: no such file or directory, stat '${e}'`);if(r.type==="symlink"){let o=this.resolveSymlink(n,r.target),i=this.data.get(o);if(!i)throw new Error(`ENOENT: no such file or directory, stat '${e}'`);r=i}let s=0;return r.type==="file"&&r.content&&(r.content instanceof Uint8Array?s=r.content.length:s=Ze.encode(r.content).length),{isFile:r.type==="file",isDirectory:r.type==="directory",isSymbolicLink:!1,mode:r.mode,size:s,mtime:r.mtime||new Date}}async lstat(e){let n=this.normalizePath(e),r=this.data.get(n);if(!r)throw new Error(`ENOENT: no such file or directory, lstat '${e}'`);if(r.type==="symlink")return{isFile:!1,isDirectory:!1,isSymbolicLink:!0,mode:r.mode,size:r.target.length,mtime:r.mtime||new Date};let s=0;return r.type==="file"&&r.content&&(r.content instanceof Uint8Array?s=r.content.length:s=Ze.encode(r.content).length),{isFile:r.type==="file",isDirectory:r.type==="directory",isSymbolicLink:!1,mode:r.mode,size:s,mtime:r.mtime||new Date}}resolveSymlink(e,n){if(n.startsWith("/"))return this.normalizePath(n);let r=this.dirname(e);return this.normalizePath(r==="/"?`/${n}`:`${r}/${n}`)}async mkdir(e,n){this.mkdirSync(e,n)}mkdirSync(e,n){let r=this.normalizePath(e);if(this.data.has(r)){if(this.data.get(r)?.type==="file")throw new Error(`EEXIST: file already exists, mkdir '${e}'`);if(!n?.recursive)throw new Error(`EEXIST: directory already exists, mkdir '${e}'`);return}let s=this.dirname(r);if(s!=="/"&&!this.data.has(s))if(n?.recursive)this.mkdirSync(s,{recursive:!0});else throw new Error(`ENOENT: no such file or directory, mkdir '${e}'`);this.data.set(r,{type:"directory",mode:493,mtime:new Date})}async readdir(e){return(await this.readdirWithFileTypes(e)).map(r=>r.name)}async readdirWithFileTypes(e){let n=this.normalizePath(e),r=this.data.get(n);if(!r)throw new Error(`ENOENT: no such file or directory, scandir '${e}'`);if(r.type!=="directory")throw new Error(`ENOTDIR: not a directory, scandir '${e}'`);let s=n==="/"?"/":`${n}/`,o=new Map;for(let[i,a]of this.data.entries())if(i!==n&&i.startsWith(s)){let l=i.slice(s.length),c=l.split("/")[0];c&&!l.includes("/",c.length)&&!o.has(c)&&o.set(c,{name:c,isFile:a.type==="file",isDirectory:a.type==="directory",isSymbolicLink:a.type==="symlink"})}return Array.from(o.values()).sort((i,a)=>i.name<a.name?-1:i.name>a.name?1:0)}async rm(e,n){let r=this.normalizePath(e),s=this.data.get(r);if(!s){if(n?.force)return;throw new Error(`ENOENT: no such file or directory, rm '${e}'`)}if(s.type==="directory"){let o=await this.readdir(r);if(o.length>0){if(!n?.recursive)throw new Error(`ENOTEMPTY: directory not empty, rm '${e}'`);for(let i of o){let a=r==="/"?`/${i}`:`${r}/${i}`;await this.rm(a,n)}}}this.data.delete(r)}async cp(e,n,r){let s=this.normalizePath(e),o=this.normalizePath(n),i=this.data.get(s);if(!i)throw new Error(`ENOENT: no such file or directory, cp '${e}'`);if(i.type==="file")this.ensureParentDirs(o),this.data.set(o,{...i});else if(i.type==="directory"){if(!r?.recursive)throw new Error(`EISDIR: is a directory, cp '${e}'`);await this.mkdir(o,{recursive:!0});let a=await this.readdir(s);for(let l of a){let c=s==="/"?`/${l}`:`${s}/${l}`,f=o==="/"?`/${l}`:`${o}/${l}`;await this.cp(c,f,r)}}}async mv(e,n){await this.cp(e,n,{recursive:!0}),await this.rm(e,{recursive:!0})}getAllPaths(){return Array.from(this.data.keys())}resolvePath(e,n){if(n.startsWith("/"))return this.normalizePath(n);let r=e==="/"?`/${n}`:`${e}/${n}`;return this.normalizePath(r)}async chmod(e,n){let r=this.normalizePath(e),s=this.data.get(r);if(!s)throw new Error(`ENOENT: no such file or directory, chmod '${e}'`);s.mode=n}async symlink(e,n){let r=this.normalizePath(n);if(this.data.has(r))throw new Error(`EEXIST: file already exists, symlink '${n}'`);this.ensureParentDirs(r),this.data.set(r,{type:"symlink",target:e,mode:511,mtime:new Date})}async link(e,n){let r=this.normalizePath(e),s=this.normalizePath(n),o=this.data.get(r);if(!o)throw new Error(`ENOENT: no such file or directory, link '${e}'`);if(o.type!=="file")throw new Error(`EPERM: operation not permitted, link '${e}'`);if(this.data.has(s))throw new Error(`EEXIST: file already exists, link '${n}'`);this.ensureParentDirs(s),this.data.set(s,{type:"file",content:o.content,mode:o.mode,mtime:o.mtime})}async readlink(e){let n=this.normalizePath(e),r=this.data.get(n);if(!r)throw new Error(`ENOENT: no such file or directory, readlink '${e}'`);if(r.type!=="symlink")throw new Error(`EINVAL: invalid argument, readlink '${e}'`);return r.target}};var Cr="5.1.0(1)-release",$r="Linux version 5.15.0-generic (just-bash) #1 SMP PREEMPT";function We(){return{pid:process.pid,ppid:process.ppid,uid:process.getuid?.()??1e3,gid:process.getgid?.()??1e3}}function Pr(){let{pid:t,ppid:e,uid:n,gid:r}=We();return`Name: bash
|
|
1
|
+
import{a as U,b as Y,c as G,d as te,e as J,f as 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
|
|
2
2
|
State: R (running)
|
|
3
3
|
Pid: ${t}
|
|
4
4
|
PPid: ${e}
|
|
5
5
|
Uid: ${n} ${n} ${n} ${n}
|
|
6
6
|
Gid: ${r} ${r} ${r} ${r}
|
|
7
|
-
`}function
|
|
7
|
+
`}function Yn(t){let e=t;return typeof e.mkdirSync=="function"&&typeof e.writeFileSync=="function"}function Jn(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 es(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 ts(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"
|
|
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=[],n=!1){return{type:"Statement",pipelines:t,operators:e,background:n}},pipeline(t,e=!1){return{type:"Pipeline",commands:t,negated:e}},simpleCommand(t,e=[],n=[],r=[]){return{type:"SimpleCommand",name:t,args:e,assignments:n,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,n=!1,r=null){return{type:"Assignment",name:t,value:e,append:n,array:r}},redirection(t,e,n=null){return{type:"Redirection",fd:n,operator:t,target:e}},hereDoc(t,e,n=!1,r=!1){return{type:"HereDoc",delimiter:t,content:e,stripTabs:n,quoted:r}},ifNode(t,e=null,n=[]){return{type:"If",clauses:t,elseBody:e,redirections:n}},forNode(t,e,n,r=[]){return{type:"For",variable:t,words:e,body:n,redirections:r}},whileNode(t,e,n=[]){return{type:"While",condition:t,body:e,redirections:n}},untilNode(t,e,n=[]){return{type:"Until",condition:t,body:e,redirections:n}},caseNode(t,e,n=[]){return{type:"Case",word:t,items:e,redirections:n}},caseItem(t,e,n=";;"){return{type:"CaseItem",patterns:t,body:e,terminator:n}},subshell(t,e=[]){return{type:"Subshell",body:t,redirections:e}},group(t,e=[]){return{type:"Group",body:t,redirections:e}},functionDef(t,e,n=[]){return{type:"FunctionDef",name:t,body:e,redirections:n}},conditionalCommand(t,e=[]){return{type:"ConditionalCommand",expression:t,redirections:e}},arithmeticCommand(t,e=[]){return{type:"ArithmeticCommand",expression:t,redirections:e}}};var
|
|
11
|
-
`)r+=2,
|
|
12
|
-
`)return this.pos=n+1,this.line++,this.column=1,{type:
|
|
13
|
-
`,start:n,end:n+1,line:r,column:s};if(
|
|
14
|
-
`?this.readWord(n,r,s):(this.pos=n+1,this.column=s+1,this.makeToken(
|
|
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
|
|
18
|
-
`||p===";"||p==="&"||p==="|"||p==="("||p===")"||p==="<"||p===">"))break;if(p==="$"&&
|
|
19
|
-
`){
|
|
20
|
-
`){
|
|
21
|
-
`;)
|
|
22
|
-
`&&(c
|
|
23
|
-
`&&(c
|
|
24
|
-
`&&(c
|
|
25
|
-
`&&(c
|
|
26
|
-
`?(c
|
|
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){Yn(t)&&(Jn(t,e),es(t),ts(t))}var rs=["tar","yq","xan","sqlite3"];function Ir(t){return rs.includes(t)}function T(t,e){return{type:"ArithmeticExpression",expression:se(t,e,0).expr}}function se(t,e,n){return ns(t,e,n)}function ns(t,e,n){let{expr:r,pos:s}=Ke(t,e,n);for(s=O(e,s);e[s]===",";){s++;let{expr:i,pos:o}=Ke(t,e,s);r={type:"ArithBinary",operator:",",left:r,right:i},s=O(e,o)}return{expr:r,pos:s}}function Ke(t,e,n){let{expr:r,pos:s}=ss(t,e,n);if(s=O(e,s),e[s]==="?"){s++;let{expr:i,pos:o}=se(t,e,s);if(s=O(e,o),e[s]===":"){s++;let{expr:a,pos:c}=se(t,e,s);return{expr:{type:"ArithTernary",condition:r,consequent:i,alternate:a},pos:c}}}return{expr:r,pos:s}}function ss(t,e,n){let{expr:r,pos:s}=Rr(t,e,n);for(;s=O(e,s),e.slice(s,s+2)==="||";){s+=2;let{expr:i,pos:o}=Rr(t,e,s);r={type:"ArithBinary",operator:"||",left:r,right:i},s=o}return{expr:r,pos:s}}function Rr(t,e,n){let{expr:r,pos:s}=Dr(t,e,n);for(;s=O(e,s),e.slice(s,s+2)==="&&";){s+=2;let{expr:i,pos:o}=Dr(t,e,s);r={type:"ArithBinary",operator:"&&",left:r,right:i},s=o}return{expr:r,pos:s}}function Dr(t,e,n){let{expr:r,pos:s}=Or(t,e,n);for(;s=O(e,s),e[s]==="|"&&e[s+1]!=="|";){s++;let{expr:i,pos:o}=Or(t,e,s);r={type:"ArithBinary",operator:"|",left:r,right:i},s=o}return{expr:r,pos:s}}function Or(t,e,n){let{expr:r,pos:s}=_r(t,e,n);for(;s=O(e,s),e[s]==="^";){s++;let{expr:i,pos:o}=_r(t,e,s);r={type:"ArithBinary",operator:"^",left:r,right:i},s=o}return{expr:r,pos:s}}function _r(t,e,n){let{expr:r,pos:s}=Lr(t,e,n);for(;s=O(e,s),e[s]==="&"&&e[s+1]!=="&";){s++;let{expr:i,pos:o}=Lr(t,e,s);r={type:"ArithBinary",operator:"&",left:r,right:i},s=o}return{expr:r,pos:s}}function Lr(t,e,n){let{expr:r,pos:s}=Tr(t,e,n);for(;s=O(e,s),e.slice(s,s+2)==="=="||e.slice(s,s+2)==="!=";){let i=e.slice(s,s+2);s+=2;let{expr:o,pos:a}=Tr(t,e,s);r={type:"ArithBinary",operator:i,left:r,right:o},s=a}return{expr:r,pos:s}}function Tr(t,e,n){let{expr:r,pos:s}=Nt(t,e,n);for(;;)if(s=O(e,s),e.slice(s,s+2)==="<="||e.slice(s,s+2)===">="){let i=e.slice(s,s+2);s+=2;let{expr:o,pos:a}=Nt(t,e,s);r={type:"ArithBinary",operator:i,left:r,right:o},s=a}else if(e[s]==="<"||e[s]===">"){let i=e[s];s++;let{expr:o,pos:a}=Nt(t,e,s);r={type:"ArithBinary",operator:i,left:r,right:o},s=a}else break;return{expr:r,pos:s}}function Nt(t,e,n){let{expr:r,pos:s}=Fr(t,e,n);for(;s=O(e,s),e.slice(s,s+2)==="<<"||e.slice(s,s+2)===">>";){let i=e.slice(s,s+2);s+=2;let{expr:o,pos:a}=Fr(t,e,s);r={type:"ArithBinary",operator:i,left:r,right:o},s=a}return{expr:r,pos:s}}function Fr(t,e,n){let{expr:r,pos:s}=Wr(t,e,n);for(;s=O(e,s),(e[s]==="+"||e[s]==="-")&&e[s+1]!==e[s];){let i=e[s];s++;let{expr:o,pos:a}=Wr(t,e,s);r={type:"ArithBinary",operator:i,left:r,right:o},s=a}return{expr:r,pos:s}}function Wr(t,e,n){let{expr:r,pos:s}=Qe(t,e,n);for(;;)if(s=O(e,s),e[s]==="*"&&e[s+1]!=="*"){s++;let{expr:i,pos:o}=Qe(t,e,s);r={type:"ArithBinary",operator:"*",left:r,right:i},s=o}else if(e[s]==="/"||e[s]==="%"){let i=e[s];s++;let{expr:o,pos:a}=Qe(t,e,s);r={type:"ArithBinary",operator:i,left:r,right:o},s=a}else break;return{expr:r,pos:s}}function Qe(t,e,n){let{expr:r,pos:s}=Pt(t,e,n),i=O(e,s);if(e.slice(i,i+2)==="**"){i+=2;let{expr:o,pos:a}=Qe(t,e,i);return{expr:{type:"ArithBinary",operator:"**",left:r,right:o},pos:a}}return{expr:r,pos:s}}function Pt(t,e,n){let r=O(e,n);if(e.slice(r,r+2)==="++"||e.slice(r,r+2)==="--"){let s=e.slice(r,r+2);r+=2;let{expr:i,pos:o}=Pt(t,e,r);return{expr:{type:"ArithUnary",operator:s,operand:i,prefix:!0},pos:o}}if(e[r]==="+"||e[r]==="-"||e[r]==="!"||e[r]==="~"){let s=e[r];r++;let{expr:i,pos:o}=Pt(t,e,r);return{expr:{type:"ArithUnary",operator:s,operand:i,prefix:!0},pos:o}}return os(t,e,r)}function is(t,e){let n=t[e];return n==="$"||n==="`"}function os(t,e,n){let{expr:r,pos:s}=Mr(t,e,n),i=[r];for(;is(e,s);){let{expr:o,pos:a}=Mr(t,e,s);i.push(o),s=a}if(i.length>1&&(r={type:"ArithConcat",parts:i}),s=O(e,s),e.slice(s,s+2)==="++"||e.slice(s,s+2)==="--"){let o=e.slice(s,s+2);return s+=2,{expr:{type:"ArithUnary",operator:o,operand:r,prefix:!1},pos:s}}return{expr:r,pos:s}}function Mr(t,e,n){let r=O(e,n);if(e.slice(r,r+3)==="$(("){r+=3;let s=1,i=r;for(;r<e.length-1&&s>0;)e[r]==="("&&e[r+1]==="("?(s++,r+=2):e[r]===")"&&e[r+1]===")"?(s--,s>0&&(r+=2)):r++;let o=e.slice(i,r),{expr:a}=se(t,o,0);return r+=2,{expr:{type:"ArithNested",expression:a},pos:r}}if(e.slice(r,r+2)==="$("&&e[r+2]!=="("){r+=2;let s=1,i=r;for(;r<e.length&&s>0;)e[r]==="("?s++:e[r]===")"&&s--,s>0&&r++;let o=e.slice(i,r);return r++,{expr:{type:"ArithCommandSubst",command:o},pos:r}}if(e[r]==="`"){r++;let s=r;for(;r<e.length&&e[r]!=="`";)r++;let i=e.slice(s,r);return e[r]==="`"&&r++,{expr:{type:"ArithCommandSubst",command:i},pos:r}}if(e[r]==="("){r++;let{expr:s,pos:i}=se(t,e,r);return r=O(e,i),e[r]===")"&&r++,{expr:{type:"ArithGroup",expression:s},pos:r}}if(/[0-9]/.test(e[r])){let s="",i=!1;for(;r<e.length;){let a=e[r];if(i)if(/[0-9a-zA-Z@_]/.test(a))s+=a,r++;else break;else if(a==="#")i=!0,s+=a,r++;else if(/[0-9a-fA-FxX]/.test(a))s+=a,r++;else break}if(e[r]==="."&&/[0-9]/.test(e[r+1]))throw new W(`${s}.${e[r+1]}...: syntax error: invalid arithmetic operator`);if(e[r]==="["){let a=e.slice(r).trim();return{expr:{type:"ArithNumberSubscript",number:s,errorToken:a},pos:e.length}}return{expr:{type:"ArithNumber",value:Ne(s)},pos:r}}if(e[r]==="$"&&e[r+1]==="{"){let s=r+2,i=1,o=s;for(;o<e.length&&i>0;)e[o]==="{"?i++:e[o]==="}"&&i--,i>0&&o++;let a=e.slice(s,o),c=o+1;if(e[c]==="#"){let l=c+1;for(;l<e.length&&/[0-9a-zA-Z@_]/.test(e[l]);)l++;let u=e.slice(c+1,l);return{expr:{type:"ArithDynamicBase",baseExpr:a,value:u},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 u=e.slice(c,l);return{expr:{type:"ArithDynamicNumber",prefix:a,suffix:u},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 s="";for(;r<e.length&&/[0-9]/.test(e[r]);)s+=e[r],r++;return{expr:{type:"ArithVariable",name:s},pos:r}}if(e[r]==="$"&&r+1<e.length&&/[a-zA-Z_]/.test(e[r+1])&&r++,/[a-zA-Z_]/.test(e[r])){let s="";for(;r<e.length&&/[a-zA-Z0-9_]/.test(e[r]);)s+=e[r],r++;if(e[r]==="["){r++;let o;if(e[r]==="'"||e[r]==='"'){let l=e[r];for(r++,o="";r<e.length&&e[r]!==l;)o+=e[r],r++;e[r]===l&&r++,r=O(e,r),e[r]==="]"&&r++}let a;if(o===void 0){let{expr:l,pos:u}=se(t,e,r);a=l,r=u,e[r]==="]"&&r++}if(r=O(e,r),e[r]==="["&&a)return{expr:{type:"ArithDoubleSubscript",array:s,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:u,pos:h}=Ke(t,e,r);return{expr:{type:"ArithAssignment",operator:l,variable:s,subscript:a,stringKey:o,value:u},pos:h}}return{expr:{type:"ArithArrayElement",array:s,index:a,stringKey:o},pos:r}}r=O(e,r);let i=["=","+=","-=","*=","/=","%=","<<=",">>=","&=","|=","^="];for(let o of i)if(e.slice(r,r+o.length)===o&&e.slice(r,r+o.length+1)!=="=="){r+=o.length;let{expr:a,pos:c}=Ke(t,e,r);return{expr:{type:"ArithAssignment",operator:o,variable:s,value:a},pos:c}}return{expr:{type:"ArithVariable",name:s},pos:r}}return{expr:{type:"ArithNumber",value:0},pos:r}}function Ne(t){if(t.includes("#")){let[e,n]=t.split("#"),r=Number.parseInt(e,10);if(r<2||r>64)return Number.NaN;if(r<=36)return Number.parseInt(n,r);let s=0;for(let i of n){let o;if(i>="0"&&i<="9")o=i.charCodeAt(0)-48;else if(i>="a"&&i<="z")o=i.charCodeAt(0)-97+10;else if(i>="A"&&i<="Z")o=i.charCodeAt(0)-65+36;else if(i==="@")o=62;else if(i==="_")o=63;else return Number.NaN;if(o>=r)return Number.NaN;s=s*r+o}return s}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=[],n=!1){return{type:"Statement",pipelines:t,operators:e,background:n}},pipeline(t,e=!1){return{type:"Pipeline",commands:t,negated:e}},simpleCommand(t,e=[],n=[],r=[]){return{type:"SimpleCommand",name:t,args:e,assignments:n,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,n=!1,r=null){return{type:"Assignment",name:t,value:e,append:n,array:r}},redirection(t,e,n=null){return{type:"Redirection",fd:n,operator:t,target:e}},hereDoc(t,e,n=!1,r=!1){return{type:"HereDoc",delimiter:t,content:e,stripTabs:n,quoted:r}},ifNode(t,e=null,n=[]){return{type:"If",clauses:t,elseBody:e,redirections:n}},forNode(t,e,n,r=[]){return{type:"For",variable:t,words:e,body:n,redirections:r}},whileNode(t,e,n=[]){return{type:"While",condition:t,body:e,redirections:n}},untilNode(t,e,n=[]){return{type:"Until",condition:t,body:e,redirections:n}},caseNode(t,e,n=[]){return{type:"Case",word:t,items:e,redirections:n}},caseItem(t,e,n=";;"){return{type:"CaseItem",patterns:t,body:e,terminator:n}},subshell(t,e=[]){return{type:"Subshell",body:t,redirections:e}},group(t,e=[]){return{type:"Group",body:t,redirections:e}},functionDef(t,e,n=[]){return{type:"FunctionDef",name:t,body:e,redirections:n}},conditionalCommand(t,e=[]){return{type:"ConditionalCommand",expression:t,redirections:e}},arithmeticCommand(t,e=[]){return{type:"ArithmeticCommand",expression:t,redirections:e}}};var f;(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"})(f||(f={}));var Xe={if:f.IF,then:f.THEN,else:f.ELSE,elif:f.ELIF,fi:f.FI,for:f.FOR,while:f.WHILE,until:f.UNTIL,do:f.DO,done:f.DONE,case:f.CASE,esac:f.ESAC,in:f.IN,function:f.FUNCTION,select:f.SELECT,time:f.TIME,coproc:f.COPROC};function Br(t){let e=t.match(/^[a-zA-Z_][a-zA-Z0-9_]*/);if(!e)return!1;let n=t.slice(e[0].length);if(n===""||n==="+")return!0;if(n[0]==="["){let r=0,s=0;for(;s<n.length;s++)if(n[s]==="[")r++;else if(n[s]==="]"&&(r--,r===0))break;if(r!==0||s>=n.length)return!1;let i=n.slice(s+1);return i===""||i==="+"}return!1}var as=[[";",";","&",f.SEMI_SEMI_AND],["<","<","<",f.TLESS],["&",">",">",f.AND_DGREAT]],cs=[["[","[",f.DBRACK_START],["]","]",f.DBRACK_END],["(","(",f.DPAREN_START],[")",")",f.DPAREN_END],["&","&",f.AND_AND],["|","|",f.OR_OR],[";",";",f.DSEMI],[";","&",f.SEMI_AND],["|","&",f.PIPE_AMP],[">",">",f.DGREAT],["<","&",f.LESSAND],[">","&",f.GREATAND],["<",">",f.LESSGREAT],[">","|",f.CLOBBER],["&",">",f.AND_GREAT]],ls={"|":f.PIPE,"&":f.AMP,";":f.SEMICOLON,"(":f.LPAREN,")":f.RPAREN,"<":f.LESS,">":f.GREAT};function us(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 n=this.input.length,r=this.tokens,s=this.pendingHeredocs;for(;this.pos<n&&(this.skipWhitespace(),!(this.pos>=n));){if(s.length>0&&r.length>0&&r[r.length-1].type===f.NEWLINE){this.readHeredocContent();continue}let i=this.nextToken();i&&r.push(i)}return r.push({type:f.EOF,value:"",start:this.pos,end:this.pos,line:this.line,column:this.column}),r}skipWhitespace(){let e=this.input,n=e.length,r=this.pos,s=this.column,i=this.line;for(;r<n;){let o=e[r];if(o===" "||o===" ")r++,s++;else if(o==="\\"&&e[r+1]===`
|
|
11
|
+
`)r+=2,i++,s=1;else break}this.pos=r,this.column=s,this.line=i}nextToken(){let e=this.input,n=this.pos,r=this.line,s=this.column,i=e[n],o=e[n+1],a=e[n+2];if(i==="#")return this.readComment(n,r,s);if(i===`
|
|
12
|
+
`)return this.pos=n+1,this.line++,this.column=1,{type:f.NEWLINE,value:`
|
|
13
|
+
`,start:n,end:n+1,line:r,column:s};if(i==="<"&&o==="<"&&a==="-")return this.pos=n+3,this.column=s+3,this.registerHeredocFromLookahead(!0),this.makeToken(f.DLESSDASH,"<<-",n,r,s);for(let[l,u,h,d]of as)if(i===l&&o===u&&a===h)return this.pos=n+3,this.column=s+3,this.makeToken(d,l+u+h,n,r,s);if(i==="<"&&o==="<")return this.pos=n+2,this.column=s+2,this.registerHeredocFromLookahead(!1),this.makeToken(f.DLESS,"<<",n,r,s);for(let[l,u,h]of cs)if(i===l&&o===u)return this.pos=n+2,this.column=s+2,this.makeToken(h,l+u,n,r,s);let c=ls[i];return c?(this.pos=n+1,this.column=s+1,this.makeToken(c,i,n,r,s)):i==="{"?o==="}"?(this.pos=n+2,this.column=s+2,{type:f.WORD,value:"{}",start:n,end:n+2,line:r,column:s,quoted:!1,singleQuoted:!1}):this.scanBraceExpansion(n)!==null?this.readWordWithBraceExpansion(n,r,s):this.scanLiteralBraceWord(n)!==null?this.readWordWithBraceExpansion(n,r,s):o!==void 0&&o!==" "&&o!==" "&&o!==`
|
|
14
|
+
`?this.readWord(n,r,s):(this.pos=n+1,this.column=s+1,this.makeToken(f.LBRACE,"{",n,r,s)):i==="}"?this.isWordCharFollowing(n+1)?this.readWord(n,r,s):(this.pos=n+1,this.column=s+1,this.makeToken(f.RBRACE,"}",n,r,s)):i==="!"?o==="="?(this.pos=n+2,this.column=s+2,this.makeToken(f.WORD,"!=",n,r,s)):(this.pos=n+1,this.column=s+1,this.makeToken(f.BANG,"!",n,r,s)):this.readWord(n,r,s)}makeToken(e,n,r,s,i){return{type:e,value:n,start:r,end:this.pos,line:s,column:i}}readComment(e,n,r){let s=this.input,i=s.length,o=this.pos;for(;o<i&&s[o]!==`
|
|
15
|
+
`;)o++;let a=s.slice(e,o);return this.pos=o,this.column=r+(o-e),{type:f.COMMENT,value:a,start:e,end:o,line:n,column:r}}readWord(e,n,r){let s=this.input,i=s.length,o=this.pos,a=o;for(;o<i;){let p=s[o];if(p===" "||p===" "||p===`
|
|
16
|
+
`||p===";"||p==="&"||p==="|"||p==="("||p===")"||p==="<"||p===">"||p==="'"||p==='"'||p==="\\"||p==="$"||p==="`"||p==="{"||p==="}"||p==="~"||p==="*"||p==="?"||p==="[")break;o++}if(o>a){let p=s[o];if(o>=i||p===" "||p===" "||p===`
|
|
17
|
+
`||p===";"||p==="&"||p==="|"||p==="("||p===")"||p==="<"||p===">"){let w=s.slice(a,o);if(this.pos=o,this.column=r+(o-a),Xe[w])return{type:Xe[w],value:w,start:e,end:o,line:n,column:r};let g=w.indexOf("=");return g>0&&Br(w.slice(0,g))?{type:f.ASSIGNMENT_WORD,value:w,start:e,end:o,line:n,column:r}:/^[0-9]+$/.test(w)?{type:f.NUMBER,value:w,start:e,end:o,line:n,column:r}:/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(w)?{type:f.NAME,value:w,start:e,end:o,line:n,column:r,quoted:!1,singleQuoted:!1}:{type:f.WORD,value:w,start:e,end:o,line:n,column:r,quoted:!1,singleQuoted:!1}}}o=this.pos;let c=this.column,l=this.line,u="",h=!1,d=!1,m=!1,y=!1,E=s[o]==='"'||s[o]==="'";for(;o<i;){let p=s[o];if(!m&&!y&&(p===" "||p===" "||p===`
|
|
18
|
+
`||p===";"||p==="&"||p==="|"||p==="("||p===")"||p==="<"||p===">"))break;if(p==="$"&&o+1<i&&s[o+1]==="'"&&!m&&!y){for(u+="$'",o+=2,c+=2;o<i&&s[o]!=="'";)s[o]==="\\"&&o+1<i?(u+=s[o]+s[o+1],o+=2,c+=2):(u+=s[o],o++,c++);o<i&&(u+="'",o++,c++);continue}if(p==="$"&&o+1<i&&s[o+1]==='"'&&!m&&!y){o++,c++,y=!0,h=!0,u===""&&(E=!0),o++,c++;continue}if(p==="'"&&!y){m?(m=!1,E||(u+=p)):(m=!0,E?(d=!0,h=!0):u+=p),o++,c++;continue}if(p==='"'&&!m){y?(y=!1,E||(u+=p)):(y=!0,E?h=!0:u+=p),o++,c++;continue}if(p==="\\"&&!m&&o+1<i){let w=s[o+1];if(w===`
|
|
19
|
+
`){o+=2,l++,c=1;continue}if(y){if(w==='"'||w==="\\"||w==="$"||w==="`"||w===`
|
|
20
|
+
`){w==="$"||w==="`"?u+=p+w:u+=w,o+=2,c+=2;continue}}else{w==='"'||w==="'"?u+=p+w:u+=w,o+=2,c+=2;continue}}if(p==="$"&&o+1<i&&s[o+1]==="("){u+=p,o++,c++,u+=s[o],o++,c++;let w=1,g=!1,b=!1,C=0,I=!1,D="",we=s[o]==="(";for(;w>0&&o<i;){let L=s[o];if(u+=L,g)L==="'"&&(g=!1);else if(b)L==="\\"&&o+1<i?(u+=s[o+1],o++,c++):L==='"'&&(b=!1);else if(L==="'")g=!0,D="";else if(L==='"')b=!0,D="";else if(L==="\\"&&o+1<i)u+=s[o+1],o++,c++,D="";else if(L==="#"&&!we&&(D===""||/\s/.test(s[o-1]||""))){for(;o+1<i&&s[o+1]!==`
|
|
21
|
+
`;)o++,c++,u+=s[o];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==="("?o>0&&s[o-1]==="$"?w++:I||w++:L===")"?I?I=!1:w--:L===";"&&C>0&&o+1<i&&s[o+1]===";"&&(I=!0));L===`
|
|
22
|
+
`&&(l++,c=0,D=""),o++,c++}continue}if(p==="$"&&o+1<i&&s[o+1]==="["){u+=p,o++,c++,u+=s[o],o++,c++;let w=1;for(;w>0&&o<i;){let g=s[o];u+=g,g==="["?w++:g==="]"?w--:g===`
|
|
23
|
+
`&&(l++,c=0),o++,c++}continue}if(p==="$"&&o+1<i&&s[o+1]==="{"){u+=p,o++,c++,u+=s[o],o++,c++;let w=1;for(;w>0&&o<i;){let g=s[o];u+=g,g==="{"?w++:g==="}"?w--:g===`
|
|
24
|
+
`&&(l++,c=0),o++,c++}continue}if(p==="$"&&o+1<i){let w=s[o+1];if(w==="#"||w==="?"||w==="$"||w==="!"||w==="@"||w==="*"||w==="-"||w>="0"&&w<="9"){u+=p+w,o+=2,c+=2;continue}}if(p==="`"){for(u+=p,o++,c++;o<i&&s[o]!=="`";){let w=s[o];u+=w,w==="\\"&&o+1<i&&(u+=s[o+1],o++,c++),w===`
|
|
25
|
+
`&&(l++,c=0),o++,c++}o<i&&(u+=s[o],o++,c++);continue}u+=p,o++,p===`
|
|
26
|
+
`?(l++,c=1):c++}if(this.pos=o,this.column=c,this.line=l,u==="")return{type:f.WORD,value:"",start:e,end:o,line:n,column:r,quoted:h,singleQuoted:d};if(!h&&Xe[u])return{type:Xe[u],value:u,start:e,end:o,line:n,column:r};if(!E){let p=u.indexOf("=");if(p>0&&Br(u.slice(0,p)))return{type:f.ASSIGNMENT_WORD,value:u,start:e,end:o,line:n,column:r,quoted:h,singleQuoted:d}}return/^[0-9]+$/.test(u)?{type:f.NUMBER,value:u,start:e,end:o,line:n,column:r}:us(u)?{type:f.NAME,value:u,start:e,end:o,line:n,column:r,quoted:h,singleQuoted:d}:{type:f.WORD,value:u,start:e,end:o,line:n,column:r,quoted:h,singleQuoted:d}}readHeredocContent(){for(;this.pendingHeredocs.length>0;){let e=this.pendingHeredocs.shift();if(!e)break;let n=this.pos,r=this.line,s=this.column,i="";for(;this.pos<this.input.length;){let o=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
|
-
`||n===";"||n==="&"||n==="|"||n==="("||n===")"||n==="<"||n===">")}readWordWithBraceExpansion(e,n,r){let s=this.input,
|
|
32
|
-
`||
|
|
33
|
-
`||
|
|
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),l=parseInt(a,16);Number.isNaN(l)?(r+="\\x",s+=2):(r+=String.fromCharCode(l),s+=4);break}case"u":{let a=e.slice(s+2,s+6),l=parseInt(a,16);Number.isNaN(l)?(r+="\\u",s+=2):(r+=String.fromCharCode(l),s+=6);break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":{let a="",l=s+1;for(;l<e.length&&l<s+4&&/[0-7]/.test(e[l]);)a+=e[l],l++;let c=parseInt(a,8);r+=String.fromCharCode(c),s=l;break}default:r+=o,s++}else r+=o,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 Vr(t){let e=[],n="",r=0;for(let s=0;s<t.length;s++){let o=t[s];o==="{"?(r++,n+=o):o==="}"?(r--,n+=o):o===","&&r===0?(e.push(n),n=""):n+=o}return e.push(n),e}function Qr(t,e,n,r){let s=vt(t,e,n,"{","}");if(s===-1)return null;let o=e.slice(n+1,s),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:s+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:s+1}:o.includes(",")&&r?{part:{type:"BraceExpansion",items:Vr(o).map(f=>({type:"Word",word:A.word(r(t,f,!1,!1,!1))}))},endIndex:s+1}:o.includes(",")?{part:{type:"BraceExpansion",items:Vr(o).map(f=>({type:"Word",word:A.word([A.literal(f)])}))},endIndex:s+1}:null}function Kr(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 Xr(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(),n=e.type;if(n===u.NUMBER){let r=t.peek(1);return e.end!==r.start?!1:Gr.has(r.type)}return Ur.has(n)}function et(t){let e=null;t.check(u.NUMBER)&&(e=Number.parseInt(t.advance().value,10));let n=t.advance(),r=Xr(t,n.type);if(n.type===u.DLESS||n.type===u.DLESSDASH)return us(t,r,e,n.type===u.DLESSDASH);t.isWord()||t.error("Expected redirection target");let s=t.parseWord();return A.redirection(r,s,e)}function us(t,e,n,r){t.isWord()||t.error("Expected here-document delimiter");let s=t.advance(),o=s.value,i=s.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),n);return t.addPendingHeredoc(a,o,r,i),a}function Jr(t){let e=t.current().line,n=[],r=null,s=[],o=[];for(;t.check(u.ASSIGNMENT_WORD);)t.checkIterationLimit(),n.push(ds(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();s.push(t.parseWordFromString(a.value,!1,!1))}else if(t.isWord())s.push(t.parseWord());else if(t.check(u.ASSIGNMENT_WORD)){let a=t.advance(),l=a.value,c=l.endsWith("="),f=l.endsWith("=(");if((c||f)&&(f||t.check(u.LPAREN))){let d=f?l.slice(0,-2):l.slice(0,-1);f||t.expect(u.LPAREN);let h=Rt(t);t.expect(u.RPAREN);let m=h.map(w=>Kr(t,w)),y=`${d}=(${m.join(" ")})`;s.push(t.parseWordFromString(y,!1,!1))}else s.push(t.parseWordFromString(l,a.quoted,a.singleQuoted))}else if(t.check(u.LPAREN))t.error("syntax error near unexpected token `('");else break;let i=A.simpleCommand(r,s,n,o);return i.line=e,i}function ds(t){let e=t.expect(u.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],o,i=s.length;if(n[i]==="["){let d=0,h=i+1;for(;i<n.length;i++)if(n[i]==="[")d++;else if(n[i]==="]"&&(d--,d===0))break;d!==0&&t.error(`Invalid assignment: ${n}`),o=n.slice(h,i),i++}let a=n[i]==="+";a&&i++,n[i]!=="="&&t.error(`Invalid assignment: ${n}`),i++;let l=n.slice(i);if(l==="("){let d=Rt(t);t.expect(u.RPAREN);let h=o!==void 0?`${s}[${o}]`:s;return A.assignment(h,null,a,d)}if(l===""&&t.check(u.LPAREN)){let d=t.current();if(e.end===d.start){t.advance();let h=Rt(t);t.expect(u.RPAREN);let m=o!==void 0?`${s}[${o}]`:s;return A.assignment(m,null,a,h)}}let c=l?t.parseWordFromString(l,e.quoted,e.singleQuoted,!0):null,f=o!==void 0?`${s}[${o}]`:s;return A.assignment(f,c,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 kt(t){t.expect(u.IF);let e=[],n=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:n,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 l=t.check(u.FI)?"fi":t.check(u.ELSE)?"else":t.check(u.ELIF)?"elif":"fi";t.error(`syntax error near unexpected token \`${l}'`)}e.push({condition:i,body:a})}let s=null;t.check(u.ELSE)&&(t.advance(),s=t.parseCompoundList(),s.length===0&&t.error("syntax error near unexpected token `fi'")),t.expect(u.FI);let o=t.parseOptionalRedirections();return A.ifNode(e,s,o)}function Dt(t){if(t.expect(u.FOR),t.check(u.DPAREN_START))return ms(t);t.isWord()||t.error("Expected variable name in for loop");let n=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 s=t.parseCompoundList();t.expect(u.DONE);let o=t.parseOptionalRedirections();return A.forNode(n,r,s,o)}function ms(t){t.expect(u.DPAREN_START);let e=null,n=null,r=null,s=["","",""],o=0,i=0;for(;!t.check(u.DPAREN_END,u.EOF);){let c=t.advance();if(c.type===u.SEMICOLON&&i===0){if(o++,o>2)break}else c.value==="("&&i++,c.value===")"&&i--,s[o]+=c.value}t.expect(u.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(u.SEMICOLON)&&t.advance(),t.skipNewlines(),t.expect(u.DO);let a=t.parseCompoundList();t.expect(u.DONE);let l=t.parseOptionalRedirections();return{type:"CStyleFor",init:e,condition:n,update:r,body:a,redirections:l}}function Ot(t){t.expect(u.WHILE);let e=t.parseCompoundList();t.expect(u.DO);let n=t.parseCompoundList();n.length===0&&t.error("syntax error near unexpected token `done'"),t.expect(u.DONE);let r=t.parseOptionalRedirections();return A.whileNode(e,n,r)}function _t(t){t.expect(u.UNTIL);let e=t.parseCompoundList();t.expect(u.DO);let n=t.parseCompoundList();n.length===0&&t.error("syntax error near unexpected token `done'"),t.expect(u.DONE);let r=t.parseOptionalRedirections();return A.untilNode(e,n,r)}function Lt(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 n=[];for(;!t.check(u.ESAC,u.EOF);){t.checkIterationLimit();let s=t.getPos(),o=ps(t);if(o&&n.push(o),t.skipNewlines(),t.getPos()===s&&!o)break}t.expect(u.ESAC);let r=t.parseOptionalRedirections();return A.caseNode(e,n,r)}function ps(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 n=[];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 s=t.getPos(),o=t.parseStatement();if(o&&n.push(o),t.skipSeparators(!1),t.getPos()===s&&!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,n,r)}function Tt(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 n=t.parseOptionalRedirections();return A.subshell(e,n)}function Ft(t){t.expect(u.LBRACE);let e=t.parseCompoundList();t.expect(u.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"],ws=["==","!=","=~","<",">","-eq","-ne","-lt","-le","-gt","-ge","-nt","-ot","-ef"];function Mt(t){return t.skipNewlines(),gs(t)}function gs(t){let e=en(t);for(t.skipNewlines();t.check(u.OR_OR);){t.advance(),t.skipNewlines();let n=en(t);e={type:"CondOr",left:e,right:n},t.skipNewlines()}return e}function en(t){let e=Wt(t);for(t.skipNewlines();t.check(u.AND_AND);){t.advance(),t.skipNewlines();let n=Wt(t);e={type:"CondAnd",left:e,right:n},t.skipNewlines()}return e}function Wt(t){return t.skipNewlines(),t.check(u.BANG)?(t.advance(),t.skipNewlines(),{type:"CondNot",operand:Wt(t)}):As(t)}function As(t){if(t.check(u.LPAREN)){t.advance();let e=Mt(t);return t.expect(u.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(u.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()&&ws.includes(t.current().value)){let s=t.advance().value,o=t.parseWord();return{type:"CondBinary",operator:s,left:r,right:o}}if(t.check(u.LESS)){t.advance();let s=t.parseWord();return{type:"CondBinary",operator:"<",left:r,right:s}}if(t.check(u.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 Ss(t,e,n){let r=n+1,s=e[r];if("@*#?$!-0123456789".includes(s))return{part:A.parameterExpansion(s),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 bs(t,e,n,r=!1){let s=n+2,o=!1;e[s]==="!"&&(o=!0,s++);let i=!1;e[s]==="#"&&!/[}:#%/^,]/.test(e[s+1]||"}")&&(i=!0,s++);let a="",l=e[s];if(/[@*#?$!-]/.test(l)&&!/[a-zA-Z0-9_]/.test(e[s+1]||""))a=l,s++;else for(;s<e.length&&/[a-zA-Z0-9_]/.test(e[s]);)a+=e[s],s++;if(e[s]==="["){let f=vt(t,e,s,"[","]");a+=e.slice(s,f+1),s=f+1}a===""&&!o&&!i&&e[s]!=="}"&&t.error(`\${${e[s]}}: bad substitution`);let c=null;if(o){let f=a.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(f)c={type:"ArrayKeys",array:f[1],star:f[2]==="*"},a="";else if(e[s]==="*"||e[s]==="@"){let d=e[s];s++,c={type:"VarNamePrefix",prefix:a,star:d==="*"},a=""}else c={type:"Indirection"}}else if(i)if(e[s]===":")for(c={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`):c={type:"Length"};if(!c&&s<e.length&&e[s]!=="}"){let f=Ns(t,e,s,a,r);c=f.operation,s=f.endIndex}if(s<e.length&&e[s]!=="}"){let f=e[s];if(!/[:\-+=?#%/^,@[]/.test(f)){let d=s;for(;d<e.length&&e[d]!=="}";)d++;let h=e.slice(n,d+1);t.error(`\${${h.slice(2,-1)}}: bad substitution`)}}for(;s<e.length&&e[s]!=="}";)s++;return{part:A.parameterExpansion(a,c),endIndex:s+1}}function Ns(t,e,n,r,s=!1){let o=n,i=e[o],a=e[o+1]||"";if(i===":"){let l=a;if("-=?+".includes(l)){o+=2;let E=ge(t,e,o),g=e.slice(o,E),b=fe(t,g,!1,!1,!0,!1,s),N=A.word(b.length>0?b:[A.literal("")]);if(l==="-")return{operation:{type:"DefaultValue",word:N,checkEmpty:!0},endIndex:E};if(l==="=")return{operation:{type:"AssignDefault",word:N,checkEmpty:!0},endIndex:E};if(l==="?")return{operation:{type:"ErrorIfUnset",word:N,checkEmpty:!0},endIndex:E};if(l==="+")return{operation:{type:"UseAlternative",word:N,checkEmpty:!0},endIndex:E}}o++;let c=ge(t,e,o),f=e.slice(o,c),d=-1,h=0,m=0;for(let p=0;p<f.length;p++){let E=f[p];if(E==="("||E==="[")h++;else if(E===")"||E==="]")h--;else if(E==="?"&&h===0)m++;else if(E===":"&&h===0)if(m>0)m--;else{d=p;break}}let y=d>=0?f.slice(0,d):f,w=d>=0?f.slice(d+1):null;return{operation:{type:"Substring",offset:It(t,y),length:w?It(t,w):null},endIndex:c}}if("-=?+".includes(i)){o++;let l=ge(t,e,o),c=e.slice(o,l),f=fe(t,c,!1,!1,!0,!1,s),d=A.word(f.length>0?f:[A.literal("")]);if(i==="-")return{operation:{type:"DefaultValue",word:d,checkEmpty:!1},endIndex:l};if(i==="=")return{operation:{type:"AssignDefault",word:d,checkEmpty:!1},endIndex:l};if(i==="?")return{operation:{type:"ErrorIfUnset",word:c?d:null,checkEmpty:!1},endIndex:l};if(i==="+")return{operation:{type:"UseAlternative",word:d,checkEmpty:!1},endIndex:l}}if(i==="#"||i==="%"){let l=a===i,c=i==="#"?"prefix":"suffix";o+=l?2:1;let f=ge(t,e,o),d=e.slice(o,f),h=fe(t,d,!1,!1,!1);return{operation:{type:"PatternRemoval",pattern:A.word(h.length>0?h:[A.literal("")]),side:c,greedy:l},endIndex:f}}if(i==="/"){let l=a==="/";o+=l?2:1;let c=null;e[o]==="#"?(c="start",o++):e[o]==="%"&&(c="end",o++);let f=jr(t,e,o),d=e.slice(o,f),h=fe(t,d,!1,!1,!1),m=A.word(h.length>0?h:[A.literal("")]),y=null,w=f;if(e[f]==="/"){let p=f+1,E=ge(t,e,p),g=e.slice(p,E),b=fe(t,g,!1,!1,!1);y=A.word(b.length>0?b:[A.literal("")]),w=E}return{operation:{type:"PatternReplacement",pattern:m,replacement:y,all:l,anchor:c},endIndex:w}}if(i==="^"||i===","){let l=a===i,c=i==="^"?"upper":"lower";o+=l?2:1;let f=ge(t,e,o),d=e.slice(o,f),h=d?A.word([A.literal(d)]):null;return{operation:{type:"CaseModification",direction:c,all:l,pattern:h},endIndex:f}}return i==="@"&&/[QPaAEK]/.test(a)?{operation:{type:"Transform",operator:a},endIndex:o+2}:{operation:null,endIndex:o}}function Bt(t,e,n,r=!1){let s=n+1;if(s>=e.length)return{part:A.literal("$"),endIndex:s};let o=e[s];if(o==="("&&e[s+1]==="(")return t.parseArithmeticExpansion(e,n);if(o==="["){let i=1,a=s+1;for(;a<e.length&&i>0;)e[a]==="["?i++:e[a]==="]"&&i--,i>0&&a++;if(i===0){let l=e.slice(s+1,a),c=T(t,l);return{part:A.arithmeticExpansion(c),endIndex:a+1}}}return o==="("?t.parseCommandSubstitution(e,n):o==="{"?bs(t,e,n,r):/[a-zA-Z_0-9@*#?$!-]/.test(o)?Ss(t,e,n):{part:A.literal("$"),endIndex:s}}function Cs(t,e){let n=[],r=0,s="",o=()=>{s&&(n.push(A.literal(s)),s="")};for(;r<e.length;){let i=e[r];if(i==="\\"&&r+1<e.length){let a=e[r+1];if(a==="$"||a==="`"){s+=a,r+=2;continue}s+=i,r++;continue}if(i==="$"){o();let{part:a,endIndex:l}=Bt(t,e,r,!0);a&&n.push(a),r=l;continue}if(i==="`"){o();let{part:a,endIndex:l}=t.parseBacktickSubstitution(e,r,!0);n.push(a),r=l;continue}s+=i,r++}return o(),n}function $s(t,e,n){let r=[],s=n,o="",i=()=>{o&&(r.push(A.literal(o)),o="")};for(;s<e.length&&e[s]!=='"';){let a=e[s];if(a==="\\"&&s+1<e.length){let l=e[s+1];if('"\\$`\n'.includes(l)){o+=l,s+=2;continue}o+=a,s++;continue}if(a==="$"){i();let{part:l,endIndex:c}=Bt(t,e,s,!0);l&&r.push(l),s=c;continue}if(a==="`"){i();let{part:l,endIndex:c}=t.parseBacktickSubstitution(e,s,!0);r.push(l),s=c;continue}o+=a,s++}return i(),{part:A.doubleQuoted(r),endIndex:s}}function fe(t,e,n=!1,r=!1,s=!1,o=!1,i=!1){if(r)return[A.singleQuoted(e)];if(n){let d=Cs(t,e);return[A.doubleQuoted(d)]}let a=[],l=0,c="",f=()=>{c&&(a.push(A.literal(c)),c="")};for(;l<e.length;){let d=e[l];if(d==="\\"&&l+1<e.length){let h=e[l+1];(o?h==="$"||h==="`"||h==="\\"||h===`
|
|
36
|
-
`:
|
|
37
|
-
`)?
|
|
38
|
-
`||r&&
|
|
39
|
-
`&&(i+=c),o+=2):(i+=e[o],o++)}else i+=e[o],o++;o>=e.length&&this.error("unexpected EOF while looking for matching ``'");let l=new t().parse(i);return{part:A.commandSubstitution(l,!0),endIndex:o+1}}parseArithmeticExpansion(e,n){let r=n+3,s=1,o=0,i=r;for(;i<e.length-1&&s>0;)e[i]==="$"&&e[i+1]==="("?e[i+2]==="("?(s++,i+=3):(o++,i+=2):e[i]==="("&&e[i+1]==="("?(s++,i+=2):e[i]===")"&&e[i+1]===")"?o>0?(o--,i++):(s--,s>0&&(i+=2)):e[i]==="("?(o++,i++):(e[i]===")"&&o>0&&o--,i++);let a=e.slice(r,i),l=this.parseArithmeticExpression(a);return{part:A.arithmeticExpansion(l),endIndex:i+2}}parseArithmeticCommand(){this.expect(u.DPAREN_START);let e="",n=1,r=0,s=!1,o=!1;for(;n>0&&!this.check(u.EOF);){if(s){if(s=!1,r>0){r--,e+=")";continue}if(this.check(u.RPAREN)){n--,o=!0,this.advance();continue}if(this.check(u.DPAREN_END)){n--,o=!0;continue}e+=")";continue}this.check(u.DPAREN_START)?(n++,e+="((",this.advance()):this.check(u.DPAREN_END)?r>=2?(r-=2,e+="))",this.advance()):r===1?(r--,e+=")",s=!0,this.advance()):(n--,o=!0,n>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=Mt(this);this.expect(u.DBRACK_END);let n=this.parseOptionalRedirections();return A.conditionalCommand(e,n)}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 n=this.parseCompoundCommandBody(),r=this.parseOptionalRedirections();return A.functionDef(e,n,r)}parseCompoundCommandBody(){if(this.check(u.LBRACE))return Ft(this);if(this.check(u.LPAREN))return Tt(this);if(this.check(u.IF))return kt(this);if(this.check(u.FOR))return Dt(this);if(this.check(u.WHILE))return Ot(this);if(this.check(u.UNTIL))return _t(this);if(this.check(u.CASE))return Lt(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 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 ue(t){return new M().parse(t)}var Pe=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((i,a)=>(n?.[a]??!1)||!this.isGlobPattern(i)?null:this.expand(i)),s=await Promise.all(r.map(i=>i||Promise.resolve(null))),o=[];for(let i=0;i<e.length;i++){let a=s[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)}async expandSimple(e){let n=[],r=e.lastIndexOf("/"),s,o;r===-1?(s=this.cwd,o=e):(s=e.slice(0,r)||"/",o=e.slice(r+1));let i=this.fs.resolvePath(this.cwd,s);try{let a=await this.fs.readdir(i);for(let l of a)if(this.matchPattern(l,o)){let c=r===-1?l:`${s}/${l}`;n.push(c)}}catch{}return n.sort()}async expandRecursive(e){let n=[],r=e.indexOf("**"),s=e.slice(0,r).replace(/\/$/,"")||".",i=e.slice(r+2).replace(/^\//,"");return await this.walkDirectory(s,i,n),n.sort()}async walkDirectory(e,n,r){let s=this.fs.resolvePath(this.cwd,e);try{if(this.fs.readdirWithFileTypes){let o=await this.fs.readdirWithFileTypes(s),i=[],a=[];for(let l of o){let c=e==="."?l.name:`${e}/${l.name}`;l.isDirectory?a.push(c):n&&this.matchPattern(l.name,n)&&i.push(c)}r.push(...i);for(let l=0;l<a.length;l+=100){let c=a.slice(l,l+100);await Promise.all(c.map(f=>this.walkDirectory(f,n,r)))}}else{let o=await this.fs.readdir(s),i=[];for(let l=0;l<o.length;l+=100){let c=o.slice(l,l+100),f=await Promise.all(c.map(async d=>{let h=e==="."?d:`${e}/${d}`,m=this.fs.resolvePath(this.cwd,h);try{let y=await this.fs.stat(m);return{name:d,path:h,isDirectory:y.isDirectory}}catch{return null}}));i.push(...f.filter(d=>d!==null))}for(let l of i)!l.isDirectory&&n&&this.matchPattern(l.name,n)&&r.push(l.path);let a=i.filter(l=>l.isDirectory);for(let l=0;l<a.length;l+=100){let c=a.slice(l,l+100);await Promise.all(c.map(f=>this.walkDirectory(f.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 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 l=e.slice(o+2,a),c=this.posixClassToRegex(l);i+=c,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+="]",n+=i,r=o}else if(s==="\\"&&r+1<e.length){let o=e[r+1];/[.+^${}()|\\*?[\]]/.test(o)?n+=`\\${o}`:n+=o,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 zt(t){let e=t.operation;return e?!!("word"in e&&e.word&&ie(e.word)||e.type==="PatternReplacement"&&(e.pattern&&ie(e.pattern)||e.replacement&&ie(e.replacement))||e.type==="PatternRemoval"&&e.pattern&&ie(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"&&ie(e.word));case"ParameterExpansion":return zt(t);default:return!1}}function ie(t){return t.parts.some(tt)}function Ut(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 tn(t){let e=!1,n=!1,r=!1,s=!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&&(s=!0);i.type==="CommandSubstitution"&&(n=!0),i.type==="ParameterExpansion"&&(o=!0,(i.parameter==="@"||i.parameter==="*")&&(r=!0),Ut(i)&&(e=!0))}return{hasQuoted:e,hasCommandSub:n,hasArrayVar:r,hasArrayAtExpansion:s,hasParamExpansion:o}}function vs(t,e,n,r,s){let o=n??1;o===0&&(o=1);let i=Math.abs(o),a=[],l=0;r?.match(/^-?0\d/)&&(l=Math.max(l,r.replace(/^-/,"").length)),s?.match(/^-?0\d/)&&(l=Math.max(l,s.replace(/^-/,"").length));let c=f=>{if(l>0){let d=f<0,h=String(Math.abs(f)).padStart(l,"0");return d?`-${h}`:h}return String(f)};if(t<=e)for(let f=t,d=0;f<=e&&d<1e4;f+=i,d++)a.push(c(f));else for(let f=t,d=0;f>=e&&d<1e4;f-=i,d++)a.push(c(f));return a}function Is(t,e,n){let r=n??1;r===0&&(r=1);let s=t.charCodeAt(0),o=e.charCodeAt(0),i=Math.abs(r),a=t>="A"&&t<="Z",l=t>="a"&&t<="z",c=e>="A"&&e<="Z",f=e>="a"&&e<="z";if(a&&f||l&&c)return null;let d=[];if(s<=o)for(let h=s,m=0;h<=o&&m<1e4;h+=i,m++)d.push(String.fromCharCode(h));else for(let h=s,m=0;h>=o&&m<1e4;h-=i,m++)d.push(String.fromCharCode(h));return d}function Me(t,e,n,r,s){let o=n!==void 0?`..${n}`:"";return typeof t=="number"&&typeof e=="number"?{expanded:vs(t,e,n,r,s),literal:`{${t}..${e}${o}}`}:typeof t=="string"&&typeof e=="string"?{expanded:Is(t,e,n),literal:`{${t}..${e}${o}}`}:{expanded:null,literal:`{${t}..${e}${o}}`}}function V(t,e){let n="",r=0;for(;r<t.length;){let s=t[r];if(s==="\\")if(r+1<t.length){let o=t[r+1];/[\\^$.|+(){}[\]*?]/.test(o)?n+=`\\${o}`:n+=o,r+=2}else n+="\\\\",r++;else if(s==="*")n+=e?".*":".*?",r++;else if(s==="?")n+=".",r++;else if(s==="["){let o=Rs(t,r);if(o===-1)n+="\\[",r++;else{let i=t.slice(r+1,o);n+=ks(i),r=o+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 ks(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 o=t.slice(n+1,s);for(let i of o)i==="\\"?e+="\\\\":i==="]"?e+="\\]":i==="^"&&e==="["?e+="\\^":e+=i;n=s+1;continue}}if(t[n]==="["&&n+1<t.length&&t[n+1]===":"){let s=t.indexOf(":]",n+2);if(s!==-1){let o=t.slice(n+2,s);e+=Os(o),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 Ds={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 Os(t){return Ds[t]??""}function Be(t,e){let n=`${e}_`,r=[];for(let s of Object.keys(t.state.env))if(s.startsWith(n)){let o=s.slice(n.length),i=Number.parseInt(o,10);!Number.isNaN(i)&&String(i)===o&&r.push(i)}return r.sort((s,o)=>s-o)}function ze(t,e){let n=`${e}_`;for(let r of Object.keys(t.state.env))r.startsWith(n)&&delete t.state.env[r]}function Gt(t,e){let n=`${e}_`,r=[];for(let s of Object.keys(t.state.env))if(s.startsWith(n)&&!s.includes("__")){let o=s.slice(n.length);r.push(o)}return r.sort()}function rn(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(...
|
|
43
|
-
`,""):t.state.env[`${
|
|
44
|
-
`:e+="\\n";break;case"\r":e+="\\r";break;case" ":e+="\\t";break;default:{let r=n.charCodeAt(0);r<32||r===127?e+=`\\x${r.toString(16).padStart(2,"0")}`:e+=n}}return`${e}'`}function
|
|
45
|
-
`)}return
|
|
46
|
-
`;case"r":return"\r";case"t":return" ";case"v":return"\v";case"'":return"'";case'"':return'"';case"?":return"?";default:return
|
|
47
|
-
`)}return
|
|
48
|
-
`,0;let
|
|
49
|
-
`,0;
|
|
50
|
-
`);n=r}throw new U(n)}async function
|
|
51
|
-
`)}catch{return
|
|
52
|
-
`)}}let
|
|
53
|
-
`:"")}function
|
|
54
|
-
`);n=r}throw new Y(n)}function
|
|
55
|
-
`):null}function
|
|
56
|
-
`}}return j(
|
|
57
|
-
`}return j(
|
|
58
|
-
`)&&!r&&!s){n&&(e.push(n),n="");continue}n+=
|
|
59
|
-
`)}return j(a)}}else if(
|
|
28
|
+
`&&(this.pos++,this.line++,this.column=1);break}i+=a,this.pos<this.input.length&&this.input[this.pos]===`
|
|
29
|
+
`&&(i+=`
|
|
30
|
+
`,this.pos++,this.line++,this.column=1)}this.tokens.push({type:f.HEREDOC_CONTENT,value:i,start:n,end:this.pos,line:r,column:s})}}addPendingHeredoc(e,n,r){this.pendingHeredocs.push({delimiter:e,stripTabs:n,quoted:r})}registerHeredocFromLookahead(e){let n=this.pos,r=this.column;for(;this.pos<this.input.length&&(this.input[this.pos]===" "||this.input[this.pos]===" ");)this.pos++,this.column++;let s="",i=!1,o=this.input[this.pos];if(o==="'"||o==='"'){i=!0;let a=o;for(this.pos++,this.column++;this.pos<this.input.length&&this.input[this.pos]!==a;)s+=this.input[this.pos],this.pos++,this.column++}else for(;this.pos<this.input.length&&!/[\s;<>&|()]/.test(this.input[this.pos]);)s+=this.input[this.pos],this.pos++,this.column++;this.pos=n,this.column=r,s&&this.pendingHeredocs.push({delimiter:s,stripTabs:e,quoted:i})}isWordCharFollowing(e){if(e>=this.input.length)return!1;let n=this.input[e];return!(n===" "||n===" "||n===`
|
|
31
|
+
`||n===";"||n==="&"||n==="|"||n==="("||n===")"||n==="<"||n===">")}readWordWithBraceExpansion(e,n,r){let s=this.input,i=s.length,o=e,a=r;for(;o<i;){let l=s[o];if(l===" "||l===" "||l===`
|
|
32
|
+
`||l===";"||l==="&"||l==="|"||l==="("||l===")"||l==="<"||l===">")break;if(l==="{"){if(this.scanBraceExpansion(o)!==null){let h=1;for(o++,a++;o<i&&h>0;)s[o]==="{"?h++:s[o]==="}"&&h--,o++,a++;continue}o++,a++;continue}if(l==="}"){o++,a++;continue}if(l==="$"&&o+1<i&&s[o+1]==="("){o++,a++,o++,a++;let u=1;for(;u>0&&o<i;)s[o]==="("?u++:s[o]===")"&&u--,o++,a++;continue}if(l==="$"&&o+1<i&&s[o+1]==="{"){o++,a++,o++,a++;let u=1;for(;u>0&&o<i;)s[o]==="{"?u++:s[o]==="}"&&u--,o++,a++;continue}if(l==="`"){for(o++,a++;o<i&&s[o]!=="`";)s[o]==="\\"&&o+1<i?(o+=2,a+=2):(o++,a++);o<i&&(o++,a++);continue}o++,a++}let c=s.slice(e,o);return this.pos=o,this.column=a,{type:f.WORD,value:c,start:e,end:o,line:n,column:r,quoted:!1,singleQuoted:!1}}scanBraceExpansion(e){let n=this.input,r=n.length,s=e+1,i=1,o=!1,a=!1;for(;s<r&&i>0;){let c=n[s];if(c==="{")i++,s++;else if(c==="}")i--,s++;else if(c===","&&i===1)o=!0,s++;else if(c==="."&&s+1<r&&n[s+1]===".")a=!0,s+=2;else{if(c===" "||c===" "||c===`
|
|
33
|
+
`||c===";"||c==="&"||c==="|")return null;s++}}return i===0&&(o||a)?n.slice(e,s):null}scanLiteralBraceWord(e){let n=this.input,r=n.length,s=e+1,i=1;for(;s<r&&i>0;){let o=n[s];if(o==="{")i++,s++;else if(o==="}"){if(i--,i===0)return n.slice(e,s+1);s++}else{if(o===" "||o===" "||o===`
|
|
34
|
+
`||o===";"||o==="&"||o==="|")return null;s++}}return null}};var vt=1e6,$t=1e5,Ur=1e6,Gr=new Set([f.LESS,f.GREAT,f.DLESS,f.DGREAT,f.LESSAND,f.GREATAND,f.LESSGREAT,f.DLESSDASH,f.CLOBBER,f.TLESS,f.AND_GREAT,f.AND_DGREAT]),Vr=new Set([f.LESS,f.GREAT,f.DLESS,f.DGREAT,f.LESSAND,f.GREATAND,f.LESSGREAT,f.DLESSDASH,f.CLOBBER,f.TLESS]),ie=class extends Error{line;column;token;constructor(e,n,r,s=void 0){super(`Parse error at ${n}:${r}: ${e}`),this.line=n,this.column=r,this.token=s,this.name="ParseException"}};function jr(t,e,n){let r=n+1;for(;r<e.length&&/[a-zA-Z0-9_-]/.test(e[r]);)r++;return r}function kt(t,e,n,r,s){let i=1,o=n+1;for(;o<e.length&&i>0;)e[o]===r?i++:e[o]===s&&i--,i>0&&o++;return i===0?o:-1}function Ae(t,e,n){let r=n,s=1;for(;r<e.length&&s>0;){let i=e[r];if(i==="\\"&&r+1<e.length){r+=2;continue}if(i==="'"){let o=e.indexOf("'",r+1);if(o!==-1){r=o+1;continue}}if(i==='"'){for(r++;r<e.length&&e[r]!=='"';)e[r]==="\\"&&r+1<e.length?r+=2:r++;r<e.length&&r++;continue}i==="{"?s++:i==="}"&&s--,s>0&&r++}return r}function qr(t,e,n){let r=n,s=!1;for(;r<e.length;){let i=e[r];if(i==="/"&&s||i==="}")break;if(i==="'"){let o=e.indexOf("'",r+1);if(o!==-1){r=o+1,s=!0;continue}}if(i==='"'){for(r++;r<e.length&&e[r]!=='"';)e[r]==="\\"&&r+1<e.length?r+=2:r++;r<e.length&&r++,s=!0;continue}i==="\\"?(r+=2,s=!0):(r++,s=!0)}return r}function Zr(t,e,n){let r=n,s="";for(;r<e.length;){let i=e[r];if(i==="*"||i==="?")s+=i,r++;else if(i==="["){let o=fs(e,r);o===-1?(s+=i,r++):(s+=e.slice(r,o+1),r=o+1)}else break}return{pattern:s,endIndex:r}}function fs(t,e){let n=e+1;for(n<t.length&&t[n]==="^"&&n++,n<t.length&&t[n]==="]"&&n++;n<t.length;){let r=t[n];if(r==="\\"&&n+1<t.length){n+=2;continue}if(r==="]")return n;if(r==='"'||r==="$"||r==="`")return-1;if(r==="'"){let s=t.indexOf("'",n+1);if(s!==-1){n=s+1;continue}}if(r==="["&&n+1<t.length&&t[n+1]===":"){let s=t.indexOf(":]",n+2);if(s!==-1){n=s+2;continue}}if(r==="["&&n+1<t.length&&(t[n+1]==="."||t[n+1]==="=")){let i=`${t[n+1]}]`,o=t.indexOf(i,n+2);if(o!==-1){n=o+2;continue}}n++}return-1}function Qr(t,e,n){let r="",s=n;for(;s<e.length&&e[s]!=="'";){let i=e[s];if(i==="\\"&&s+1<e.length)switch(e[s+1]){case"n":r+=`
|
|
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===`
|
|
36
|
+
`:d==="$"||d==="`"||d==="\\"||d==='"'||d===`
|
|
37
|
+
`)?l+=d:l+=`\\${d}`,c+=2;continue}if(h==="'"&&!o&&!i){u();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==='"'&&!i){u();let{part:d,endIndex:m}=vs(t,e,c+1);a.push(d),c=m+1;continue}if(h==="$"&&e[c+1]==="'"){u();let{part:d,endIndex:m}=Qr(t,e,c+2);a.push(d),c=m;continue}if(h==="$"){u();let{part:d,endIndex:m}=Bt(t,e,c);d&&a.push(d),c=m;continue}if(h==="`"){u();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==="="||s&&d===":"){let y=jr(t,e,c),E=e[y];if(E===void 0||E==="/"||E===":"){u();let p=e.slice(c+1,y)||null;a.push({type:"TildeExpansion",user:p}),c=y;continue}}}if(h==="*"||h==="?"||h==="["){u();let{pattern:d,endIndex:m}=Zr(t,e,c);a.push({type:"Glob",pattern:d}),c=m;continue}if(h==="{"&&!s){let d=Kr(t,e,c,fe);if(d){u(),a.push(d.part),c=d.endIndex;continue}}l+=h,c++}return u(),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 n=new Ye(e);if(this.tokens=n.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,n,r,s,...i){let o=this.tokens[this.pos]?.type;return o===e||n!==void 0&&o===n||r!==void 0&&o===r||s!==void 0&&o===s?!0:i.length>0?i.includes(o):!1}expect(e,n){if(this.check(e))return this.advance();let r=this.current();throw new ie(n||`Expected ${e}, got ${r.type}`,r.line,r.column,r)}error(e){let n=this.current();throw new ie(e,n.line,n.column,n)}skipNewlines(){for(;this.check(f.NEWLINE,f.COMMENT);)this.check(f.NEWLINE)?(this.advance(),this.processHeredocs()):this.advance()}skipSeparators(e=!0){for(;;){if(this.check(f.NEWLINE)){this.advance(),this.processHeredocs();continue}if(this.check(f.SEMICOLON,f.COMMENT)){this.advance();continue}if(e&&this.check(f.DSEMI,f.SEMI_AND,f.SEMI_SEMI_AND)){this.advance();continue}break}}addPendingHeredoc(e,n,r,s){this.pendingHeredocs.push({redirect:e,delimiter:n,stripTabs:r,quoted:s})}processHeredocs(){for(let e of this.pendingHeredocs)if(this.check(f.HEREDOC_CONTENT)){let n=this.advance(),r;e.quoted?r=A.word([A.literal(n.value)]):r=this.parseWordFromString(n.value,!1,!1,!1,!0),e.redirect.target=A.hereDoc(e.delimiter,r,e.stripTabs,e.quoted)}this.pendingHeredocs=[]}isStatementEnd(){return this.check(f.EOF,f.NEWLINE,f.SEMICOLON,f.AMP,f.AND_AND,f.OR_OR,f.RPAREN,f.RBRACE,f.DSEMI,f.SEMI_AND,f.SEMI_SEMI_AND)}isCommandStart(){let e=this.current().type;return e===f.WORD||e===f.NAME||e===f.NUMBER||e===f.ASSIGNMENT_WORD||e===f.IF||e===f.FOR||e===f.WHILE||e===f.UNTIL||e===f.CASE||e===f.LPAREN||e===f.LBRACE||e===f.DPAREN_START||e===f.DBRACK_START||e===f.FUNCTION||e===f.BANG||e===f.IN||e===f.LESS||e===f.GREAT||e===f.DLESS||e===f.DGREAT||e===f.LESSAND||e===f.GREATAND||e===f.LESSGREAT||e===f.DLESSDASH||e===f.CLOBBER||e===f.TLESS||e===f.AND_GREAT||e===f.AND_DGREAT}parseScript(){let e=[],r=0;for(this.skipNewlines();!this.check(f.EOF);){r++,r>1e4&&this.error("Parser stuck: too many iterations (>10000)"),this.checkUnexpectedToken();let s=this.pos,i=this.parseStatement();i&&e.push(i),this.skipSeparators(!1),this.check(f.DSEMI,f.SEMI_AND,f.SEMI_SEMI_AND)&&this.error(`syntax error near unexpected token \`${this.current().value}'`),this.pos===s&&!this.check(f.EOF)&&this.advance()}return A.script(e)}checkUnexpectedToken(){let e=this.current().type,n=this.current().value;(e===f.DO||e===f.DONE||e===f.THEN||e===f.ELSE||e===f.ELIF||e===f.FI||e===f.ESAC)&&this.error(`syntax error near unexpected token \`${n}'`),(e===f.RBRACE||e===f.RPAREN)&&this.error(`syntax error near unexpected token \`${n}'`),(e===f.DSEMI||e===f.SEMI_AND||e===f.SEMI_SEMI_AND)&&this.error(`syntax error near unexpected token \`${n}'`),e===f.SEMICOLON&&this.error(`syntax error near unexpected token \`${n}'`)}parseStatement(){if(this.skipNewlines(),!this.isCommandStart())return null;let e=[],n=[],r=!1,s=this.parsePipeline();for(e.push(s);this.check(f.AND_AND,f.OR_OR);){let i=this.advance();n.push(i.type===f.AND_AND?"&&":"||"),this.skipNewlines();let o=this.parsePipeline();e.push(o)}return this.check(f.AMP)&&(this.advance(),r=!0),A.statement(e,n,r)}parsePipeline(){let e=0;for(;this.check(f.BANG);)this.advance(),e++;let n=e%2===1,r=[],s=this.parseCommand();for(r.push(s);this.check(f.PIPE,f.PIPE_AMP);){let i=this.advance();this.skipNewlines();let o=this.parseCommand();i.type===f.PIPE_AMP&&o.type==="SimpleCommand"&&o.redirections.unshift(A.redirection(">&",A.word([A.literal("1")]),2)),r.push(o)}return A.pipeline(r,n)}parseCommand(){return this.check(f.IF)?Dt(this):this.check(f.FOR)?Ot(this):this.check(f.WHILE)?_t(this):this.check(f.UNTIL)?Lt(this):this.check(f.CASE)?Tt(this):this.check(f.LPAREN)?Ft(this):this.check(f.LBRACE)?Wt(this):this.check(f.DPAREN_START)?this.parseArithmeticCommand():this.check(f.DBRACK_START)?this.parseConditionalCommand():this.check(f.FUNCTION)?this.parseFunctionDef():this.check(f.NAME,f.WORD)&&this.peek(1).type===f.LPAREN&&this.peek(2).type===f.RPAREN?this.parseFunctionDef():en(this)}isWord(){let e=this.current().type;return e===f.WORD||e===f.NAME||e===f.NUMBER||e===f.IF||e===f.FOR||e===f.WHILE||e===f.UNTIL||e===f.CASE||e===f.FUNCTION||e===f.ELSE||e===f.ELIF||e===f.FI||e===f.THEN||e===f.DO||e===f.DONE||e===f.ESAC||e===f.IN||e===f.SELECT||e===f.TIME||e===f.COPROC||e===f.BANG}parseWord(){let e=this.advance();return this.parseWordFromString(e.value,e.quoted,e.singleQuoted)}parseWordFromString(e,n=!1,r=!1,s=!1,i=!1){let o=fe(this,e,n,r,s,i);return A.word(o)}parseCommandSubstitution(e,n){let r=n+2,s=1,i=r,o=!1,a=!1,c=0,l=!1,u="";for(;i<e.length&&s>0;){let y=e[i];o?y==="'"&&(o=!1):a?y==="\\"&&i+1<e.length?i++:y==='"'&&(a=!1):y==="'"?(o=!0,u=""):y==='"'?(a=!0,u=""):y==="\\"&&i+1<e.length?(i++,u=""):/[a-zA-Z_]/.test(y)?u+=y:(u==="case"?(c++,l=!1):u==="in"&&c>0?l=!0:u==="esac"&&c>0&&(c--,l=!1),u="",y==="("?i>0&&e[i-1]==="$"?s++:l||s++:y===")"?l?l=!1:s--:y===";"&&c>0&&i+1<e.length&&e[i+1]===";"&&(l=!0)),s>0&&i++}s>0&&this.error("unexpected EOF while looking for matching `)'");let h=e.slice(r,i),m=new t().parse(h);return{part:A.commandSubstitution(m,!1),endIndex:i+1}}parseBacktickSubstitution(e,n,r=!1){let i=n+1,o="";for(;i<e.length&&e[i]!=="`";)if(e[i]==="\\"){let l=e[i+1];l==="$"||l==="`"||l==="\\"||l===`
|
|
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 sn(t){return t.IFS===""}function Ue(t){return t.split("").map(e=>/[\\^$.*+?()[\]{}|-]/.test(e)?`\\${e}`:e===" "?"\\t":e===`
|
|
41
|
+
`?"\\n":e).join("")}function Ls(t,e){let n=Ue(t);return new RegExp(`[${n}]+`,e)}function Ts(t){let e=Ue(t);return new RegExp(`^[${e}]+`)}function Fs(t){let e=Ue(t);return new RegExp(`[${e}]+$`)}function $e(t){let e=t.IFS;return e===void 0?" ":e[0]||""}function on(t,e){if(e==="")return{words:[t],wordStarts:[0]};let n=[],r=[],s=Ls(e,"g"),i=0,o=t.match(Ts(e));o&&(i=o[0].length),s.lastIndex=i;let a=s.exec(t);for(;a!==null;)a.index>i&&(r.push(i),n.push(t.substring(i,a.index))),i=s.lastIndex,a=s.exec(t);return i<t.length&&(r.push(i),n.push(t.substring(i))),{words:n,wordStarts:r}}function an(t,e){return e===""?t:t.replace(Fs(e),"")}function F(t,e){return t.state.associativeArrays?.has(e)?Vt(t,e).map(i=>[i,t.state.env[`${e}_${i}`]]):ze(t,e).map(s=>[s,t.state.env[`${e}_${s}`]])}function cn(t,e){return t.state.associativeArrays?.has(e)?Vt(t,e).length>0:ze(t,e).length>0}function Q(t,e,n=!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 o="";return t.state.options.errexit&&(o+="e"),t.state.options.nounset&&(o+="u"),t.state.options.verbose&&(o+="v"),t.state.options.xtrace&&(o+="x"),t.state.options.pipefail&&(o+="p"),o}case"*":{let o=Number.parseInt(t.state.env["#"]||"0",10);if(o===0)return"";let a=[];for(let c=1;c<=o;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:o}=We();return String(o)}case"UID":{let{uid:o}=We();return String(o)}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 s=e.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(s){let o=s[1],a=s[2];if(a==="@"||a==="*"){let h=F(t,o);if(h.length>0)return h.map(([,m])=>m).join(" ");let d=t.state.env[o];return d!==void 0?d:""}if(t.state.associativeArrays?.has(o)){let h=nn(a),d=t.state.env[`${o}_${h}`];if(d===void 0&&n&&t.state.options.nounset)throw new J(`${o}[${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,o);if(h.length===0)return t.state.expansionStderr=(t.state.expansionStderr||"")+`bash: ${o}: 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: ${o}: bad array subscript
|
|
43
|
+
`,""):t.state.env[`${o}_${m}`]||""}let u=t.state.env[`${o}_${l}`];if(u===void 0&&n&&t.state.options.nounset)throw new J(`${o}[${l}]`);return u||""}if(/^[1-9][0-9]*$/.test(e)){let o=t.state.env[e];if(o===void 0&&n&&t.state.options.nounset)throw new J(e);return o||""}let i=t.state.env[e];if(i===void 0&&n&&t.state.options.nounset)throw new J(e);return i||""}async function ln(t,e,n,r,s){let i=[];for(let u of e){let h=u.type==="ParameterExpansion"||u.type==="CommandSubstitution"||u.type==="ArithmeticExpansion";if(u.type==="ParameterExpansion"&&Gt(u)){let d=await s(t,u);i.push({value:d,splittable:!1})}else{let d=await s(t,u);i.push({value:d,splittable:h})}}if(!i.some(u=>u.splittable&&new RegExp(`[${r}]`).test(u.value))){let u=i.map(h=>h.value).join("");return u?[u]:[]}let a=new RegExp(`[${r}]+`),c=[],l="";for(let u=0;u<i.length;u++){let h=i[u];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 un(t){switch(t.type){case"Literal":return t.value;case"SingleQuoted":return t.value;case"Escaped":return t.value;default:return null}}function fn(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 n of t)switch(n){case"'":e+="\\'";break;case"\\":e+="\\\\";break;case`
|
|
44
|
+
`:e+="\\n";break;case"\r":e+="\\r";break;case" ":e+="\\t";break;default:{let r=n.charCodeAt(0);r<32||r===127?e+=`\\x${r.toString(16).padStart(2,"0")}`:e+=n}}return`${e}'`}function Se(t,e,n=!1){return e.map(r=>ae(t,r,n)).join("")}async function xe(t,e,n=!1){let r=[];for(let s of e)r.push(await K(t,s));return r.join("")}function Ws(t){return fn(t)}function hn(t){if(t.parts.length===0)return!0;for(let e of t.parts)if(!Ws(e))return!1;return!0}function dn(t){return t.replace(/([*?[\]\\])/g,"\\$1")}function mn(t,e,n=!1){let r=un(e);if(r!==null)return r;switch(e.type){case"ParameterExpansion":return gn(t,e,n);case"TildeExpansion":return n?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,n=!1){let r=mn(t,e,n);if(r!==null)return r;switch(e.type){case"DoubleQuoted":{let s=[];for(let i of e.parts)s.push(ae(t,i,!0));return s.join("")}case"ArithmeticExpansion":return String(P(t,e.expression.expression));case"BraceExpansion":{let s=[];for(let i of e.items)if(i.type==="Range"){let o=Me(i.start,i.end,i.step,i.startStr,i.endStr);if(o.expanded)s.push(...o.expanded);else return o.literal}else s.push(nt(t,i.word));return s.join(" ")}default:return""}}function nt(t,e){let n=e.parts,r=n.length;if(r===1)return ae(t,n[0]);let s=[];for(let i=0;i<r;i++)s.push(ae(t,n[i]));return s.join("")}async function k(t,e){return oe(e)?En(t,e):nt(t,e)}function st(t){for(let e of t)if(e.type==="BraceExpansion"||e.type==="DoubleQuoted"&&st(e.parts))return!0;return!1}function Ms(t){for(let e of t){if(e.type==="BraceExpansion"){for(let n of e.items)if(n.type==="Word"&&oe(n.word))return!0}if(tt(e))return!0}return!1}var pn=1e4,ke=1e5;function yn(t,e,n={count:0}){if(n.count>ke)return[[]];let r=[[]];for(let s of e)if(s.type==="BraceExpansion"){let i=[],o=!1,a="";for(let u of s.items)if(u.type==="Range"){let h=Me(u.start,u.end,u.step,u.startStr,u.endStr);if(h.expanded)for(let d of h.expanded)n.count++,i.push(d);else{o=!0,a=h.literal;break}}else{let h=yn(t,u.word.parts,n);for(let d of h)n.count++,i.push(d.join(""))}if(o){for(let u of r)n.count++,u.push(a);continue}if(r.length*i.length>pn||n.count>ke)return r;let l=[];for(let u of r)for(let h of i){if(n.count++,n.count>ke)return l.length>0?l:r;l.push([...u,h])}r=l}else{let i=ae(t,s);for(let o of r)n.count++,o.push(i)}return r}function zs(t,e){let n=e.parts;return st(n)?yn(t,n).map(s=>s.join("")):[nt(t,e)]}async function wn(t,e,n={count:0}){if(n.count>ke)return[[]];let r=[[]];for(let s of e)if(s.type==="BraceExpansion"){let i=[],o=!1,a="";for(let u of s.items)if(u.type==="Range"){let h=Me(u.start,u.end,u.step,u.startStr,u.endStr);if(h.expanded)for(let d of h.expanded)n.count++,i.push(d);else{o=!0,a=h.literal;break}}else{let h=await wn(t,u.word.parts,n);for(let d of h)n.count++,i.push(d.join(""))}if(o){for(let u of r)n.count++,u.push(a);continue}if(r.length*i.length>pn||n.count>ke)return r;let l=[];for(let u of r)for(let h of i){if(n.count++,n.count>ke)return l.length>0?l:r;l.push([...u,h])}r=l}else{let i=await K(t,s);for(let o of r)n.count++,o.push(i)}return r}async function Bs(t,e){let n=e.parts;return st(n)?(await wn(t,n)).map(s=>s.join("")):[await k(t,e)]}async function Ge(t,e){let n=e.parts,{hasQuoted:r,hasCommandSub:s,hasArrayVar:i,hasArrayAtExpansion:o,hasParamExpansion:a}=rn(n),l=st(n)?Ms(n)?await Bs(t,e):zs(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(o&&n.length===1&&n[0].type==="DoubleQuoted"){let d=n[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(n.length===1&&n[0].type==="DoubleQuoted"){let d=n[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((s||i||a)&&!sn(t.state.env)){let d=rt(t.state.env),m=Ue(d),y=await ln(t,n,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 En(t,e):nt(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 En(t,e){let n=e.parts,r=n.length;if(r===1)return K(t,n[0]);let s=[];for(let i=0;i<r;i++)s.push(await K(t,n[i]));return s.join("")}async function K(t,e){if(e.type==="ParameterExpansion"&&Ut(e))return Us(t,e);let n=mn(t,e);if(n!==null)return n;switch(e.type){case"DoubleQuoted":{let r=[];for(let s of e.parts)r.push(await K(t,s));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 s of e.items)if(s.type==="Range"){let i=Me(s.start,s.end,s.step,s.startStr,s.endStr);if(i.expanded)r.push(...i.expanded);else return i.literal}else r.push(await k(t,s.word));return r.join(" ")}default:return""}}function gn(t,e,n=!1){let{parameter:r,operation:s}=e,i=s&&(s.type==="DefaultValue"||s.type==="AssignDefault"||s.type==="UseAlternative"||s.type==="ErrorIfUnset"),o=Q(t,r,!i);if(!s)return o;let a=!(r in t.state.env),c=o==="";switch(s.type){case"DefaultValue":return(a||s.checkEmpty&&c)&&s.word?Se(t,s.word.parts,n):o;case"AssignDefault":{if((a||s.checkEmpty&&c)&&s.word){let u=Se(t,s.word.parts,n),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}`]=u;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]=u;return u}return o}case"ErrorIfUnset":{if(a||s.checkEmpty&&c){let u=s.word?Se(t,s.word.parts,n):`${r}: parameter null or not set`;throw new R(1,"",`bash: ${u}
|
|
45
|
+
`)}return o}case"UseAlternative":return!(a||s.checkEmpty&&c)&&s.word?Se(t,s.word.parts,n):"";case"Length":{let l=r.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[[@*]\]$/);if(l){let u=F(t,l[1]);return String(u.length)}if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(r)&&cn(t,r)){let u=t.state.env[`${r}_0`]||"";return String(u.length)}return String(o.length)}case"LengthSliceError":throw new Ee(r);case"Substring":{let l=s.offset?P(t,s.offset.expression):0,u=s.length?P(t,s.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(u!==void 0){let g=u<0?p.length+u:w+u;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(u!==void 0){if(u<0){let w=E.length+u;return E.slice(p,Math.max(p,w)).join(" ")}return E.slice(p,p+u).join(" ")}return E.slice(p).join(" ")}let d=[...o],m=l;if(m<0&&(m=Math.max(0,d.length+m)),u!==void 0){if(u<0){let y=d.length+u;return d.slice(m,Math.max(m,y)).join("")}return d.slice(m,m+u).join("")}return d.slice(m).join("")}case"PatternRemoval":{let l="";if(s.pattern)for(let h of s.pattern.parts)if(h.type==="Glob")l+=V(h.pattern,s.greedy);else if(h.type==="Literal")l+=V(h.value,s.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,s.greedy)}else{let d=ae(t,h);l+=H(d)}if(s.side==="prefix")return o.replace(new RegExp(`^${l}`),"");let u=new RegExp(`${l}$`);if(s.greedy)return o.replace(u,"");for(let h=o.length;h>=0;h--){let d=o.slice(h);if(u.test(d))return o.slice(0,h)}return o}case"PatternReplacement":{let l="";if(s.pattern)for(let d of s.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 u=s.replacement?Se(t,s.replacement.parts):"";if(l==="")return o;s.anchor==="start"?l=`^${l}`:s.anchor==="end"&&(l=`${l}$`);let h=s.all?"g":"";try{let d=new RegExp(l,h);if(s.all){let m="",y=0,E=d.exec(o);for(;E!==null&&!(E[0].length===0&&E.index===o.length);)m+=o.slice(y,E.index)+u,y=E.index+E[0].length,E[0].length===0&&y++,E=d.exec(o);return m+=o.slice(y),m}return o.replace(d,u)}catch{return o}}case"CaseModification":return s.direction==="upper"?s.all?o.toUpperCase():o.charAt(0).toUpperCase()+o.slice(1):s.all?o.toLowerCase():o.charAt(0).toLowerCase()+o.slice(1);case"Transform":{let l=r.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[[@*]\]$/);if(l&&s.operator==="Q")return F(t,l[1]).map(([,d])=>Ht(d)).join(" ");switch(s.operator){case"Q":return Ht(o);case"P":return o;case"a":return"";case"A":return`${r}=${Ht(o)}`;case"E":return o.replace(/\\([\\abefnrtv'"?])/g,(u,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 o}}case"Indirection":return Q(t,o);case"ArrayKeys":{let u=F(t,s.array).map(([h])=>String(h));return s.star?u.join($e(t.state.env)):u.join(" ")}case"VarNamePrefix":{let l=Object.keys(t.state.env).filter(u=>u.startsWith(s.prefix)&&!u.includes("__")).sort();return s.star?l.join($e(t.state.env)):l.join(" ")}default:return o}}async function Us(t,e,n=!1){let{parameter:r,operation:s}=e,i=s&&(s.type==="DefaultValue"||s.type==="AssignDefault"||s.type==="UseAlternative"||s.type==="ErrorIfUnset"),o=Q(t,r,!i);if(!s)return o;let a=!(r in t.state.env),c=o==="";switch(s.type){case"DefaultValue":return(a||s.checkEmpty&&c)&&s.word?xe(t,s.word.parts,n):o;case"AssignDefault":{if((a||s.checkEmpty&&c)&&s.word){let u=await xe(t,s.word.parts,n),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}`]=u;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]=u;return u}return o}case"ErrorIfUnset":{if(a||s.checkEmpty&&c){let u=s.word?await xe(t,s.word.parts,n):`${r}: parameter null or not set`;throw new R(1,"",`bash: ${u}
|
|
47
|
+
`)}return o}case"UseAlternative":return!(a||s.checkEmpty&&c)&&s.word?xe(t,s.word.parts,n):"";case"PatternRemoval":{let l="";if(s.pattern)for(let h of s.pattern.parts)if(h.type==="Glob")l+=V(h.pattern,s.greedy);else if(h.type==="Literal")l+=V(h.value,s.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,s.greedy)}else{let d=await K(t,h);l+=H(d)}if(s.side==="prefix")return o.replace(new RegExp(`^${l}`),"");let u=new RegExp(`${l}$`);if(s.greedy)return o.replace(u,"");for(let h=o.length;h>=0;h--){let d=o.slice(h);if(u.test(d))return o.slice(0,h)}return o}case"PatternReplacement":{let l="";if(s.pattern)for(let d of s.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 u=s.replacement?await xe(t,s.replacement.parts):"";if(l==="")return o;s.anchor==="start"?l=`^${l}`:s.anchor==="end"&&(l=`${l}$`);let h=s.all?"g":"";try{let d=new RegExp(l,h);if(s.all){let m="",y=0,E=d.exec(o);for(;E!==null&&!(E[0].length===0&&E.index===o.length);)m+=o.slice(y,E.index)+u,y=E.index+E[0].length,E[0].length===0&&y++,E=d.exec(o);return m+=o.slice(y),m}return o.replace(d,u)}catch{return o}}default:return gn(t,e,n)}}function jt(t,e,n){switch(n){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 An(t,e,n){switch(n){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 Gs(t,e){let n=t.state.env[e];if(n!==void 0)return n;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 n=t.trim();if(!n)return 0;try{let r=new z,{expr:s,pos:i}=se(r,n,0);if(i<n.length){let o=n.slice(i).trim().split(/\s+/)[0];throw new W(`${n}: syntax error in expression (error token is "${o}")`)}return s.type==="ArithNumber"?s.value:e||0}catch(r){if(r instanceof W)throw r;let s=n.split(/\s+/).slice(1)[0]||n;throw new W(`${n}: syntax error in expression (error token is "${s}")`)}}function it(t,e,n=new Set){if(n.has(e))return 0;n.add(e);let r=Gs(t,e);if(!r)return 0;let s=Number.parseInt(r,10);if(!Number.isNaN(s)&&/^-?\d+$/.test(r.trim()))return s;let i=r.trim();if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(i))return it(t,i,n);try{let o=new z,{expr:a}=se(o,i,0);return X(t,a,n)}catch{return 0}}function X(t,e,n){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,n);case"ArithBinary":{if(e.operator==="||")return X(t,e.left,n)||X(t,e.right,n)?1:0;if(e.operator==="&&")return X(t,e.left,n)&&X(t,e.right,n)?1:0;let r=X(t,e.left,n),s=X(t,e.right,n);return jt(r,s,e.operator)}case"ArithUnary":{let r=X(t,e.operand,n);return qt(r,e.operator)}case"ArithTernary":return X(t,e.condition,n)?X(t,e.consequent,n):X(t,e.alternate,n);case"ArithGroup":return X(t,e.expression,n);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 n=[":-",":=",":?",":+","-","=","?","+"],r=-1,s="";for(let h of n){let d=e.indexOf(h);d>0&&(r===-1||d<r)&&(r=d,s=h)}if(r===-1)return Q(t,e);let i=e.slice(0,r),o=e.slice(r+s.length),a=t.state.env[i],c=a===void 0,l=a==="",u=s.startsWith(":");switch(s){case":-":case"-":return c||u&&l?o:a||"";case":=":case"=":return c||u&&l?(t.state.env[i]=o,o):a||"";case":+":case"+":return!(c||u&&l)?o:"";case":?":case"?":{if(c||u&&l)throw new Error(o||`${i}: 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 n=de(t,e.content);return Number.parseInt(n,10)||0}case"ArithDynamicBase":{let n=de(t,e.baseExpr),r=Number.parseInt(n,10);if(r<2||r>64)return 0;let s=`${r}#${e.value}`;return Ne(s)}case"ArithDynamicNumber":{let r=de(t,e.prefix)+e.suffix;return Ne(r)}case"ArithArrayElement":{let n=t.state.associativeArrays?.has(e.array),r;if(e.stringKey!==void 0)r=`${e.array}_${e.stringKey}`;else if(n&&e.index?.type==="ArithVariable")r=`${e.array}_${e.index.name}`;else if(e.index){let i=P(t,e.index);if(i<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(([u])=>typeof u=="number"?u:0))+1+i;if(l<0)return t.state.expansionStderr=(t.state.expansionStderr||"")+`bash: ${e.array}: bad array subscript
|
|
49
|
+
`,0;i=l}r=`${e.array}_${i}`;let o=t.state.env[r];if(o!==void 0)return Ie(o);if(i===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}[${i}]`);return 0}else return 0;let s=t.state.env[r];return s!==void 0?Ie(s):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 n=P(t,e.left),r=P(t,e.right);return jt(n,r,e.operator)}case"ArithUnary":{let n=P(t,e.operand);if(e.operator==="++"||e.operator==="--"){if(e.operand.type==="ArithVariable"){let r=e.operand.name,s=Number.parseInt(Q(t,r),10)||0,i=e.operator==="++"?s+1:s-1;return t.state.env[r]=String(i),e.prefix?i:s}if(e.operand.type==="ArithArrayElement"){let r=e.operand.array,s=t.state.associativeArrays?.has(r),i;if(e.operand.stringKey!==void 0)i=`${r}_${e.operand.stringKey}`;else if(s&&e.operand.index?.type==="ArithVariable")i=`${r}_${e.operand.index.name}`;else if(e.operand.index){let c=P(t,e.operand.index);i=`${r}_${c}`}else return n;let o=Number.parseInt(t.state.env[i]||"0",10)||0,a=e.operator==="++"?o+1:o-1;return t.state.env[i]=String(a),e.prefix?a:o}return n}return qt(n,e.operator)}case"ArithTernary":return P(t,e.condition)?P(t,e.consequent):P(t,e.alternate);case"ArithAssignment":{let n=e.variable,r=n;if(e.stringKey!==void 0)r=`${n}_${e.stringKey}`;else if(e.subscript){let a=t.state.associativeArrays?.has(n);if(a&&e.subscript.type==="ArithVariable")r=`${n}_${e.subscript.name}`;else if(a){let c=P(t,e.subscript);r=`${n}_${c}`}else{let c=P(t,e.subscript);if(c<0){let l=F(t,n);l.length>0&&(c=Math.max(...l.map(([h])=>typeof h=="number"?h:0))+1+c)}r=`${n}_${c}`}}let s=Number.parseInt(t.state.env[r]||"0",10)||0,i=P(t,e.value),o=An(s,i,e.operator);return t.state.env[r]=String(o),o}case"ArithGroup":return P(t,e.expression);case"ArithConcat":{let n="";for(let r of e.parts)n+=Sn(t,r);return Number.parseInt(n,10)||0}default:return 0}}function Sn(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 n="";for(let r of e.parts)n+=Sn(t,r);return n}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 n=de(t,e.content);return Number.parseInt(n,10)||0}case"ArithDynamicBase":{let n=de(t,e.baseExpr),r=Number.parseInt(n,10);if(r<2||r>64)return 0;let s=`${r}#${e.value}`;return Ne(s)}case"ArithDynamicNumber":{let r=de(t,e.prefix)+e.suffix;return Ne(r)}case"ArithArrayElement":{let n=t.state.associativeArrays?.has(e.array),r;if(e.stringKey!==void 0)r=`${e.array}_${e.stringKey}`;else if(n&&e.index?.type==="ArithVariable")r=`${e.array}_${e.index.name}`;else if(e.index){let i=await v(t,e.index);r=`${e.array}_${i}`;let o=t.state.env[r];if(o!==void 0)return Ie(o);if(i===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}[${i}]`);return 0}else return 0;let s=t.state.env[r];return s!==void 0?Ie(s):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 n=await v(t,e.left),r=await v(t,e.right);return jt(n,r,e.operator)}case"ArithUnary":{let n=await v(t,e.operand);if(e.operator==="++"||e.operator==="--"){if(e.operand.type==="ArithVariable"){let r=e.operand.name,s=Number.parseInt(Q(t,r),10)||0,i=e.operator==="++"?s+1:s-1;return t.state.env[r]=String(i),e.prefix?i:s}if(e.operand.type==="ArithArrayElement"){let r=e.operand.array,s=t.state.associativeArrays?.has(r),i;if(e.operand.stringKey!==void 0)i=`${r}_${e.operand.stringKey}`;else if(s&&e.operand.index?.type==="ArithVariable")i=`${r}_${e.operand.index.name}`;else if(e.operand.index){let c=await v(t,e.operand.index);i=`${r}_${c}`}else return n;let o=Number.parseInt(t.state.env[i]||"0",10)||0,a=e.operator==="++"?o+1:o-1;return t.state.env[i]=String(a),e.prefix?a:o}return n}return qt(n,e.operator)}case"ArithTernary":return await v(t,e.condition)?await v(t,e.consequent):await v(t,e.alternate);case"ArithAssignment":{let n=e.variable,r=n;if(e.stringKey!==void 0)r=`${n}_${e.stringKey}`;else if(e.subscript){let a=t.state.associativeArrays?.has(n);if(a&&e.subscript.type==="ArithVariable")r=`${n}_${e.subscript.name}`;else if(a){let c=await v(t,e.subscript);r=`${n}_${c}`}else{let c=await v(t,e.subscript);if(c<0){let l=F(t,n);l.length>0&&(c=Math.max(...l.map(([h])=>typeof h=="number"?h:0))+1+c)}r=`${n}_${c}`}}let s=Number.parseInt(t.state.env[r]||"0",10)||0,i=await v(t,e.value),o=An(s,i,e.operator);return t.state.env[r]=String(o),o}case"ArithGroup":return await v(t,e.expression);case"ArithConcat":{let n="";for(let r of e.parts)n+=await xn(t,r);return Number.parseInt(n,10)||0}default:return 0}}async function xn(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 n="";for(let r of e.parts)n+=await xn(t,r);return n}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,n){return{stdout:t,stderr:e,exitCode:n}}function _(t){return{stdout:"",stderr:"",exitCode:t?0:1}}function ce(t,e,n="",r=""){throw new B(t,e,n,r)}function Zt(t,e){if(t.state.loopDepth===0){if(t.state.parentHasLoopContext)throw new ue;return N}let n=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
|
+
`);n=r}throw new U(n)}async function Qt(t,e){let n,r=!1,s=!1,i=0;for(;i<e.length;)if(e[i]==="--"){i++;break}else if(e[i]==="-L")s=!1,i++;else if(e[i]==="-P")s=!0,i++;else if(e[i].startsWith("-")&&e[i]!=="-")i++;else break;let o=e.slice(i);if(o.length===0||o[0]==="~"?n=t.state.env.HOME||"/":o[0]==="-"?(n=t.state.previousDir,r=!0):n=o[0],!n.startsWith("/")&&!n.startsWith("./")&&!n.startsWith("../")&&n!=="."&&n!==".."){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}/${n}`:`${t.state.cwd}/${m}/${n}`;try{if((await t.fs.stat(y)).isDirectory){n=y,r=!0;break}}catch{}}}}let c=(n.startsWith("/")?n:`${t.state.cwd}/${n}`).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: ${n}: Not a directory
|
|
51
|
+
`)}catch{return x(`bash: cd: ${n}: No such file or directory
|
|
52
|
+
`)}}let u=l||"/";return t.state.previousDir=t.state.cwd,t.state.cwd=u,t.state.env.PWD=t.state.cwd,t.state.env.OLDPWD=t.state.previousDir,j(r?`${u}
|
|
53
|
+
`:"")}function Kt(t,e){if(t.state.loopDepth===0){if(t.state.parentHasLoopContext)throw new ue;return N}if(e.length>1)throw new U(1);let n=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
|
+
`);n=r}throw new Y(n)}function be(t,e){t.state.readonlyVars=t.state.readonlyVars||new Set,t.state.readonlyVars.add(e)}function Vs(t,e){return t.state.readonlyVars?.has(e)??!1}function me(t,e,n="bash"){return Vs(t,e)?x(`${n}: ${e}: readonly variable
|
|
55
|
+
`):null}function bn(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 n=t.indexOf("=");return{name:t.slice(0,n),isArray:!1,value:t.slice(n+1)}}return{name:t,isArray:!1}}function Cn(t,e,n={}){let{name:r,isArray:s,arrayElements:i,value:o}=e,{makeReadonly:a=!1,checkReadonly:c=!0}=n;if(c){let l=me(t,r);if(l)return l}if(s&&i){for(let l=0;l<i.length;l++)t.state.env[`${r}_${l}`]=i[l];t.state.env[`${r}__length`]=String(i.length)}else o!==void 0&&(t.state.env[r]=o);return a&&be(t,r),null}function Yt(t,e){let n=!1,r=!1,s=!1,i=!1,o=!1,a=[];for(let c=0;c<e.length;c++){let l=e[c];if(l==="-a")n=!0;else if(l==="-A")r=!0;else if(l==="-r")s=!0;else if(l==="-x")i=!0;else if(l==="-p")o=!0;else if(l==="--"){a.push(...e.slice(c+1));break}else if(l.startsWith("-"))for(let u of l.slice(1))u==="a"?n=!0:u==="A"?r=!0:u==="r"?s=!0:u==="x"?i=!0:u==="p"&&(o=!0);else a.push(l)}if(o&&a.length>0){let c="";for(let l of a){let u=t.state.env[l];if(u!==void 0){let h=u.replace(/\\/g,"\\\\").replace(/"/g,'\\"');c+=`declare -- ${l}="${h}"
|
|
56
|
+
`}}return j(c)}if(a.length===0&&!o){let c="",l=Object.entries(t.state.env).filter(([u])=>!u.startsWith("BASH_")).sort(([u],[h])=>u.localeCompare(h));for(let[u,h]of l){let d=h.replace(/'/g,"'\\''");c+=`declare -- ${u}='${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 u=l[1],h=l[2];if(r&&(t.state.associativeArrays??=new Set,t.state.associativeArrays.add(u)),r&&h.includes("[")){let d=Hs(h);for(let[m,y]of d)t.state.env[`${u}_${m}`]=y}else{let d=Xt(h);for(let m=0;m<d.length;m++)t.state.env[`${u}_${m}`]=d[m];t.state.env[`${u}__length`]=String(d.length)}s&&be(t,u);continue}if(c.includes("=")){let u=c.indexOf("="),h=c.slice(0,u),d=c.slice(u+1),m=me(t,h);if(m)return m;t.state.env[h]=d,s&&be(t,h)}else{let u=c;r&&(t.state.associativeArrays??=new Set,t.state.associativeArrays.add(u));let h=Object.keys(t.state.env).some(d=>d.startsWith(`${u}_`)&&!d.startsWith(`${u}__length`));!(u in t.state.env)&&!h&&(n||r?t.state.env[`${u}__length`]="0":t.state.env[u]=""),s&&be(t,u)}}return N}function Xt(t){let e=[],n="",r=!1,s=!1,i=!1;for(let o of t){if(i){n+=o,i=!1;continue}if(o==="\\"){i=!0;continue}if(o==="'"&&!s){r=!r;continue}if(o==='"'&&!r){s=!s;continue}if((o===" "||o===" "||o===`
|
|
58
|
+
`)&&!r&&!s){n&&(e.push(n),n="");continue}n+=o}return n&&e.push(n),e}function Hs(t){let e=[],n=0;for(;n<t.length;){for(;n<t.length&&/\s/.test(t[n]);)n++;if(n>=t.length)break;if(t[n]!=="["){n++;continue}n++;let r="";if(t[n]==="'"||t[n]==='"'){let i=t[n];for(n++;n<t.length&&t[n]!==i;)r+=t[n],n++;t[n]===i&&n++}else for(;n<t.length&&t[n]!=="]"&&t[n]!=="=";)r+=t[n],n++;for(;n<t.length&&t[n]!=="]";)n++;if(t[n]==="]"&&n++,t[n]!=="=")continue;n++;let s="";if(t[n]==="'"||t[n]==='"'){let i=t[n];for(n++;n<t.length&&t[n]!==i;)t[n]==="\\"&&n+1<t.length&&n++,s+=t[n],n++;t[n]===i&&n++}else for(;n<t.length&&!/\s/.test(t[n]);)s+=t[n],n++;e.push([r,s])}return e}function Jt(t,e){let n=!1,r=!1,s=[];for(let i=0;i<e.length;i++){let o=e[i];if(o==="-a")n=!0;else if(o==="-A")r=!0;else if(o==="-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(o==="--"){s.push(...e.slice(i+1));break}else o.startsWith("-")||s.push(o)}for(let i of s){let o=bn(i);if(o.value===void 0&&!o.isArray){be(t,o.name);continue}let a=Cn(t,o,{makeReadonly:!0});if(a)return a}return N}async function er(t,e){let n=e;if(n.length>0){let s=n[0];if(s==="--")n=n.slice(1);else if(s.startsWith("-")&&s!=="-"&&s.length>1)return x(`bash: eval: ${s}: invalid option
|
|
60
60
|
eval: usage: eval [arg ...]
|
|
61
|
-
`,2)}if(n.length===0)return
|
|
62
|
-
`);throw s}}function
|
|
63
|
-
`,n=2):n=(
|
|
64
|
-
`}return j(
|
|
65
|
-
`,
|
|
66
|
-
`);let n=
|
|
67
|
-
`)}return
|
|
68
|
-
`);let n=t.state.localScopes[t.state.localScopes.length-1],r="",s=0;for(let
|
|
69
|
-
`,s=1;continue}n.has(
|
|
70
|
-
`,s=0,
|
|
71
|
-
`,
|
|
72
|
-
`,
|
|
73
|
-
`&&
|
|
74
|
-
`)&&(
|
|
75
|
-
`,2);n=(s%256+256)%256}throw new G(n)}function
|
|
61
|
+
`,2)}if(n.length===0)return N;let r=n.join(" ");if(r.trim()==="")return N;try{let s=he(r);return t.executeScript(s)}catch(s){if(s instanceof U||s instanceof Y||s instanceof G||s instanceof R)throw s;if(s.name==="ParseException")return x(`bash: eval: ${s.message}
|
|
62
|
+
`);throw s}}function tr(t,e){let n,r="";if(e.length===0)n=t.state.lastExitCode;else{let s=e[0],i=Number.parseInt(s,10);s===""||Number.isNaN(i)||!/^-?\d+$/.test(s)?(r=`bash: exit: ${s}: numeric argument required
|
|
63
|
+
`,n=2):n=(i%256+256)%256}throw new R(n,"",r)}function rr(t,e){let n=!1,r=[];for(let o of e)o==="-n"?n=!0:o==="-p"||o==="--"||r.push(o);if(r.length===0&&!n){let o="",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 u=l.replace(/'/g,"'\\''");o+=`declare -x ${c}='${u}'
|
|
64
|
+
`}return j(o)}if(n){for(let o of r){let a=o.split("=")[0];delete t.state.env[a]}return N}let s="",i=0;for(let o of r){let a,c;if(o.includes("=")){let l=o.indexOf("=");a=o.slice(0,l),c=o.slice(l+1)}else a=o;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(a)){s+=`bash: export: \`${o}': not a valid identifier
|
|
65
|
+
`,i=1;continue}c!==void 0?t.state.env[a]=c:a in t.state.env||(t.state.env[a]="")}return S("",s,i)}function js(t){let e=[],n="",r=0;for(let s of t){for(let i of s)i==="("?r++:i===")"&&r--;n?n+=` ${s}`:n=s,r===0&&(e.push(n),n="")}return n&&e.push(n),e}async function nr(t,e){if(e.length===0)return x(`bash: let: expression expected
|
|
66
|
+
`);let n=js(e),r=0;for(let s of n)try{let o=he(`(( ${s} ))`).statements[0];if(o&&o.pipelines.length>0&&o.pipelines[0].commands.length>0){let a=o.pipelines[0].commands[0];a.type==="ArithmeticCommand"&&(r=await v(t,a.expression.expression))}}catch(i){return x(`bash: let: ${s}: ${i.message}
|
|
67
|
+
`)}return S("","",r===0?1:0)}function qs(t,e){let n=t.state.env.HOME||"/home/user";return e.split(":").map(i=>i==="~"?n:i==="~root"?"/root":i.startsWith("~/")?n+i.slice(1):i.startsWith("~root/")?`/root${i.slice(5)}`:i).join(":")}function sr(t,e){if(t.state.localScopes.length===0)return x(`bash: local: can only be used in a function
|
|
68
|
+
`);let n=t.state.localScopes[t.state.localScopes.length-1],r="",s=0;for(let i of e){let o,a;if(i.includes("=")){let c=i.indexOf("=");o=i.slice(0,c),a=qs(t,i.slice(c+1))}else o=i;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(o)){r+=`bash: local: \`${i}': not a valid identifier
|
|
69
|
+
`,s=1;continue}n.has(o)||n.set(o,t.state.env[o]),a!==void 0&&(t.state.env[o]=a)}return S("",r,s)}function ir(t,e,n){let r=`
|
|
70
|
+
`,s=0,i=0,o=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?(s=Number.parseInt(e[l+1],10)||0,l+=2):E==="-O"&&l+1<e.length?(i=Number.parseInt(e[l+1],10)||0,l+=2):E==="-s"&&l+1<e.length?(o=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 u=n;!u&&t.state.groupStdin!==void 0&&(u=t.state.groupStdin);let h=[],d=u,m=0,y=0;for(;d.length>0;){let E=d.indexOf(r);if(E===-1){d.length>0&&(y<o?y++:(s===0||m<s)&&(h.push(d),m++));break}let p=d.substring(0,E);if(a||(p+=r),d=d.substring(E+r.length),y<o){y++;continue}if(s>0&&m>=s)break;h.push(p),m++}Be(t,c);for(let E=0;E<h.length;E++)t.state.env[`${c}_${i+E}`]=h[E];return h.length>0&&(t.state.env[`${c}__length`]=String(i+h.length)),t.state.groupStdin!==void 0&&!n&&(t.state.groupStdin=""),S("","",0)}function or(t,e,n){let r=!1,s=`
|
|
72
|
+
`,i="",o=-1,a=null,c=[],l=0,u=!1;for(;l<e.length;){let g=e[l];g==="-r"?r=!0:g==="-d"&&l+1<e.length?(s=e[l+1],l++):g==="-p"&&l+1<e.length?(i=e[l+1],l++):g==="-n"&&l+1<e.length?(o=Number.parseInt(e[l+1],10),(Number.isNaN(o)||o<0)&&(u=!0,o=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(u)return S("","",1);c.length===0&&a===null&&c.push("REPLY");let h=n;!h&&t.state.groupStdin!==void 0&&(h=t.state.groupStdin);let d="",m=0,y=!0;if(o>=0){for(let g=0;g<h.length&&g<o;g++){let b=h[g];if(b===s){m=g+1;break}d+=b,m=g+1}t.state.groupStdin!==void 0&&!n&&(t.state.groupStdin=h.substring(m))}else{let g=h;for(m=0;;){let b=g.indexOf(s);if(b!==-1){let C=g.substring(0,b);if(m+=b+s.length,g=g.substring(b+s.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&&!n&&(t.state.groupStdin=h.substring(m))}if(s===`
|
|
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}=on(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=an(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 n=t.state.lastExitCode;if(e.length>0){let r=e[0],s=Number.parseInt(r,10);if(r===""||Number.isNaN(s)||!/^-?\d+$/.test(r))return x(`bash: return: ${r}: numeric argument required
|
|
75
|
+
`,2);n=(s%256+256)%256}throw new G(n)}function Zs(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
|
-
`,Nn={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},
|
|
91
|
+
`,Nn={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},Pn={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},vn=["errexit","nounset","pipefail","verbose","xtrace"],$n=["allexport","braceexpand","emacs","errtrace","functrace","hashall","histexpand","history","ignoreeof","interactive-comments","keyword","monitor","noclobber","noexec","noglob","nolog","notify","onecmd","physical","posix","privileged","vi"];function kn(t,e,n){e!==null&&(t.state.options[e]=n)}function Qs(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(([s])=>/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(s)).sort(([s],[i])=>s.localeCompare(i)).map(([s,i])=>`${s}=${Zs(i)}`).join(`
|
|
92
92
|
`);return j(r?`${r}
|
|
93
|
-
`:"")}let n=0;for(;n<e.length;){let r=e[n];if((r==="-o"||r==="+o")&&
|
|
94
|
-
${ot}`);
|
|
93
|
+
`:"")}let n=0;for(;n<e.length;){let r=e[n];if((r==="-o"||r==="+o")&&Qs(e,n)){let s=e[n+1];if(!(s in Pn))return x(`bash: set: ${s}: invalid option name
|
|
94
|
+
${ot}`);kn(t,Pn[s],r==="-o"),n+=2;continue}if(r==="-o"){let s=vn.map(a=>`${a.padEnd(16)}${t.state.options[a]?"on":"off"}`),i=$n.map(a=>`${a.padEnd(16)}off`),o=[...s,...i].sort();return j(`${o.join(`
|
|
95
95
|
`)}
|
|
96
|
-
`)}if(r==="+o"){let s
|
|
96
|
+
`)}if(r==="+o"){let s=vn.map(a=>`set ${t.state.options[a]?"-o":"+o"} ${a}`),i=$n.map(a=>`set +o ${a}`),o=[...s,...i].sort();return j(`${o.join(`
|
|
97
97
|
`)}
|
|
98
|
-
`)}if(r.length>1&&(r[0]==="-"||r[0]==="+")&&r[1]!=="-"){let s=r[0]==="-";for(let
|
|
99
|
-
${ot}`);
|
|
100
|
-
${ot}`):(
|
|
101
|
-
`);n=
|
|
102
|
-
`);if(n===0)return
|
|
103
|
-
`,2);let r=n[0],s=null,
|
|
104
|
-
`);let
|
|
105
|
-
`);throw
|
|
106
|
-
`,s=1;continue}let h
|
|
107
|
-
`,s=1;continue}let m=
|
|
108
|
-
`,2):at(r)?_(await ct(t,r,s)):yt(r)?_(
|
|
109
|
-
`,2):
|
|
110
|
-
`,2):_(n.value)}async function
|
|
111
|
-
`,exitCode:1}}async function At(t,e,n="",r=""){let s=n,
|
|
112
|
-
`,exitCode:1}}return{stdout:s,stderr:
|
|
113
|
-
`);let
|
|
114
|
-
`).map(h=>h.replace(/^\t+/,"")).join(`
|
|
115
|
-
`)),a=d}else if(c.operator==="<<<"&&c.target.type==="Word")a=`${await I(t,c.target)}
|
|
116
|
-
`;else if(c.operator==="<"&&c.target.type==="Word")try{let f=await I(t,c.target),d=t.fs.resolvePath(t.state.cwd,f);a=await t.fs.readFile(d)}catch{let f=await I(t,c.target);return S(`bash: ${f}: No such file or directory
|
|
117
|
-
`)}let l=t.state.groupStdin;a&&(t.state.groupStdin=a),t.state.loopDepth++;try{for(;;){i++,i>t.limits.maxLoopIterations&&ae(`while loop: too many iterations (${t.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",r,s);let c=0,f=!1,d=!1,h=t.state.inCondition;t.state.inCondition=!0;try{for(let m of e.condition){let y=await t.executeStatement(m);r+=y.stdout,s+=y.stderr,c=y.exitCode}}catch(m){if(m instanceof U){if(r+=m.stdout,s+=m.stderr,m.levels>1&&t.state.loopDepth>1)throw m.levels--,m.stdout=r,m.stderr=s,t.state.inCondition=h,m;f=!0}else if(m instanceof Y){if(r+=m.stdout,s+=m.stderr,m.levels>1&&t.state.loopDepth>1)throw m.levels--,m.stdout=r,m.stderr=s,t.state.inCondition=h,m;d=!0}else throw t.state.inCondition=h,m}finally{t.state.inCondition=h}if(f)break;if(!d){if(c!==0)break;try{for(let m of e.body){let y=await t.executeStatement(m);r+=y.stdout,s+=y.stderr,o=y.exitCode}}catch(m){let y=Ve(m,r,s,t.state.loopDepth);if(r=y.stdout,s=y.stderr,y.action==="break")break;if(y.action==="continue")continue;if(y.action==="error")return x(r,s,y.exitCode??1);throw y.error}}}}finally{t.state.loopDepth--,t.state.groupStdin=l}return x(r,s,o)}async function Fn(t,e){let n="",r="",s=0,o=0;t.state.loopDepth++;try{for(;;){o++,o>t.limits.maxLoopIterations&&ae(`until loop: too many iterations (${t.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",n,r);let i=await pr(t,e.condition);if(n+=i.stdout,r+=i.stderr,i.exitCode===0)break;try{for(let a of e.body){let l=await t.executeStatement(a);n+=l.stdout,r+=l.stderr,s=l.exitCode}}catch(a){let l=Ve(a,n,r,t.state.loopDepth);if(n=l.stdout,r=l.stderr,l.action==="break")break;if(l.action==="continue")continue;if(l.action==="error")return x(n,r,l.exitCode??1);throw l.error}}}finally{t.state.loopDepth--}return x(n,r,s)}async function Wn(t,e){let n="",r="",s=0,o=await I(t,e.word),i=!1;for(let a=0;a<e.items.length;a++){let l=e.items[a],c=i;if(!i)for(let f of l.patterns){let d=await I(t,f);if(un(f)&&(d=dn(d)),pt(o,d)){c=!0;break}}if(c){let f=await At(t,l.body,n,r);if(n=f.stdout,r=f.stderr,s=f.exitCode,l.terminator===";;")break;l.terminator===";&"?i=!0:i=!1}else i=!1}return x(n,r,s)}function Mn(t,e){return t.state.functions.set(e.name,e),C}async function Bn(t,e,n){t.state.callDepth++,t.state.callDepth>t.limits.maxCallDepth&&(t.state.callDepth--,ae(`${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<n.length;o++)r[String(o+1)]=t.state.env[String(o+1)],t.state.env[String(o+1)]=n[o];r["@"]=t.state.env["@"],r["#"]=t.state.env["#"],t.state.env["@"]=n.join(" "),t.state.env["#"]=String(n.length);let s=()=>{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 s(),o}catch(o){if(s(),o instanceof G)return x(o.stdout,o.stderr,o.exitCode);throw o}}async function zn(t,e,n){let{stdout:r,stderr:s,exitCode:o}=e;for(let i of n){if(i.target.type==="HereDoc")continue;let a=await I(t,i.target);switch(i.operator){case">":{let l=i.fd??1;if(l===1){let c=t.fs.resolvePath(t.state.cwd,a);try{if((await t.fs.stat(c)).isDirectory){s+=`bash: ${a}: Is a directory
|
|
118
|
-
`,o=1,r="";break}}catch{}await t.fs.writeFile(c,r),r=""}else if(l===2)if(a==="/dev/null")s="";else{let c=t.fs.resolvePath(t.state.cwd,a);try{if((await t.fs.stat(c)).isDirectory){s+=`bash: ${a}: Is a directory
|
|
119
|
-
`,o=1;break}}catch{}await t.fs.writeFile(c,s),s=""}break}case">>":{let l=i.fd??1;if(l===1){let c=t.fs.resolvePath(t.state.cwd,a);try{if((await t.fs.stat(c)).isDirectory){s+=`bash: ${a}: Is a directory
|
|
120
|
-
`,o=1,r="";break}}catch{}await t.fs.appendFile(c,r),r=""}else if(l===2){let c=t.fs.resolvePath(t.state.cwd,a);try{if((await t.fs.stat(c)).isDirectory){s+=`bash: ${a}: Is a directory
|
|
121
|
-
`,o=1;break}}catch{}await t.fs.appendFile(c,s),s=""}break}case">&":{let l=i.fd??1;a==="2"||a==="&2"?l===1&&(s+=r,r=""):(a==="1"||a==="&1")&&(r+=s,s="");break}case"&>":{let l=t.fs.resolvePath(t.state.cwd,a);try{if((await t.fs.stat(l)).isDirectory){s=`bash: ${a}: Is a directory
|
|
122
|
-
`,o=1,r="";break}}catch{}await t.fs.writeFile(l,r+s),r="",s="";break}case"&>>":{let l=t.fs.resolvePath(t.state.cwd,a);try{if((await t.fs.stat(l)).isDirectory){s=`bash: ${a}: Is a directory
|
|
123
|
-
`,o=1,r="";break}}catch{}await t.fs.appendFile(l,r+s),r="",s="";break}}}return x(r,s,o)}var He=class{ctx;constructor(e,n){this.ctx={state:n,fs:e.fs,commands:e.commands,limits:e.limits,execFn:e.exec,executeScript:this.executeScript.bind(this),executeStatement:this.executeStatement.bind(this),executeCommand:this.executeCommand.bind(this),fetch:e.fetch,sleep:e.sleep,trace:e.trace}}async executeScript(e){let n="",r="",s=0;for(let o of e.statements)try{let i=await this.executeStatement(o);n+=i.stdout,r+=i.stderr,s=i.exitCode,this.ctx.state.lastExitCode=s,this.ctx.state.env["?"]=String(s)}catch(i){if(i instanceof k)throw i.prependOutput(n,r),i;if(i instanceof z)throw i;if(i instanceof te)return n+=i.stdout,r+=i.stderr,s=i.exitCode,this.ctx.state.lastExitCode=s,this.ctx.state.env["?"]=String(s),{stdout:n,stderr:r,exitCode:s,env:{...this.ctx.state.env}};if(i instanceof J)return n+=i.stdout,r+=i.stderr,s=1,this.ctx.state.lastExitCode=s,this.ctx.state.env["?"]=String(s),{stdout:n,stderr:r,exitCode:s,env:{...this.ctx.state.env}};if(i instanceof Ee)return n+=i.stdout,r+=i.stderr,s=1,this.ctx.state.lastExitCode=s,this.ctx.state.env["?"]=String(s),{stdout:n,stderr:r,exitCode:s,env:{...this.ctx.state.env}};if(i instanceof U||i instanceof Y){if(this.ctx.state.loopDepth>0)throw i.prependOutput(n,r),i;n+=i.stdout,r+=i.stderr;continue}throw i instanceof G&&i.prependOutput(n,r),i}return{stdout:n,stderr:r,exitCode:s,env:{...this.ctx.state.env}}}async executeStatement(e){this.ctx.state.commandCount++,this.ctx.state.commandCount>this.ctx.limits.maxCommandCount&&ae(`too many commands executed (>${this.ctx.limits.maxCommandCount}), increase executionLimits.maxCommandCount`,"commands");let n="",r="",s=0,o=-1,i=!1;for(let a=0;a<e.pipelines.length;a++){let l=e.pipelines[a],c=a>0?e.operators[a-1]:null;if(c==="&&"&&s!==0||c==="||"&&s===0)continue;let f=await this.executePipeline(l);n+=f.stdout,r+=f.stderr,s=f.exitCode,o=a,i=l.negated,this.ctx.state.lastExitCode=s,this.ctx.state.env["?"]=String(s)}if(this.ctx.state.options.errexit&&s!==0&&o===e.pipelines.length-1&&!i&&!this.ctx.state.inCondition)throw new te(s,n,r);return x(n,r,s)}async executePipeline(e){let n="",r=C,s=0,o=[];for(let i=0;i<e.commands.length;i++){let a=e.commands[i],l=i===e.commands.length-1,c;try{c=await this.executeCommand(a,n)}catch(f){if(f instanceof Ee)c={stdout:f.stdout,stderr:f.stderr,exitCode:1};else if(f instanceof k&&e.commands.length>1)c={stdout:f.stdout,stderr:f.stderr,exitCode:f.exitCode};else throw f}o.push(c.exitCode),c.exitCode!==0&&(s=c.exitCode),l?r=c:(n=c.stdout,r={stdout:"",stderr:c.stderr,exitCode:c.exitCode})}for(let i of Object.keys(this.ctx.state.env))i.startsWith("PIPESTATUS_")&&delete this.ctx.state.env[i];for(let i=0;i<o.length;i++)this.ctx.state.env[`PIPESTATUS_${i}`]=String(o[i]);return this.ctx.state.env.PIPESTATUS__length=String(o.length),this.ctx.state.options.pipefail&&s!==0&&(r={...r,exitCode:s}),e.negated&&(r={...r,exitCode:r.exitCode===0?1:0}),r}async executeCommand(e,n){switch(e.type){case"SimpleCommand":return this.executeSimpleCommand(e,n);case"If":return On(this.ctx,e);case"For":return _n(this.ctx,e);case"CStyleFor":return Ln(this.ctx,e);case"While":return Tn(this.ctx,e,n);case"Until":return Fn(this.ctx,e);case"Case":return Wn(this.ctx,e);case"Subshell":return this.executeSubshell(e,n);case"Group":return this.executeGroup(e,n);case"FunctionDef":return Mn(this.ctx,e);case"ArithmeticCommand":return this.executeArithmeticCommand(e);case"ConditionalCommand":return this.executeConditionalCommand(e);default:return C}}async executeSimpleCommand(e,n){try{return await this.executeSimpleCommandInner(e,n)}catch(r){if(r instanceof W)return S(r.stderr);throw r}}async executeSimpleCommandInner(e,n){e.line!==void 0&&(this.ctx.state.currentLine=e.line),this.ctx.state.expansionStderr="";let r={};for(let l of e.assignments){let c=l.name;if(l.array){if(/\[.+\]$/.test(c))return x("",`bash: ${c}: cannot assign list to array member
|
|
124
|
-
`,1);let w=he(this.ctx,c);if(w)return w;let p=[];for(let g of l.array){let b=await Ge(this.ctx,g);p.push(...b.values)}let E=0;if(l.append){let g=F(this.ctx,c);g.length>0&&(E=Math.max(...g.map(([N])=>typeof N=="number"?N:0))+1)}else{let g=`${c}_`;for(let b of Object.keys(this.ctx.state.env))b.startsWith(g)&&!b.includes("__")&&delete this.ctx.state.env[b]}for(let g=0;g<p.length;g++)this.ctx.state.env[`${c}_${E+g}`]=p[g];l.append||(this.ctx.state.env[`${c}__length`]=String(p.length));continue}let f=l.value?await I(this.ctx,l.value):"";if(c.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[\]$/))return x("",`bash: ${c}: bad array subscript
|
|
125
|
-
`,1);let h=c.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(h){let w=h[1],p=h[2],E=he(this.ctx,w);if(E)return E;let g=this.ctx.state.associativeArrays?.has(w),b;if(g){let R;if(p.startsWith("'")&&p.endsWith("'"))R=p.slice(1,-1);else if(p.startsWith('"')&&p.endsWith('"')){let D=p.slice(1,-1),L=new M().parseWordFromString(D,!0,!1);R=await I(this.ctx,L)}else if(p.includes("$")){let ye=new M().parseWordFromString(p,!1,!1);R=await I(this.ctx,ye)}else R=p;b=`${w}_${R}`}else{let R;if(/^-?\d+$/.test(p))R=Number.parseInt(p,10);else{try{let D=new M,ye=T(D,p);R=$(this.ctx,ye.expression)}catch{let D=this.ctx.state.env[p];R=D?Number.parseInt(D,10):0}Number.isNaN(R)&&(R=0)}if(R<0){let D=F(this.ctx,w);if(D.length===0)return x("",`bash: ${w}[${p}]: bad array subscript
|
|
126
|
-
`,1);if(R=Math.max(...D.map(([L])=>typeof L=="number"?L:0))+1+R,R<0)return x("",`bash: ${w}[${p}]: bad array subscript
|
|
127
|
-
`,1)}b=`${w}_${R}`}let N=l.append?(this.ctx.state.env[b]||"")+f:f;e.name?(r[b]=this.ctx.state.env[b],this.ctx.state.env[b]=N):this.ctx.state.env[b]=N;continue}let m=he(this.ctx,c);if(m)return m;let y=l.append?(this.ctx.state.env[c]||"")+f:f;e.name?(r[c]=this.ctx.state.env[c],this.ctx.state.env[c]=y):this.ctx.state.env[c]=y}if(!e.name)return x("","",this.ctx.state.lastExitCode);for(let l of e.redirections){if((l.operator==="<<"||l.operator==="<<-")&&l.target.type==="HereDoc"){let c=l.target,f=await I(this.ctx,c.content);c.stripTabs&&(f=f.split(`
|
|
98
|
+
`)}if(r.length>1&&(r[0]==="-"||r[0]==="+")&&r[1]!=="-"){let s=r[0]==="-";for(let i=1;i<r.length;i++){let o=r[i];if(!(o in Nn))return x(`bash: set: ${r[0]}${o}: invalid option
|
|
99
|
+
${ot}`);kn(t,Nn[o],s)}n++;continue}if(r==="--")return cr(t,e.slice(n+1)),N;if(r==="-"){if(t.state.options.xtrace=!1,t.state.options.verbose=!1,n+1<e.length)return cr(t,e.slice(n+1)),N;n++;continue}if(r==="+"){n++;continue}return r.startsWith("-")||r.startsWith("+")?x(`bash: set: ${r}: invalid option
|
|
100
|
+
${ot}`):(cr(t,e.slice(n)),N)}return N}function cr(t,e){let n=1;for(;t.state.env[String(n)]!==void 0;)delete t.state.env[String(n)],n++;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 ur(t,e){let n=1;if(e.length>0){let o=Number.parseInt(e[0],10);if(Number.isNaN(o)||o<0)return x(`bash: shift: ${e[0]}: numeric argument required
|
|
101
|
+
`);n=o}let r=Number.parseInt(t.state.env["#"]||"0",10);if(n>r)return x(`bash: shift: shift count out of range
|
|
102
|
+
`);if(n===0)return N;let s=[];for(let o=1;o<=r;o++)s.push(t.state.env[String(o)]||"");let i=s.slice(n);for(let o=1;o<=r;o++)delete t.state.env[String(o)];for(let o=0;o<i.length;o++)t.state.env[String(o+1)]=i[o];return t.state.env["#"]=String(i.length),t.state.env["@"]=i.join(" "),N}async function fr(t,e){let n=e;if(n.length>0&&n[0]==="--"&&(n=n.slice(1)),n.length===0)return S("",`bash: source: filename argument required
|
|
103
|
+
`,2);let r=n[0],s=null,i=null;if(r.includes("/")){let c=t.fs.resolvePath(t.state.cwd,r);try{i=await t.fs.readFile(c),s=c}catch{}}else{let l=(t.state.env.PATH||"").split(":").filter(u=>u);for(let u of l){let h=t.fs.resolvePath(t.state.cwd,`${u}/${r}`);try{if((await t.fs.stat(h)).isDirectory)continue;i=await t.fs.readFile(h),s=h;break}catch{}}if(i===null){let u=t.fs.resolvePath(t.state.cwd,r);try{i=await t.fs.readFile(u),s=u}catch{}}}if(i===null)return x(`bash: ${r}: No such file or directory
|
|
104
|
+
`);let o={};if(n.length>1){for(let l=1;l<=9;l++)o[String(l)]=t.state.env[String(l)];o["#"]=t.state.env["#"],o["@"]=t.state.env["@"];let c=n.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--,n.length>1)for(let[c,l]of Object.entries(o))l===void 0?delete t.state.env[c]:t.state.env[c]=l};t.state.sourceDepth++;try{let c=he(i),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 n="variable",r="",s=0;for(let i of e){if(i==="-v"){n="variable";continue}if(i==="-f"){n="function";continue}if(n==="function"){t.state.functions.delete(i);continue}let o=i.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(o){let a=o[1],c=o[2];if(c==="@"||c==="*"){let u=F(t,a);for(let[h]of u)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 u=t.state.env[c];l=u?Number.parseInt(u,10):0,Number.isNaN(l)&&(l=0)}if(l<0){let u=F(t,a),h=u.length;if(h===0){r+=`bash: unset: [${l}]: bad array subscript
|
|
106
|
+
`,s=1;continue}let d=h+l;if(d<0){r+=`bash: unset: [${l}]: bad array subscript
|
|
107
|
+
`,s=1;continue}let m=u[d][0];delete t.state.env[`${a}_${m}`];continue}delete t.state.env[`${a}_${l}`];continue}delete t.state.env[i],t.state.functions.delete(i)}return S("",r,s)}function dr(t,e){return t.fs.resolvePath(t.state.cwd,e)}var Ks=["-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 Ks.includes(t)}async function ct(t,e,n){let r=dr(t,n);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(i=>r===i||r.endsWith(i));case"-p":return!1;case"-S":return!1;case"-t":return!1;case"-N":return t.fs.exists(r);default:return!1}}var Xs=["-nt","-ot","-ef"];function lt(t){return Xs.includes(t)}async function ut(t,e,n,r){let s=dr(t,n),i=dr(t,r);switch(e){case"-nt":try{let o=await t.fs.stat(s),a=await t.fs.stat(i);return o.mtime>a.mtime}catch{return!1}case"-ot":try{let o=await t.fs.stat(s),a=await t.fs.stat(i);return o.mtime<a.mtime}catch{return!1}case"-ef":try{if(!await t.fs.exists(s)||!await t.fs.exists(i))return!1;let o=t.fs.resolvePath(t.state.cwd,s),a=t.fs.resolvePath(t.state.cwd,i);return o===a}catch{return!1}default:return!1}}var Ys=new Set(["-eq","-ne","-lt","-le","-gt","-ge"]);function ft(t){return Ys.has(t)}function ht(t,e,n){switch(t){case"-eq":return e===n;case"-ne":return e!==n;case"-lt":return e<n;case"-le":return e<=n;case"-gt":return e>n;case"-ge":return e>=n}}function dt(t){return t==="="||t==="=="||t==="!="}function mt(t,e,n,r=!1){let s=r?pt(e,n):e===n;return t==="!="?!s:s}var Js=new Set(["-z","-n"]);function yt(t){return Js.has(t)}function wt(t,e){switch(t){case"-z":return e==="";case"-n":return e!==""}}function Et(t,e){let n=e.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(n){let r=n[1],s=n[2];s=s.replace(/\$([a-zA-Z_][a-zA-Z0-9_]*)/g,(o,a)=>t.state.env[a]||"");let i;if(/^-?\d+$/.test(s))i=Number.parseInt(s,10);else try{let o=Function(`"use strict"; return (${s})`)();i=typeof o=="number"?Math.floor(o):0}catch{let o=t.state.env[s];i=o?Number.parseInt(o,10):0}if(i<0){let o=ze(t,r);if(o.length===0||(i=Math.max(...o)+1+i,i<0))return!1}return`${r}_${i}`in t.state.env}return e in t.state.env}async function pe(t,e){switch(e.type){case"CondBinary":{let n=await k(t,e.left),r=await k(t,e.right),s=e.right.parts.length>0&&e.right.parts.every(i=>i.type==="SingleQuoted"||i.type==="DoubleQuoted"||i.type==="Escaped");if(dt(e.operator))return mt(e.operator,n,r,!s);if(ft(e.operator))return ht(e.operator,Rn(t,n),Rn(t,r));if(lt(e.operator))return ut(t,e.operator,n,r);switch(e.operator){case"=~":try{let i=new RegExp(r),o=n.match(i);if(o){t.state.env.BASH_REMATCH=o[0];for(let a=1;a<o.length;a++)t.state.env[`BASH_REMATCH_${a}`]=o[a]||""}return o!==null}catch{throw new Error("syntax error in regular expression")}case"<":return n<r;case">":return n>r;default:return!1}}case"CondUnary":{let n=await k(t,e.operand);return at(e.operator)?ct(t,e.operator,n):yt(e.operator)?wt(e.operator,n):e.operator==="-v"?Et(t,n):e.operator==="-o"?pr(t,n):!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],s=e[1];return r==="("?x(`test: '(' without matching ')'
|
|
108
|
+
`,2):at(r)?_(await ct(t,r,s)):yt(r)?_(wt(r,s)):r==="!"?_(!s):r==="-v"?_(Et(t,s)):r==="-o"?_(pr(t,s)):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],s=e[1],i=e[2];if(dt(s))return _(mt(s,r,i));if(ft(s)){let o=gt(r),a=gt(i);return!o.valid||!a.valid?S("","",2):_(ht(s,o.value,a.value))}if(lt(s))return _(await ut(t,s,r,i));switch(s){case"-a":return _(r!==""&&i!=="");case"-o":return _(r!==""||i!=="");case">":return _(r>i);case"<":return _(r<i)}if(r==="!"){let o=await Re(t,[s,i]);return S("",o.stderr,o.exitCode===0?1:o.exitCode===1?0:o.exitCode)}if(r==="("&&i===")")return _(s!=="")}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 n=await On(t,e,0);return n.pos<e.length?x(`test: too many arguments
|
|
110
|
+
`,2):_(n.value)}async function On(t,e,n){return ei(t,e,n)}async function ei(t,e,n){let{value:r,pos:s}=await In(t,e,n);for(;e[s]==="-o";){let i=await In(t,e,s+1);r=r||i.value,s=i.pos}return{value:r,pos:s}}async function In(t,e,n){let{value:r,pos:s}=await mr(t,e,n);for(;e[s]==="-a";){let i=await mr(t,e,s+1);r=r&&i.value,s=i.pos}return{value:r,pos:s}}async function mr(t,e,n){if(e[n]==="!"){let{value:r,pos:s}=await mr(t,e,n+1);return{value:!r,pos:s}}return ti(t,e,n)}async function ti(t,e,n){let r=e[n];if(r==="("){let{value:i,pos:o}=await On(t,e,n+1);return{value:i,pos:e[o]===")"?o+1:o}}if(at(r)){let i=e[n+1]??"";return{value:await ct(t,r,i),pos:n+2}}if(yt(r)){let i=e[n+1]??"";return{value:wt(r,i),pos:n+2}}if(r==="-v"){let i=e[n+1]??"";return{value:Et(t,i),pos:n+2}}if(r==="-o"){let i=e[n+1]??"";return{value:pr(t,i),pos:n+2}}let s=e[n+1];if(dt(s)){let i=r,o=e[n+2]??"";return{value:mt(s,i,o),pos:n+3}}if(ft(s)){let i=gt(r),o=gt(e[n+2]??"0");return!i.valid||!o.valid?{value:!1,pos:n+3}:{value:ht(s,i.value,o.value),pos:n+3}}if(lt(s)){let i=r,o=e[n+2]??"";return{value:await ut(t,s,i,o),pos:n+3}}return{value:r!==void 0&&r!=="",pos:n+1}}function pt(t,e){let n="^";for(let r=0;r<e.length;r++){let s=e[r];if(s==="\\")if(r+1<e.length){let i=e[r+1];/[\\^$.|+(){}[\]*?]/.test(i)?n+=`\\${i}`:n+=i,r++}else n+="\\\\";else if(s==="*")n+=".*";else if(s==="?")n+=".";else if(s==="["){let i=e.indexOf("]",r+1);i!==-1?(n+=e.slice(r,i+1),r=i):n+="\\["}else/[\\^$.|+(){}]/.test(s)?n+=`\\${s}`:n+=s}return n+="$",new RegExp(n).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 Rn(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 Dn(e);try{let n=new z,r=T(n,e);return P(t,r.expression)}catch{return Dn(e)}}function ri(t,e){let n=0;for(let r of t){let s;if(r>="0"&&r<="9")s=r.charCodeAt(0)-48;else if(r>="a"&&r<="z")s=r.charCodeAt(0)-97+10;else if(r>="A"&&r<="Z")s=r.charCodeAt(0)-65+36;else if(r==="@")s=62;else if(r==="_")s=63;else return Number.NaN;if(s>=e)return Number.NaN;n=n*e+s}return n}function Dn(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 n,r=t.match(/^(\d+)#([a-zA-Z0-9@_]+)$/);if(r){let s=Number.parseInt(r[1],10);s>=2&&s<=64?n=ri(r[2],s):n=0}else/^0[xX][0-9a-fA-F]+$/.test(t)?n=Number.parseInt(t,16):/^0[0-7]+$/.test(t)?n=Number.parseInt(t,8):n=Number.parseInt(t,10);return Number.isNaN(n)&&(n=0),e?-n:n}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 n=Number.parseInt(t,10);return Number.isNaN(n)?{value:0,valid:!1}:{value:e?-n:n,valid:!0}}async function yr(t,e){let n=t.state.inCondition;t.state.inCondition=!0;let r="",s="",i=0;try{for(let o of e){let a=await t.executeStatement(o);r+=a.stdout,s+=a.stderr,i=a.exitCode}}finally{t.state.inCondition=n}return{stdout:r,stderr:s,exitCode:i}}function Ve(t,e,n,r){if(t instanceof U)return e+=t.stdout,n+=t.stderr,t.levels>1&&r>1?(t.levels--,t.stdout=e,t.stderr=n,{action:"rethrow",stdout:e,stderr:n,error:t}):{action:"break",stdout:e,stderr:n};if(t instanceof Y)return e+=t.stdout,n+=t.stderr,t.levels>1&&r>1?(t.levels--,t.stdout=e,t.stderr=n,{action:"rethrow",stdout:e,stderr:n,error:t}):{action:"continue",stdout:e,stderr:n};if(t instanceof G||t instanceof te||t instanceof R||t instanceof B)return t.prependOutput(e,n),{action:"rethrow",stdout:e,stderr:n,error:t};let s=le(t);return{action:"error",stdout:e,stderr:`${n}${s}
|
|
111
|
+
`,exitCode:1}}async function At(t,e,n="",r=""){let s=n,i=r,o=0;try{for(let a of e){let c=await t.executeStatement(a);s+=c.stdout,i+=c.stderr,o=c.exitCode}}catch(a){if(qe(a)||a instanceof te||a instanceof R||a instanceof B||a instanceof ue)throw a.prependOutput(s,i),a;return{stdout:s,stderr:`${i}${le(a)}
|
|
112
|
+
`,exitCode:1}}return{stdout:s,stderr:i,exitCode:o}}async function _n(t,e){let n="",r="";for(let s of e.clauses){let i=await yr(t,s.condition);if(n+=i.stdout,r+=i.stderr,i.exitCode===0)return At(t,s.body,n,r)}return e.elseBody?At(t,e.elseBody,n,r):S(n,r,0)}async function Ln(t,e){let n="",r="",s=0,i=0;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e.variable))return x(`bash: \`${e.variable}': not a valid identifier
|
|
113
|
+
`);let o=[];if(e.words===null)o=(t.state.env["@"]||"").split(" ").filter(Boolean);else if(e.words.length===0)o=[];else for(let a of e.words){let c=await Ge(t,a);o.push(...c.values)}t.state.loopDepth++;try{for(let a of o){i++,i>t.limits.maxLoopIterations&&ce(`for loop: too many iterations (${t.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",n,r),t.state.env[e.variable]=a;try{for(let c of e.body){let l=await t.executeStatement(c);n+=l.stdout,r+=l.stderr,s=l.exitCode}}catch(c){let l=Ve(c,n,r,t.state.loopDepth);if(n=l.stdout,r=l.stderr,l.action==="break")break;if(l.action==="continue")continue;if(l.action==="error")return S(n,r,l.exitCode??1);throw l.error}}}finally{t.state.loopDepth--}return S(n,r,s)}async function Tn(t,e){let n="",r="",s=0,i=0;e.init&&await v(t,e.init.expression),t.state.loopDepth++;try{for(;i++,i>t.limits.maxLoopIterations&&ce(`for loop: too many iterations (${t.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",n,r),!(e.condition&&await v(t,e.condition.expression)===0);){try{for(let o of e.body){let a=await t.executeStatement(o);n+=a.stdout,r+=a.stderr,s=a.exitCode}}catch(o){let a=Ve(o,n,r,t.state.loopDepth);if(n=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(n,r,a.exitCode??1);throw a.error}e.update&&await v(t,e.update.expression)}}finally{t.state.loopDepth--}return S(n,r,s)}async function Fn(t,e,n=""){let r="",s="",i=0,o=0,a=n;for(let l of e.redirections)if((l.operator==="<<"||l.operator==="<<-")&&l.target.type==="HereDoc"){let u=l.target,h=await k(t,u.content);u.stripTabs&&(h=h.split(`
|
|
128
114
|
`).map(d=>d.replace(/^\t+/,"")).join(`
|
|
129
|
-
`)),
|
|
130
|
-
`;
|
|
131
|
-
`)}
|
|
132
|
-
`,
|
|
133
|
-
`,
|
|
134
|
-
`,
|
|
135
|
-
|
|
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 u=await k(t,l.target),h=t.fs.resolvePath(t.state.cwd,u);a=await t.fs.readFile(h)}catch{let u=await k(t,l.target);return x(`bash: ${u}: No such file or directory
|
|
117
|
+
`)}let c=t.state.groupStdin;a&&(t.state.groupStdin=a),t.state.loopDepth++;try{for(;;){o++,o>t.limits.maxLoopIterations&&ce(`while loop: too many iterations (${t.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",r,s);let l=0,u=!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,s+=y.stderr,l=y.exitCode}}catch(m){if(m instanceof U){if(r+=m.stdout,s+=m.stderr,m.levels>1&&t.state.loopDepth>1)throw m.levels--,m.stdout=r,m.stderr=s,t.state.inCondition=d,m;u=!0}else if(m instanceof Y){if(r+=m.stdout,s+=m.stderr,m.levels>1&&t.state.loopDepth>1)throw m.levels--,m.stdout=r,m.stderr=s,t.state.inCondition=d,m;h=!0}else throw t.state.inCondition=d,m}finally{t.state.inCondition=d}if(u)break;if(!h){if(l!==0)break;try{for(let m of e.body){let y=await t.executeStatement(m);r+=y.stdout,s+=y.stderr,i=y.exitCode}}catch(m){let y=Ve(m,r,s,t.state.loopDepth);if(r=y.stdout,s=y.stderr,y.action==="break")break;if(y.action==="continue")continue;if(y.action==="error")return S(r,s,y.exitCode??1);throw y.error}}}}finally{t.state.loopDepth--,t.state.groupStdin=c}return S(r,s,i)}async function Wn(t,e){let n="",r="",s=0,i=0;t.state.loopDepth++;try{for(;;){i++,i>t.limits.maxLoopIterations&&ce(`until loop: too many iterations (${t.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",n,r);let o=await yr(t,e.condition);if(n+=o.stdout,r+=o.stderr,o.exitCode===0)break;try{for(let a of e.body){let c=await t.executeStatement(a);n+=c.stdout,r+=c.stderr,s=c.exitCode}}catch(a){let c=Ve(a,n,r,t.state.loopDepth);if(n=c.stdout,r=c.stderr,c.action==="break")break;if(c.action==="continue")continue;if(c.action==="error")return S(n,r,c.exitCode??1);throw c.error}}}finally{t.state.loopDepth--}return S(n,r,s)}async function Mn(t,e){let n="",r="",s=0,i=await k(t,e.word),o=!1;for(let a=0;a<e.items.length;a++){let c=e.items[a],l=o;if(!o)for(let u of c.patterns){let h=await k(t,u);if(hn(u)&&(h=dn(h)),pt(i,h)){l=!0;break}}if(l){let u=await At(t,c.body,n,r);if(n=u.stdout,r=u.stderr,s=u.exitCode,c.terminator===";;")break;c.terminator===";&"?o=!0:o=!1}else o=!1}return S(n,r,s)}function zn(t,e){return t.state.functions.set(e.name,e),N}async function Bn(t,e,n){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 i=0;i<n.length;i++)r[String(i+1)]=t.state.env[String(i+1)],t.state.env[String(i+1)]=n[i];r["@"]=t.state.env["@"],r["#"]=t.state.env["#"],t.state.env["@"]=n.join(" "),t.state.env["#"]=String(n.length);let s=()=>{let i=t.state.localScopes.pop();if(i)for(let[o,a]of i)a===void 0?delete t.state.env[o]:t.state.env[o]=a;for(let[o,a]of Object.entries(r))a===void 0?delete t.state.env[o]:t.state.env[o]=a;t.state.callDepth--};try{let i=await t.executeCommand(e.body,"");return s(),i}catch(i){if(s(),i instanceof G)return S(i.stdout,i.stderr,i.exitCode);throw i}}async function Un(t,e,n){let{stdout:r,stderr:s,exitCode:i}=e;for(let o of n){if(o.target.type==="HereDoc")continue;let a=await k(t,o.target);switch(o.operator){case">":{let c=o.fd??1;if(c===1){let l=t.fs.resolvePath(t.state.cwd,a);try{if((await t.fs.stat(l)).isDirectory){s+=`bash: ${a}: Is a directory
|
|
118
|
+
`,i=1,r="";break}}catch{}await t.fs.writeFile(l,r,"binary"),r=""}else if(c===2)if(a==="/dev/null")s="";else{let l=t.fs.resolvePath(t.state.cwd,a);try{if((await t.fs.stat(l)).isDirectory){s+=`bash: ${a}: Is a directory
|
|
119
|
+
`,i=1;break}}catch{}await t.fs.writeFile(l,s,"binary"),s=""}break}case">>":{let c=o.fd??1;if(c===1){let l=t.fs.resolvePath(t.state.cwd,a);try{if((await t.fs.stat(l)).isDirectory){s+=`bash: ${a}: Is a directory
|
|
120
|
+
`,i=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){s+=`bash: ${a}: Is a directory
|
|
121
|
+
`,i=1;break}}catch{}await t.fs.appendFile(l,s,"binary"),s=""}break}case">&":{let c=o.fd??1;a==="2"||a==="&2"?c===1&&(s+=r,r=""):(a==="1"||a==="&1")&&(r+=s,s="");break}case"&>":{let c=t.fs.resolvePath(t.state.cwd,a);try{if((await t.fs.stat(c)).isDirectory){s=`bash: ${a}: Is a directory
|
|
122
|
+
`,i=1,r="";break}}catch{}await t.fs.writeFile(c,r+s,"binary"),r="",s="";break}case"&>>":{let c=t.fs.resolvePath(t.state.cwd,a);try{if((await t.fs.stat(c)).isDirectory){s=`bash: ${a}: Is a directory
|
|
123
|
+
`,i=1,r="";break}}catch{}await t.fs.appendFile(c,r+s,"binary"),r="",s="";break}}}return S(r,s,i)}var He=class{ctx;constructor(e,n){this.ctx={state:n,fs:e.fs,commands:e.commands,limits:e.limits,execFn:e.exec,executeScript:this.executeScript.bind(this),executeStatement:this.executeStatement.bind(this),executeCommand:this.executeCommand.bind(this),fetch:e.fetch,sleep:e.sleep,trace:e.trace}}async executeScript(e){let n="",r="",s=0;for(let i of e.statements)try{let o=await this.executeStatement(i);n+=o.stdout,r+=o.stderr,s=o.exitCode,this.ctx.state.lastExitCode=s,this.ctx.state.env["?"]=String(s)}catch(o){if(o instanceof R)throw o.prependOutput(n,r),o;if(o instanceof B)throw o;if(o instanceof te)return n+=o.stdout,r+=o.stderr,s=o.exitCode,this.ctx.state.lastExitCode=s,this.ctx.state.env["?"]=String(s),{stdout:n,stderr:r,exitCode:s,env:{...this.ctx.state.env}};if(o instanceof J)return n+=o.stdout,r+=o.stderr,s=1,this.ctx.state.lastExitCode=s,this.ctx.state.env["?"]=String(s),{stdout:n,stderr:r,exitCode:s,env:{...this.ctx.state.env}};if(o instanceof Ee)return n+=o.stdout,r+=o.stderr,s=1,this.ctx.state.lastExitCode=s,this.ctx.state.env["?"]=String(s),{stdout:n,stderr:r,exitCode:s,env:{...this.ctx.state.env}};if(o instanceof U||o instanceof Y){if(this.ctx.state.loopDepth>0)throw o.prependOutput(n,r),o;n+=o.stdout,r+=o.stderr;continue}throw o instanceof G&&o.prependOutput(n,r),o}return{stdout:n,stderr:r,exitCode:s,env:{...this.ctx.state.env}}}async executeStatement(e){this.ctx.state.commandCount++,this.ctx.state.commandCount>this.ctx.limits.maxCommandCount&&ce(`too many commands executed (>${this.ctx.limits.maxCommandCount}), increase executionLimits.maxCommandCount`,"commands");let n="",r="",s=0,i=-1,o=!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==="&&"&&s!==0||l==="||"&&s===0)continue;let u=await this.executePipeline(c);n+=u.stdout,r+=u.stderr,s=u.exitCode,i=a,o=c.negated,this.ctx.state.lastExitCode=s,this.ctx.state.env["?"]=String(s)}if(this.ctx.state.options.errexit&&s!==0&&i===e.pipelines.length-1&&!o&&!this.ctx.state.inCondition)throw new te(s,n,r);return S(n,r,s)}async executePipeline(e){let n="",r=N,s=0,i=[];for(let o=0;o<e.commands.length;o++){let a=e.commands[o],c=o===e.commands.length-1,l;try{l=await this.executeCommand(a,n)}catch(u){if(u instanceof Ee)l={stdout:u.stdout,stderr:u.stderr,exitCode:1};else if(u instanceof R&&e.commands.length>1)l={stdout:u.stdout,stderr:u.stderr,exitCode:u.exitCode};else throw u}i.push(l.exitCode),l.exitCode!==0&&(s=l.exitCode),c?r=l:(n=l.stdout,r={stdout:"",stderr:l.stderr,exitCode:l.exitCode})}for(let o of Object.keys(this.ctx.state.env))o.startsWith("PIPESTATUS_")&&delete this.ctx.state.env[o];for(let o=0;o<i.length;o++)this.ctx.state.env[`PIPESTATUS_${o}`]=String(i[o]);return this.ctx.state.env.PIPESTATUS__length=String(i.length),this.ctx.state.options.pipefail&&s!==0&&(r={...r,exitCode:s}),e.negated&&(r={...r,exitCode:r.exitCode===0?1:0}),r}async executeCommand(e,n){switch(e.type){case"SimpleCommand":return this.executeSimpleCommand(e,n);case"If":return _n(this.ctx,e);case"For":return Ln(this.ctx,e);case"CStyleFor":return Tn(this.ctx,e);case"While":return Fn(this.ctx,e,n);case"Until":return Wn(this.ctx,e);case"Case":return Mn(this.ctx,e);case"Subshell":return this.executeSubshell(e,n);case"Group":return this.executeGroup(e,n);case"FunctionDef":return zn(this.ctx,e);case"ArithmeticCommand":return this.executeArithmeticCommand(e);case"ConditionalCommand":return this.executeConditionalCommand(e);default:return N}}async executeSimpleCommand(e,n){try{return await this.executeSimpleCommandInner(e,n)}catch(r){if(r instanceof W)return x(r.stderr);throw r}}async executeSimpleCommandInner(e,n){e.line!==void 0&&(this.ctx.state.currentLine=e.line),this.ctx.state.expansionStderr="";let r={};for(let 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 u=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
|
+
`,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
|
+
`,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]||"")+u:u;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]||"")+u:u;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,u=await k(this.ctx,l.content);l.stripTabs&&(u=u.split(`
|
|
128
|
+
`).map(h=>h.replace(/^\t+/,"")).join(`
|
|
129
|
+
`)),n=u;continue}if(c.operator==="<<<"&&c.target.type==="Word"){n=`${await k(this.ctx,c.target)}
|
|
130
|
+
`;continue}if(c.operator==="<"&&c.target.type==="Word")try{let l=await k(this.ctx,c.target),u=this.ctx.fs.resolvePath(this.ctx.state.cwd,l);n=await this.ctx.fs.readFile(u)}catch{let l=await k(this.ctx,c.target);for(let[u,h]of Object.entries(r))h===void 0?delete this.ctx.state.env[u]:this.ctx.state.env[u]=h;return x(`bash: ${l}: No such file or directory
|
|
131
|
+
`)}}let s=await k(this.ctx,e.name),i=[],o=[];for(let c of e.args){let l=await Ge(this.ctx,c);for(let u of l.values)i.push(u),o.push(l.quoted)}if(!s){if(e.name.parts.every(l=>l.type==="CommandSubstitution"||l.type==="ParameterExpansion"||l.type==="ArithmeticExpansion")){if(i.length>0){let l=i.shift();return o.shift(),await this.runCommand(l,i,o,n)}return S("","",this.ctx.state.lastExitCode)}return x(`bash: : command not found
|
|
132
|
+
`,127)}let a=await this.runCommand(s,i,o,n);a=await Un(this.ctx,a,e.redirections),this.ctx.state.lastArg=i.length>0?i[i.length-1]:s;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,n,r,s,i=!1){if(e==="cd")return await Qt(this.ctx,n);if(e==="export")return rr(this.ctx,n);if(e==="unset")return hr(this.ctx,n);if(e==="exit")return tr(this.ctx,n);if(e==="local")return sr(this.ctx,n);if(e==="set")return lr(this.ctx,n);if(e==="break")return Zt(this.ctx,n);if(e==="continue")return Kt(this.ctx,n);if(e==="return")return ar(this.ctx,n);if(e==="eval")return er(this.ctx,n);if(e==="shift")return ur(this.ctx,n);if(e==="source"||e===".")return fr(this.ctx,n);if(e==="read")return or(this.ctx,n,s);if(e==="mapfile"||e==="readarray")return ir(this.ctx,n,s);if(e==="declare"||e==="typeset")return Yt(this.ctx,n);if(e==="readonly")return Jt(this.ctx,n);if(!i){let u=this.ctx.state.functions.get(e);if(u)return Bn(this.ctx,u,n)}if(e===":"||e==="true")return N;if(e==="false")return _(!1);if(e==="let")return nr(this.ctx,n);if(e==="command"){if(n.length===0)return N;let u=n;for(;u.length>0&&u[0].startsWith("-");)u=u.slice(1);if(u.length===0)return N;let[h,...d]=u;return this.runCommand(h,d,[],s,!0)}if(e==="builtin"){if(n.length===0)return N;let[u,...h]=n;return this.runCommand(u,h,[],s)}if(e==="shopt")return N;if(e==="exec"){if(n.length===0)return N;let[u,...h]=n;return this.runCommand(u,h,[],s)}if(e==="wait")return N;if(e==="type")return this.handleType(n);if(e==="[["){let u=n.lastIndexOf("]]");if(u!==-1){let h=n.slice(0,u);return Re(this.ctx,h)}return x("bash: [[: missing `]]'\n",2)}if(e==="["||e==="test"){let u=n;if(e==="["){if(n[n.length-1]!=="]")return x("[: missing `]'\n",2);u=n.slice(0,-1)}return Re(this.ctx,u)}let o=await this.resolveCommand(e);if(!o)return Ir(e)?x(`bash: ${e}: command not available in browser environments. Exclude '${e}' from your commands or use the Node.js bundle.
|
|
133
|
+
`,127):x(`bash: ${e}: command not found
|
|
134
|
+
`,127);let{cmd:a,path:c}=o,l={fs:this.ctx.fs,cwd:this.ctx.state.cwd,env:this.ctx.state.env,stdin:s,limits:this.ctx.limits,exec:this.ctx.execFn,fetch:this.ctx.fetch,getRegisteredCommands:()=>Array.from(this.ctx.commands.keys()),sleep:this.ctx.sleep,trace:this.ctx.trace};try{return await a.execute(n,l)}catch(u){return x(`${e}: ${le(u)}
|
|
135
|
+
`)}}async resolveCommand(e){if(e.includes("/")){let i=this.ctx.fs.resolvePath(this.ctx.state.cwd,e);if(!await this.ctx.fs.exists(i))return null;let o=i.split("/").pop()||e,a=this.ctx.commands.get(o);return a?{cmd:a,path:i}:null}let r=(this.ctx.state.env.PATH||"/bin:/usr/bin").split(":");for(let i of r){if(!i)continue;let o=`${i}/${e}`;if(await this.ctx.fs.exists(o)){let a=this.ctx.commands.get(e);if(a)return{cmd:a,path:o}}}if(!await this.ctx.fs.exists("/bin")){let i=this.ctx.commands.get(e);if(i)return{cmd:i,path:`/bin/${e}`}}return null}async findCommandInPath(e){let n=[],s=(this.ctx.state.env.PATH||"/bin:/usr/bin").split(":");for(let i of s){if(!i)continue;let o=`${i}/${e}`;await this.ctx.fs.exists(o)&&n.push(o)}return n}handleType(e){let n=new Set(["if","then","else","elif","fi","case","esac","for","select","while","until","do","done","in","function","{","}","time","[[","]]","!"]),r=new Set(["cd","export","unset","exit","local","set","break","continue","return","eval","shift","source",".","read","declare","typeset","readonly",":","true","false","let","command","builtin","shopt","exec","wait","type","[","test"]),s="",i="",o=0;for(let a of e)n.has(a)?s+=`${a} is a shell keyword
|
|
136
136
|
`:r.has(a)?s+=`${a} is a shell builtin
|
|
137
137
|
`:this.ctx.state.functions.has(a)?s+=`${a} is a function
|
|
138
138
|
`:this.ctx.commands.has(a)?s+=`${a} is /bin/${a}
|
|
139
|
-
`:(
|
|
140
|
-
`,
|
|
141
|
-
`,1)}return this.ctx.state.env=r,this.ctx.state.cwd=s,this.ctx.state.loopDepth=
|
|
142
|
-
`,1)}return this.ctx.state.groupStdin=
|
|
143
|
-
`)}}async executeConditionalCommand(e){try{let n=await
|
|
144
|
-
`,2)}}};var
|
|
145
|
-
`,OSTYPE:"linux-gnu",MACHTYPE:"x86_64-pc-linux-gnu",HOSTTYPE:"x86_64",PWD:r,OLDPWD:r,...e.env};if(this.limits=
|
|
139
|
+
`:(i+=`bash: type: ${a}: not found
|
|
140
|
+
`,o=1);return S(s,i,o)}async executeSubshell(e,n=""){let r={...this.ctx.state.env},s=this.ctx.state.cwd,i=this.ctx.state.loopDepth,o=this.ctx.state.parentHasLoopContext;this.ctx.state.parentHasLoopContext=i>0,this.ctx.state.loopDepth=0;let a=this.ctx.state.groupStdin;n&&(this.ctx.state.groupStdin=n);let c="",l="",u=0;try{for(let h of e.body){let d=await this.executeStatement(h);c+=d.stdout,l+=d.stderr,u=d.exitCode}}catch(h){if(this.ctx.state.env=r,this.ctx.state.cwd=s,this.ctx.state.loopDepth=i,this.ctx.state.parentHasLoopContext=o,this.ctx.state.groupStdin=a,h instanceof B)throw h;if(h instanceof ue)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=s,this.ctx.state.loopDepth=i,this.ctx.state.parentHasLoopContext=o,this.ctx.state.groupStdin=a,S(c,l,u)}async executeGroup(e,n=""){let r="",s="",i=0,o=this.ctx.state.groupStdin;n&&(this.ctx.state.groupStdin=n);try{for(let a of e.body){let c=await this.executeStatement(a);r+=c.stdout,s+=c.stderr,i=c.exitCode}}catch(a){if(this.ctx.state.groupStdin=o,a instanceof B)throw a;if(qe(a)||a instanceof te||a instanceof R)throw a.prependOutput(r,s),a;return S(r,`${s}${le(a)}
|
|
142
|
+
`,1)}return this.ctx.state.groupStdin=o,S(r,s,i)}async executeArithmeticCommand(e){try{let n=await v(this.ctx,e.expression.expression);return _(n!==0)}catch(n){return x(`bash: arithmetic expression: ${n.message}
|
|
143
|
+
`)}}async executeConditionalCommand(e){try{let n=await pe(this.ctx,e.expression);return _(n)}catch(n){return x(`bash: conditional expression: ${n.message}
|
|
144
|
+
`,2)}}};var ye={maxCallDepth:100,maxCommandCount:1e4,maxLoopIterations:1e4,maxAwkIterations:1e4,maxSedIterations:1e4,maxJqIterations:1e4,maxSqliteTimeoutMs:5e3};function Gn(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 Vn(t){try{let e=new URL(t);return{origin:e.origin,pathname:e.pathname,href:e.href}}catch{return null}}function ni(t){let e=Vn(t);return e?{origin:e.origin,pathPrefix:e.pathname}:null}function si(t,e){let n=Vn(t);if(!n)return!1;let r=ni(e);return!r||n.origin!==r.origin?!1:r.pathPrefix==="/"||r.pathPrefix===""?!0:n.pathname.startsWith(r.pathPrefix)}function wr(t,e){return!e||e.length===0?!1:e.some(n=>si(t,n))}var De=class extends Error{constructor(e){super(`Network access denied: URL not in allow-list: ${e}`),this.name="NetworkAccessDeniedError"}},Oe=class extends Error{constructor(e){super(`Too many redirects (max: ${e})`),this.name="TooManyRedirectsError"}},_e=class extends Error{constructor(e){super(`Redirect target not in allow-list: ${e}`),this.name="RedirectNotAllowedError"}},St=class extends Error{constructor(e,n){super(`HTTP method '${e}' not allowed. Allowed methods: ${n.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,n=t.timeoutMs??oi,r=t.dangerouslyAllowFullInternetAccess?["GET","HEAD","POST","PUT","DELETE","PATCH","OPTIONS"]:t.allowedMethods??ai;function s(a){if(!t.dangerouslyAllowFullInternetAccess&&!wr(a,t.allowedUrlPrefixes??[]))throw new De(a)}function i(a){if(t.dangerouslyAllowFullInternetAccess)return;let c=a.toUpperCase();if(!r.includes(c))throw new St(c,r)}async function o(a,c={}){let l=c.method?.toUpperCase()??"GET";s(a),i(l);let u=a,h=0,d=c.followRedirects??!0,m=c.timeoutMs!==void 0?Math.min(c.timeoutMs,n):n;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(u,p);if(li.has(w.status)&&d){let g=w.headers.get("location");if(!g)return await Hn(w,u);let b=new URL(g,u).href;if(!t.dangerouslyAllowFullInternetAccess&&!wr(b,t.allowedUrlPrefixes??[]))throw new _e(b);if(h++,h>e)throw new Oe(e);u=b;continue}return await Hn(w,u)}finally{clearTimeout(E)}}}return o}async function Hn(t,e){let n={};return t.headers.forEach((r,s)=>{n[s.toLowerCase()]=r}),{status:t.status,statusText:t.statusText,headers:n,body:await t.text(),url:e}}var je=class{fs;commands=new Map;useDefaultLayout=!1;limits;secureFetch;sleepFn;traceFn;logger;state;constructor(e={}){let n=e.fs??new ne(e.files);this.fs=n,this.useDefaultLayout=!e.cwd&&!e.files;let r=e.cwd||(this.useDefaultLayout?"/home/user":"/"),s={HOME:this.useDefaultLayout?"/home/user":"/",PATH:"/bin:/usr/bin",IFS:`
|
|
145
|
+
`,OSTYPE:"linux-gnu",MACHTYPE:"x86_64-pc-linux-gnu",HOSTTYPE:"x86_64",PWD:r,OLDPWD:r,...e.env};if(this.limits=Gn({...e.executionLimits,...e.maxCallDepth!==void 0&&{maxCallDepth:e.maxCallDepth},...e.maxCommandCount!==void 0&&{maxCommandCount:e.maxCommandCount},...e.maxLoopIterations!==void 0&&{maxLoopIterations:e.maxLoopIterations}}),e.network&&(this.secureFetch=Er(e.network)),this.sleepFn=e.sleep,this.traceFn=e.trace,this.logger=e.logger,this.state={env:s,cwd:r,previousDir:"/home/user",functions:new Map,localScopes:[],callDepth:0,sourceDepth:0,commandCount:0,lastExitCode:0,lastArg:"",startTime:Date.now(),lastBackgroundPid:0,currentLine:1,options:{errexit:!1,pipefail:!1,nounset:!1,xtrace:!1,verbose:!1},inCondition:!1,loopDepth:0},kr(n,this.useDefaultLayout),r!=="/"&&n instanceof ne)try{n.mkdirSync(r,{recursive:!0})}catch{}for(let i of xr(e.commands))this.registerCommand(i);if(e.network)for(let i of br())this.registerCommand(i);if(e.customCommands)for(let i of e.customCommands)Cr(i)?this.registerCommand(Nr(i)):this.registerCommand(i)}registerCommand(e){this.commands.set(e.name,e);let n=this.fs;if(typeof n.writeFileSync=="function")try{n.writeFileSync(`/bin/${e.name}`,`#!/bin/bash
|
|
146
146
|
# Built-in command: ${e.name}
|
|
147
147
|
`)}catch{}}logResult(e){return this.logger&&(e.stdout&&this.logger.debug("stdout",{output:e.stdout}),e.stderr&&this.logger.info("stderr",{output:e.stderr}),this.logger.info("exit",{exitCode:e.exitCode})),e}async exec(e,n){if(this.state.callDepth===0&&(this.state.commandCount=0),this.state.commandCount++,this.state.commandCount>this.limits.maxCommandCount)return{stdout:"",stderr:`bash: maximum command count (${this.limits.maxCommandCount}) exceeded (possible infinite loop). Increase with executionLimits.maxCommandCount option.
|
|
148
|
-
`,exitCode:1,env:{...this.state.env,...n?.env}};if(!e.trim())return{stdout:"",stderr:"",exitCode:0,env:{...this.state.env,...n?.env}};this.logger?.info("exec",{command:e});let r=n?.cwd??this.state.cwd,s={...this.state,env:{...this.state.env,...n?.env,...n?.cwd?{PWD:n.cwd}:{}},cwd:r,functions:new Map(this.state.functions),localScopes:[...this.state.localScopes],options:{...this.state.options}},
|
|
148
|
+
`,exitCode:1,env:{...this.state.env,...n?.env}};if(!e.trim())return{stdout:"",stderr:"",exitCode:0,env:{...this.state.env,...n?.env}};this.logger?.info("exec",{command:e});let r=n?.cwd??this.state.cwd,s={...this.state,env:{...this.state.env,...n?.env,...n?.cwd?{PWD:n.cwd}:{}},cwd:r,functions:new Map(this.state.functions),localScopes:[...this.state.localScopes],options:{...this.state.options}},i=e;n?.rawScript||(i=e.split(`
|
|
149
149
|
`).map(a=>a.trimStart()).join(`
|
|
150
|
-
`));try{let
|
|
151
|
-
`,exitCode:2,env:{...this.state.env,...n?.env}});if(
|
|
152
|
-
`,exitCode:1,env:{...this.state.env,...n?.env}});throw i}}async readFile(e){return this.fs.readFile(this.fs.resolvePath(this.state.cwd,e))}async writeFile(e,n){return this.fs.writeFile(this.fs.resolvePath(this.state.cwd,e),n)}getCwd(){return this.state.cwd}getEnv(){return{...this.state.env}}};import*as B from"node:fs";import*as Le from"node:path";var li="/home/user/project",Te=class{root;mountPoint;readOnly;memory=new Map;deleted=new Set;constructor(e){this.root=Le.resolve(e.root);let n=e.mountPoint??li;if(this.mountPoint=n==="/"?"/":n.replace(/\/+$/,""),!this.mountPoint.startsWith("/"))throw new Error(`Mount point must be an absolute path: ${n}`);if(this.readOnly=e.readOnly??!1,!B.existsSync(this.root))throw new Error(`OverlayFs root does not exist: ${this.root}`);if(!B.statSync(this.root).isDirectory())throw new Error(`OverlayFs root is not a directory: ${this.root}`);this.createMountPointDirs()}assertWritable(e){if(this.readOnly)throw new Error(`EROFS: read-only file system, ${e}`)}createMountPointDirs(){let e=this.mountPoint.split("/").filter(Boolean),n="";for(let r of e)n+=`/${r}`,this.memory.has(n)||this.memory.set(n,{type:"directory",mode:493,mtime:new Date});this.memory.has("/")||this.memory.set("/",{type:"directory",mode:493,mtime:new Date})}getMountPoint(){return this.mountPoint}mkdirSync(e,n){let s=this.normalizePath(e).split("/").filter(Boolean),o="";for(let i of s)o+=`/${i}`,this.memory.has(o)||this.memory.set(o,{type:"directory",mode:493,mtime:new Date})}writeFileSync(e,n){let r=this.normalizePath(e),s=this.getDirname(r);s!=="/"&&this.mkdirSync(s);let o=n instanceof Uint8Array?n:new TextEncoder().encode(n);this.memory.set(r,{type:"file",content:o,mode:420,mtime:new Date})}getDirname(e){let n=e.lastIndexOf("/");return n===0?"/":e.slice(0,n)}normalizePath(e){if(!e||e==="/")return"/";let n=e.endsWith("/")&&e!=="/"?e.slice(0,-1):e;n.startsWith("/")||(n=`/${n}`);let r=n.split("/").filter(o=>o&&o!=="."),s=[];for(let o of r)o===".."?s.pop():s.push(o);return`/${s.join("/")}`||"/"}getRelativeToMount(e){return this.mountPoint==="/"?e:e===this.mountPoint?"/":e.startsWith(`${this.mountPoint}/`)?e.slice(this.mountPoint.length):null}toRealPath(e){let n=this.normalizePath(e),r=this.getRelativeToMount(n);if(r===null)return null;let s=Le.join(this.root,r),o=Le.resolve(s);return!o.startsWith(this.root)&&o!==this.root.replace(/\/$/,"")?null:o}dirname(e){let n=this.normalizePath(e);if(n==="/")return"/";let r=n.lastIndexOf("/");return r===0?"/":n.slice(0,r)}ensureParentDirs(e){let n=this.dirname(e);n!=="/"&&(this.memory.has(n)||(this.ensureParentDirs(n),this.memory.set(n,{type:"directory",mode:493,mtime:new Date})),this.deleted.delete(n))}async existsInOverlay(e){let n=this.normalizePath(e);if(this.deleted.has(n))return!1;if(this.memory.has(n))return!0;let r=this.toRealPath(n);if(!r)return!1;try{return await B.promises.access(r),!0}catch{return!1}}async readFile(e,n){let r=await this.readFileBuffer(e),s=q(n);return Ne(r,s)}async readFileBuffer(e,n=new Set){let r=this.normalizePath(e);if(n.has(r))throw new Error(`ELOOP: too many levels of symbolic links, open '${e}'`);if(n.add(r),this.deleted.has(r))throw new Error(`ENOENT: no such file or directory, open '${e}'`);let s=this.memory.get(r);if(s){if(s.type==="symlink"){let i=this.resolveSymlink(r,s.target);return this.readFileBuffer(i,n)}if(s.type!=="file")throw new Error(`EISDIR: illegal operation on a directory, read '${e}'`);return s.content}let o=this.toRealPath(r);if(!o)throw new Error(`ENOENT: no such file or directory, open '${e}'`);try{let i=await B.promises.lstat(o);if(i.isSymbolicLink()){let l=await B.promises.readlink(o),c=this.resolveSymlink(r,l);return this.readFileBuffer(c,n)}if(i.isDirectory())throw new Error(`EISDIR: illegal operation on a directory, read '${e}'`);let a=await B.promises.readFile(o);return new Uint8Array(a)}catch(i){throw i.code==="ENOENT"?new Error(`ENOENT: no such file or directory, open '${e}'`):i}}async writeFile(e,n,r){this.assertWritable(`write '${e}'`);let s=this.normalizePath(e);this.ensureParentDirs(s);let o=q(r),i=re(n,o);this.memory.set(s,{type:"file",content:i,mode:420,mtime:new Date}),this.deleted.delete(s)}async appendFile(e,n,r){this.assertWritable(`append '${e}'`);let s=this.normalizePath(e),o=q(r),i=re(n,o),a;try{a=await this.readFileBuffer(s)}catch{a=new Uint8Array(0)}let l=new Uint8Array(a.length+i.length);l.set(a),l.set(i,a.length),this.ensureParentDirs(s),this.memory.set(s,{type:"file",content:l,mode:420,mtime:new Date}),this.deleted.delete(s)}async exists(e){return this.existsInOverlay(e)}async stat(e,n=new Set){let r=this.normalizePath(e);if(n.has(r))throw new Error(`ELOOP: too many levels of symbolic links, stat '${e}'`);if(n.add(r),this.deleted.has(r))throw new Error(`ENOENT: no such file or directory, stat '${e}'`);let s=this.memory.get(r);if(s){if(s.type==="symlink"){let a=this.resolveSymlink(r,s.target);return this.stat(a,n)}let i=0;return s.type==="file"&&(i=s.content.length),{isFile:s.type==="file",isDirectory:s.type==="directory",isSymbolicLink:!1,mode:s.mode,size:i,mtime:s.mtime}}let o=this.toRealPath(r);if(!o)throw new Error(`ENOENT: no such file or directory, stat '${e}'`);try{let i=await B.promises.stat(o);return{isFile:i.isFile(),isDirectory:i.isDirectory(),isSymbolicLink:!1,mode:i.mode,size:i.size,mtime:i.mtime}}catch(i){throw i.code==="ENOENT"?new Error(`ENOENT: no such file or directory, stat '${e}'`):i}}async lstat(e){let n=this.normalizePath(e);if(this.deleted.has(n))throw new Error(`ENOENT: no such file or directory, lstat '${e}'`);let r=this.memory.get(n);if(r){if(r.type==="symlink")return{isFile:!1,isDirectory:!1,isSymbolicLink:!0,mode:r.mode,size:r.target.length,mtime:r.mtime};let o=0;return r.type==="file"&&(o=r.content.length),{isFile:r.type==="file",isDirectory:r.type==="directory",isSymbolicLink:!1,mode:r.mode,size:o,mtime:r.mtime}}let s=this.toRealPath(n);if(!s)throw new Error(`ENOENT: no such file or directory, lstat '${e}'`);try{let o=await B.promises.lstat(s);return{isFile:o.isFile(),isDirectory:o.isDirectory(),isSymbolicLink:o.isSymbolicLink(),mode:o.mode,size:o.size,mtime:o.mtime}}catch(o){throw o.code==="ENOENT"?new Error(`ENOENT: no such file or directory, lstat '${e}'`):o}}resolveSymlink(e,n){if(n.startsWith("/"))return this.normalizePath(n);let r=this.dirname(e);return this.normalizePath(r==="/"?`/${n}`:`${r}/${n}`)}async mkdir(e,n){this.assertWritable(`mkdir '${e}'`);let r=this.normalizePath(e);if(await this.existsInOverlay(r)){if(!n?.recursive)throw new Error(`EEXIST: file already exists, mkdir '${e}'`);return}let o=this.dirname(r);if(o!=="/"&&!await this.existsInOverlay(o))if(n?.recursive)await this.mkdir(o,{recursive:!0});else throw new Error(`ENOENT: no such file or directory, mkdir '${e}'`);this.memory.set(r,{type:"directory",mode:493,mtime:new Date}),this.deleted.delete(r)}async readdirCore(e,n){if(this.deleted.has(n))throw new Error(`ENOENT: no such file or directory, scandir '${e}'`);let r=new Map,s=new Set,o=n==="/"?"/":`${n}/`;for(let a of this.deleted)if(a.startsWith(o)){let l=a.slice(o.length),c=l.split("/")[0];c&&!l.includes("/",c.length)&&s.add(c)}for(let[a,l]of this.memory)if(a!==n&&a.startsWith(o)){let c=a.slice(o.length),f=c.split("/")[0];f&&!s.has(f)&&!c.includes("/",1)&&r.set(f,{name:f,isFile:l.type==="file",isDirectory:l.type==="directory",isSymbolicLink:l.type==="symlink"})}let i=this.toRealPath(n);if(i)try{let a=await B.promises.readdir(i,{withFileTypes:!0});for(let l of a)!s.has(l.name)&&!r.has(l.name)&&r.set(l.name,{name:l.name,isFile:l.isFile(),isDirectory:l.isDirectory(),isSymbolicLink:l.isSymbolicLink()})}catch(a){if(a.code==="ENOENT"){if(!this.memory.has(n))throw new Error(`ENOENT: no such file or directory, scandir '${e}'`)}else if(a.code!=="ENOTDIR")throw a}return r}async readdir(e){let n=this.normalizePath(e),r=await this.readdirCore(e,n);return Array.from(r.keys()).sort((s,o)=>s<o?-1:s>o?1:0)}async readdirWithFileTypes(e){let n=this.normalizePath(e),r=await this.readdirCore(e,n);return Array.from(r.values()).sort((s,o)=>s.name<o.name?-1:s.name>o.name?1:0)}async rm(e,n){this.assertWritable(`rm '${e}'`);let r=this.normalizePath(e);if(!await this.existsInOverlay(r)){if(n?.force)return;throw new Error(`ENOENT: no such file or directory, rm '${e}'`)}try{if((await this.stat(r)).isDirectory){let i=await this.readdir(r);if(i.length>0){if(!n?.recursive)throw new Error(`ENOTEMPTY: directory not empty, rm '${e}'`);for(let a of i){let l=r==="/"?`/${a}`:`${r}/${a}`;await this.rm(l,n)}}}}catch{}this.deleted.add(r),this.memory.delete(r)}async cp(e,n,r){this.assertWritable(`cp '${n}'`);let s=this.normalizePath(e),o=this.normalizePath(n);if(!await this.existsInOverlay(s))throw new Error(`ENOENT: no such file or directory, cp '${e}'`);let a=await this.stat(s);if(a.isFile){let l=await this.readFileBuffer(s);await this.writeFile(o,l)}else if(a.isDirectory){if(!r?.recursive)throw new Error(`EISDIR: is a directory, cp '${e}'`);await this.mkdir(o,{recursive:!0});let l=await this.readdir(s);for(let c of l){let f=s==="/"?`/${c}`:`${s}/${c}`,d=o==="/"?`/${c}`:`${o}/${c}`;await this.cp(f,d,r)}}}async mv(e,n){this.assertWritable(`mv '${n}'`),await this.cp(e,n,{recursive:!0}),await this.rm(e,{recursive:!0})}resolvePath(e,n){if(n.startsWith("/"))return this.normalizePath(n);let r=e==="/"?`/${n}`:`${e}/${n}`;return this.normalizePath(r)}getAllPaths(){let e=new Set(this.memory.keys());for(let n of this.deleted)e.delete(n);return this.scanRealFs("/",e),Array.from(e)}scanRealFs(e,n){if(this.deleted.has(e))return;let r=this.toRealPath(e);if(r)try{let s=B.readdirSync(r);for(let o of s){let i=e==="/"?`/${o}`:`${e}/${o}`;if(this.deleted.has(i))continue;n.add(i);let a=Le.join(r,o);B.statSync(a).isDirectory()&&this.scanRealFs(i,n)}}catch{}}async chmod(e,n){this.assertWritable(`chmod '${e}'`);let r=this.normalizePath(e);if(!await this.existsInOverlay(r))throw new Error(`ENOENT: no such file or directory, chmod '${e}'`);let o=this.memory.get(r);if(o){o.mode=n;return}let i=await this.stat(r);if(i.isFile){let a=await this.readFileBuffer(r);this.memory.set(r,{type:"file",content:a,mode:n,mtime:new Date})}else i.isDirectory&&this.memory.set(r,{type:"directory",mode:n,mtime:new Date})}async symlink(e,n){this.assertWritable(`symlink '${n}'`);let r=this.normalizePath(n);if(await this.existsInOverlay(r))throw new Error(`EEXIST: file already exists, symlink '${n}'`);this.ensureParentDirs(r),this.memory.set(r,{type:"symlink",target:e,mode:511,mtime:new Date}),this.deleted.delete(r)}async link(e,n){this.assertWritable(`link '${n}'`);let r=this.normalizePath(e),s=this.normalizePath(n);if(!await this.existsInOverlay(r))throw new Error(`ENOENT: no such file or directory, link '${e}'`);let i=await this.stat(r);if(!i.isFile)throw new Error(`EPERM: operation not permitted, link '${e}'`);if(await this.existsInOverlay(s))throw new Error(`EEXIST: file already exists, link '${n}'`);let l=await this.readFileBuffer(r);this.ensureParentDirs(s),this.memory.set(s,{type:"file",content:l,mode:i.mode,mtime:new Date}),this.deleted.delete(s)}async readlink(e){let n=this.normalizePath(e);if(this.deleted.has(n))throw new Error(`ENOENT: no such file or directory, readlink '${e}'`);let r=this.memory.get(n);if(r){if(r.type!=="symlink")throw new Error(`EINVAL: invalid argument, readlink '${e}'`);return r.target}let s=this.toRealPath(n);if(!s)throw new Error(`ENOENT: no such file or directory, readlink '${e}'`);try{return await B.promises.readlink(s)}catch(o){throw o.code==="ENOENT"?new Error(`ENOENT: no such file or directory, readlink '${e}'`):o.code==="EINVAL"?new Error(`EINVAL: invalid argument, readlink '${e}'`):o}}};import*as v from"node:fs";import*as ee from"node:path";var St=class{root;constructor(e){if(this.root=ee.resolve(e.root),!v.existsSync(this.root))throw new Error(`ReadWriteFs root does not exist: ${this.root}`);if(!v.statSync(this.root).isDirectory())throw new Error(`ReadWriteFs root is not a directory: ${this.root}`)}toRealPath(e){let n=this.normalizePath(e),r=ee.join(this.root,n);return ee.resolve(r)}normalizePath(e){if(!e||e==="/")return"/";let n=e.endsWith("/")&&e!=="/"?e.slice(0,-1):e;n.startsWith("/")||(n=`/${n}`);let r=n.split("/").filter(o=>o&&o!=="."),s=[];for(let o of r)o===".."?s.pop():s.push(o);return`/${s.join("/")}`||"/"}async readFile(e,n){let r=await this.readFileBuffer(e),s=q(n);return Ne(r,s)}async readFileBuffer(e){let n=this.toRealPath(e);try{let r=await v.promises.readFile(n);return new Uint8Array(r)}catch(r){let s=r;throw s.code==="ENOENT"?new Error(`ENOENT: no such file or directory, open '${e}'`):s.code==="EISDIR"?new Error(`EISDIR: illegal operation on a directory, read '${e}'`):r}}async writeFile(e,n,r){let s=this.toRealPath(e),o=q(r),i=re(n,o),a=ee.dirname(s);await v.promises.mkdir(a,{recursive:!0}),await v.promises.writeFile(s,i)}async appendFile(e,n,r){let s=this.toRealPath(e),o=q(r),i=re(n,o),a=ee.dirname(s);await v.promises.mkdir(a,{recursive:!0}),await v.promises.appendFile(s,i)}async exists(e){let n=this.toRealPath(e);try{return await v.promises.access(n),!0}catch{return!1}}async stat(e){let n=this.toRealPath(e);try{let r=await v.promises.stat(n);return{isFile:r.isFile(),isDirectory:r.isDirectory(),isSymbolicLink:!1,mode:r.mode,size:r.size,mtime:r.mtime}}catch(r){throw r.code==="ENOENT"?new Error(`ENOENT: no such file or directory, stat '${e}'`):r}}async lstat(e){let n=this.toRealPath(e);try{let r=await v.promises.lstat(n);return{isFile:r.isFile(),isDirectory:r.isDirectory(),isSymbolicLink:r.isSymbolicLink(),mode:r.mode,size:r.size,mtime:r.mtime}}catch(r){throw r.code==="ENOENT"?new Error(`ENOENT: no such file or directory, lstat '${e}'`):r}}async mkdir(e,n){let r=this.toRealPath(e);try{await v.promises.mkdir(r,{recursive:n?.recursive})}catch(s){let o=s;throw o.code==="EEXIST"?new Error(`EEXIST: file already exists, mkdir '${e}'`):o.code==="ENOENT"?new Error(`ENOENT: no such file or directory, mkdir '${e}'`):s}}async readdir(e){return(await this.readdirWithFileTypes(e)).map(r=>r.name)}async readdirWithFileTypes(e){let n=this.toRealPath(e);try{return(await v.promises.readdir(n,{withFileTypes:!0})).map(s=>({name:s.name,isFile:s.isFile(),isDirectory:s.isDirectory(),isSymbolicLink:s.isSymbolicLink()})).sort((s,o)=>s.name<o.name?-1:s.name>o.name?1:0)}catch(r){let s=r;throw s.code==="ENOENT"?new Error(`ENOENT: no such file or directory, scandir '${e}'`):s.code==="ENOTDIR"?new Error(`ENOTDIR: not a directory, scandir '${e}'`):r}}async rm(e,n){let r=this.toRealPath(e);try{await v.promises.rm(r,{recursive:n?.recursive??!1,force:n?.force??!1})}catch(s){let o=s;throw o.code==="ENOENT"&&!n?.force?new Error(`ENOENT: no such file or directory, rm '${e}'`):o.code==="ENOTEMPTY"?new Error(`ENOTEMPTY: directory not empty, rm '${e}'`):s}}async cp(e,n,r){let s=this.toRealPath(e),o=this.toRealPath(n);try{await v.promises.cp(s,o,{recursive:r?.recursive??!1})}catch(i){let a=i;throw a.code==="ENOENT"?new Error(`ENOENT: no such file or directory, cp '${e}'`):a.code==="EISDIR"?new Error(`EISDIR: is a directory, cp '${e}'`):i}}async mv(e,n){let r=this.toRealPath(e),s=this.toRealPath(n),o=ee.dirname(s);await v.promises.mkdir(o,{recursive:!0});try{await v.promises.rename(r,s)}catch(i){let a=i;if(a.code==="ENOENT")throw new Error(`ENOENT: no such file or directory, mv '${e}'`);if(a.code==="EXDEV"){await this.cp(e,n,{recursive:!0}),await this.rm(e,{recursive:!0});return}throw i}}resolvePath(e,n){if(n.startsWith("/"))return this.normalizePath(n);let r=e==="/"?`/${n}`:`${e}/${n}`;return this.normalizePath(r)}getAllPaths(){let e=[];return this.scanDir("/",e),e}scanDir(e,n){let r=this.toRealPath(e);try{let s=v.readdirSync(r);for(let o of s){let i=e==="/"?`/${o}`:`${e}/${o}`;n.push(i);let a=ee.join(r,o);v.statSync(a).isDirectory()&&this.scanDir(i,n)}}catch{}}async chmod(e,n){let r=this.toRealPath(e);try{await v.promises.chmod(r,n)}catch(s){throw s.code==="ENOENT"?new Error(`ENOENT: no such file or directory, chmod '${e}'`):s}}async symlink(e,n){let r=this.toRealPath(n);try{await v.promises.symlink(e,r)}catch(s){throw s.code==="EEXIST"?new Error(`EEXIST: file already exists, symlink '${n}'`):s}}async link(e,n){let r=this.toRealPath(e),s=this.toRealPath(n);try{await v.promises.link(r,s)}catch(o){let i=o;throw i.code==="ENOENT"?new Error(`ENOENT: no such file or directory, link '${e}'`):i.code==="EEXIST"?new Error(`EEXIST: file already exists, link '${n}'`):i.code==="EPERM"?new Error(`EPERM: operation not permitted, link '${e}'`):o}}async readlink(e){let n=this.toRealPath(e);try{return await v.promises.readlink(n)}catch(r){let s=r;throw s.code==="ENOENT"?new Error(`ENOENT: no such file or directory, readlink '${e}'`):s.code==="EINVAL"?new Error(`EINVAL: invalid argument, readlink '${e}'`):r}}};var Fe=class{cmdId;cwd;startedAt;exitCode;bashEnv;cmdLine;env;explicitCwd;resultPromise;constructor(e,n,r,s,o=!1){this.cmdId=crypto.randomUUID(),this.cwd=r,this.startedAt=new Date,this.bashEnv=e,this.cmdLine=n,this.env=s,this.explicitCwd=o,this.resultPromise=this.execute()}async execute(){let e=this.env||this.explicitCwd?{cwd:this.explicitCwd?this.cwd:void 0,env:this.env}:void 0,n=await this.bashEnv.exec(this.cmdLine,e);return this.exitCode=n.exitCode,n}async*logs(){let e=await this.resultPromise;e.stdout&&(yield{type:"stdout",data:e.stdout,timestamp:new Date}),e.stderr&&(yield{type:"stderr",data:e.stderr,timestamp:new Date})}async wait(){return await this.resultPromise,this}async output(){let e=await this.resultPromise;return e.stdout+e.stderr}async stdout(){return(await this.resultPromise).stdout}async stderr(){return(await this.resultPromise).stderr}async kill(){}};var bt=class t{bashEnv;constructor(e){this.bashEnv=e}static async create(e){let n=e?.fs;if(e?.overlayRoot){if(e?.fs)throw new Error("Cannot specify both 'fs' and 'overlayRoot' options");n=new Te({root:e.overlayRoot})}let r=new je({env:e?.env,cwd:e?.cwd,fs:n,maxCallDepth:e?.maxCallDepth,maxCommandCount:e?.maxCommandCount,maxLoopIterations:e?.maxLoopIterations,network:e?.network});return new t(r)}async runCommand(e,n){let r=n?.cwd??this.bashEnv.getCwd(),s=n?.cwd!==void 0;return new Fe(this.bashEnv,e,r,n?.env,s)}async writeFiles(e){for(let[n,r]of Object.entries(e)){let s;typeof r=="string"?s=r:r.encoding==="base64"?s=Buffer.from(r.content,"base64").toString("utf-8"):s=r.content;let o=n.substring(0,n.lastIndexOf("/"))||"/";o!=="/"&&await this.bashEnv.exec(`mkdir -p ${o}`),await this.bashEnv.writeFile(n,s)}}async readFile(e,n){let r=await this.bashEnv.readFile(e);return n==="base64"?Buffer.from(r).toString("base64"):r}async mkDir(e,n){let r=n?.recursive?"-p":"";await this.bashEnv.exec(`mkdir ${r} ${e}`)}async stop(){}async extendTimeout(e){}get domain(){}get bashEnvInstance(){return this.bashEnv}};export{je as Bash,we as InMemoryFs,De as NetworkAccessDeniedError,Te as OverlayFs,St as ReadWriteFs,_e as RedirectNotAllowedError,bt as Sandbox,Fe as SandboxCommand,Oe as TooManyRedirectsError,qn as defineCommand,Hn as getCommandNames,jn as getNetworkCommandNames};
|
|
150
|
+
`));try{let o=he(i),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,s).executeScript(o);return this.logResult(l)}catch(o){if(o instanceof R)return this.logResult({stdout:o.stdout,stderr:o.stderr,exitCode:o.exitCode,env:{...this.state.env,...n?.env}});if(o instanceof W)return this.logResult({stdout:o.stdout,stderr:o.stderr,exitCode:1,env:{...this.state.env,...n?.env}});if(o instanceof B)return this.logResult({stdout:o.stdout,stderr:o.stderr,exitCode:B.EXIT_CODE,env:{...this.state.env,...n?.env}});if(o.name==="ParseException")return this.logResult({stdout:"",stderr:`bash: syntax error: ${o.message}
|
|
151
|
+
`,exitCode:2,env:{...this.state.env,...n?.env}});if(o instanceof RangeError)return this.logResult({stdout:"",stderr:`bash: ${o.message}
|
|
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};
|