just-bash 1.4.0 → 1.4.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin/chunks/{find-D3ZC5DXH.js → find-TRBVCSI6.js} +8 -8
- package/dist/bin/chunks/jq-TRAUXD47.js +19 -0
- package/dist/bin/just-bash.js +13 -13
- package/dist/bin/shell/chunks/{find-D3ZC5DXH.js → find-TRBVCSI6.js} +8 -8
- package/dist/bin/shell/chunks/jq-TRAUXD47.js +19 -0
- package/dist/bin/shell/shell.js +13 -13
- package/dist/bundle/ai/index.js +401 -396
- package/dist/bundle/chunks/{find-R6LJIRBI.js → find-GM7FJ4D3.js} +8 -8
- package/dist/bundle/chunks/jq-PO3DWIV2.js +18 -0
- package/dist/bundle/index.js +13 -13
- package/dist/commands/jq/evaluator.d.ts +18 -0
- package/dist/commands/jq/jq.d.ts +1 -8
- package/dist/commands/jq/parser.d.ts +138 -0
- package/dist/limits.d.ts +2 -0
- package/package.json +1 -1
- package/dist/bin/chunks/jq-ME57VHK6.js +0 -14
- package/dist/bin/shell/chunks/jq-ME57VHK6.js +0 -14
- package/dist/bundle/chunks/jq-ABWUP4LV.js +0 -13
package/dist/bundle/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
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 ye,i as z,j as le,k as He}from"./chunks/chunk-CG2HXOFG.js";import{a as ce}from"./chunks/chunk-44UOCSGV.js";import"./chunks/chunk-2RUN43TJ.js";var St=[{name:"echo",load:async()=>(await import("./chunks/echo-WUKBESC7.js")).echoCommand},{name:"cat",load:async()=>(await import("./chunks/cat-47EP4IAV.js")).catCommand},{name:"printf",load:async()=>(await import("./chunks/printf-HBP44PXI.js")).printfCommand},{name:"ls",load:async()=>(await import("./chunks/ls-JGYJQA2Y.js")).lsCommand},{name:"mkdir",load:async()=>(await import("./chunks/mkdir-HA2FJX4O.js")).mkdirCommand},{name:"touch",load:async()=>(await import("./chunks/touch-FOE745V2.js")).touchCommand},{name:"rm",load:async()=>(await import("./chunks/rm-NF3FNLAY.js")).rmCommand},{name:"cp",load:async()=>(await import("./chunks/cp-37OVLNLD.js")).cpCommand},{name:"mv",load:async()=>(await import("./chunks/mv-7I62SB3I.js")).mvCommand},{name:"ln",load:async()=>(await import("./chunks/ln-XFYHBIFL.js")).lnCommand},{name:"chmod",load:async()=>(await import("./chunks/chmod-XJXFAD4M.js")).chmodCommand},{name:"pwd",load:async()=>(await import("./chunks/pwd-CEF235GL.js")).pwdCommand},{name:"readlink",load:async()=>(await import("./chunks/readlink-MQIMKDSA.js")).readlinkCommand},{name:"head",load:async()=>(await import("./chunks/head-6PAUYCDP.js")).headCommand},{name:"tail",load:async()=>(await import("./chunks/tail-QXKYHAML.js")).tailCommand},{name:"wc",load:async()=>(await import("./chunks/wc-GV5WUREX.js")).wcCommand},{name:"stat",load:async()=>(await import("./chunks/stat-FVFLDQGP.js")).statCommand},{name:"grep",load:async()=>(await import("./chunks/grep-ZJVDG3FA.js")).grepCommand},{name:"fgrep",load:async()=>(await import("./chunks/grep-ZJVDG3FA.js")).fgrepCommand},{name:"egrep",load:async()=>(await import("./chunks/grep-ZJVDG3FA.js")).egrepCommand},{name:"sed",load:async()=>(await import("./chunks/sed-H2RWPMTM.js")).sedCommand},{name:"awk",load:async()=>(await import("./chunks/awk2-QWBT4IFJ.js")).awkCommand2},{name:"sort",load:async()=>(await import("./chunks/sort-XODGFZC4.js")).sortCommand},{name:"uniq",load:async()=>(await import("./chunks/uniq-7PFWPNWK.js")).uniqCommand},{name:"comm",load:async()=>(await import("./chunks/comm-KSJ4BBRQ.js")).commCommand},{name:"cut",load:async()=>(await import("./chunks/cut-FIZRELKC.js")).cutCommand},{name:"paste",load:async()=>(await import("./chunks/paste-QBGVCQFT.js")).pasteCommand},{name:"tr",load:async()=>(await import("./chunks/tr-LMLGE4IE.js")).trCommand},{name:"tee",load:async()=>(await import("./chunks/tee-W5HCCBPO.js")).teeCommand},{name:"find",load:async()=>(await import("./chunks/find-R6LJIRBI.js")).findCommand},{name:"basename",load:async()=>(await import("./chunks/basename-5UVU5RXR.js")).basenameCommand},{name:"dirname",load:async()=>(await import("./chunks/dirname-U2KVUSQY.js")).dirnameCommand},{name:"tree",load:async()=>(await import("./chunks/tree-WBUGLVP5.js")).treeCommand},{name:"du",load:async()=>(await import("./chunks/du-KRAFOIQK.js")).duCommand},{name:"env",load:async()=>(await import("./chunks/env-MSPSPGCD.js")).envCommand},{name:"printenv",load:async()=>(await import("./chunks/env-MSPSPGCD.js")).printenvCommand},{name:"alias",load:async()=>(await import("./chunks/alias-JFIUWFGE.js")).aliasCommand},{name:"unalias",load:async()=>(await import("./chunks/alias-JFIUWFGE.js")).unaliasCommand},{name:"history",load:async()=>(await import("./chunks/history-SG6VRATI.js")).historyCommand},{name:"xargs",load:async()=>(await import("./chunks/xargs-NQBNFMCT.js")).xargsCommand},{name:"true",load:async()=>(await import("./chunks/true-6LGCG4EY.js")).trueCommand},{name:"false",load:async()=>(await import("./chunks/true-6LGCG4EY.js")).falseCommand},{name:"clear",load:async()=>(await import("./chunks/clear-XD3TJRVQ.js")).clearCommand},{name:"bash",load:async()=>(await import("./chunks/bash-BASUPKHJ.js")).bashCommand},{name:"sh",load:async()=>(await import("./chunks/bash-BASUPKHJ.js")).shCommand},{name:"jq",load:async()=>(await import("./chunks/jq-ABWUP4LV.js")).jqCommand},{name:"base64",load:async()=>(await import("./chunks/base64-TUA2XORD.js")).base64Command},{name:"diff",load:async()=>(await import("./chunks/diff-GLRVCAKJ.js")).diffCommand},{name:"date",load:async()=>(await import("./chunks/date-NN5C354M.js")).dateCommand},{name:"sleep",load:async()=>(await import("./chunks/sleep-AFN3PHJW.js")).sleepCommand},{name:"timeout",load:async()=>(await import("./chunks/timeout-XAA3N7CF.js")).timeoutCommand},{name:"seq",load:async()=>(await import("./chunks/seq-VKYIUOPJ.js")).seqCommand},{name:"expr",load:async()=>(await import("./chunks/expr-HYOCSWK6.js")).exprCommand},{name:"md5sum",load:async()=>(await import("./chunks/md5sum-PIH6F3O3.js")).md5sumCommand},{name:"sha1sum",load:async()=>(await import("./chunks/sha1sum-HVHNZSEC.js")).sha1sumCommand},{name:"sha256sum",load:async()=>(await import("./chunks/sha256sum-REOOJORK.js")).sha256sumCommand},{name:"file",load:async()=>(await import("./chunks/file-LQXX6P4Y.js")).fileCommand},{name:"html-to-markdown",load:async()=>(await import("./chunks/html-to-markdown-ZSZ34PAN.js")).htmlToMarkdownCommand},{name:"help",load:async()=>(await import("./chunks/help-5E6PYJWQ.js")).helpCommand},{name:"which",load:async()=>(await import("./chunks/which-KHFYPBWW.js")).whichCommand},{name:"tac",load:async()=>(await import("./chunks/tac-VIFKNLII.js")).tac},{name:"hostname",load:async()=>(await import("./chunks/hostname-K4BA3P6X.js")).hostname},{name:"od",load:async()=>(await import("./chunks/od-SOCTFI2F.js")).od}],wr=[{name:"curl",load:async()=>(await import("./chunks/curl-C43O5WQS.js")).curlCommand}],Er=new Map;function gr(t){return{name:t.name,async execute(e,n){let r=Er.get(t.name);return r||(r=await t.load(),Er.set(t.name,r)),r.execute(e,n)}}}function Gn(){return St.map(t=>t.name)}function Vn(){return wr.map(t=>t.name)}function Ar(t){return(t?St.filter(n=>t.includes(n.name)):St).map(gr)}function xr(){return wr.map(gr)}function Sr(t){return"load"in t&&typeof t.load=="function"}function Hn(t,e){return{name:t,execute:e}}function br(t){let e=null;return{name:t.name,async execute(n,r){return e||(e=await t.load()),e.execute(n,r)}}}var jn=new TextEncoder,Zn=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 jn.encode(t)}}function Se(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 Zn.decode(t)}}function Z(t){if(t!=null)return typeof t=="string"?t:t.encoding??void 0}var je=new TextEncoder;function qn(t){return typeof t=="object"&&t!==null&&!(t instanceof Uint8Array)&&"content"in t}var Ee=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))qn(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=Z(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=Z(n);return Se(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:je.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=Z(r),a=re(n,i);if(o?.type==="file"){let l=o.content instanceof Uint8Array?o.content:je.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=je.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=je.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){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=[];for(let i of this.data.keys())if(i!==n&&i.startsWith(s)){let l=i.slice(s.length).split("/")[0];l&&!o.includes(l)&&o.push(l)}return o.sort()}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 Nr="5.1.0(1)-release",Cr="Linux version 5.15.0-generic (just-bash) #1 SMP PREEMPT";function Te(){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}=Te();return`Name: bash
|
|
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 ye,i as z,j as le,k as He}from"./chunks/chunk-CG2HXOFG.js";import{a as ce}from"./chunks/chunk-44UOCSGV.js";import"./chunks/chunk-2RUN43TJ.js";var St=[{name:"echo",load:async()=>(await import("./chunks/echo-WUKBESC7.js")).echoCommand},{name:"cat",load:async()=>(await import("./chunks/cat-47EP4IAV.js")).catCommand},{name:"printf",load:async()=>(await import("./chunks/printf-HBP44PXI.js")).printfCommand},{name:"ls",load:async()=>(await import("./chunks/ls-JGYJQA2Y.js")).lsCommand},{name:"mkdir",load:async()=>(await import("./chunks/mkdir-HA2FJX4O.js")).mkdirCommand},{name:"touch",load:async()=>(await import("./chunks/touch-FOE745V2.js")).touchCommand},{name:"rm",load:async()=>(await import("./chunks/rm-NF3FNLAY.js")).rmCommand},{name:"cp",load:async()=>(await import("./chunks/cp-37OVLNLD.js")).cpCommand},{name:"mv",load:async()=>(await import("./chunks/mv-7I62SB3I.js")).mvCommand},{name:"ln",load:async()=>(await import("./chunks/ln-XFYHBIFL.js")).lnCommand},{name:"chmod",load:async()=>(await import("./chunks/chmod-XJXFAD4M.js")).chmodCommand},{name:"pwd",load:async()=>(await import("./chunks/pwd-CEF235GL.js")).pwdCommand},{name:"readlink",load:async()=>(await import("./chunks/readlink-MQIMKDSA.js")).readlinkCommand},{name:"head",load:async()=>(await import("./chunks/head-6PAUYCDP.js")).headCommand},{name:"tail",load:async()=>(await import("./chunks/tail-QXKYHAML.js")).tailCommand},{name:"wc",load:async()=>(await import("./chunks/wc-GV5WUREX.js")).wcCommand},{name:"stat",load:async()=>(await import("./chunks/stat-FVFLDQGP.js")).statCommand},{name:"grep",load:async()=>(await import("./chunks/grep-ZJVDG3FA.js")).grepCommand},{name:"fgrep",load:async()=>(await import("./chunks/grep-ZJVDG3FA.js")).fgrepCommand},{name:"egrep",load:async()=>(await import("./chunks/grep-ZJVDG3FA.js")).egrepCommand},{name:"sed",load:async()=>(await import("./chunks/sed-H2RWPMTM.js")).sedCommand},{name:"awk",load:async()=>(await import("./chunks/awk2-QWBT4IFJ.js")).awkCommand2},{name:"sort",load:async()=>(await import("./chunks/sort-XODGFZC4.js")).sortCommand},{name:"uniq",load:async()=>(await import("./chunks/uniq-7PFWPNWK.js")).uniqCommand},{name:"comm",load:async()=>(await import("./chunks/comm-KSJ4BBRQ.js")).commCommand},{name:"cut",load:async()=>(await import("./chunks/cut-FIZRELKC.js")).cutCommand},{name:"paste",load:async()=>(await import("./chunks/paste-QBGVCQFT.js")).pasteCommand},{name:"tr",load:async()=>(await import("./chunks/tr-LMLGE4IE.js")).trCommand},{name:"tee",load:async()=>(await import("./chunks/tee-W5HCCBPO.js")).teeCommand},{name:"find",load:async()=>(await import("./chunks/find-GM7FJ4D3.js")).findCommand},{name:"basename",load:async()=>(await import("./chunks/basename-5UVU5RXR.js")).basenameCommand},{name:"dirname",load:async()=>(await import("./chunks/dirname-U2KVUSQY.js")).dirnameCommand},{name:"tree",load:async()=>(await import("./chunks/tree-WBUGLVP5.js")).treeCommand},{name:"du",load:async()=>(await import("./chunks/du-KRAFOIQK.js")).duCommand},{name:"env",load:async()=>(await import("./chunks/env-MSPSPGCD.js")).envCommand},{name:"printenv",load:async()=>(await import("./chunks/env-MSPSPGCD.js")).printenvCommand},{name:"alias",load:async()=>(await import("./chunks/alias-JFIUWFGE.js")).aliasCommand},{name:"unalias",load:async()=>(await import("./chunks/alias-JFIUWFGE.js")).unaliasCommand},{name:"history",load:async()=>(await import("./chunks/history-SG6VRATI.js")).historyCommand},{name:"xargs",load:async()=>(await import("./chunks/xargs-NQBNFMCT.js")).xargsCommand},{name:"true",load:async()=>(await import("./chunks/true-6LGCG4EY.js")).trueCommand},{name:"false",load:async()=>(await import("./chunks/true-6LGCG4EY.js")).falseCommand},{name:"clear",load:async()=>(await import("./chunks/clear-XD3TJRVQ.js")).clearCommand},{name:"bash",load:async()=>(await import("./chunks/bash-BASUPKHJ.js")).bashCommand},{name:"sh",load:async()=>(await import("./chunks/bash-BASUPKHJ.js")).shCommand},{name:"jq",load:async()=>(await import("./chunks/jq-PO3DWIV2.js")).jqCommand},{name:"base64",load:async()=>(await import("./chunks/base64-TUA2XORD.js")).base64Command},{name:"diff",load:async()=>(await import("./chunks/diff-GLRVCAKJ.js")).diffCommand},{name:"date",load:async()=>(await import("./chunks/date-NN5C354M.js")).dateCommand},{name:"sleep",load:async()=>(await import("./chunks/sleep-AFN3PHJW.js")).sleepCommand},{name:"timeout",load:async()=>(await import("./chunks/timeout-XAA3N7CF.js")).timeoutCommand},{name:"seq",load:async()=>(await import("./chunks/seq-VKYIUOPJ.js")).seqCommand},{name:"expr",load:async()=>(await import("./chunks/expr-HYOCSWK6.js")).exprCommand},{name:"md5sum",load:async()=>(await import("./chunks/md5sum-PIH6F3O3.js")).md5sumCommand},{name:"sha1sum",load:async()=>(await import("./chunks/sha1sum-HVHNZSEC.js")).sha1sumCommand},{name:"sha256sum",load:async()=>(await import("./chunks/sha256sum-REOOJORK.js")).sha256sumCommand},{name:"file",load:async()=>(await import("./chunks/file-LQXX6P4Y.js")).fileCommand},{name:"html-to-markdown",load:async()=>(await import("./chunks/html-to-markdown-ZSZ34PAN.js")).htmlToMarkdownCommand},{name:"help",load:async()=>(await import("./chunks/help-5E6PYJWQ.js")).helpCommand},{name:"which",load:async()=>(await import("./chunks/which-KHFYPBWW.js")).whichCommand},{name:"tac",load:async()=>(await import("./chunks/tac-VIFKNLII.js")).tac},{name:"hostname",load:async()=>(await import("./chunks/hostname-K4BA3P6X.js")).hostname},{name:"od",load:async()=>(await import("./chunks/od-SOCTFI2F.js")).od}],wr=[{name:"curl",load:async()=>(await import("./chunks/curl-C43O5WQS.js")).curlCommand}],Er=new Map;function gr(t){return{name:t.name,async execute(e,n){let r=Er.get(t.name);return r||(r=await t.load(),Er.set(t.name,r)),r.execute(e,n)}}}function Gn(){return St.map(t=>t.name)}function Vn(){return wr.map(t=>t.name)}function Ar(t){return(t?St.filter(n=>t.includes(n.name)):St).map(gr)}function xr(){return wr.map(gr)}function Sr(t){return"load"in t&&typeof t.load=="function"}function Hn(t,e){return{name:t,execute:e}}function br(t){let e=null;return{name:t.name,async execute(n,r){return e||(e=await t.load()),e.execute(n,r)}}}var jn=new TextEncoder,Zn=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 jn.encode(t)}}function be(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 Zn.decode(t)}}function Z(t){if(t!=null)return typeof t=="string"?t:t.encoding??void 0}var je=new TextEncoder;function qn(t){return typeof t=="object"&&t!==null&&!(t instanceof Uint8Array)&&"content"in t}var Ee=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))qn(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=Z(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=Z(n);return be(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:je.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=Z(r),a=re(n,i);if(o?.type==="file"){let l=o.content instanceof Uint8Array?o.content:je.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=je.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=je.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){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=[];for(let i of this.data.keys())if(i!==n&&i.startsWith(s)){let l=i.slice(s.length).split("/")[0];l&&!o.includes(l)&&o.push(l)}return o.sort()}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 Nr="5.1.0(1)-release",Cr="Linux version 5.15.0-generic (just-bash) #1 SMP PREEMPT";function Te(){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}=Te();return`Name: bash
|
|
2
2
|
State: R (running)
|
|
3
3
|
Pid: ${t}
|
|
4
4
|
PPid: ${e}
|
|
@@ -6,7 +6,7 @@ Uid: ${n} ${n} ${n} ${n}
|
|
|
6
6
|
Gid: ${r} ${r} ${r} ${r}
|
|
7
7
|
`}function Qn(t){let e=t;return typeof e.mkdirSync=="function"&&typeof e.writeFileSync=="function"}function Kn(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 Xn(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 Yn(t){t.mkdirSync("/proc/self/fd",{recursive:!0}),t.writeFileSync("/proc/version",`${Cr}
|
|
8
8
|
`),t.writeFileSync("/proc/self/exe","/bin/bash"),t.writeFileSync("/proc/self/cmdline","bash\0"),t.writeFileSync("/proc/self/comm",`bash
|
|
9
|
-
`),t.writeFileSync("/proc/self/status",$r()),t.writeFileSync("/proc/self/fd/0","/dev/stdin"),t.writeFileSync("/proc/self/fd/1","/dev/stdout"),t.writeFileSync("/proc/self/fd/2","/dev/stderr")}function Pr(t,e){Qn(t)&&(Kn(t,e),Xn(t),Yn(t))}function T(t,e){return{type:"ArithmeticExpression",expression:ne(t,e,0).expr}}function ne(t,e,n){return Jn(t,e,n)}function Jn(t,e,n){let{expr:r,pos:s}=qe(t,e,n);for(s=O(e,s);e[s]===",";){s++;let{expr:o,pos:i}=qe(t,e,s);r={type:"ArithBinary",operator:",",left:r,right:o},s=O(e,i)}return{expr:r,pos:s}}function qe(t,e,n){let{expr:r,pos:s}=es(t,e,n);if(s=O(e,s),e[s]==="?"){s++;let{expr:o,pos:i}=ne(t,e,s);if(s=O(e,i),e[s]===":"){s++;let{expr:a,pos:l}=ne(t,e,s);return{expr:{type:"ArithTernary",condition:r,consequent:o,alternate:a},pos:l}}}return{expr:r,pos:s}}function es(t,e,n){let{expr:r,pos:s}=vr(t,e,n);for(;s=O(e,s),e.slice(s,s+2)==="||";){s+=2;let{expr:o,pos:i}=vr(t,e,s);r={type:"ArithBinary",operator:"||",left:r,right:o},s=i}return{expr:r,pos:s}}function vr(t,e,n){let{expr:r,pos:s}=Ir(t,e,n);for(;s=O(e,s),e.slice(s,s+2)==="&&";){s+=2;let{expr:o,pos:i}=Ir(t,e,s);r={type:"ArithBinary",operator:"&&",left:r,right:o},s=i}return{expr:r,pos:s}}function Ir(t,e,n){let{expr:r,pos:s}=Rr(t,e,n);for(;s=O(e,s),e[s]==="|"&&e[s+1]!=="|";){s++;let{expr:o,pos:i}=Rr(t,e,s);r={type:"ArithBinary",operator:"|",left:r,right:o},s=i}return{expr:r,pos:s}}function Rr(t,e,n){let{expr:r,pos:s}=kr(t,e,n);for(;s=O(e,s),e[s]==="^";){s++;let{expr:o,pos:i}=kr(t,e,s);r={type:"ArithBinary",operator:"^",left:r,right:o},s=i}return{expr:r,pos:s}}function kr(t,e,n){let{expr:r,pos:s}=Dr(t,e,n);for(;s=O(e,s),e[s]==="&"&&e[s+1]!=="&";){s++;let{expr:o,pos:i}=Dr(t,e,s);r={type:"ArithBinary",operator:"&",left:r,right:o},s=i}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.slice(s,s+2)==="=="||e.slice(s,s+2)==="!=";){let o=e.slice(s,s+2);s+=2;let{expr:i,pos:a}=Or(t,e,s);r={type:"ArithBinary",operator:o,left:r,right:i},s=a}return{expr:r,pos:s}}function Or(t,e,n){let{expr:r,pos:s}=bt(t,e,n);for(;;)if(s=O(e,s),e.slice(s,s+2)==="<="||e.slice(s,s+2)===">="){let o=e.slice(s,s+2);s+=2;let{expr:i,pos:a}=bt(t,e,s);r={type:"ArithBinary",operator:o,left:r,right:i},s=a}else if(e[s]==="<"||e[s]===">"){let o=e[s];s++;let{expr:i,pos:a}=bt(t,e,s);r={type:"ArithBinary",operator:o,left:r,right:i},s=a}else break;return{expr:r,pos:s}}function bt(t,e,n){let{expr:r,pos:s}=_r(t,e,n);for(;s=O(e,s),e.slice(s,s+2)==="<<"||e.slice(s,s+2)===">>";){let o=e.slice(s,s+2);s+=2;let{expr:i,pos:a}=_r(t,e,s);r={type:"ArithBinary",operator:o,left:r,right:i},s=a}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]==="-")&&e[s+1]!==e[s];){let o=e[s];s++;let{expr:i,pos:a}=Lr(t,e,s);r={type:"ArithBinary",operator:o,left:r,right:i},s=a}return{expr:r,pos:s}}function Lr(t,e,n){let{expr:r,pos:s}=Ze(t,e,n);for(;;)if(s=O(e,s),e[s]==="*"&&e[s+1]!=="*"){s++;let{expr:o,pos:i}=Ze(t,e,s);r={type:"ArithBinary",operator:"*",left:r,right:o},s=i}else if(e[s]==="/"||e[s]==="%"){let o=e[s];s++;let{expr:i,pos:a}=Ze(t,e,s);r={type:"ArithBinary",operator:o,left:r,right:i},s=a}else break;return{expr:r,pos:s}}function Ze(t,e,n){let{expr:r,pos:s}=Nt(t,e,n),o=O(e,s);if(e.slice(o,o+2)==="**"){o+=2;let{expr:i,pos:a}=Ze(t,e,o);return{expr:{type:"ArithBinary",operator:"**",left:r,right:i},pos:a}}return{expr:r,pos:s}}function Nt(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:o,pos:i}=Nt(t,e,r);return{expr:{type:"ArithUnary",operator:s,operand:o,prefix:!0},pos:i}}if(e[r]==="+"||e[r]==="-"||e[r]==="!"||e[r]==="~"){let s=e[r];r++;let{expr:o,pos:i}=Nt(t,e,r);return{expr:{type:"ArithUnary",operator:s,operand:o,prefix:!0},pos:i}}return rs(t,e,r)}function ts(t,e){let n=t[e];return n==="$"||n==="`"}function rs(t,e,n){let{expr:r,pos:s}=Tr(t,e,n),o=[r];for(;ts(e,s);){let{expr:i,pos:a}=Tr(t,e,s);o.push(i),s=a}if(o.length>1&&(r={type:"ArithConcat",parts:o}),s=O(e,s),e.slice(s,s+2)==="++"||e.slice(s,s+2)==="--"){let i=e.slice(s,s+2);return s+=2,{expr:{type:"ArithUnary",operator:i,operand:r,prefix:!1},pos:s}}return{expr:r,pos:s}}function Tr(t,e,n){let r=O(e,n);if(e.slice(r,r+3)==="$(("){r+=3;let s=1,o=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 i=e.slice(o,r),{expr:a}=ne(t,i,0);return r+=2,{expr:{type:"ArithNested",expression:a},pos:r}}if(e.slice(r,r+2)==="$("&&e[r+2]!=="("){r+=2;let s=1,o=r;for(;r<e.length&&s>0;)e[r]==="("?s++:e[r]===")"&&s--,s>0&&r++;let i=e.slice(o,r);return r++,{expr:{type:"ArithCommandSubst",command:i},pos:r}}if(e[r]==="`"){r++;let s=r;for(;r<e.length&&e[r]!=="`";)r++;let o=e.slice(s,r);return e[r]==="`"&&r++,{expr:{type:"ArithCommandSubst",command:o},pos:r}}if(e[r]==="("){r++;let{expr:s,pos:o}=ne(t,e,r);return r=O(e,o),e[r]===")"&&r++,{expr:{type:"ArithGroup",expression:s},pos:r}}if(/[0-9]/.test(e[r])){let s="",o=!1;for(;r<e.length;){let a=e[r];if(o)if(/[0-9a-zA-Z@_]/.test(a))s+=a,r++;else break;else if(a==="#")o=!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:
|
|
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 Pr(t,e){Qn(t)&&(Kn(t,e),Xn(t),Yn(t))}function T(t,e){return{type:"ArithmeticExpression",expression:ne(t,e,0).expr}}function ne(t,e,n){return Jn(t,e,n)}function Jn(t,e,n){let{expr:r,pos:s}=qe(t,e,n);for(s=O(e,s);e[s]===",";){s++;let{expr:o,pos:i}=qe(t,e,s);r={type:"ArithBinary",operator:",",left:r,right:o},s=O(e,i)}return{expr:r,pos:s}}function qe(t,e,n){let{expr:r,pos:s}=es(t,e,n);if(s=O(e,s),e[s]==="?"){s++;let{expr:o,pos:i}=ne(t,e,s);if(s=O(e,i),e[s]===":"){s++;let{expr:a,pos:l}=ne(t,e,s);return{expr:{type:"ArithTernary",condition:r,consequent:o,alternate:a},pos:l}}}return{expr:r,pos:s}}function es(t,e,n){let{expr:r,pos:s}=vr(t,e,n);for(;s=O(e,s),e.slice(s,s+2)==="||";){s+=2;let{expr:o,pos:i}=vr(t,e,s);r={type:"ArithBinary",operator:"||",left:r,right:o},s=i}return{expr:r,pos:s}}function vr(t,e,n){let{expr:r,pos:s}=Ir(t,e,n);for(;s=O(e,s),e.slice(s,s+2)==="&&";){s+=2;let{expr:o,pos:i}=Ir(t,e,s);r={type:"ArithBinary",operator:"&&",left:r,right:o},s=i}return{expr:r,pos:s}}function Ir(t,e,n){let{expr:r,pos:s}=Rr(t,e,n);for(;s=O(e,s),e[s]==="|"&&e[s+1]!=="|";){s++;let{expr:o,pos:i}=Rr(t,e,s);r={type:"ArithBinary",operator:"|",left:r,right:o},s=i}return{expr:r,pos:s}}function Rr(t,e,n){let{expr:r,pos:s}=kr(t,e,n);for(;s=O(e,s),e[s]==="^";){s++;let{expr:o,pos:i}=kr(t,e,s);r={type:"ArithBinary",operator:"^",left:r,right:o},s=i}return{expr:r,pos:s}}function kr(t,e,n){let{expr:r,pos:s}=Dr(t,e,n);for(;s=O(e,s),e[s]==="&"&&e[s+1]!=="&";){s++;let{expr:o,pos:i}=Dr(t,e,s);r={type:"ArithBinary",operator:"&",left:r,right:o},s=i}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.slice(s,s+2)==="=="||e.slice(s,s+2)==="!=";){let o=e.slice(s,s+2);s+=2;let{expr:i,pos:a}=Or(t,e,s);r={type:"ArithBinary",operator:o,left:r,right:i},s=a}return{expr:r,pos:s}}function Or(t,e,n){let{expr:r,pos:s}=bt(t,e,n);for(;;)if(s=O(e,s),e.slice(s,s+2)==="<="||e.slice(s,s+2)===">="){let o=e.slice(s,s+2);s+=2;let{expr:i,pos:a}=bt(t,e,s);r={type:"ArithBinary",operator:o,left:r,right:i},s=a}else if(e[s]==="<"||e[s]===">"){let o=e[s];s++;let{expr:i,pos:a}=bt(t,e,s);r={type:"ArithBinary",operator:o,left:r,right:i},s=a}else break;return{expr:r,pos:s}}function bt(t,e,n){let{expr:r,pos:s}=_r(t,e,n);for(;s=O(e,s),e.slice(s,s+2)==="<<"||e.slice(s,s+2)===">>";){let o=e.slice(s,s+2);s+=2;let{expr:i,pos:a}=_r(t,e,s);r={type:"ArithBinary",operator:o,left:r,right:i},s=a}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]==="-")&&e[s+1]!==e[s];){let o=e[s];s++;let{expr:i,pos:a}=Lr(t,e,s);r={type:"ArithBinary",operator:o,left:r,right:i},s=a}return{expr:r,pos:s}}function Lr(t,e,n){let{expr:r,pos:s}=Ze(t,e,n);for(;;)if(s=O(e,s),e[s]==="*"&&e[s+1]!=="*"){s++;let{expr:o,pos:i}=Ze(t,e,s);r={type:"ArithBinary",operator:"*",left:r,right:o},s=i}else if(e[s]==="/"||e[s]==="%"){let o=e[s];s++;let{expr:i,pos:a}=Ze(t,e,s);r={type:"ArithBinary",operator:o,left:r,right:i},s=a}else break;return{expr:r,pos:s}}function Ze(t,e,n){let{expr:r,pos:s}=Nt(t,e,n),o=O(e,s);if(e.slice(o,o+2)==="**"){o+=2;let{expr:i,pos:a}=Ze(t,e,o);return{expr:{type:"ArithBinary",operator:"**",left:r,right:i},pos:a}}return{expr:r,pos:s}}function Nt(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:o,pos:i}=Nt(t,e,r);return{expr:{type:"ArithUnary",operator:s,operand:o,prefix:!0},pos:i}}if(e[r]==="+"||e[r]==="-"||e[r]==="!"||e[r]==="~"){let s=e[r];r++;let{expr:o,pos:i}=Nt(t,e,r);return{expr:{type:"ArithUnary",operator:s,operand:o,prefix:!0},pos:i}}return rs(t,e,r)}function ts(t,e){let n=t[e];return n==="$"||n==="`"}function rs(t,e,n){let{expr:r,pos:s}=Tr(t,e,n),o=[r];for(;ts(e,s);){let{expr:i,pos:a}=Tr(t,e,s);o.push(i),s=a}if(o.length>1&&(r={type:"ArithConcat",parts:o}),s=O(e,s),e.slice(s,s+2)==="++"||e.slice(s,s+2)==="--"){let i=e.slice(s,s+2);return s+=2,{expr:{type:"ArithUnary",operator:i,operand:r,prefix:!1},pos:s}}return{expr:r,pos:s}}function Tr(t,e,n){let r=O(e,n);if(e.slice(r,r+3)==="$(("){r+=3;let s=1,o=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 i=e.slice(o,r),{expr:a}=ne(t,i,0);return r+=2,{expr:{type:"ArithNested",expression:a},pos:r}}if(e.slice(r,r+2)==="$("&&e[r+2]!=="("){r+=2;let s=1,o=r;for(;r<e.length&&s>0;)e[r]==="("?s++:e[r]===")"&&s--,s>0&&r++;let i=e.slice(o,r);return r++,{expr:{type:"ArithCommandSubst",command:i},pos:r}}if(e[r]==="`"){r++;let s=r;for(;r<e.length&&e[r]!=="`";)r++;let o=e.slice(s,r);return e[r]==="`"&&r++,{expr:{type:"ArithCommandSubst",command:o},pos:r}}if(e[r]==="("){r++;let{expr:s,pos:o}=ne(t,e,r);return r=O(e,o),e[r]===")"&&r++,{expr:{type:"ArithGroup",expression:s},pos:r}}if(/[0-9]/.test(e[r])){let s="",o=!1;for(;r<e.length;){let a=e[r];if(o)if(/[0-9a-zA-Z@_]/.test(a))s+=a,r++;else break;else if(a==="#")o=!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,o=1,i=s;for(;i<e.length&&o>0;)e[i]==="{"?o++:e[i]==="}"&&o--,o>0&&i++;let a=e.slice(s,i),l=i+1;if(e[l]==="#"){let c=l+1;for(;c<e.length&&/[0-9a-zA-Z@_]/.test(e[c]);)c++;let f=e.slice(l+1,c);return{expr:{type:"ArithDynamicBase",baseExpr:a,value:f},pos:c}}if(/[0-9]/.test(e[l])||e[l]==="x"||e[l]==="X"){let c=l;if(e[l]==="x"||e[l]==="X")for(c++;c<e.length&&/[0-9a-fA-F]/.test(e[c]);)c++;else for(;c<e.length&&/[0-9]/.test(e[c]);)c++;let f=e.slice(l,c);return{expr:{type:"ArithDynamicNumber",prefix:a,suffix:f},pos:c}}return r=l,{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 i;if(e[r]==="'"||e[r]==='"'){let c=e[r];for(r++,i="";r<e.length&&e[r]!==c;)i+=e[r],r++;e[r]===c&&r++,r=O(e,r),e[r]==="]"&&r++}let a;if(i===void 0){let{expr:c,pos:f}=ne(t,e,r);a=c,r=f,e[r]==="]"&&r++}if(r=O(e,r),e[r]==="["&&a)return{expr:{type:"ArithDoubleSubscript",array:s,index:a},pos:r};let l=["=","+=","-=","*=","/=","%=","<<=",">>=","&=","|=","^="];for(let c of l)if(e.slice(r,r+c.length)===c&&e.slice(r,r+c.length+1)!=="=="){r+=c.length;let{expr:f,pos:d}=qe(t,e,r);return{expr:{type:"ArithAssignment",operator:c,variable:s,subscript:a,stringKey:i,value:f},pos:d}}return{expr:{type:"ArithArrayElement",array:s,index:a,stringKey:i},pos:r}}r=O(e,r);let o=["=","+=","-=","*=","/=","%=","<<=",">>=","&=","|=","^="];for(let i of o)if(e.slice(r,r+i.length)===i&&e.slice(r,r+i.length+1)!=="=="){r+=i.length;let{expr:a,pos:l}=qe(t,e,r);return{expr:{type:"ArithAssignment",operator:i,variable:s,value:a},pos:l}}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 o of n){let i;if(o>="0"&&o<="9")i=o.charCodeAt(0)-48;else if(o>="a"&&o<="z")i=o.charCodeAt(0)-97+10;else if(o>="A"&&o<="Z")i=o.charCodeAt(0)-65+36;else if(o==="@")i=62;else if(o==="_")i=63;else return Number.NaN;if(i>=r)return Number.NaN;s=s*r+i}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
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 u;(function(t){t.EOF="EOF",t.NEWLINE="NEWLINE",t.SEMICOLON="SEMICOLON",t.AMP="AMP",t.PIPE="PIPE",t.PIPE_AMP="PIPE_AMP",t.AND_AND="AND_AND",t.OR_OR="OR_OR",t.BANG="BANG",t.LESS="LESS",t.GREAT="GREAT",t.DLESS="DLESS",t.DGREAT="DGREAT",t.LESSAND="LESSAND",t.GREATAND="GREATAND",t.LESSGREAT="LESSGREAT",t.DLESSDASH="DLESSDASH",t.CLOBBER="CLOBBER",t.TLESS="TLESS",t.AND_GREAT="AND_GREAT",t.AND_DGREAT="AND_DGREAT",t.LPAREN="LPAREN",t.RPAREN="RPAREN",t.LBRACE="LBRACE",t.RBRACE="RBRACE",t.DSEMI="DSEMI",t.SEMI_AND="SEMI_AND",t.SEMI_SEMI_AND="SEMI_SEMI_AND",t.DBRACK_START="DBRACK_START",t.DBRACK_END="DBRACK_END",t.DPAREN_START="DPAREN_START",t.DPAREN_END="DPAREN_END",t.IF="IF",t.THEN="THEN",t.ELSE="ELSE",t.ELIF="ELIF",t.FI="FI",t.FOR="FOR",t.WHILE="WHILE",t.UNTIL="UNTIL",t.DO="DO",t.DONE="DONE",t.CASE="CASE",t.ESAC="ESAC",t.IN="IN",t.FUNCTION="FUNCTION",t.SELECT="SELECT",t.TIME="TIME",t.COPROC="COPROC",t.WORD="WORD",t.NAME="NAME",t.NUMBER="NUMBER",t.ASSIGNMENT_WORD="ASSIGNMENT_WORD",t.COMMENT="COMMENT",t.HEREDOC_CONTENT="HEREDOC_CONTENT"})(u||(u={}));var Qe={if:u.IF,then:u.THEN,else:u.ELSE,elif:u.ELIF,fi:u.FI,for:u.FOR,while:u.WHILE,until:u.UNTIL,do:u.DO,done:u.DONE,case:u.CASE,esac:u.ESAC,in:u.IN,function:u.FUNCTION,select:u.SELECT,time:u.TIME,coproc:u.COPROC};function Wr(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 o=n.slice(s+1);return o===""||o==="+"}return!1}var ns=[[";",";","&",u.SEMI_SEMI_AND],["<","<","<",u.TLESS],["&",">",">",u.AND_DGREAT]],ss=[["[","[",u.DBRACK_START],["]","]",u.DBRACK_END],["(","(",u.DPAREN_START],[")",")",u.DPAREN_END],["&","&",u.AND_AND],["|","|",u.OR_OR],[";",";",u.DSEMI],[";","&",u.SEMI_AND],["|","&",u.PIPE_AMP],[">",">",u.DGREAT],["<","&",u.LESSAND],[">","&",u.GREATAND],["<",">",u.LESSGREAT],[">","|",u.CLOBBER],["&",">",u.AND_GREAT]],is={"|":u.PIPE,"&":u.AMP,";":u.SEMICOLON,"(":u.LPAREN,")":u.RPAREN,"<":u.LESS,">":u.GREAT};function os(t){return/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t)}var Ke=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===u.NEWLINE){this.readHeredocContent();continue}let o=this.nextToken();o&&r.push(o)}return r.push({type:u.EOF,value:"",start:this.pos,end:this.pos,line:this.line,column:this.column}),r}skipWhitespace(){let e=this.input,n=e.length,r=this.pos,s=this.column,o=this.line;for(;r<n;){let i=e[r];if(i===" "||i===" ")r++,s++;else if(i==="\\"&&e[r+1]===`
|
|
11
11
|
`)r+=2,o++,s=1;else break}this.pos=r,this.column=s,this.line=o}nextToken(){let e=this.input,n=this.pos,r=this.line,s=this.column,o=e[n],i=e[n+1],a=e[n+2];if(o==="#")return this.readComment(n,r,s);if(o===`
|
|
12
12
|
`)return this.pos=n+1,this.line++,this.column=1,{type:u.NEWLINE,value:`
|
|
@@ -36,17 +36,17 @@ Gid: ${r} ${r} ${r} ${r}
|
|
|
36
36
|
`:h==="$"||h==="`"||h==="\\"||h==='"'||h===`
|
|
37
37
|
`)?c+=h:c+=`\\${h}`,l+=2;continue}if(d==="'"&&!i&&!o){f();let h=e.indexOf("'",l+1);if(h===-1){c+=e.slice(l);break}a.push(A.singleQuoted(e.slice(l+1,h))),l=h+1;continue}if(d==='"'&&!o){f();let{part:h,endIndex:m}=bs(t,e,l+1);a.push(h),l=m+1;continue}if(d==="$"&&e[l+1]==="'"){f();let{part:h,endIndex:m}=jr(t,e,l+2);a.push(h),l=m;continue}if(d==="$"){f();let{part:h,endIndex:m}=Mt(t,e,l);h&&a.push(h),l=m;continue}if(d==="`"){f();let{part:h,endIndex:m}=t.parseBacktickSubstitution(e,l);a.push(h),l=m;continue}if(d==="~"){let h=l>0?e[l-1]:"";if(l===0||h==="="||s&&h===":"){let y=Gr(t,e,l),w=e[y];if(w===void 0||w==="/"||w===":"){f();let p=e.slice(l+1,y)||null;a.push({type:"TildeExpansion",user:p}),l=y;continue}}}if(d==="*"||d==="?"||d==="["){f();let{pattern:h,endIndex:m}=Hr(t,e,l);a.push({type:"Glob",pattern:h}),l=m;continue}if(d==="{"&&!s){let h=Zr(t,e,l,fe);if(h){f(),a.push(h.part),l=h.endIndex;continue}}c+=d,l++}return f(),a}var M=class t{tokens=[];pos=0;pendingHeredocs=[];parseIterations=0;checkIterationLimit(){if(this.parseIterations++,this.parseIterations>Mr)throw new se("Maximum parse iterations exceeded (possible infinite loop)",this.current().line,this.current().column)}parse(e){if(e.length>Ct)throw new se(`Input too large: ${e.length} bytes exceeds limit of ${Ct}`,1,1);let n=new Ke(e);if(this.tokens=n.tokenize(),this.tokens.length>$t)throw new se(`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,...o){let i=this.tokens[this.pos]?.type;return i===e||n!==void 0&&i===n||r!==void 0&&i===r||s!==void 0&&i===s?!0:o.length>0?o.includes(i):!1}expect(e,n){if(this.check(e))return this.advance();let r=this.current();throw new se(n||`Expected ${e}, got ${r.type}`,r.line,r.column,r)}error(e){let n=this.current();throw new se(e,n.line,n.column,n)}skipNewlines(){for(;this.check(u.NEWLINE,u.COMMENT);)this.check(u.NEWLINE)?(this.advance(),this.processHeredocs()):this.advance()}skipSeparators(e=!0){for(;;){if(this.check(u.NEWLINE)){this.advance(),this.processHeredocs();continue}if(this.check(u.SEMICOLON,u.COMMENT)){this.advance();continue}if(e&&this.check(u.DSEMI,u.SEMI_AND,u.SEMI_SEMI_AND)){this.advance();continue}break}}addPendingHeredoc(e,n,r,s){this.pendingHeredocs.push({redirect:e,delimiter:n,stripTabs:r,quoted:s})}processHeredocs(){for(let e of this.pendingHeredocs)if(this.check(u.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(u.EOF,u.NEWLINE,u.SEMICOLON,u.AMP,u.AND_AND,u.OR_OR,u.RPAREN,u.RBRACE,u.DSEMI,u.SEMI_AND,u.SEMI_SEMI_AND)}isCommandStart(){let e=this.current().type;return e===u.WORD||e===u.NAME||e===u.NUMBER||e===u.ASSIGNMENT_WORD||e===u.IF||e===u.FOR||e===u.WHILE||e===u.UNTIL||e===u.CASE||e===u.LPAREN||e===u.LBRACE||e===u.DPAREN_START||e===u.DBRACK_START||e===u.FUNCTION||e===u.BANG||e===u.IN||e===u.LESS||e===u.GREAT||e===u.DLESS||e===u.DGREAT||e===u.LESSAND||e===u.GREATAND||e===u.LESSGREAT||e===u.DLESSDASH||e===u.CLOBBER||e===u.TLESS||e===u.AND_GREAT||e===u.AND_DGREAT}parseScript(){let e=[],r=0;for(this.skipNewlines();!this.check(u.EOF);){r++,r>1e4&&this.error("Parser stuck: too many iterations (>10000)"),this.checkUnexpectedToken();let s=this.pos,o=this.parseStatement();o&&e.push(o),this.skipSeparators(!1),this.check(u.DSEMI,u.SEMI_AND,u.SEMI_SEMI_AND)&&this.error(`syntax error near unexpected token \`${this.current().value}'`),this.pos===s&&!this.check(u.EOF)&&this.advance()}return A.script(e)}checkUnexpectedToken(){let e=this.current().type,n=this.current().value;(e===u.DO||e===u.DONE||e===u.THEN||e===u.ELSE||e===u.ELIF||e===u.FI||e===u.ESAC)&&this.error(`syntax error near unexpected token \`${n}'`),(e===u.RBRACE||e===u.RPAREN)&&this.error(`syntax error near unexpected token \`${n}'`),(e===u.DSEMI||e===u.SEMI_AND||e===u.SEMI_SEMI_AND)&&this.error(`syntax error near unexpected token \`${n}'`),e===u.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(u.AND_AND,u.OR_OR);){let o=this.advance();n.push(o.type===u.AND_AND?"&&":"||"),this.skipNewlines();let i=this.parsePipeline();e.push(i)}return this.check(u.AMP)&&(this.advance(),r=!0),A.statement(e,n,r)}parsePipeline(){let e=0;for(;this.check(u.BANG);)this.advance(),e++;let n=e%2===1,r=[],s=this.parseCommand();for(r.push(s);this.check(u.PIPE,u.PIPE_AMP);){let o=this.advance();this.skipNewlines();let i=this.parseCommand();o.type===u.PIPE_AMP&&i.type==="SimpleCommand"&&i.redirections.unshift(A.redirection(">&",A.word([A.literal("1")]),2)),r.push(i)}return A.pipeline(r,n)}parseCommand(){return this.check(u.IF)?Rt(this):this.check(u.FOR)?kt(this):this.check(u.WHILE)?Dt(this):this.check(u.UNTIL)?Ot(this):this.check(u.CASE)?_t(this):this.check(u.LPAREN)?Lt(this):this.check(u.LBRACE)?Tt(this):this.check(u.DPAREN_START)?this.parseArithmeticCommand():this.check(u.DBRACK_START)?this.parseConditionalCommand():this.check(u.FUNCTION)?this.parseFunctionDef():this.check(u.NAME,u.WORD)&&this.peek(1).type===u.LPAREN&&this.peek(2).type===u.RPAREN?this.parseFunctionDef():Xr(this)}isWord(){let e=this.current().type;return e===u.WORD||e===u.NAME||e===u.NUMBER||e===u.IF||e===u.FOR||e===u.WHILE||e===u.UNTIL||e===u.CASE||e===u.FUNCTION||e===u.ELSE||e===u.ELIF||e===u.FI||e===u.THEN||e===u.DO||e===u.DONE||e===u.ESAC||e===u.IN||e===u.BANG}parseWord(){let e=this.advance();return this.parseWordFromString(e.value,e.quoted,e.singleQuoted)}parseWordFromString(e,n=!1,r=!1,s=!1,o=!1){let i=fe(this,e,n,r,s,o);return A.word(i)}parseCommandSubstitution(e,n){let r=n+2,s=1,o=r,i=!1,a=!1,l=0,c=!1,f="";for(;o<e.length&&s>0;){let y=e[o];i?y==="'"&&(i=!1):a?y==="\\"&&o+1<e.length?o++:y==='"'&&(a=!1):y==="'"?(i=!0,f=""):y==='"'?(a=!0,f=""):y==="\\"&&o+1<e.length?(o++,f=""):/[a-zA-Z_]/.test(y)?f+=y:(f==="case"?(l++,c=!1):f==="in"&&l>0?c=!0:f==="esac"&&l>0&&(l--,c=!1),f="",y==="("?o>0&&e[o-1]==="$"?s++:c||s++:y===")"?c?c=!1:s--:y===";"&&l>0&&o+1<e.length&&e[o+1]===";"&&(c=!0)),s>0&&o++}s>0&&this.error("unexpected EOF while looking for matching `)'");let d=e.slice(r,o),m=new t().parse(d);return{part:A.commandSubstitution(m,!1),endIndex:o+1}}parseBacktickSubstitution(e,n,r=!1){let o=n+1,i="";for(;o<e.length&&e[o]!=="`";)if(e[o]==="\\"){let c=e[o+1];c==="$"||c==="`"||c==="\\"||c===`
|
|
38
38
|
`||r&&c==='"'?(c!==`
|
|
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=Wt(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 Tt(this);if(this.check(u.LPAREN))return Lt(this);if(this.check(u.IF))return Rt(this);if(this.check(u.FOR))return kt(this);if(this.check(u.WHILE))return Dt(this);if(this.check(u.UNTIL))return Ot(this);if(this.check(u.CASE))return _t(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(;Xe(this);){this.checkIterationLimit();let n=this.pos;if(e.push(Ye(this)),this.pos===n)break}return e}parseArithmeticExpression(e){return T(this,e)}};function ue(t){return new M().parse(t)}var Ne=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=[];for(let s=0;s<e.length;s++){let o=e[s];if((n?.[s]??!1)||!this.isGlobPattern(o))r.push(o);else{let a=await this.expand(o);a.length>0?r.push(...a):r.push(o)}}return r}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{let o=await this.fs.readdir(s);for(let i of o){let a=e==="."?i:`${e}/${i}`,l=this.fs.resolvePath(this.cwd,a);try{(await this.fs.stat(l)).isDirectory?await this.walkDirectory(a,n,r):n&&this.matchPattern(i,n)&&r.push(a)}catch{}}}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 q(t){switch(t.type){case"ArithCommandSubst":return!0;case"ArithNested":return q(t.expression);case"ArithBinary":return q(t.left)||q(t.right);case"ArithUnary":return q(t.operand);case"ArithTernary":return q(t.condition)||q(t.consequent)||q(t.alternate);case"ArithAssignment":return q(t.value);case"ArithGroup":return q(t.expression);case"ArithArrayElement":return t.index?q(t.index):!1;case"ArithConcat":return t.parts.some(q);default:return!1}}function Bt(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 Je(t){switch(t.type){case"CommandSubstitution":return!0;case"ArithmeticExpansion":return q(t.expression.expression);case"DoubleQuoted":return t.parts.some(Je);case"BraceExpansion":return t.items.some(e=>e.type==="Word"&&ie(e.word));case"ParameterExpansion":return Bt(t);default:return!1}}function ie(t){return t.parts.some(Je)}function zt(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 Jr(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),zt(i)&&(e=!0))}return{hasQuoted:e,hasCommandSub:n,hasArrayVar:r,hasArrayAtExpansion:s,hasParamExpansion:o}}function Cs(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 $s(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 Fe(t,e,n,r,s){let o=n!==void 0?`..${n}`:"";return typeof t=="number"&&typeof e=="number"?{expanded:Cs(t,e,n,r,s),literal:`{${t}..${e}${o}}`}:typeof t=="string"&&typeof e=="string"?{expanded:$s(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=Ps(t,r);if(o===-1)n+="\\[",r++;else{let i=t.slice(r+1,o);n+=vs(i),r=o+1}}else/[\^$.|+(){}]/.test(s)?(n+=`\\${s}`,r++):(n+=s,r++)}return n}function Ps(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 vs(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+=Rs(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 Is={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 Rs(t){return Is[t]??""}function We(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 Me(t,e){let n=`${e}_`;for(let r of Object.keys(t.state.env))r.startsWith(n)&&delete t.state.env[r]}function Ut(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 en(t){return t.startsWith("'")&&t.endsWith("'")||t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1):t}function et(t){return t.IFS??`
|
|
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=Wt(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 Tt(this);if(this.check(u.LPAREN))return Lt(this);if(this.check(u.IF))return Rt(this);if(this.check(u.FOR))return kt(this);if(this.check(u.WHILE))return Dt(this);if(this.check(u.UNTIL))return Ot(this);if(this.check(u.CASE))return _t(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(;Xe(this);){this.checkIterationLimit();let n=this.pos;if(e.push(Ye(this)),this.pos===n)break}return e}parseArithmeticExpression(e){return T(this,e)}};function ue(t){return new M().parse(t)}var Ce=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=[];for(let s=0;s<e.length;s++){let o=e[s];if((n?.[s]??!1)||!this.isGlobPattern(o))r.push(o);else{let a=await this.expand(o);a.length>0?r.push(...a):r.push(o)}}return r}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{let o=await this.fs.readdir(s);for(let i of o){let a=e==="."?i:`${e}/${i}`,l=this.fs.resolvePath(this.cwd,a);try{(await this.fs.stat(l)).isDirectory?await this.walkDirectory(a,n,r):n&&this.matchPattern(i,n)&&r.push(a)}catch{}}}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 q(t){switch(t.type){case"ArithCommandSubst":return!0;case"ArithNested":return q(t.expression);case"ArithBinary":return q(t.left)||q(t.right);case"ArithUnary":return q(t.operand);case"ArithTernary":return q(t.condition)||q(t.consequent)||q(t.alternate);case"ArithAssignment":return q(t.value);case"ArithGroup":return q(t.expression);case"ArithArrayElement":return t.index?q(t.index):!1;case"ArithConcat":return t.parts.some(q);default:return!1}}function Bt(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 Je(t){switch(t.type){case"CommandSubstitution":return!0;case"ArithmeticExpansion":return q(t.expression.expression);case"DoubleQuoted":return t.parts.some(Je);case"BraceExpansion":return t.items.some(e=>e.type==="Word"&&ie(e.word));case"ParameterExpansion":return Bt(t);default:return!1}}function ie(t){return t.parts.some(Je)}function zt(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 Jr(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),zt(i)&&(e=!0))}return{hasQuoted:e,hasCommandSub:n,hasArrayVar:r,hasArrayAtExpansion:s,hasParamExpansion:o}}function Cs(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 $s(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 Fe(t,e,n,r,s){let o=n!==void 0?`..${n}`:"";return typeof t=="number"&&typeof e=="number"?{expanded:Cs(t,e,n,r,s),literal:`{${t}..${e}${o}}`}:typeof t=="string"&&typeof e=="string"?{expanded:$s(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=Ps(t,r);if(o===-1)n+="\\[",r++;else{let i=t.slice(r+1,o);n+=vs(i),r=o+1}}else/[\^$.|+(){}]/.test(s)?(n+=`\\${s}`,r++):(n+=s,r++)}return n}function Ps(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 vs(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+=Rs(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 Is={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 Rs(t){return Is[t]??""}function We(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 Me(t,e){let n=`${e}_`;for(let r of Object.keys(t.state.env))r.startsWith(n)&&delete t.state.env[r]}function Ut(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 en(t){return t.startsWith("'")&&t.endsWith("'")||t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1):t}function et(t){return t.IFS??`
|
|
40
40
|
`}function tn(t){return t.IFS===""}function Be(t){return t.split("").map(e=>/[\\^$.*+?()[\]{}|-]/.test(e)?`\\${e}`:e===" "?"\\t":e===`
|
|
41
|
-
`?"\\n":e).join("")}function ks(t,e){let n=Be(t);return new RegExp(`[${n}]+`,e)}function Ds(t){let e=Be(t);return new RegExp(`^[${e}]+`)}function Os(t){let e=Be(t);return new RegExp(`[${e}]+$`)}function
|
|
41
|
+
`?"\\n":e).join("")}function ks(t,e){let n=Be(t);return new RegExp(`[${n}]+`,e)}function Ds(t){let e=Be(t);return new RegExp(`^[${e}]+`)}function Os(t){let e=Be(t);return new RegExp(`[${e}]+$`)}function $e(t){let e=t.IFS;return e===void 0?" ":e[0]||""}function rn(t,e){if(e==="")return{words:[t],wordStarts:[0]};let n=[],r=[],s=ks(e,"g"),o=0,i=t.match(Ds(e));i&&(o=i[0].length),s.lastIndex=o;let a=s.exec(t);for(;a!==null;)a.index>o&&(r.push(o),n.push(t.substring(o,a.index))),o=s.lastIndex,a=s.exec(t);return o<t.length&&(r.push(o),n.push(t.substring(o))),{words:n,wordStarts:r}}function nn(t,e){return e===""?t:t.replace(Os(e),"")}function F(t,e){return t.state.associativeArrays?.has(e)?Ut(t,e).map(o=>[o,t.state.env[`${e}_${o}`]]):We(t,e).map(s=>[s,t.state.env[`${e}_${s}`]])}function sn(t,e){return t.state.associativeArrays?.has(e)?Ut(t,e).length>0:We(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 i="";return t.state.options.errexit&&(i+="e"),t.state.options.nounset&&(i+="u"),t.state.options.verbose&&(i+="v"),t.state.options.xtrace&&(i+="x"),t.state.options.pipefail&&(i+="p"),i}case"*":{let i=Number.parseInt(t.state.env["#"]||"0",10);if(i===0)return"";let a=[];for(let l=1;l<=i;l++)a.push(t.state.env[String(l)]||"");return a.join($e(t.state.env))}case"0":return t.state.env[0]||"bash";case"PWD":return t.state.env.PWD!==void 0?t.state.env.PWD:"";case"OLDPWD":return t.state.env.OLDPWD!==void 0?t.state.env.OLDPWD:"";case"PPID":{let{ppid:i}=Te();return String(i)}case"UID":{let{uid:i}=Te();return String(i)}case"EUID":return String(process.geteuid?.()??Te().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 Nr;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 ye(`\${${e}}`);let s=e.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(s){let i=s[1],a=s[2];if(a==="@"||a==="*"){let d=F(t,i);if(d.length>0)return d.map(([,m])=>m).join(" ");let h=t.state.env[i];return h!==void 0?h:""}if(t.state.associativeArrays?.has(i)){let d=en(a),h=t.state.env[`${i}_${d}`];if(h===void 0&&n&&t.state.options.nounset)throw new J(`${i}[${a}]`);return h||""}let c;if(/^-?\d+$/.test(a))c=Number.parseInt(a,10);else try{let d=new M,h=T(d,a);c=$(t,h.expression)}catch{let d=t.state.env[a];c=d?Number.parseInt(d,10):0,Number.isNaN(c)&&(c=0)}if(c<0){let d=F(t,i);if(d.length===0)return t.state.expansionStderr=(t.state.expansionStderr||"")+`bash: ${i}: bad array subscript
|
|
42
42
|
`,"";let m=Math.max(...d.map(([w])=>typeof w=="number"?w:0))+1+c;return m<0?(t.state.expansionStderr=(t.state.expansionStderr||"")+`bash: ${i}: bad array subscript
|
|
43
43
|
`,""):t.state.env[`${i}_${m}`]||""}let f=t.state.env[`${i}_${c}`];if(f===void 0&&n&&t.state.options.nounset)throw new J(`${i}[${c}]`);return f||""}if(/^[1-9][0-9]*$/.test(e)){let i=t.state.env[e];if(i===void 0&&n&&t.state.options.nounset)throw new J(e);return i||""}let o=t.state.env[e];if(o===void 0&&n&&t.state.options.nounset)throw new J(e);return o||""}async function on(t,e,n,r,s){let o=[];for(let f of e){let d=f.type==="ParameterExpansion"||f.type==="CommandSubstitution"||f.type==="ArithmeticExpansion";if(f.type==="ParameterExpansion"&&zt(f)){let h=await s(t,f);o.push({value:h,splittable:!1})}else{let h=await s(t,f);o.push({value:h,splittable:d})}}if(!o.some(f=>f.splittable&&new RegExp(`[${r}]`).test(f.value))){let f=o.map(d=>d.value).join("");return f?[f]:[]}let a=new RegExp(`[${r}]+`),l=[],c="";for(let f=0;f<o.length;f++){let d=o[f];if(!d.splittable)c+=d.value;else{let h=d.value.split(a);for(let m=0;m<h.length;m++)m===0?c+=h[m]:(c!==""&&l.push(c),c=h[m])}}return c!==""&&l.push(c),l}function H(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function an(t){switch(t.type){case"Literal":return t.value;case"SingleQuoted":return t.value;case"Escaped":return t.value;default:return null}}function cn(t){switch(t.type){case"SingleQuoted":case"Escaped":case"DoubleQuoted":return!0;case"Literal":return t.value==="";default:return!1}}function Gt(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 ge(t,e,n=!1){return e.map(r=>oe(t,r,n)).join("")}async function Ae(t,e,n=!1){let r=[];for(let s of e)r.push(await K(t,s));return r.join("")}function _s(t){return cn(t)}function ln(t){if(t.parts.length===0)return!0;for(let e of t.parts)if(!_s(e))return!1;return!0}function fn(t){return t.replace(/([*?[\]\\])/g,"\\$1")}function un(t,e,n=!1){let r=an(e);if(r!==null)return r;switch(e.type){case"ParameterExpansion":return yn(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 oe(t,e,n=!1){let r=un(t,e,n);if(r!==null)return r;switch(e.type){case"DoubleQuoted":{let s=[];for(let o of e.parts)s.push(oe(t,o,!0));return s.join("")}case"ArithmeticExpansion":return String($(t,e.expression.expression));case"BraceExpansion":{let s=[];for(let o of e.items)if(o.type==="Range"){let i=Fe(o.start,o.end,o.step,o.startStr,o.endStr);if(i.expanded)s.push(...i.expanded);else return i.literal}else s.push(tt(t,o.word));return s.join(" ")}default:return""}}function tt(t,e){let n=e.parts,r=n.length;if(r===1)return oe(t,n[0]);let s=[];for(let o=0;o<r;o++)s.push(oe(t,n[o]));return s.join("")}async function I(t,e){return ie(e)?pn(t,e):tt(t,e)}function rt(t){for(let e of t)if(e.type==="BraceExpansion"||e.type==="DoubleQuoted"&&rt(e.parts))return!0;return!1}function Ls(t){for(let e of t){if(e.type==="BraceExpansion"){for(let n of e.items)if(n.type==="Word"&&ie(n.word))return!0}if(Je(e))return!0}return!1}var dn=1e4
|
|
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 ge(t,e,n=!1){return e.map(r=>oe(t,r,n)).join("")}async function Ae(t,e,n=!1){let r=[];for(let s of e)r.push(await K(t,s));return r.join("")}function _s(t){return cn(t)}function ln(t){if(t.parts.length===0)return!0;for(let e of t.parts)if(!_s(e))return!1;return!0}function fn(t){return t.replace(/([*?[\]\\])/g,"\\$1")}function un(t,e,n=!1){let r=an(e);if(r!==null)return r;switch(e.type){case"ParameterExpansion":return yn(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 oe(t,e,n=!1){let r=un(t,e,n);if(r!==null)return r;switch(e.type){case"DoubleQuoted":{let s=[];for(let o of e.parts)s.push(oe(t,o,!0));return s.join("")}case"ArithmeticExpansion":return String($(t,e.expression.expression));case"BraceExpansion":{let s=[];for(let o of e.items)if(o.type==="Range"){let i=Fe(o.start,o.end,o.step,o.startStr,o.endStr);if(i.expanded)s.push(...i.expanded);else return i.literal}else s.push(tt(t,o.word));return s.join(" ")}default:return""}}function tt(t,e){let n=e.parts,r=n.length;if(r===1)return oe(t,n[0]);let s=[];for(let o=0;o<r;o++)s.push(oe(t,n[o]));return s.join("")}async function I(t,e){return ie(e)?pn(t,e):tt(t,e)}function rt(t){for(let e of t)if(e.type==="BraceExpansion"||e.type==="DoubleQuoted"&&rt(e.parts))return!0;return!1}function Ls(t){for(let e of t){if(e.type==="BraceExpansion"){for(let n of e.items)if(n.type==="Word"&&ie(n.word))return!0}if(Je(e))return!0}return!1}var dn=1e4,Pe=1e5;function hn(t,e,n={count:0}){if(n.count>Pe)return[[]];let r=[[]];for(let s of e)if(s.type==="BraceExpansion"){let o=[],i=!1,a="";for(let f of s.items)if(f.type==="Range"){let d=Fe(f.start,f.end,f.step,f.startStr,f.endStr);if(d.expanded)for(let h of d.expanded)n.count++,o.push(h);else{i=!0,a=d.literal;break}}else{let d=hn(t,f.word.parts,n);for(let h of d)n.count++,o.push(h.join(""))}if(i){for(let f of r)n.count++,f.push(a);continue}if(r.length*o.length>dn||n.count>Pe)return r;let c=[];for(let f of r)for(let d of o){if(n.count++,n.count>Pe)return c.length>0?c:r;c.push([...f,d])}r=c}else{let o=oe(t,s);for(let i of r)n.count++,i.push(o)}return r}function Ts(t,e){let n=e.parts;return rt(n)?hn(t,n).map(s=>s.join("")):[tt(t,e)]}async function mn(t,e,n={count:0}){if(n.count>Pe)return[[]];let r=[[]];for(let s of e)if(s.type==="BraceExpansion"){let o=[],i=!1,a="";for(let f of s.items)if(f.type==="Range"){let d=Fe(f.start,f.end,f.step,f.startStr,f.endStr);if(d.expanded)for(let h of d.expanded)n.count++,o.push(h);else{i=!0,a=d.literal;break}}else{let d=await mn(t,f.word.parts,n);for(let h of d)n.count++,o.push(h.join(""))}if(i){for(let f of r)n.count++,f.push(a);continue}if(r.length*o.length>dn||n.count>Pe)return r;let c=[];for(let f of r)for(let d of o){if(n.count++,n.count>Pe)return c.length>0?c:r;c.push([...f,d])}r=c}else{let o=await K(t,s);for(let i of r)n.count++,i.push(o)}return r}async function Fs(t,e){let n=e.parts;return rt(n)?(await mn(t,n)).map(s=>s.join("")):[await I(t,e)]}async function ze(t,e){let n=e.parts,{hasQuoted:r,hasCommandSub:s,hasArrayVar:o,hasArrayAtExpansion:i,hasParamExpansion:a}=Jr(n),c=rt(n)?Ls(n)?await Fs(t,e):Ts(t,e):null;if(c&&c.length>1){let h=[];for(let m of c)if(!r&&/[*?[]/.test(m)){let w=await new Ce(t.fs,t.state.cwd).expand(m);w.length>0?h.push(...w):h.push(m)}else h.push(m);return{values:h,quoted:!1}}if(i&&n.length===1&&n[0].type==="DoubleQuoted"){let h=n[0];if(h.parts.length===1&&h.parts[0].type==="ParameterExpansion"){let y=h.parts[0].parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[[@]\]$/);if(y){let w=y[1],p=F(t,w);if(p.length>0)return{values:p.map(([,g])=>g),quoted:!0};let E=t.state.env[w];return E!==void 0?{values:[E],quoted:!0}:{values:[],quoted:!0}}}}if(n.length===1&&n[0].type==="DoubleQuoted"){let h=n[0],m=-1,y=!1;for(let w=0;w<h.parts.length;w++){let p=h.parts[w];if(p.type==="ParameterExpansion"&&(p.parameter==="@"||p.parameter==="*")){m=w,y=p.parameter==="*";break}}if(m!==-1){let w=h.parts[m];w.type==="ParameterExpansion"&&w.operation&&(m=-1)}if(m!==-1){let w=Number.parseInt(t.state.env["#"]||"0",10),p="";for(let N=0;N<m;N++)p+=await K(t,h.parts[N]);let E="";for(let N=m+1;N<h.parts.length;N++)E+=await K(t,h.parts[N]);if(w===0){if(y)return{values:[p+E],quoted:!0};let N=p+E;return{values:N?[N]:[],quoted:!0}}let g=[];for(let N=1;N<=w;N++)g.push(t.state.env[String(N)]||"");if(y){let N=$e(t.state.env);return{values:[p+g.join(N)+E],quoted:!0}}return g.length===1?{values:[p+g[0]+E],quoted:!0}:{values:[p+g[0],...g.slice(1,-1),g[g.length-1]+E],quoted:!0}}}if((s||o||a)&&!tn(t.state.env)){let h=et(t.state.env),m=Be(h),y=await on(t,n,h,m,K),w=[],p=new Ce(t.fs,t.state.cwd);for(let E of y)if(/[*?[]/.test(E)){let g=await p.expand(E);g.length>0?w.push(...g):w.push(E)}else w.push(E);return{values:w,quoted:!1}}let d=ie(e)?await pn(t,e):tt(t,e);if(!r&&/[*?[]/.test(d)){let m=await new Ce(t.fs,t.state.cwd).expand(d);if(m.length>0)return{values:m,quoted:!1}}return d===""&&!r?{values:[],quoted:!1}:{values:[d],quoted:r}}async function pn(t,e){let n=e.parts,r=n.length;if(r===1)return K(t,n[0]);let s=[];for(let o=0;o<r;o++)s.push(await K(t,n[o]));return s.join("")}async function K(t,e){if(e.type==="ParameterExpansion"&&Bt(e))return Ws(t,e);let n=un(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 z)throw r;if(r instanceof k)return t.state.lastExitCode=r.exitCode,t.state.env["?"]=String(r.exitCode),r.stdout.replace(/\n+$/,"");throw r}case"ArithmeticExpansion":return String(await P(t,e.expression.expression));case"BraceExpansion":{let r=[];for(let s of e.items)if(s.type==="Range"){let o=Fe(s.start,s.end,s.step,s.startStr,s.endStr);if(o.expanded)r.push(...o.expanded);else return o.literal}else r.push(await I(t,s.word));return r.join(" ")}default:return""}}function yn(t,e,n=!1){let{parameter:r,operation:s}=e,o=s&&(s.type==="DefaultValue"||s.type==="AssignDefault"||s.type==="UseAlternative"||s.type==="ErrorIfUnset"),i=Q(t,r,!o);if(!s)return i;let a=!(r in t.state.env),l=i==="";switch(s.type){case"DefaultValue":return(a||s.checkEmpty&&l)&&s.word?ge(t,s.word.parts,n):i;case"AssignDefault":{if((a||s.checkEmpty&&l)&&s.word){let f=ge(t,s.word.parts,n),d=r.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(d){let[,h,m]=d,y;if(/^\d+$/.test(m))y=Number.parseInt(m,10);else{try{let p=new M,E=T(p,m);y=$(t,E.expression)}catch{let p=t.state.env[m];y=p?Number.parseInt(p,10):0}Number.isNaN(y)&&(y=0)}t.state.env[`${h}_${y}`]=f;let w=Number.parseInt(t.state.env[`${h}__length`]||"0",10);y>=w&&(t.state.env[`${h}__length`]=String(y+1))}else t.state.env[r]=f;return f}return i}case"ErrorIfUnset":{if(a||s.checkEmpty&&l){let f=s.word?ge(t,s.word.parts,n):`${r}: parameter null or not set`;throw new k(1,"",`bash: ${f}
|
|
45
45
|
`)}return i}case"UseAlternative":return!(a||s.checkEmpty&&l)&&s.word?ge(t,s.word.parts,n):"";case"Length":{let c=r.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[[@*]\]$/);if(c){let f=F(t,c[1]);return String(f.length)}if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(r)&&sn(t,r)){let f=t.state.env[`${r}_0`]||"";return String(f.length)}return String(i.length)}case"LengthSliceError":throw new ye(r);case"Substring":{let c=s.offset?$(t,s.offset.expression):0,f=s.length?$(t,s.length.expression):void 0;if(r==="@"||r==="*"){let y=(t.state.env["@"]||"").split(" ").filter(g=>g),w=t.state.env[0]||"bash",p=c===0?[w,...y]:y,E=c===0?0:c-1;if(E<0||E>=p.length)return"";if(f!==void 0){let g=f<0?p.length+f:E+f;return p.slice(E,Math.max(E,g)).join(" ")}return p.slice(E).join(" ")}let d=r.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[[@*]\]$/);if(d){let w=F(t,d[1]).map(([,E])=>E),p=c;if(p<0&&(p=w.length+p,p<0))return"";if(f!==void 0){if(f<0){let E=w.length+f;return w.slice(p,Math.max(p,E)).join(" ")}return w.slice(p,p+f).join(" ")}return w.slice(p).join(" ")}let h=[...i],m=c;if(m<0&&(m=Math.max(0,h.length+m)),f!==void 0){if(f<0){let y=h.length+f;return h.slice(m,Math.max(m,y)).join("")}return h.slice(m,m+f).join("")}return h.slice(m).join("")}case"PatternRemoval":{let c="";if(s.pattern)for(let d of s.pattern.parts)if(d.type==="Glob")c+=V(d.pattern,s.greedy);else if(d.type==="Literal")c+=V(d.value,s.greedy);else if(d.type==="SingleQuoted"||d.type==="Escaped")c+=H(d.value);else if(d.type==="DoubleQuoted"){let h=ge(t,d.parts);c+=H(h)}else if(d.type==="ParameterExpansion"){let h=oe(t,d);c+=V(h,s.greedy)}else{let h=oe(t,d);c+=H(h)}if(s.side==="prefix")return i.replace(new RegExp(`^${c}`),"");let f=new RegExp(`${c}$`);if(s.greedy)return i.replace(f,"");for(let d=i.length;d>=0;d--){let h=i.slice(d);if(f.test(h))return i.slice(0,d)}return i}case"PatternReplacement":{let c="";if(s.pattern)for(let h of s.pattern.parts)if(h.type==="Glob")c+=V(h.pattern,!0);else if(h.type==="Literal")c+=V(h.value,!0);else if(h.type==="SingleQuoted"||h.type==="Escaped")c+=H(h.value);else if(h.type==="DoubleQuoted"){let m=ge(t,h.parts);c+=H(m)}else if(h.type==="ParameterExpansion"){let m=oe(t,h);c+=V(m,!0)}else{let m=oe(t,h);c+=H(m)}let f=s.replacement?ge(t,s.replacement.parts):"";if(c==="")return i;s.anchor==="start"?c=`^${c}`:s.anchor==="end"&&(c=`${c}$`);let d=s.all?"g":"";try{let h=new RegExp(c,d);if(s.all){let m="",y=0,w=h.exec(i);for(;w!==null&&!(w[0].length===0&&w.index===i.length);)m+=i.slice(y,w.index)+f,y=w.index+w[0].length,w[0].length===0&&y++,w=h.exec(i);return m+=i.slice(y),m}return i.replace(h,f)}catch{return i}}case"CaseModification":return s.direction==="upper"?s.all?i.toUpperCase():i.charAt(0).toUpperCase()+i.slice(1):s.all?i.toLowerCase():i.charAt(0).toLowerCase()+i.slice(1);case"Transform":{let c=r.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[[@*]\]$/);if(c&&s.operator==="Q")return F(t,c[1]).map(([,h])=>Gt(h)).join(" ");switch(s.operator){case"Q":return Gt(i);case"P":return i;case"a":return"";case"A":return`${r}=${Gt(i)}`;case"E":return i.replace(/\\([\\abefnrtv'"?])/g,(f,d)=>{switch(d){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 d}});case"K":return"";default:return i}}case"Indirection":return Q(t,i);case"ArrayKeys":{let f=F(t,s.array).map(([d])=>String(d));return s.star?f.join(
|
|
47
|
-
`)}return i}case"UseAlternative":return!(a||s.checkEmpty&&l)&&s.word?Ae(t,s.word.parts,n):"";case"PatternRemoval":{let c="";if(s.pattern)for(let d of s.pattern.parts)if(d.type==="Glob")c+=V(d.pattern,s.greedy);else if(d.type==="Literal")c+=V(d.value,s.greedy);else if(d.type==="SingleQuoted"||d.type==="Escaped")c+=H(d.value);else if(d.type==="DoubleQuoted"){let h=await Ae(t,d.parts);c+=H(h)}else if(d.type==="ParameterExpansion"){let h=await K(t,d);c+=V(h,s.greedy)}else{let h=await K(t,d);c+=H(h)}if(s.side==="prefix")return i.replace(new RegExp(`^${c}`),"");let f=new RegExp(`${c}$`);if(s.greedy)return i.replace(f,"");for(let d=i.length;d>=0;d--){let h=i.slice(d);if(f.test(h))return i.slice(0,d)}return i}case"PatternReplacement":{let c="";if(s.pattern)for(let h of s.pattern.parts)if(h.type==="Glob")c+=V(h.pattern,!0);else if(h.type==="Literal")c+=V(h.value,!0);else if(h.type==="SingleQuoted"||h.type==="Escaped")c+=H(h.value);else if(h.type==="DoubleQuoted"){let m=await Ae(t,h.parts);c+=H(m)}else if(h.type==="ParameterExpansion"){let m=await K(t,h);c+=V(m,!0)}else{let m=await K(t,h);c+=H(m)}let f=s.replacement?await Ae(t,s.replacement.parts):"";if(c==="")return i;s.anchor==="start"?c=`^${c}`:s.anchor==="end"&&(c=`${c}$`);let d=s.all?"g":"";try{let h=new RegExp(c,d);if(s.all){let m="",y=0,w=h.exec(i);for(;w!==null&&!(w[0].length===0&&w.index===i.length);)m+=i.slice(y,w.index)+f,y=w.index+w[0].length,w[0].length===0&&y++,w=h.exec(i);return m+=i.slice(y),m}return i.replace(h,f)}catch{return i}}default:return yn(t,e,n)}}function Vt(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 En(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 Ht(t,e){switch(e){case"-":return-t;case"+":return+t;case"!":return t===0?1:0;case"~":return~t;default:return t}}function Ms(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
|
|
46
|
+
`;case"r":return"\r";case"t":return" ";case"v":return"\v";case"'":return"'";case'"':return'"';case"?":return"?";default:return d}});case"K":return"";default:return i}}case"Indirection":return Q(t,i);case"ArrayKeys":{let f=F(t,s.array).map(([d])=>String(d));return s.star?f.join($e(t.state.env)):f.join(" ")}case"VarNamePrefix":{let c=Object.keys(t.state.env).filter(f=>f.startsWith(s.prefix)&&!f.includes("__")).sort();return s.star?c.join($e(t.state.env)):c.join(" ")}default:return i}}async function Ws(t,e,n=!1){let{parameter:r,operation:s}=e,o=s&&(s.type==="DefaultValue"||s.type==="AssignDefault"||s.type==="UseAlternative"||s.type==="ErrorIfUnset"),i=Q(t,r,!o);if(!s)return i;let a=!(r in t.state.env),l=i==="";switch(s.type){case"DefaultValue":return(a||s.checkEmpty&&l)&&s.word?Ae(t,s.word.parts,n):i;case"AssignDefault":{if((a||s.checkEmpty&&l)&&s.word){let f=await Ae(t,s.word.parts,n),d=r.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(d){let[,h,m]=d,y;if(/^\d+$/.test(m))y=Number.parseInt(m,10);else{try{let p=new M,E=T(p,m);y=await P(t,E.expression)}catch{let p=t.state.env[m];y=p?Number.parseInt(p,10):0}Number.isNaN(y)&&(y=0)}t.state.env[`${h}_${y}`]=f;let w=Number.parseInt(t.state.env[`${h}__length`]||"0",10);y>=w&&(t.state.env[`${h}__length`]=String(y+1))}else t.state.env[r]=f;return f}return i}case"ErrorIfUnset":{if(a||s.checkEmpty&&l){let f=s.word?await Ae(t,s.word.parts,n):`${r}: parameter null or not set`;throw new k(1,"",`bash: ${f}
|
|
47
|
+
`)}return i}case"UseAlternative":return!(a||s.checkEmpty&&l)&&s.word?Ae(t,s.word.parts,n):"";case"PatternRemoval":{let c="";if(s.pattern)for(let d of s.pattern.parts)if(d.type==="Glob")c+=V(d.pattern,s.greedy);else if(d.type==="Literal")c+=V(d.value,s.greedy);else if(d.type==="SingleQuoted"||d.type==="Escaped")c+=H(d.value);else if(d.type==="DoubleQuoted"){let h=await Ae(t,d.parts);c+=H(h)}else if(d.type==="ParameterExpansion"){let h=await K(t,d);c+=V(h,s.greedy)}else{let h=await K(t,d);c+=H(h)}if(s.side==="prefix")return i.replace(new RegExp(`^${c}`),"");let f=new RegExp(`${c}$`);if(s.greedy)return i.replace(f,"");for(let d=i.length;d>=0;d--){let h=i.slice(d);if(f.test(h))return i.slice(0,d)}return i}case"PatternReplacement":{let c="";if(s.pattern)for(let h of s.pattern.parts)if(h.type==="Glob")c+=V(h.pattern,!0);else if(h.type==="Literal")c+=V(h.value,!0);else if(h.type==="SingleQuoted"||h.type==="Escaped")c+=H(h.value);else if(h.type==="DoubleQuoted"){let m=await Ae(t,h.parts);c+=H(m)}else if(h.type==="ParameterExpansion"){let m=await K(t,h);c+=V(m,!0)}else{let m=await K(t,h);c+=H(m)}let f=s.replacement?await Ae(t,s.replacement.parts):"";if(c==="")return i;s.anchor==="start"?c=`^${c}`:s.anchor==="end"&&(c=`${c}$`);let d=s.all?"g":"";try{let h=new RegExp(c,d);if(s.all){let m="",y=0,w=h.exec(i);for(;w!==null&&!(w[0].length===0&&w.index===i.length);)m+=i.slice(y,w.index)+f,y=w.index+w[0].length,w[0].length===0&&y++,w=h.exec(i);return m+=i.slice(y),m}return i.replace(h,f)}catch{return i}}default:return yn(t,e,n)}}function Vt(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 En(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 Ht(t,e){switch(e){case"-":return-t;case"+":return+t;case"!":return t===0?1:0;case"~":return~t;default:return t}}function Ms(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 ve(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 M,{expr:s,pos:o}=ne(r,n,0);if(o<n.length){let i=n.slice(o).trim().split(/\s+/)[0];throw new W(`${n}: syntax error in expression (error token is "${i}")`)}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 nt(t,e,n=new Set){if(n.has(e))return 0;n.add(e);let r=Ms(t,e);if(!r)return 0;let s=Number.parseInt(r,10);if(!Number.isNaN(s)&&/^-?\d+$/.test(r.trim()))return s;let o=r.trim();if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(o))return nt(t,o,n);try{let i=new M,{expr:a}=ne(i,o,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 nt(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 Vt(r,s,e.operator)}case"ArithUnary":{let r=X(t,e.operand,n);return Ht(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 $(t,e)}}function de(t,e){if(e.startsWith("#")){let d=e.slice(1),h=t.state.env[d]||"";return String(h.length)}if(e.startsWith("!")){let d=e.slice(1),h=t.state.env[d]||"";return t.state.env[h]||""}let n=[":-",":=",":?",":+","-","=","?","+"],r=-1,s="";for(let d of n){let h=e.indexOf(d);h>0&&(r===-1||h<r)&&(r=h,s=d)}if(r===-1)return Q(t,e);let o=e.slice(0,r),i=e.slice(r+s.length),a=t.state.env[o],l=a===void 0,c=a==="",f=s.startsWith(":");switch(s){case":-":case"-":return l||f&&c?i:a||"";case":=":case"=":return l||f&&c?(t.state.env[o]=i,i):a||"";case":+":case"+":return!(l||f&&c)?i:"";case":?":case"?":{if(l||f&&c)throw new Error(i||`${o}: parameter null or not set`);return a||""}default:return a||""}}function $(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 nt(t,e.name);case"ArithNested":return $(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 o=$(t,e.index);if(o<0){let a=F(t,e.array);if(a.length===0)return t.state.expansionStderr=(t.state.expansionStderr||"")+`bash: ${e.array}: bad array subscript
|
|
48
48
|
`,0;let c=Math.max(...a.map(([f])=>typeof f=="number"?f:0))+1+o;if(c<0)return t.state.expansionStderr=(t.state.expansionStderr||"")+`bash: ${e.array}: bad array subscript
|
|
49
|
-
`,0;o=c}r=`${e.array}_${o}`;let i=t.state.env[r];if(i!==void 0)return
|
|
49
|
+
`,0;o=c}r=`${e.array}_${o}`;let i=t.state.env[r];if(i!==void 0)return ve(i);if(o===0){let a=t.state.env[e.array];if(a!==void 0)return ve(a)}if(t.state.options.nounset&&!Object.keys(t.state.env).some(l=>l===e.array||l.startsWith(`${e.array}_`)))throw new J(`${e.array}[${o}]`);return 0}else return 0;let s=t.state.env[r];return s!==void 0?ve(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 $(t,e.left)||$(t,e.right)?1:0;if(e.operator==="&&")return $(t,e.left)&&$(t,e.right)?1:0;let n=$(t,e.left),r=$(t,e.right);return Vt(n,r,e.operator)}case"ArithUnary":{let n=$(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,o=e.operator==="++"?s+1:s-1;return t.state.env[r]=String(o),e.prefix?o:s}if(e.operand.type==="ArithArrayElement"){let r=e.operand.array,s=t.state.associativeArrays?.has(r),o;if(e.operand.stringKey!==void 0)o=`${r}_${e.operand.stringKey}`;else if(s&&e.operand.index?.type==="ArithVariable")o=`${r}_${e.operand.index.name}`;else if(e.operand.index){let l=$(t,e.operand.index);o=`${r}_${l}`}else return n;let i=Number.parseInt(t.state.env[o]||"0",10)||0,a=e.operator==="++"?i+1:i-1;return t.state.env[o]=String(a),e.prefix?a:i}return n}return Ht(n,e.operator)}case"ArithTernary":return $(t,e.condition)?$(t,e.consequent):$(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 l=$(t,e.subscript);r=`${n}_${l}`}else{let l=$(t,e.subscript);if(l<0){let c=F(t,n);c.length>0&&(l=Math.max(...c.map(([d])=>typeof d=="number"?d:0))+1+l)}r=`${n}_${l}`}}let s=Number.parseInt(t.state.env[r]||"0",10)||0,o=$(t,e.value),i=En(s,o,e.operator);return t.state.env[r]=String(i),i}case"ArithGroup":return $(t,e.expression);case"ArithConcat":{let n="";for(let r of e.parts)n+=wn(t,r);return Number.parseInt(n,10)||0}default:return 0}}function wn(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+=wn(t,r);return n}default:return String($(t,e))}}async 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 nt(t,e.name);case"ArithNested":return P(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 o=await P(t,e.index);r=`${e.array}_${o}`;let i=t.state.env[r];if(i!==void 0)return ve(i);if(o===0){let a=t.state.env[e.array];if(a!==void 0)return ve(a)}if(t.state.options.nounset&&!Object.keys(t.state.env).some(l=>l===e.array||l.startsWith(`${e.array}_`)))throw new J(`${e.array}[${o}]`);return 0}else return 0;let s=t.state.env[r];return s!==void 0?ve(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 P(t,e.left)||await P(t,e.right)?1:0;if(e.operator==="&&")return await P(t,e.left)&&await P(t,e.right)?1:0;let n=await P(t,e.left),r=await P(t,e.right);return Vt(n,r,e.operator)}case"ArithUnary":{let n=await 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,o=e.operator==="++"?s+1:s-1;return t.state.env[r]=String(o),e.prefix?o:s}if(e.operand.type==="ArithArrayElement"){let r=e.operand.array,s=t.state.associativeArrays?.has(r),o;if(e.operand.stringKey!==void 0)o=`${r}_${e.operand.stringKey}`;else if(s&&e.operand.index?.type==="ArithVariable")o=`${r}_${e.operand.index.name}`;else if(e.operand.index){let l=await P(t,e.operand.index);o=`${r}_${l}`}else return n;let i=Number.parseInt(t.state.env[o]||"0",10)||0,a=e.operator==="++"?i+1:i-1;return t.state.env[o]=String(a),e.prefix?a:i}return n}return Ht(n,e.operator)}case"ArithTernary":return await P(t,e.condition)?await P(t,e.consequent):await 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 l=await P(t,e.subscript);r=`${n}_${l}`}else{let l=await P(t,e.subscript);if(l<0){let c=F(t,n);c.length>0&&(l=Math.max(...c.map(([d])=>typeof d=="number"?d:0))+1+l)}r=`${n}_${l}`}}let s=Number.parseInt(t.state.env[r]||"0",10)||0,o=await P(t,e.value),i=En(s,o,e.operator);return t.state.env[r]=String(i),i}case"ArithGroup":return await P(t,e.expression);case"ArithConcat":{let n="";for(let r of e.parts)n+=await gn(t,r);return Number.parseInt(n,10)||0}default:return 0}}async function gn(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 gn(t,r);return n}default:return String(await P(t,e))}}var C=Object.freeze({stdout:"",stderr:"",exitCode:0});function j(t=""){return{stdout:t,stderr:"",exitCode:0}}function S(t,e=1){return{stdout:"",stderr:t,exitCode:e}}function x(t,e,n){return{stdout:t,stderr:e,exitCode:n}}function _(t){return{stdout:"",stderr:"",exitCode:t?0:1}}function ae(t,e,n="",r=""){throw new z(t,e,n,r)}function jt(t,e){if(t.state.loopDepth===0){if(t.state.parentHasLoopContext)throw new le;return C}let n=1;if(e.length>0){let r=Number.parseInt(e[0],10);if(Number.isNaN(r)||r<1)throw new k(128,"",`bash: break: ${e[0]}: numeric argument required
|
|
50
50
|
`);n=r}throw new U(n)}async function Zt(t,e){let n,r=!1,s=!1,o=0;for(;o<e.length;)if(e[o]==="--"){o++;break}else if(e[o]==="-L")s=!1,o++;else if(e[o]==="-P")s=!0,o++;else if(e[o].startsWith("-")&&e[o]!=="-")o++;else break;let i=e.slice(o);if(i.length===0||i[0]==="~"?n=t.state.env.HOME||"/":i[0]==="-"?(n=t.state.previousDir,r=!0):n=i[0],!n.startsWith("/")&&!n.startsWith("./")&&!n.startsWith("../")&&n!=="."&&n!==".."){let d=t.state.env.CDPATH;if(d){let h=d.split(":").filter(m=>m);for(let m of h){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 l=(n.startsWith("/")?n:`${t.state.cwd}/${n}`).split("/").filter(d=>d&&d!=="."),c="";for(let d of l)if(d==="..")c=c.split("/").slice(0,-1).join("/")||"/";else{c=c?`${c}/${d}`:`/${d}`;try{if(!(await t.fs.stat(c)).isDirectory)return S(`bash: cd: ${n}: Not a directory
|
|
51
51
|
`)}catch{return S(`bash: cd: ${n}: No such file or directory
|
|
52
52
|
`)}}let f=c||"/";return t.state.previousDir=t.state.cwd,t.state.cwd=f,t.state.env.PWD=t.state.cwd,t.state.env.OLDPWD=t.state.previousDir,j(r?`${f}
|
|
@@ -104,9 +104,9 @@ ${st}`):(or(t,e.slice(n)),C)}return C}function or(t,e){let n=1;for(;t.state.env[
|
|
|
104
104
|
`);let i={};if(n.length>1){for(let c=1;c<=9;c++)i[String(c)]=t.state.env[String(c)];i["#"]=t.state.env["#"],i["@"]=t.state.env["@"];let l=n.slice(1);t.state.env["#"]=String(l.length),t.state.env["@"]=l.join(" ");for(let c=0;c<l.length&&c<9;c++)t.state.env[String(c+1)]=l[c];for(let c=l.length+1;c<=9;c++)delete t.state.env[String(c)]}let a=()=>{if(t.state.sourceDepth--,n.length>1)for(let[l,c]of Object.entries(i))c===void 0?delete t.state.env[l]:t.state.env[l]=c};t.state.sourceDepth++;try{let l=ue(o),c=await t.executeScript(l);return a(),c}catch(l){if(a(),l instanceof k)throw l;if(l instanceof G)return x(l.stdout,l.stderr,l.exitCode);if(l.name==="ParseException")return S(`bash: ${r}: ${l.message}
|
|
105
105
|
`);throw l}}function fr(t,e){let n="variable",r="",s=0;for(let o of e){if(o==="-v"){n="variable";continue}if(o==="-f"){n="function";continue}if(n==="function"){t.state.functions.delete(o);continue}let i=o.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(i){let a=i[1],l=i[2];if(l==="@"||l==="*"){let f=F(t,a);for(let[d]of f)delete t.state.env[`${a}_${d}`];delete t.state.env[a];continue}let c;if(/^-?\d+$/.test(l))c=Number.parseInt(l,10);else{let f=t.state.env[l];c=f?Number.parseInt(f,10):0,Number.isNaN(c)&&(c=0)}if(c<0){let f=F(t,a),d=f.length;if(d===0){r+=`bash: unset: [${c}]: bad array subscript
|
|
106
106
|
`,s=1;continue}let h=d+c;if(h<0){r+=`bash: unset: [${c}]: bad array subscript
|
|
107
|
-
`,s=1;continue}let m=f[h][0];delete t.state.env[`${a}_${m}`];continue}delete t.state.env[`${a}_${c}`];continue}delete t.state.env[o],t.state.functions.delete(o)}return x("",r,s)}function ur(t,e){return t.fs.resolvePath(t.state.cwd,e)}var js=["-e","-a","-f","-d","-r","-w","-x","-s","-L","-h","-k","-g","-u","-G","-O","-b","-c","-p","-S","-t","-N"];function it(t){return js.includes(t)}async function ot(t,e,n){let r=ur(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(o=>r===o||r.endsWith(o));case"-p":return!1;case"-S":return!1;case"-t":return!1;case"-N":return t.fs.exists(r);default:return!1}}var Zs=["-nt","-ot","-ef"];function at(t){return Zs.includes(t)}async function ct(t,e,n,r){let s=ur(t,n),o=ur(t,r);switch(e){case"-nt":try{let i=await t.fs.stat(s),a=await t.fs.stat(o);return i.mtime>a.mtime}catch{return!1}case"-ot":try{let i=await t.fs.stat(s),a=await t.fs.stat(o);return i.mtime<a.mtime}catch{return!1}case"-ef":try{if(!await t.fs.exists(s)||!await t.fs.exists(o))return!1;let i=t.fs.resolvePath(t.state.cwd,s),a=t.fs.resolvePath(t.state.cwd,o);return i===a}catch{return!1}default:return!1}}var qs=new Set(["-eq","-ne","-lt","-le","-gt","-ge"]);function lt(t){return qs.has(t)}function ft(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 ut(t){return t==="="||t==="=="||t==="!="}function dt(t,e,n,r=!1){let s=r?ht(e,n):e===n;return t==="!="?!s:s}var Qs=new Set(["-z","-n"]);function mt(t){return Qs.has(t)}function pt(t,e){switch(t){case"-z":return e==="";case"-n":return e!==""}}function yt(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,(i,a)=>t.state.env[a]||"");let o;if(/^-?\d+$/.test(s))o=Number.parseInt(s,10);else try{let i=Function(`"use strict"; return (${s})`)();o=typeof i=="number"?Math.floor(i):0}catch{let i=t.state.env[s];o=i?Number.parseInt(i,10):0}if(o<0){let i=We(t,r);if(i.length===0||(o=Math.max(...i)+1+o,o<0))return!1}return`${r}_${o}`in t.state.env}return e in t.state.env}async function me(t,e){switch(e.type){case"CondBinary":{let n=await I(t,e.left),r=await I(t,e.right),s=e.right.parts.length>0&&e.right.parts.every(o=>o.type==="SingleQuoted"||o.type==="DoubleQuoted"||o.type==="Escaped");if(ut(e.operator))return dt(e.operator,n,r,!s);if(lt(e.operator))return ft(e.operator,vn(t,n),vn(t,r));if(at(e.operator))return ct(t,e.operator,n,r);switch(e.operator){case"=~":try{let o=new RegExp(r),i=n.match(o);if(i){t.state.env.BASH_REMATCH=i[0];for(let a=1;a<i.length;a++)t.state.env[`BASH_REMATCH_${a}`]=i[a]||""}return i!==null}catch{throw new Error("syntax error in regular expression")}case"<":return n<r;case">":return n>r;default:return!1}}case"CondUnary":{let n=await I(t,e.operand);return it(e.operator)?ot(t,e.operator,n):mt(e.operator)?pt(e.operator,n):e.operator==="-v"?yt(t,n):e.operator==="-o"?hr(t,n):!1}case"CondNot":return!await me(t,e.operand);case"CondAnd":return await me(t,e.left)?await me(t,e.right):!1;case"CondOr":return await me(t,e.left)?!0:await me(t,e.right);case"CondGroup":return await me(t,e.expression);case"CondWord":return await I(t,e.word)!=="";default:return!1}}async function
|
|
107
|
+
`,s=1;continue}let m=f[h][0];delete t.state.env[`${a}_${m}`];continue}delete t.state.env[`${a}_${c}`];continue}delete t.state.env[o],t.state.functions.delete(o)}return x("",r,s)}function ur(t,e){return t.fs.resolvePath(t.state.cwd,e)}var js=["-e","-a","-f","-d","-r","-w","-x","-s","-L","-h","-k","-g","-u","-G","-O","-b","-c","-p","-S","-t","-N"];function it(t){return js.includes(t)}async function ot(t,e,n){let r=ur(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(o=>r===o||r.endsWith(o));case"-p":return!1;case"-S":return!1;case"-t":return!1;case"-N":return t.fs.exists(r);default:return!1}}var Zs=["-nt","-ot","-ef"];function at(t){return Zs.includes(t)}async function ct(t,e,n,r){let s=ur(t,n),o=ur(t,r);switch(e){case"-nt":try{let i=await t.fs.stat(s),a=await t.fs.stat(o);return i.mtime>a.mtime}catch{return!1}case"-ot":try{let i=await t.fs.stat(s),a=await t.fs.stat(o);return i.mtime<a.mtime}catch{return!1}case"-ef":try{if(!await t.fs.exists(s)||!await t.fs.exists(o))return!1;let i=t.fs.resolvePath(t.state.cwd,s),a=t.fs.resolvePath(t.state.cwd,o);return i===a}catch{return!1}default:return!1}}var qs=new Set(["-eq","-ne","-lt","-le","-gt","-ge"]);function lt(t){return qs.has(t)}function ft(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 ut(t){return t==="="||t==="=="||t==="!="}function dt(t,e,n,r=!1){let s=r?ht(e,n):e===n;return t==="!="?!s:s}var Qs=new Set(["-z","-n"]);function mt(t){return Qs.has(t)}function pt(t,e){switch(t){case"-z":return e==="";case"-n":return e!==""}}function yt(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,(i,a)=>t.state.env[a]||"");let o;if(/^-?\d+$/.test(s))o=Number.parseInt(s,10);else try{let i=Function(`"use strict"; return (${s})`)();o=typeof i=="number"?Math.floor(i):0}catch{let i=t.state.env[s];o=i?Number.parseInt(i,10):0}if(o<0){let i=We(t,r);if(i.length===0||(o=Math.max(...i)+1+o,o<0))return!1}return`${r}_${o}`in t.state.env}return e in t.state.env}async function me(t,e){switch(e.type){case"CondBinary":{let n=await I(t,e.left),r=await I(t,e.right),s=e.right.parts.length>0&&e.right.parts.every(o=>o.type==="SingleQuoted"||o.type==="DoubleQuoted"||o.type==="Escaped");if(ut(e.operator))return dt(e.operator,n,r,!s);if(lt(e.operator))return ft(e.operator,vn(t,n),vn(t,r));if(at(e.operator))return ct(t,e.operator,n,r);switch(e.operator){case"=~":try{let o=new RegExp(r),i=n.match(o);if(i){t.state.env.BASH_REMATCH=i[0];for(let a=1;a<i.length;a++)t.state.env[`BASH_REMATCH_${a}`]=i[a]||""}return i!==null}catch{throw new Error("syntax error in regular expression")}case"<":return n<r;case">":return n>r;default:return!1}}case"CondUnary":{let n=await I(t,e.operand);return it(e.operator)?ot(t,e.operator,n):mt(e.operator)?pt(e.operator,n):e.operator==="-v"?yt(t,n):e.operator==="-o"?hr(t,n):!1}case"CondNot":return!await me(t,e.operand);case"CondAnd":return await me(t,e.left)?await me(t,e.right):!1;case"CondOr":return await me(t,e.left)?!0:await me(t,e.right);case"CondGroup":return await me(t,e.expression);case"CondWord":return await I(t,e.word)!=="";default:return!1}}async function Ie(t,e){if(e.length===0)return x("","",1);if(e.length===1)return _(!!e[0]);if(e.length===2){let r=e[0],s=e[1];return r==="("?S(`test: '(' without matching ')'
|
|
108
108
|
`,2):it(r)?_(await ot(t,r,s)):mt(r)?_(pt(r,s)):r==="!"?_(!s):r==="-v"?_(yt(t,s)):r==="-o"?_(hr(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"?S(`test: ${r}: unary operator expected
|
|
109
|
-
`,2):x("","",1)}if(e.length===3){let r=e[0],s=e[1],o=e[2];if(ut(s))return _(dt(s,r,o));if(lt(s)){let i=Et(r),a=Et(o);return!i.valid||!a.valid?x("","",2):_(ft(s,i.value,a.value))}if(at(s))return _(await ct(t,s,r,o));switch(s){case"-a":return _(r!==""&&o!=="");case"-o":return _(r!==""||o!=="");case">":return _(r>o);case"<":return _(r<o)}if(r==="!"){let i=await
|
|
109
|
+
`,2):x("","",1)}if(e.length===3){let r=e[0],s=e[1],o=e[2];if(ut(s))return _(dt(s,r,o));if(lt(s)){let i=Et(r),a=Et(o);return!i.valid||!a.valid?x("","",2):_(ft(s,i.value,a.value))}if(at(s))return _(await ct(t,s,r,o));switch(s){case"-a":return _(r!==""&&o!=="");case"-o":return _(r!==""||o!=="");case">":return _(r>o);case"<":return _(r<o)}if(r==="!"){let i=await Ie(t,[s,o]);return x("",i.stderr,i.exitCode===0?1:i.exitCode===1?0:i.exitCode)}if(r==="("&&o===")")return _(s!=="")}if(e.length===4){if(e[0]==="!"){let r=await Ie(t,e.slice(1));return x("",r.stderr,r.exitCode===0?1:r.exitCode===1?0:r.exitCode)}if(e[0]==="("&&e[3]===")")return Ie(t,[e[1],e[2]])}let n=await Rn(t,e,0);return n.pos<e.length?S(`test: too many arguments
|
|
110
110
|
`,2):_(n.value)}async function Rn(t,e,n){return Ks(t,e,n)}async function Ks(t,e,n){let{value:r,pos:s}=await Pn(t,e,n);for(;e[s]==="-o";){let o=await Pn(t,e,s+1);r=r||o.value,s=o.pos}return{value:r,pos:s}}async function Pn(t,e,n){let{value:r,pos:s}=await dr(t,e,n);for(;e[s]==="-a";){let o=await dr(t,e,s+1);r=r&&o.value,s=o.pos}return{value:r,pos:s}}async function dr(t,e,n){if(e[n]==="!"){let{value:r,pos:s}=await dr(t,e,n+1);return{value:!r,pos:s}}return Xs(t,e,n)}async function Xs(t,e,n){let r=e[n];if(r==="("){let{value:o,pos:i}=await Rn(t,e,n+1);return{value:o,pos:e[i]===")"?i+1:i}}if(it(r)){let o=e[n+1]??"";return{value:await ot(t,r,o),pos:n+2}}if(mt(r)){let o=e[n+1]??"";return{value:pt(r,o),pos:n+2}}if(r==="-v"){let o=e[n+1]??"";return{value:yt(t,o),pos:n+2}}if(r==="-o"){let o=e[n+1]??"";return{value:hr(t,o),pos:n+2}}let s=e[n+1];if(ut(s)){let o=r,i=e[n+2]??"";return{value:dt(s,o,i),pos:n+3}}if(lt(s)){let o=Et(r),i=Et(e[n+2]??"0");return!o.valid||!i.valid?{value:!1,pos:n+3}:{value:ft(s,o.value,i.value),pos:n+3}}if(at(s)){let o=r,i=e[n+2]??"";return{value:await ct(t,s,o,i),pos:n+3}}return{value:r!==void 0&&r!=="",pos:n+1}}function ht(t,e){let n="^";for(let r=0;r<e.length;r++){let s=e[r];if(s==="\\")if(r+1<e.length){let o=e[r+1];/[\\^$.|+(){}[\]*?]/.test(o)?n+=`\\${o}`:n+=o,r++}else n+="\\\\";else if(s==="*")n+=".*";else if(s==="?")n+=".";else if(s==="["){let o=e.indexOf("]",r+1);o!==-1?(n+=e.slice(r,o+1),r=o):n+="\\["}else/[\\^$.|+(){}]/.test(s)?n+=`\\${s}`:n+=s}return n+="$",new RegExp(n).test(t)}function hr(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 vn(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 In(e);try{let n=new M,r=T(n,e);return $(t,r.expression)}catch{return In(e)}}function Ys(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 In(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=Ys(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 Et(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 mr(t,e){let n=t.state.inCondition;t.state.inCondition=!0;let r="",s="",o=0;try{for(let i of e){let a=await t.executeStatement(i);r+=a.stdout,s+=a.stderr,o=a.exitCode}}finally{t.state.inCondition=n}return{stdout:r,stderr:s,exitCode:o}}function Ue(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 k||t instanceof z)return t.prependOutput(e,n),{action:"rethrow",stdout:e,stderr:n,error:t};let s=ce(t);return{action:"error",stdout:e,stderr:`${n}${s}
|
|
111
111
|
`,exitCode:1}}async function wt(t,e,n="",r=""){let s=n,o=r,i=0;try{for(let a of e){let l=await t.executeStatement(a);s+=l.stdout,o+=l.stderr,i=l.exitCode}}catch(a){if(He(a)||a instanceof te||a instanceof k||a instanceof z||a instanceof le)throw a.prependOutput(s,o),a;return{stdout:s,stderr:`${o}${ce(a)}
|
|
112
112
|
`,exitCode:1}}return{stdout:s,stderr:o,exitCode:i}}async function kn(t,e){let n="",r="";for(let s of e.clauses){let o=await mr(t,s.condition);if(n+=o.stdout,r+=o.stderr,o.exitCode===0)return wt(t,s.body,n,r)}return e.elseBody?wt(t,e.elseBody,n,r):x(n,r,0)}async function Dn(t,e){let n="",r="",s=0,o=0;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e.variable))return S(`bash: \`${e.variable}': not a valid identifier
|
|
@@ -129,7 +129,7 @@ ${st}`):(or(t,e.slice(n)),C)}return C}function or(t,e){let n=1;for(;t.state.env[
|
|
|
129
129
|
`)),n=f;continue}if(l.operator==="<<<"&&l.target.type==="Word"){n=`${await I(this.ctx,l.target)}
|
|
130
130
|
`;continue}if(l.operator==="<"&&l.target.type==="Word")try{let c=await I(this.ctx,l.target),f=this.ctx.fs.resolvePath(this.ctx.state.cwd,c);n=await this.ctx.fs.readFile(f)}catch{let c=await I(this.ctx,l.target);for(let[f,d]of Object.entries(r))d===void 0?delete this.ctx.state.env[f]:this.ctx.state.env[f]=d;return S(`bash: ${c}: No such file or directory
|
|
131
131
|
`)}}let s=await I(this.ctx,e.name),o=[],i=[];for(let l of e.args){let c=await ze(this.ctx,l);for(let f of c.values)o.push(f),i.push(c.quoted)}if(!s){if(e.name.parts.every(c=>c.type==="CommandSubstitution"||c.type==="ParameterExpansion"||c.type==="ArithmeticExpansion")){if(o.length>0){let c=o.shift();return i.shift(),await this.runCommand(c,o,i,n)}return x("","",this.ctx.state.lastExitCode)}return S(`bash: : command not found
|
|
132
|
-
`,127)}let a=await this.runCommand(s,o,i,n);a=await Mn(this.ctx,a,e.redirections),this.ctx.state.lastArg=o.length>0?o[o.length-1]:s;for(let[l,c]of Object.entries(r))c===void 0?delete this.ctx.state.env[l]:this.ctx.state.env[l]=c;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,o=!1){if(e==="cd")return await Zt(this.ctx,n);if(e==="export")return er(this.ctx,n);if(e==="unset")return fr(this.ctx,n);if(e==="exit")return Jt(this.ctx,n);if(e==="local")return rr(this.ctx,n);if(e==="set")return ar(this.ctx,n);if(e==="break")return jt(this.ctx,n);if(e==="continue")return qt(this.ctx,n);if(e==="return")return ir(this.ctx,n);if(e==="eval")return Yt(this.ctx,n);if(e==="shift")return cr(this.ctx,n);if(e==="source"||e===".")return lr(this.ctx,n);if(e==="read")return sr(this.ctx,n,s);if(e==="mapfile"||e==="readarray")return nr(this.ctx,n,s);if(e==="declare"||e==="typeset")return Kt(this.ctx,n);if(e==="readonly")return Xt(this.ctx,n);if(!o){let f=this.ctx.state.functions.get(e);if(f)return Wn(this.ctx,f,n)}if(e===":"||e==="true")return C;if(e==="false")return _(!1);if(e==="let")return tr(this.ctx,n);if(e==="command"){if(n.length===0)return C;let f=n;for(;f.length>0&&f[0].startsWith("-");)f=f.slice(1);if(f.length===0)return C;let[d,...h]=f;return this.runCommand(d,h,[],s,!0)}if(e==="builtin"){if(n.length===0)return C;let[f,...d]=n;return this.runCommand(f,d,[],s)}if(e==="shopt")return C;if(e==="exec"){if(n.length===0)return C;let[f,...d]=n;return this.runCommand(f,d,[],s)}if(e==="wait")return C;if(e==="type")return this.handleType(n);if(e==="[["){let f=n.lastIndexOf("]]");if(f!==-1){let d=n.slice(0,f);return
|
|
132
|
+
`,127)}let a=await this.runCommand(s,o,i,n);a=await Mn(this.ctx,a,e.redirections),this.ctx.state.lastArg=o.length>0?o[o.length-1]:s;for(let[l,c]of Object.entries(r))c===void 0?delete this.ctx.state.env[l]:this.ctx.state.env[l]=c;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,o=!1){if(e==="cd")return await Zt(this.ctx,n);if(e==="export")return er(this.ctx,n);if(e==="unset")return fr(this.ctx,n);if(e==="exit")return Jt(this.ctx,n);if(e==="local")return rr(this.ctx,n);if(e==="set")return ar(this.ctx,n);if(e==="break")return jt(this.ctx,n);if(e==="continue")return qt(this.ctx,n);if(e==="return")return ir(this.ctx,n);if(e==="eval")return Yt(this.ctx,n);if(e==="shift")return cr(this.ctx,n);if(e==="source"||e===".")return lr(this.ctx,n);if(e==="read")return sr(this.ctx,n,s);if(e==="mapfile"||e==="readarray")return nr(this.ctx,n,s);if(e==="declare"||e==="typeset")return Kt(this.ctx,n);if(e==="readonly")return Xt(this.ctx,n);if(!o){let f=this.ctx.state.functions.get(e);if(f)return Wn(this.ctx,f,n)}if(e===":"||e==="true")return C;if(e==="false")return _(!1);if(e==="let")return tr(this.ctx,n);if(e==="command"){if(n.length===0)return C;let f=n;for(;f.length>0&&f[0].startsWith("-");)f=f.slice(1);if(f.length===0)return C;let[d,...h]=f;return this.runCommand(d,h,[],s,!0)}if(e==="builtin"){if(n.length===0)return C;let[f,...d]=n;return this.runCommand(f,d,[],s)}if(e==="shopt")return C;if(e==="exec"){if(n.length===0)return C;let[f,...d]=n;return this.runCommand(f,d,[],s)}if(e==="wait")return C;if(e==="type")return this.handleType(n);if(e==="[["){let f=n.lastIndexOf("]]");if(f!==-1){let d=n.slice(0,f);return Ie(this.ctx,d)}return S("bash: [[: missing `]]'\n",2)}if(e==="["||e==="test"){let f=n;if(e==="["){if(n[n.length-1]!=="]")return S("[: missing `]'\n",2);f=n.slice(0,-1)}return Ie(this.ctx,f)}let i=await this.resolveCommand(e);if(!i)return S(`bash: ${e}: command not found
|
|
133
133
|
`,127);let{cmd:a,path:l}=i,c={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};try{return await a.execute(n,c)}catch(f){return S(`${e}: ${ce(f)}
|
|
134
134
|
`)}}async resolveCommand(e){if(e.includes("/")){let o=this.ctx.fs.resolvePath(this.ctx.state.cwd,e);if(!await this.ctx.fs.exists(o))return null;let i=o.split("/").pop()||e,a=this.ctx.commands.get(i);return a?{cmd:a,path:o}:null}let r=(this.ctx.state.env.PATH||"/bin:/usr/bin").split(":");for(let o of r){if(!o)continue;let i=`${o}/${e}`;if(await this.ctx.fs.exists(i)){let a=this.ctx.commands.get(e);if(a)return{cmd:a,path:i}}}if(!await this.ctx.fs.exists("/bin")){let o=this.ctx.commands.get(e);if(o)return{cmd:o,path:`/bin/${e}`}}return null}async findCommandInPath(e){let n=[],s=(this.ctx.state.env.PATH||"/bin:/usr/bin").split(":");for(let o of s){if(!o)continue;let i=`${o}/${e}`;await this.ctx.fs.exists(i)&&n.push(i)}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="",o="",i=0;for(let a of e)n.has(a)?s+=`${a} is a shell keyword
|
|
135
135
|
`:r.has(a)?s+=`${a} is a shell builtin
|
|
@@ -140,7 +140,7 @@ ${st}`):(or(t,e.slice(n)),C)}return C}function or(t,e){let n=1;for(;t.state.env[
|
|
|
140
140
|
`,1)}return this.ctx.state.env=r,this.ctx.state.cwd=s,this.ctx.state.loopDepth=o,this.ctx.state.parentHasLoopContext=i,this.ctx.state.groupStdin=a,x(l,c,f)}async executeGroup(e,n=""){let r="",s="",o=0,i=this.ctx.state.groupStdin;n&&(this.ctx.state.groupStdin=n);try{for(let a of e.body){let l=await this.executeStatement(a);r+=l.stdout,s+=l.stderr,o=l.exitCode}}catch(a){if(this.ctx.state.groupStdin=i,a instanceof z)throw a;if(He(a)||a instanceof te||a instanceof k)throw a.prependOutput(r,s),a;return x(r,`${s}${ce(a)}
|
|
141
141
|
`,1)}return this.ctx.state.groupStdin=i,x(r,s,o)}async executeArithmeticCommand(e){try{let n=await P(this.ctx,e.expression.expression);return _(n!==0)}catch(n){return S(`bash: arithmetic expression: ${n.message}
|
|
142
142
|
`)}}async executeConditionalCommand(e){try{let n=await me(this.ctx,e.expression);return _(n)}catch(n){return S(`bash: conditional expression: ${n.message}
|
|
143
|
-
`,2)}}};var
|
|
143
|
+
`,2)}}};var Se={maxCallDepth:100,maxCommandCount:1e4,maxLoopIterations:1e4,maxAwkIterations:1e4,maxSedIterations:1e4,maxJqIterations:1e4};function Bn(t){return t?{maxCallDepth:t.maxCallDepth??Se.maxCallDepth,maxCommandCount:t.maxCommandCount??Se.maxCommandCount,maxLoopIterations:t.maxLoopIterations??Se.maxLoopIterations,maxAwkIterations:t.maxAwkIterations??Se.maxAwkIterations,maxSedIterations:t.maxSedIterations??Se.maxSedIterations,maxJqIterations:t.maxJqIterations??Se.maxJqIterations}:{...Se}}function zn(t){try{let e=new URL(t);return{origin:e.origin,pathname:e.pathname,href:e.href}}catch{return null}}function Js(t){let e=zn(t);return e?{origin:e.origin,pathPrefix:e.pathname}:null}function ei(t,e){let n=zn(t);if(!n)return!1;let r=Js(e);return!r||n.origin!==r.origin?!1:r.pathPrefix==="/"||r.pathPrefix===""?!0:n.pathname.startsWith(r.pathPrefix)}function pr(t,e){return!e||e.length===0?!1:e.some(n=>ei(t,n))}var Re=class extends Error{constructor(e){super(`Network access denied: URL not in allow-list: ${e}`),this.name="NetworkAccessDeniedError"}},ke=class extends Error{constructor(e){super(`Too many redirects (max: ${e})`),this.name="TooManyRedirectsError"}},De=class extends Error{constructor(e){super(`Redirect target not in allow-list: ${e}`),this.name="RedirectNotAllowedError"}},gt=class extends Error{constructor(e,n){super(`HTTP method '${e}' not allowed. Allowed methods: ${n.join(", ")}`),this.name="MethodNotAllowedError"}};var ti=20,ri=3e4,ni=["GET","HEAD"],si=new Set(["GET","HEAD","OPTIONS"]),ii=new Set([301,302,303,307,308]);function yr(t){let e=t.maxRedirects??ti,n=t.timeoutMs??ri,r=t.dangerouslyAllowFullInternetAccess?["GET","HEAD","POST","PUT","DELETE","PATCH","OPTIONS"]:t.allowedMethods??ni;function s(a){if(!t.dangerouslyAllowFullInternetAccess&&!pr(a,t.allowedUrlPrefixes??[]))throw new Re(a)}function o(a){if(t.dangerouslyAllowFullInternetAccess)return;let l=a.toUpperCase();if(!r.includes(l))throw new gt(l,r)}async function i(a,l={}){let c=l.method?.toUpperCase()??"GET";s(a),o(c);let f=a,d=0,h=l.followRedirects??!0,m=l.timeoutMs!==void 0?Math.min(l.timeoutMs,n):n;for(;;){let y=new AbortController,w=setTimeout(()=>y.abort(),m);try{let p={method:c,headers:l.headers,signal:y.signal,redirect:"manual"};l.body&&!si.has(c)&&(p.body=l.body);let E=await fetch(f,p);if(ii.has(E.status)&&h){let g=E.headers.get("location");if(!g)return await Un(E,f);let b=new URL(g,f).href;if(!t.dangerouslyAllowFullInternetAccess&&!pr(b,t.allowedUrlPrefixes??[]))throw new De(b);if(d++,d>e)throw new ke(e);f=b;continue}return await Un(E,f)}finally{clearTimeout(w)}}}return i}async function Un(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 Ve=class{fs;commands=new Map;useDefaultLayout=!1;limits;secureFetch;sleepFn;logger;state;constructor(e={}){let n=e.fs??new Ee(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:`
|
|
144
144
|
`,OSTYPE:"linux-gnu",MACHTYPE:"x86_64-pc-linux-gnu",HOSTTYPE:"x86_64",PWD:r,OLDPWD:r,...e.env};if(this.limits=Bn({...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=yr(e.network)),this.sleepFn=e.sleep,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},Pr(n,this.useDefaultLayout),r!=="/"&&n instanceof Ee)try{n.mkdirSync(r,{recursive:!0})}catch{}for(let o of Ar(e.commands))this.registerCommand(o);if(e.network)for(let o of xr())this.registerCommand(o);if(e.customCommands)for(let o of e.customCommands)Sr(o)?this.registerCommand(br(o)):this.registerCommand(o)}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
|
|
145
145
|
# Built-in command: ${e.name}
|
|
146
146
|
`)}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,4 +148,4 @@ ${st}`):(or(t,e.slice(n)),C)}return C}function or(t,e){let n=1;for(;t.state.env[
|
|
|
148
148
|
`).map(a=>a.trimStart()).join(`
|
|
149
149
|
`));try{let i=ue(o),a={fs:this.fs,commands:this.commands,limits:this.limits,exec:this.exec.bind(this),fetch:this.secureFetch,sleep:this.sleepFn},c=await new Ge(a,s).executeScript(i);return this.logResult(c)}catch(i){if(i instanceof k)return this.logResult({stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode,env:{...this.state.env,...n?.env}});if(i instanceof W)return this.logResult({stdout:i.stdout,stderr:i.stderr,exitCode:1,env:{...this.state.env,...n?.env}});if(i instanceof z)return this.logResult({stdout:i.stdout,stderr:i.stderr,exitCode:z.EXIT_CODE,env:{...this.state.env,...n?.env}});if(i.name==="ParseException")return this.logResult({stdout:"",stderr:`bash: syntax error: ${i.message}
|
|
150
150
|
`,exitCode:2,env:{...this.state.env,...n?.env}});if(i instanceof RangeError)return this.logResult({stdout:"",stderr:`bash: ${i.message}
|
|
151
|
-
`,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 Oe from"node:path";var oi="/home/user/project",_e=class{root;mountPoint;readOnly;memory=new Map;deleted=new Set;constructor(e){this.root=Oe.resolve(e.root);let n=e.mountPoint??oi;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=Oe.join(this.root,r),o=Oe.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=Z(n);return Se(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=Z(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=Z(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 readdir(e){let n=this.normalizePath(e);if(this.deleted.has(n))throw new Error(`ENOENT: no such file or directory, scandir '${e}'`);let r=new Set,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 of this.memory.keys())if(a!==n&&a.startsWith(o)){let c=a.slice(o.length).split("/")[0];c&&!s.has(c)&&r.add(c)}let i=this.toRealPath(n);if(i)try{let a=await B.promises.readdir(i);for(let l of a)s.has(l)||r.add(l)}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 Array.from(r).sort()}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=Oe.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 At=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=Z(n);return Se(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=Z(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=Z(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){let n=this.toRealPath(e);try{return(await v.promises.readdir(n)).sort()}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 Le=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 xt=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 _e({root:e.overlayRoot})}let r=new Ve({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 Le(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{Ve as Bash,Ee as InMemoryFs,Re as NetworkAccessDeniedError,_e as OverlayFs,At as ReadWriteFs,De as RedirectNotAllowedError,xt as Sandbox,Le as SandboxCommand,ke as TooManyRedirectsError,Hn as defineCommand,Gn as getCommandNames,Vn as getNetworkCommandNames};
|
|
151
|
+
`,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 Oe from"node:path";var oi="/home/user/project",_e=class{root;mountPoint;readOnly;memory=new Map;deleted=new Set;constructor(e){this.root=Oe.resolve(e.root);let n=e.mountPoint??oi;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=Oe.join(this.root,r),o=Oe.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=Z(n);return be(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=Z(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=Z(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 readdir(e){let n=this.normalizePath(e);if(this.deleted.has(n))throw new Error(`ENOENT: no such file or directory, scandir '${e}'`);let r=new Set,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 of this.memory.keys())if(a!==n&&a.startsWith(o)){let c=a.slice(o.length).split("/")[0];c&&!s.has(c)&&r.add(c)}let i=this.toRealPath(n);if(i)try{let a=await B.promises.readdir(i);for(let l of a)s.has(l)||r.add(l)}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 Array.from(r).sort()}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=Oe.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 At=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=Z(n);return be(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=Z(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=Z(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){let n=this.toRealPath(e);try{return(await v.promises.readdir(n)).sort()}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 Le=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 xt=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 _e({root:e.overlayRoot})}let r=new Ve({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 Le(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{Ve as Bash,Ee as InMemoryFs,Re as NetworkAccessDeniedError,_e as OverlayFs,At as ReadWriteFs,De as RedirectNotAllowedError,xt as Sandbox,Le as SandboxCommand,ke as TooManyRedirectsError,Hn as defineCommand,Gn as getCommandNames,Vn as getNetworkCommandNames};
|